DSA Factory
Free lessonsArrays · Stage 1 · Traversal · Step 4

Walk backwards

Build a reversed copy of a list. About 7 minutes.

Loops can walk backwards

Reading a list from the bottom up is as easy as from the top down. Start at the last box and step down one at a time until you've visited box 0.

The last box is the length minus one, and the loop must still include box 0 before it stops. Getting either end wrong by one is the classic slip, so it's worth tracing a tiny example by hand the first time.

Start at the last box: the length minus one.
Include box 0: stop only after it.
Walk from the end
1
0
2
1
3
2
4
3
i

i = 3. result = [4]

Move 1 of 4

Build a new list as you go

Start with an empty list. As you walk backwards, add each value to the end of the new list. The first value you meet is the old last value, so it lands first. By the end the new list is the old one reversed.

The original array isn't touched at all. That matters when some other part of the program still needs it in its original order.

Walk backwards, add to the end: the copy comes out reversed.
In code
result = []
for i in range(len(nums) - 1, -1, -1):
    result.append(nums[i])
return result
Quick check

You walk 6, 2, 9 from the last box to the first, adding each value to a new list. What's the new list?

  1. A9, 2, 6
  2. B6, 2, 9
  3. C2, 9, 6
Show the answer

9, 2, 6. The walk starts at the last box, so 9 goes in first.

Your problem

Reversed copy

Return a new list with the same values in reverse order. Build a new list rather than changing the one you're given.

Example
nums = [1, 2, 3, 4] → [4, 3, 2, 1]

0 ≤ n ≤ 1,000

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding