How to Use Stack in Daily Coding Problems

When you start practicing coding, one of the first data structures you’ll encounter is the Stack. At first glance, it may seem like a simple structure a pile of items where you can only add or remove from the top. But in reality, stacks are the backbone of solving many real-world and competitive programming problems.

How to Use Stack in Daily Coding Problems

From checking balanced parentheses to evaluating expressions, from undo features in editors to recursive function calls stacks are everywhere. In this blog, we’ll break down what a stack is, how it works, and how you can use it to solve daily coding problems with examples

What is a Stack? 

A Stack is a linear data structure that follows the LIFO (Last In, First Out) principle. 

  • The element inserted last will be the first one removed. 
  • Think of a stack of plates you can only take the plate from the top. 

Basic operations of a stack: 

1. Push → Add an element to the top of the stack. 

2. Pop → Remove the top element. 

3. Peek/Top → View the top element without removing it. 

4. isEmpty() → Check if the stack is empty. 

Real-Life Analogies of Stack 

  • Plates in a cafeteria: You add (push) plates on top and remove (pop) from the top. 
  • Undo operations in text editors: Every action is pushed into a stack, and undo pops the last action. 
  • Browser history: When you go back, the last visited page is popped from the stack. 

Why Use a Stack in Coding? 

Stacks simplify problems where order matters and where we need to reverse operations. They are especially useful for: 

  • Parsing problems (like balanced parentheses). 
  • Expression evaluation. 
  • Backtracking. 
  • Function call management in recursion. 

Example 1: Balanced Parentheses Problem 

Problem: Check if a string of brackets is balanced (e.g., {[()]} is balanced, but {[(])} is not). 

Code (C++): 

Copy Code

#include <iostream> 

#include <stack> 

using namespace std; 

 

bool isBalanced(string s) { 

    stack<char> st; 

    for (char ch : s) { 

        if (ch == '(' || ch == '{' || ch == '[') { 

            st.push(ch); 

        } else { 

            if (st.empty()) return false; 

            char top = st.top(); 

            if ((ch == ')' && top != '(') || 

                (ch == '}' && top != '{') || 

                (ch == ']' && top != '[')) { 

                return false; 

            } 

            st.pop(); 

        } 

    } 

    return st.empty(); 

} 

 

int main() { 

    string s = "{[()]}"; 

    cout << (isBalanced(s) ? "Balanced" : "Not Balanced"); 

}

Output: 

Balanced 

This is one of the most popular stack problems in coding interviews. 

Example 2: Reverse a String Using Stack 

Copy Code

#include <iostream> 

#include <stack> 

using namespace std; 

string reverseString(string s) { 

    stack<char> st; 

    for (char ch : s) st.push(ch); 

    string rev = ""; 

    while (!st.empty()) { 

        rev += st.top(); 

        st.pop(); 

    } 

    return rev; 

} 

int main() { 

    string s = "hello"; 

    cout << "Reversed: " << reverseString(s); 

}

Output: 

Reversed: olleh 

Example 3: Evaluate Postfix Expression 

Copy Code

#include <iostream> 

#include <stack> 

using namespace std; 

int evaluatePostfix(string exp) { 

    stack<int> st; 

    for (char ch : exp) { 

        if (isdigit(ch)) { 

            st.push(ch - '0'); // convert char to int 

        } else { 

            int val2 = st.top(); st.pop(); 

            int val1 = st.top(); st.pop(); 

            switch (ch) { 

                case '+': st.push(val1 + val2); break; 

                case '-': st.push(val1 - val2); break; 

                case '*': st.push(val1 * val2); break; 

                case '/': st.push(val1 / val2); break; 

            } 

        } 

    } 

    return st.top(); 

} 

 

int main() { 

    string exp = "231*+9-"; // (2 + (3 * 1)) - 9 = -4 

    cout << "Postfix Evaluation: " << evaluatePostfix(exp); 

}

Output: 

Postfix Evaluation: -4 

Example 4: Implement Undo Feature 

Many applications (like MS Word, Notepad, and even coding IDEs) use stacks to implement the Undo feature

  • Every action is stored (pushed) into a stack. 
  • Undo simply pops the last action and reverts it. 

You can simulate this in code with two stacks: 

  • One stack for performed actions. 
  • Another stack for undone actions. 

Example 5: Stock Span Problem (Interview Favorite) 

Problem: Given stock prices for n days, find the span of stock’s price for each day. The span is the number of consecutive days before the given day, where the stock price was less than or equal to today’s price. 

Input: [100, 80, 60, 70, 60, 75, 85] 
Output: [1, 1, 1, 2, 1, 4, 6] 

This is solved efficiently using a stack. 

When Not to Use Stack 

  • When random access is needed. 
  • When insertion/deletion in the middle of a list is required. 
  • When you need two-way access (use a queue or deque instead). 

FAQs on Using Stack in Daily Coding Problems 

Q1. Why is stack called LIFO? 
Because the last element inserted is the first one removed, just like a stack of plates. 

Q2. Which real-world problems use stacks? 
Undo/redo, expression evaluation, browser history, function calls in recursion. 

Q3. What is the time complexity of stack operations? 
Push, pop, and peek all take O(1) time. 

Q4. How is stack different from queue? 
Stack follows LIFO (Last In, First Out) while Queue follows FIFO (First In, First Out). 

Q5. Is stack important for interviews? 
Yes! Stack-based problems like balanced parentheses, expression evaluation, and stock span are interview favorites. 

Conclusion 

The stack may seem like a small and simple data structure, but its applications are vast. Whether it’s solving balanced parentheses, reversing strings, evaluating expressions, or implementing undo functionality, stacks are everywhere in coding. 

If you’re preparing for coding interviews, mastering stack problems is a must. Start practicing with easy problems and gradually move to advanced ones like stock span, trapping rainwater, and histogram problems. 

👉 Want to master data structures and algorithms with hands-on practice? Check out Uncodemy’s DSA Courses and get guided by industry experts. 

Placed Students

Our Clients

Partners

...

Uncodemy Learning Platform

Uncodemy Free Premium Features

Popular Courses