Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Data Structures & Algorithms»Implement Stack Using Array | GFG Practice | Complete Guide in Python
    Data Structures & Algorithms

    Implement Stack Using Array | GFG Practice | Complete Guide in Python

    codeanddebugBy codeanddebug26 July 2025No Comments3 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Featured image of a question to implement stack using arrays
    Share
    Facebook Twitter LinkedIn Pinterest Email

    You need to implement a stack using an array (Python list works as an array here). The stack should support two main operations:

    • Push(x): Insert element x on top of the stack.
    • Pop(): Remove and return the top element of the stack. If the stack is empty, return -1.

    Here’s the [Problem Link] to begin with.

    Contents:
     [show]
    • What is a Stack?
    • Approach and Intuition
    • Why use list’s .append() and .pop()?
    • Step-By-Step Explanation with Code
    • Dry Run Example
    • Time and Space Complexity
    • Key Takeaways

    What is a Stack?

    • A stack is a simple data structure that works on LIFO (Last In, First Out) principle.
    • That means: the last item that was added (pushed) is the first item to be removed (popped).

    Think of a stack like a pile of books: you add (push) books on top and remove (pop) books from the top only.

    Approach and Intuition

    • We’ll use a Python list (self.arr) as the internal storage for the stack.
    • push(data):
      • Add the given data at the end of the list (top of the stack).
    • pop():
      • Remove and return the last element from the list (top of the stack).
      • If the list (our stack) is empty, return -1 (as per the problem!).

    Why use list’s .append() and .pop()?

    • append() adds element at the end → top of stack.
    • pop() removes and returns the last element → top of stack.

    Step-By-Step Explanation with Code

    class MyStack:
        def __init__(self):
            # Create an empty list to represent the stack
            self.arr = []
        
        # Function to push an integer into the stack.
        def push(self, data):
            # Add (append) data to the end of the list
            self.arr.append(data)
        
        # Function to remove an item from top of the stack.
        def pop(self):
            # Check if the stack is empty
            if not self.arr:
                return -1  # If empty, return -1
            return self.arr.pop()  # Remove and return the last element

    Dry Run Example

    Scenario:
    Let’s say we do the following operations:

    stack = MyStack()
    stack.push(2)
    stack.push(3)
    stack.push(5)
    print(stack.pop())  # Output? 5
    print(stack.pop())  # Output? 3
    print(stack.pop())  # Output? 2
    print(stack.pop())  # Output? -1 (since stack is now empty)

    Time and Space Complexity

    • push(): O(1) per operation
    • pop(): O(1) per operation
    • Space: O(n) where n is the number of elements in the stack

    Key Takeaways

    • Python list is a perfect fit for stack because append() and pop() at end are both O(1).
    • Always check for empty stack before popping, as popping from an empty stack is an error (here, we return -1).
    • This is the basic way to build a stack in Python and under-the-hood in many programming languages!

    If you understand this, you understand the fundamentals of stack implementation. Practice these operations and try to extend to other stack problems!

    Join our Advance DSA COURSE

    For any changes to the article, kindly email at code@codeanddebug.in or contact us at +91-9712928220.

    Easy Stack and Queues
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleClimbing Stairs | Leetcode 70 | Solved using Dynamic Programming
    Next Article Implement Queue Using Array: Complete Guide with Normal and Optimal Solutions
    codeanddebug
    • Website

    Related Posts

    Data Structures & Algorithms

    Implement Stack using Queues | Leetcode 225 | Complete Python Code

    26 July 2025
    Data Structures & Algorithms

    Implement Queue Using Array: Complete Guide with Normal and Optimal Solutions

    26 July 2025
    Data Structures & Algorithms

    Climbing Stairs | Leetcode 70 | Solved using Dynamic Programming

    24 July 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • Data Structures & Algorithms (159)
      • Beginner (61)
      • Expert (38)
      • Intermediate (60)
    • Uncategorised (1)
    Recent Posts

    Implement Stack using Queues | Leetcode 225 | Complete Python Code

    26 July 2025

    Implement Queue Using Array: Complete Guide with Normal and Optimal Solutions

    26 July 2025

    Implement Stack Using Array | GFG Practice | Complete Guide in Python

    26 July 2025

    Climbing Stairs | Leetcode 70 | Solved using Dynamic Programming

    24 July 2025

    Nth Fibonacci Number | Introduction to Dynamic Programming

    24 July 2025
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.