Stack with push() and pop()
Write a JavaScript function that takes an array of numbers, pushes a new value onto the end using push(), then pops a value from the end using pop(), and returns the popped value.
Array.prototype.push() adds one or more elements to the end of an array and returns the new length. Array.prototype.pop() removes the last element from an array and returns that element. Together, they implement a stack data structure with LIFO (Last In, First Out) behavior. These methods modify the original array in place.
The push/pop pattern is fundamental to JavaScript programming. push() is O(1) amortized because arrays grow dynamically, and pop() is O(1) because removing from the end requires no element shifting. These methods are the most efficient way to add and remove elements from an array compared to shift() and unshift() which operate on the front.
Time complexity is O(1) amortized for both push() and pop(). Space complexity is O(1) per operation. The array's internal buffer may be resized occasionally when capacity is exceeded during push operations.
Edge cases include popping from an empty array (returns undefined), pushing multiple values at once, and ensuring pushing returns the new length while popping returns the removed element.
Example Input & Output
Push 20, pop returns 20
Empty array, push 5, pop returns 5
Push 4, then pop returns 4
Push 99, pop returns 99
Push 10, pop returns 10
Algorithm Flow

Solution Approach
Best Answers
function solution(arr, val) {
arr.push(val);
return arr.pop();
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
