oneby7

Recursion and Backtracking Recursion on a stack

316. Reverse a Stack with Recursion

Medium

You are given a stack of integers. Reverse it in place, so the order of its values is turned around: the value at the bottom ends up on top, and the value on top ends up at the bottom. The function returns nothing. The answer is the stack after it returns.

The examples write a stack as its values from the bottom up, so stack = [4,9,1] has 4 at the bottom and 1 on top. The output is written the same way.

The exercise is to do it with recursion, using only the stack's own operations: push, pop, top and isEmpty. Do not copy the values into an array, a list or a second stack, and do not loop over them. The judge checks only the stack you leave behind, so it cannot tell whether you kept to this rule. That part is up to you.

Each language gets its usual stack: std::stack<int> in C++, Stack<Integer> in Java and Stack<int> in C#. Python, JavaScript, Go and Rust use a list with its top at the end: a list (append, pop), an array (push, pop), a *[]int and a Vec<i32> (push, pop).

Example 1

Input: stack = [3, 8, -2, 6, 1]

Output: [1,6,-2,8,3]

Explanation: 1 was on top and is now at the bottom, and 3, the old bottom, is now on top. Popping the stack now gives 3, 8, -2, 6, 1, the order in which the values were first pushed.

Example 2

Input: stack = []

Output: []

Explanation: An empty stack has nothing to reverse, so it stays empty.

Example 3

Input: stack = [1000000000, 1000000000, -1000000000]

Output: [-1000000000,1000000000,1000000000]

Explanation: The −109 on top moves to the bottom. The two equal values move up together, so the stack changes even though half of it looks the same.

Check your understanding

Work out the answer for this input before you write any code.

stack = [4, 9, 1, 6]

Constraints

  • 0 ≤ number of values in the stack ≤ 3000
  • -109 ≤ each value ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.