Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Stack
  • Practice Stack
  • MCQs on Stack
  • Stack Tutorial
  • Stack Operations
  • Stack Implementations
  • Monotonic Stack
  • Infix to Postfix
  • Prefix to Postfix
  • Prefix to Infix
  • Advantages & Disadvantages
Open In App
Next Article:
Arrays for Competitive Programming
Next article icon

Stack for Competitive Programming

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

For competitive programming to be successful, efficient data structures and algorithms are essential. The stack is one such tool. In this article, we will examine how stack data structures play an important role in solving problems efficiently during competitive programming challenges. We will explore the basics of stacks with its use cases and some important problems related to stack that will help you to sharpen your competitive programming skills.

Table of Content

  • Introduction of Stack
  • Stack Operations
  • Must do Stack problems to understand the working of Stack
  • Use Cases of Stack in Competitive Programming
  • Practice problems on Stack for Competitive Programming

Introduction of Stack

A stack is a linear data structure in which the insertion of a new element and removal of an existing element takes place at the same end represented as the top of the stack. A Stack works on the LIFO process (Last In First Out), i.e., the element that was inserted last will be removed first.

Stack Data Structure

Declaring a Stack

C++
#include<iostream> #include <stack> using namespace std; int main(){   stack<dataType> myStack; } 
Java
import java.util.Stack;  public class Main {     public static void main(String[] args) {         Stack<DataType> myStack = new Stack<>();     } } 
Python3
my_stack = [] 
C#
using System; using System.Collections.Generic;  public class Main {     public static void Main(string[] args)     {         Stack<DataType> myStack = new Stack<DataType>();     }      // Define DataType class if not already defined     public class DataType     {         // Define class members if necessary     } } 
JavaScript
let myStack = []; 

Stack Operations

There are various stack operations that are applicable on a stack. Stack operations are generally used to extract information and data from a stack data structure.

Some of the stack operations are given below:

1. Push element X into the stack

C++
myStack.push(X); 
Java
myStack.push(X); 
Python3
myStack.push(X); 
C#
myStack.Push(X); 
JavaScript
myStack.push(X); 

2. Pop the topmost element of the stack

C++
myStack.pop(); 
Java
myStack.pop(); 
Python3
myStack.pop() 
C#
myStack.Pop(); 
JavaScript
myStack.pop(); 

3. Get the Topmost of the stack

C++
int topElement = myStack.top(); 
Java
int topElement = myStack.top(); 
Python3
top_element = my_stack[-1] 
C#
int topElement = myStack.Top(); 
JavaScript
let topElement = myStack[myStack.length - 1]; 

4. Size of Stack

C++
int stackSize = myStack.size(); 
Java
int stackSize = myStack.size(); 
Python3
stack_size = len(my_stack) 
C#
int stackSize = myStack.Size(); 
JavaScript
let stackSize = myStack.length; 

5. Checks if the stack is empty

C++
if (myStack.empty()) {     // Stack is empty } 
Java
if (myStack.isEmpty()) {     // Stack is empty } 
Python3
if not my_stack:     # Stack is empty 
C#
if (myStack.Empty()) {     // Stack is empty } 
JavaScript
if (myStack.length === 0) {     // Stack is empty } 

6. Swap two stacks

C++
stack<int> myStack; stack<int> anotherStack; myStack.swap(anotherStack); 
Java
// Using Deque instead of Stack for flexibility Deque<Integer> myStack = new ArrayDeque<>(); Deque<Integer> anotherStack = new ArrayDeque<>();  // Add elements to myStack and anotherStack  // Swap the contents of myStack and anotherStack using a // temporary variable Deque<Integer> tempStack = myStack; myStack = anotherStack; anotherStack = tempStack; 
Python3
my_stack = [] another_stack = []  # Add elements to my_stack and another_stack  # Swap the contents of my_stack and another_stack my_stack, another_stack = another_stack, my_stack 
C#
// Using Queue instead of Stack for flexibility Queue<int> myStack = new Queue<int>(); Queue<int> anotherStack = new Queue<int>();  // Add elements to myStack and anotherStack  // Swap the contents of myStack and anotherStack using a temporary variable Queue<int> tempStack = myStack; myStack = anotherStack; anotherStack = tempStack; 
JavaScript
let myStack = [];  let anotherStack = [];  // Add elements to myStack and anotherStack  // Swap the contents of myStack and anotherStack using array destructuring [myStack, anotherStack] = [anotherStack, myStack]; 

Must do Stack problems to understand the working of Stack

Problem

Practice link

Convert Infix expression to Postfix expression

Solve

Evaluation of Postfix Expression

Solve

Check for Balanced Brackets in an expression

Solve

Implement Stack using Queues

Solve

Use Cases of Stack in Competitive Programming

Here are some use cases of the stack data structure in competitive programming:

1. Next Greater element in O(N) / Next Smaller Element in O(N)

Many coding problems requires the pre-calculation of next smaller/greater element for each index of the array on left as well as right side. This can be calculated using stack in O(N) complexity

Example: Arr = [4,2,1,5,2,3,1]
Next greater on Left: [-1,4,2,-1,5,5,3] //-1 indicates that no greater element exists on left
Next greater on right:[5,5,5,-1,3,-1,-1] //-1 indicates that no greater element exists on right
Next smaller on left: [-1,-1,-1,1,1,2,-1] //-1 indicates that no smaller element exists on left
Next smaller on right:[2,1,-1,2,1,1,-1] //-1 indicates that no smaller element exists on right

2. Balanced Bracket Problems

Bracket problems in programming typically refer to problems that involve working with parentheses, and/or braces in expressions or sequences. It typically refers to problems related to the correct and balanced usage of parentheses, and braces in expressions or code.

These problems often involve checking if a given sequence of these symbols is well-formed, meaning that each opening symbol has a corresponding closing symbol in the correct order, and there are no unmatched or incorrectly nested symbols.

The most basic problem that falls under this category is balanced parenthesis, which state that Given a string containing various types of parentheses, such as ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘, ‘]’, you need to determine if the parentheses are balanced.

This problem is solved using a stack data structure. A stack can help you keep track of the opening parentheses you’ve seen so far. When you encounter a closing parenthesis, you can easily check if the top element of the stack matches it. If it does, you pop the opening parenthesis from the stack, indicating that it has been properly closed.

3. Monotonic Stacks

A monotonic stack is a stack whose elements are monotonically increasing or decreasing. It contains all qualities that a typical stack has and its elements are all monotonic decreasing or increasing.

Below are the features of a monotonic stack:

  • It is a range of queries in an array situation
  • The minima/maxima elements
  • When an element is popped from the monotonic stack, it will never be utilised again.

The monotonic stack problem is mainly the previous/next smaller/larger problem. It maintains monotonicity while popping elements when a new item is pushed into the stack.

4. Find the minimum in all subarrays of a fixed length in an array in   O(N)

Suppose we have a problem in which we need to calculate the maximum for each and every contiguous subarray of size K for a given any given array. This problem can be solved in O(n) using a Deque data structure which has functionality of a stack as well as a queue. click here to see how.

5. Finding Cycle in a directed graph

To find cycle in a directed graph we can use the Depth First Traversal (DFS) technique. It is based on the idea that there is a cycle in a graph only if there is a back edge [i.e., a node points to one of its ancestors] present in the graph.

To detect a back edge, we need to keep track of the nodes visited till now and the nodes that are in the current recursion stack [i.e., the current path that we are visiting]. If during recursion, we reach a node that is already in the recursion stack, there is a cycle present in the graph.

Practice problems on Stack for Competitive Programming

Problem

Practice link

Largest Rectangular Area in a Histogram using Stack

Solve

Merge Overlapping Intervals

Solve

Design a stack that supports getMin() in O(1) time and O(1) extra space

Solve

Maximum size rectangle binary sub-matrix with all 1s

Solve

The Stock Span Problem

Solve

The Celebrity Problem

Solve

ZigZag Tree Traversal

Solve

Length of the longest valid substring

Solve

Reduce the string by removing K consecutive identical characters

Solve

Minimum number of bracket reversals needed to make an expression balanced

Solve



Next Article
Arrays for Competitive Programming

V

vaibhav_gfg
Improve
Article Tags :
  • Stack
  • Competitive Programming
  • DSA
  • Data Structures-Stack
Practice Tags :
  • Stack

Similar Reads

  • Queue for Competitive Programming
    In competitive programming, a queue is a data structure that is often used to solve problems that involve tasks that need to be completed in a specific order. This article explores the queue data structure and identifies its role as a critical tool for overcoming coding challenges in competitive pro
    8 min read
  • String Guide for Competitive Programming
    Strings are a sequence of characters, and are one of the most fundamental data structures in Competitive Programming. String problems are very common in competitive programming contests, and can range from simple to very challenging. In this article we are going to discuss about most frequent string
    15 min read
  • Arrays for Competitive Programming
    In this article, we will be discussing Arrays which is one of the most commonly used data structure. It also plays a major part in Competitive Programming. Moreover, we will see built-in methods used to write short codes for array operations that can save some crucial time during contests. Table of
    15+ min read
  • Heap Data Structure for Competitive Programming
    Competitive programming needs smart tools to solve problems quickly. One key tool is the Heap Data Structure, which helps organize data in a way that's super fast. In this article, we'll break down the Heap, looking at its types, basic moves, and how it's a big deal in competitive programming. We'll
    15+ min read
  • My Journey of Competitive Programming
    Hello geeks, Today I want to share with you my competitive programming journey. Competitive programming means solving problems in different platforms. There are many benefits to do this. Even many companies directly select candidates through their coding profile. And you can also add this profile in
    3 min read
  • How to read Competitive Programming Questions?
    Competitive Programming is considered as a sport in the field of computer science. The culture of this sport is growing day by day and a lot of people are also considering this as a career choice. So, to help the participants with improving their efficiency in this sport, in this post, we have tried
    5 min read
  • 7 Best Books for Competitive Programming
    Do you have a dream to win a Gold Medal in the Olympics of Programming (ACM ICPC)? Do you want to ace your career with Google Kickstart or want to win a prize amount of $20,000 to become a world champion in Facebook Hackercup or Google Code jam? Then you have to be an out-of-the-box problem solver.
    8 min read
  • Why Should You Do Competitive Programming?
    Competitive programming is a mind sport, where people compete against each other to solve some programming questions/logic with an efficient approach and within a time constraint. The goal of competitive programming is to write code to solve a problem within a given timeframe. There are mainly mathe
    8 min read
  • Best Courses on Competitive Programming
    Competitive programming has gone beyond being a niche interest. Has become a skill, for computer science enthusiasts. Being able to solve algorithmic problems is highly valued in the tech industry. Recognizing this demand various online platforms offer courses tailored to skill levels and learning p
    5 min read
  • How to Get Started with Competitive Programming?
    If you're a Computer Science student or a coding enthusiast, chances are more you've heard individuals discussing their Competitive Programming skills and rankings & achievements in various coding challenges or contests. And truly, Competitive Programming skills are one of those few skills that
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences