The "Sum of All Odd Length Subarrays" problem asks you to calculate the sum of all elements in every possible subarray of an array that has an odd length. A subarray is defined as a contiguous sequence of elements within the array. For example, in the array [1, 4, 2, 5, 3], odd-length subarrays include [1], [4], [2], [1, 4, 2], [4, 2, 5], and the entire array [1, 4, 2, 5, 3]. You must sum all elements from all these subarrays and return the total.
This "Easy" level question is a frequent flyer in interviews at Amazon, Google, and LinkedIn. It tests a candidate's ability to handle array indexing and nested loops efficiently. While a brute-force approach is often acceptable for smaller constraints, the problem also provides an opportunity for candidates to demonstrate their knowledge of "Contribution Technique"—calculating how many times each element appears in the final sum—which leads to a more optimized linear-time solution.
There are two main patterns:
i and all odd lengths k, then sum the elements in arr[i...i+k].i, you calculate how many subarrays it belongs to. Specifically, how many odd-length subarrays? An element at index i is included in a subarray if the start index is ≤ i and the end index is ≥ i. By counting the combinations of even/odd prefixes and suffixes, you can find the exact number of times arr[i] contributes to the total sum in O(N) time.Let's take arr = [1, 2, 3].
Odd-length subarrays:
[1], [2], [3]. Sums: 1, 2, 3.[1, 2, 3]. Sum: 6.
Total Sum = 1 + 2 + 3 + 6 = 12.
Using the contribution technique:[1] and [1,2,3]. (2 times)[2] and [1,2,3]. (2 times)[3] and [1,2,3]. (2 times)
Sum = (12) + (22) + (3*2) = 2 + 4 + 6 = 12.Even if you solve an "Easy" problem with brute force, always ask the interviewer: "Would you like me to optimize this?" Explaining the contribution technique (how many subarrays contain this element) shows a higher level of mathematical maturity and algorithmic thinking.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Sum of Absolute Differences in a Sorted Array | Medium | Solve | |
| Number of Sub-arrays With Odd Sum | Medium | Solve | |
| Continuous Subarray Sum | Medium | Solve | |
| Find the Pivot Integer | Easy | Solve | |
| Find the Middle Index in Array | Easy | Solve |