Reverse a Stack Recursively
Updated
Problem statement
Reverse a stack using recursion. During the reversal, use only the stack operations push, pop, top and empty; do not use a second stack, queue, list or other collection to hold removed elements. Each recursive call may hold an individual value.
For this exercise, assume the input array stack lists the stack from bottom to top, so its last element is the top. Return the reversed stack in the same bottom-to-top representation. The array is used only to pass the stack in and out of the function. The restrictions apply to the reversal itself, not to building the stack from the array or converting the result back to an array.
Function
reverseStack(stack: int[]) → int[]Examples
Example 1
stack = [1,2,3]return = [3,2,1]The original top is 3. The returned stack has 3 at the bottom and 1 at the top.
Example 2
stack = [4,4,-1,7]return = [7,-1,4,4]Reverse positions while preserving both occurrences of 4.
Constraints
- For this exercise, assume
0 <= stack.length <= 500. - Elements are integers in
[-10^9,10^9]and may repeat. - The required reversal procedure uses recursion and no auxiliary collection.
More PeopleStrong Onsite Interview questions
- Add Two Binary StringsONSITE INTERVIEW · Seen Mar 2026
- Four SumONSITE INTERVIEW · Seen Mar 2026
- LRU Cache OperationsONSITE INTERVIEW · Seen Mar 2026
- Sliding Window MaximumONSITE INTERVIEW · Seen Mar 2026
- Find the Entry of a Linked List CycleONSITE INTERVIEW · Seen Sep 2025
- Integer to English Words: Up to 20 DigitsONSITE INTERVIEW · Seen Sep 2025
- Word Ladder II: All Shortest TransformationsONSITE INTERVIEW · Seen Sep 2025
- Detect a Cycle in a Linked ListONSITE INTERVIEW · Seen May 2025
- First Nonrepeating CharacterONSITE INTERVIEW · Seen May 2025
- Longest Subarray with a Target SumONSITE INTERVIEW · Seen May 2025
Similar questions at other companies
- Single-Pass S-Expression ParserBaseten · ONSITE INTERVIEW
- Decode StringBloomberg LP · PHONE SCREEN · ONSITE INTERVIEW
- Calculator with ParenthesesGoogle · PHONE SCREEN · ONSITE INTERVIEW
- Flatten a Nested ArrayFreshworks · ONSITE INTERVIEW
- Verify Postorder Sequence of a BSTMicrosoft · ONSITE INTERVIEW
- Expand a Repeat-Encoded StringExpedia · ONSITE INTERVIEW
- Ternary Expression to Binary TreeNutanix · ONSITE INTERVIEW
- Construct a Tree from Level-Order and Inorder TraversalsSalesforce · ONSITE INTERVIEW
- Basic CalculatorAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Evaluate an Arithmetic Expression with DivisionMotive · ONSITE INTERVIEW