Fold and Add
Fold the list nums in half and add the items that land on each other: the first item meets the last, the second meets the second to last, and so on. Return the list of these sums, from the outside in. If nums has an odd number of items, the middle item meets nothing, so append it on its own at the end.
For [1, 2, 3, 4, 5] the pairs are 1 + 5 and 2 + 4, then the middle 3 is left over, giving [6, 6, 3]. An empty list gives an empty list.
Example 1
nums [1,2,3,4,5]
returns [6,6,3]
1 + 5 = 6, 2 + 4 = 6, and the middle item 3 stays alone.
Example 2
nums [1,2,3,4]
returns [5,5]
With an even count every item has a partner: 1 + 4 and 2 + 3.
Constraints
0 <= len(nums) <= 100-1000 <= nums[i] <= 1000
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Two pointers problems
- Lighten the ShelfBeginner
- Peel Matching EndsBeginner
- Sums of Every WindowBeginner
- Trim the ZerosBeginner
- Written BackwardsBeginner
- Zip Two Sorted ListsBeginner
- Best Window of Distinct NumbersEasy
- Closest Pair Sum in a Sorted ListEasy