oneby7

Recursion and Backtracking Recursion on a stack

317. Sort a Stack with Recursion

Medium

You are given a stack of integers. Sort it in place, so the values grow from the bottom of the stack to the top: the smallest value ends up at the bottom and the largest value ends up on top. Repeated values all stay on the stack. 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,1,6] has 4 at the bottom and 6 on top. The output is written the same way, so a sorted stack reads from the smallest value to the largest.

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 = [41, -3, 17, 8, -3]

Output: [-3,-3,8,17,41]

Explanation: 41 starts at the bottom and ends on top, because it is the largest. The two -3s are the smallest, so they end at the bottom, one on the other.

Example 2

Input: stack = []

Output: []

Explanation: An empty stack is already sorted, so it stays empty.

Example 3

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

Output: [-1000000000,5,1000000000]

Explanation: This stack is already sorted, with the largest value on top. Sorting it changes nothing.

Check your understanding

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

stack = [3, -1, 2, -1]

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.