awelgorithms

Restore by reversing twice

Updated

Two reverses are identity: reverse(reverse(a)) = a. Using a stack twice returns the original order. One reverse is the transformation. Two is a round trip (and a way to copy through a helper without flipping).

What to focus on

Copy-via-stack once reverses. Copy-via-stack twice (or stack then stack) restores. One-item is identity either way.

Worked examples

round trip

a = [4, 1, 9], reverse, reverse
  1. [9, 1, 4] then [4, 1, 9]

Result: [4, 1, 9]

one reverse

a = [4, 1, 9], reverse once
  1. [9, 1, 4]

Result: not restored

one item

a = [7], reverse twice
  1. still [7]

Result: [7]

Try it

Write reverseTwice(a). a is an array of integers. Reverse with a stack twice and return the original. One reverse is not enough. Reverse [4, 1, 9] twice → [4, 1, 9]. Reverse once → [9, 1, 4]. [7] stays [7].

a is a non-empty list of integers.