Push a Value to the Very Bottom of a Stack

Implement insertAtBottom

Given a stack of integers and a value val, insert val at the very bottom of the stack, preserving the relative order of everything already there — using only the standard stack operations (push, pop, top, isEmpty), with no other explicit data structure to hold values in transit. Recursion turns out to be exactly the tool for this: popping the top element and holding it as a local variable in the current recursive call is functionally identical to pushing it onto an auxiliary stack — except the "stack" being used is the program's own call stack, never declared explicitly anywhere in the code. Recursing all the way down to an empty stack (the base case) is where the new value actually gets pushed; as the recursion unwinds, each call restores its own held-aside value on top, rebuilding the original order above the new bottom.

Example 1:

Input: stack = [1,2,3], val = 10

Output: [10,1,2,3]

Example 2:

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

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

Example 3:

Input: stack = [5], val = 9

Output: [9,5]

+ 2 hidden test cases run on Submit.

Constraints:

  • 0 ≤ stack.length ≤ 12
  • stack is given bottom-to-top (index 0 is the bottom, the last index is the top)
  • -100 ≤ stack[i], val ≤ 100
  • Only push, pop, top/peek, and isEmpty are considered valid stack operations — no other data structure may be used to solve this with the intended technique

stack =

[1, 2, 3]

val =

10