Tutorialspoint
Problem
Solution
Submissions

Stack using Arrays

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a JavaScript program to implement a stack data structure using arrays. A stack is a linear data structure that follows the Last In First Out (LIFO) principle. The stack should support basic operations like push (add element to top), pop (remove element from top), peek/top (get top element without removing), isEmpty (check if stack is empty), and size (get number of elements).

Example 1
  • Input: Push operations: [1, 2, 3, 4], Pop operation called twice
  • Output: Stack contains [1, 2], popped elements are 4 and 3
  • Explanation:
    • Initially stack is empty [], then push 1, 2, 3, 4 sequentially.
    • Stack becomes [1, 2, 3, 4]. 
    • Pop operation removes 4, stack becomes [1, 2, 3].
    • Pop operation removes 3, stack becomes [1, 2].
Example 2
  • Input: Push operations: [10, 20], Peek operation, Pop operation, isEmpty check
  • Output: Peek returns 20, pop returns 20, stack contains [10], isEmpty returns false
  • Explanation:
    • Initially stack is empty [], push 10 and 20.
    • Stack becomes [10, 20].
    • Peek operation returns 20 without removing it.
    • Pop operation removes and returns 20, stack becomes [10].
    • isEmpty check returns false since stack has one element.
Constraints
  • The stack should handle integer values
  • Maximum stack size can be up to 10^4 elements
  • Pop and peek operations on empty stack should return null or undefined
  • Time Complexity: O(1) for all operations
  • Space Complexity: O(n) where n is the number of elements
ArraysStackAccentureShopify
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use an array to store stack elements where the last element represents the top
  • Maintain a pointer or use array length to track the top position
  • For push operation, add element to the end of array
  • For pop operation, remove and return the last element
  • For peek operation, return the last element without removing it
  • Use array length to check if stack is empty and get size

Steps to solve by this approach:

 Step 1: Initialize an empty array to store stack elements
 Step 2: Implement push method by adding elements to the end of array using push()
 Step 3: Implement pop method by removing last element using pop() after checking if stack is empty
 Step 4: Implement peek method by returning last element without removing it
 Step 5: Implement isEmpty method by checking if array length is zero
 Step 6: Implement size method by returning array length
 Step 7: Test all operations with sample data to verify functionality

Submitted Code :