Sum of All Odd Length Subarrays
EasyMathprefix sum
Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.
Practice this as a mock interviewFree to start, no account neededProblem
Given an array of positive integers arr, consider every contiguous subarray whose length is odd. Return the total of all elements across all of those subarrays.
An O(n^2) prefix-sum approach works; there is also an O(n) solution that counts how many odd-length subarrays contain each element.
Examples
Input: arr = [1,4,2,5,3]
Output: 58
Length 1: 15, length 3: 7+11+10 = 28, length 5: 15. Total 15+28+15 = 58.
Input: arr = [1,2]
Output: 3
Only the two length-1 subarrays count.
Input: arr = [10,11,12]
Output: 66
Length 1 sums to 33 and the whole array sums to 33.
Constraints
- 1 <= arr.length <= 100
- 1 <= arr[i] <= 1000
What the interviewer grades
A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.