FunctionRacerProblemsRace

Fold and Add

BeginnerTwo pointersPython, JavaScript, TypeScript, Java, C++

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

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Two pointers problems