The Wayback Machine - https://web.archive.org/web/20240930183410/https://www.geeksforgeeks.org/stack-for-competitive-programming/
Open In App

Stack for Competitive Programming

Last Updated : 09 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

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



Similar Reads

Tips and Tricks for Competitive Programmers | Set 2 (Language to be used for Competitive Programming)
This is a question asked quite often as in which language should be preferred to be efficient in competitive programming. It is something one should not worry about as what matters is the logic, not the language. Most of the languages are more or less same, but till now the most preferred language is C++, and here are the reasons. Python Simple and
5 min read
Competitive Programming vs General Programming
Programming enthusiasts face a crossroads - Competitive Programming or General Programming? This article sheds light on the distinctions between Competitive Programming vs General Programming, offering a quick guide for those navigating the coding landscape. Whether you're aiming for speed and precision in competitions or tackling real-world projec
3 min read
Dynamic Programming in Game Theory for Competitive Programming
In the fast-paced world of competitive programming, mastering dynamic programming in game theory is the key to solving complex strategic challenges. This article explores how dynamic programming in game theory can enhance your problem-solving skills and strategic insights, giving you a competitive edge. Whether you're a seasoned coder or a newcomer
15+ min read
Top Programming Languages For Competitive Programming
Building an application, running a server, or even implementing a game needs a programming language as the foundation. There are almost more than 700 programming languages which are the most popular ones and this number will increase day by day. But, you don't need to learn all of them. Having a good command of anyone is enough for you to grow your
13 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 to cover all possible things, needed to keep in m
5 min read
Some useful C++ tricks for beginners in Competitive Programming
Here are some of the basic C++ tricks that every beginner in Competitive Programming should follow for increased speed. However, competitive programming can only be mastered with time and lots of practice. These tricks will just help you to save a little time during the contests which sometimes matters a lot. Using the auto keyword to declare data
3 min read
Importance of Testing In Competitive Programming
Many times while solving problems, we face issues like time limit exceeds, wrong solution, runtime error, and memory limit exceeds because after designing algorithm we don't test algorithm efficiency, correctness, time complexity and running the algorithm on a large set of inputs for testing purpose. This is where stress testing comes for rescue. S
3 min read
Writing code faster during Competitive Programming in C++
This article focuses on how to implement your solutions and implement them fast while doing competitive programming. Setup Please refer Setting up a C++ Competitive Programming Environment Snippets Snippet is a programming term for a small region of re-usable source Code. A lot of modern text editors like Sublime provide you a functionality to auto
3 min read
Mathematics Tricks For Competitive Programming In Python 3
Here are some of the exciting features that Python 3.8 provides for programmers in competitive programming. These new features are related to some math functions and algorithms that are frequently used by competitive programmers. The implementation of these features has the time complexity which is the same in case of a program when implemented fro
3 min read
5 Best Languages for Competitive Programming
Needless to say, Competitive Programming is one of the most crucial and popular aspects of a programmer's journey. Though, all the programmers are strongly recommended to participate in such coding challenges to enhance their coding skills and to get various ravishing prizes, rewards, and other career opportunities. Meanwhile, there's a question th
5 min read
Fast I/O for Competitive Programming in Python
In Competitive Programming, it is important to read input as fast as possible to save valuable time. Input/Output in Python can be sometimes time taking in cases when the input is huge or to output any numbers of lines or a huge number of arrays(lists) line after line. Fast Input Normally, the input is taken from STDIN in the form of String using i
3 min read
How to get started with Competitive Programming in JavaScript
Competitive programming is a popular activity among programmers looking to enhance their problem-solving skills and algorithmic thinking. JavaScript is a wonderful language for competitive programming because of how simple it is to use, how powerful its libraries are, and how quickly it can prototype ideas. JavaScript is a great option for programm
5 min read
Why Java Language is Slower Than CPP for Competitive Programming?
Choosing the appropriate language while starting competitive programming is the most important factor. Generally, we choose that language that has short syntax and executes very fast or which is familiar to us, and we know all the working patterns of that particular whether it is Java or C++. Most of the programmers use C++ for competitive programm
5 min read
Points to focus on while doing Competitive Programming
Competitive Programming is vital for one’s development in the coding field. This article is going to discuss some basics points one should keep in mind while competing. Make a list of functions to perform tasks that are encountered frequently in questions and add them to your code in the form of a template. This saves time during contests and helps
5 min read
How to Use int as long long int for Competitive Programming?
Most of the time, input constraints in Competitive programming questions are bigger than the limits of int. Therefore, there is a need to use long int or even long long int. Here let us take two cases so that if a naive user writes correct logic still input is not getting accepted can get to know where the rectification is required. Case 1: Big int
3 min read
Java Generics to Code Efficiently in Competitive Programming
Templates are the foundation of generic programming, which involve writing code in a way that is independent of any particular type. These powerful tools can be used for writing our code effectively. Some cool tricks that may be used in Competitive Programming are given as follows: Fast Input/Output: This uses the time advantage of BufferedReader a
9 min read
Setting up Java Competitive Programming Environment
An operating system is required to be installed on your system. here we will be discussing the setup in windows. However, you can choose any operating system. Install JDK (Java Development Kit) JDK, is a program that allows you to write Java code from the comfort of your desktop. It contains a variety of tools that are very useful for creating, run
5 min read
Creation and Utilisation of Custom Snippets for Competitive programming in VScode
Coding down the whole algorithm from scratch during the online contest can cost you plenty of time and may lead to a bad rank. There is no point in coding the same algorithm you have coded hundreds of times earlier. Why not utilize your previously coded implementations? You can do that by creating custom code snippets and summoning them just by a k
2 min read
Java Competitive Programming Setup in VS Code with Fast I/O and Snippets
Though C++ is the dominating language in the competitive programming universe, there is a fair share of users who still continue to use Java as it has been there seen in the development arena and at the same time can be used competitive programming being fast as it can be toggled to and from where python being slowest among dynamic is hardly seen i
8 min read
Most Critical Mistakes & Tips in Competitive Programming
The moment a beginner hears this word, an image pops up in one's mind where students are sitting in a room full of Computers and coding some out of the world stuff, We'll to be honest it's nothing too hard to grasp so we will be proposing tips that help a programmer to level up faster. So let's begin with the most underrated points on each topic wh
15+ min read
What are Ad Hoc Problems in Competitive Programming?
The Ad Hoc problems are problems that cannot be classified anywhere else in the categories with well-studied solutions since each problem description and its corresponding solution are unique. These problems don't fall under standard categories, there is no specific or general technique exists to solve them. Many Ad Hoc problems are easy, but this
5 min read
Is Competitive Programming Must For Software Development Roles?
Competitive Programming is a mental sport that involves programmers competing against each other within the given time limit. It makes your problem-solving and coding skills better and efficient - also, it provides you with an edge over other candidates during the tech interviews. It makes you an amazing problem solver which is important in softwar
5 min read
What are Online and Offline query-based questions in Competitive Programming
The query-based questions of competitive programming are mainly of two types: Offline Query.Online Query. Offline Query An offline algorithm allows us to manipulate the data to be queried before any answer is printed. This is usually only possible when the queries do not update the original element set before printing the result. Features: Offline
4 min read
Top 10 Most Used Inbuilt C++ functions for Competitive Programming
In this article, we will discuss about the 10 most used inbuilt functions of C++ which will help you to save time and make code concise as well during competitive programming. List of top 10 inbuilt functions in C++ pow()sqrt()min()max()swap()gcd()toupper()tolower()floor()ceil()1. pow( ) This function helps to find the value of a number raised to a
7 min read
Setting up Sublime Text For Competitive Programming (C++) Using Fast Olympic Coding Plugin
Competitive Programming is a mind sport where time matters the most. For that, a fast and easy-to-use tool is required for writing code. Sublime text along with the CppFastOlympicCoding plugin provides the same. Sublime text is popular for its fast performance and aesthetic UI. The CppFastOlympicCoding plugin offers features such as: TestManager: W
4 min read
How to Setup IntelliJ IDEA For Java Competitive Programming Environment?
IntelliJ IDEA is a popular Integrated Development Environment (IDE) used by many developers for Java programming. In this article, we'll walk through the steps to set up IntelliJ IDEA for competitive programming. Competitive programming is a popular activity among computer science students and professionals, as it provides an opportunity to test th
4 min read
Interactive Problems in Competitive Programming | Set 2
Introduction to interactive problems in competitive programming is already discussed in the previous article. In this article, another problem based on the same concept is discussed. Assume that the judge has a hidden (it means the user can't access it) sorted array. The user (i.e. you) need to tell whether a given element VAL lies in that sorted a
3 min read
Getting Started with Competitive Programming in Python
Python is a great option for programming in Competitive Programming. First off, its easy-to-understand and concise grammar enables quicker development and simpler debugging. The huge standard library of Python offers a wide range of modules and functions that can be used to effectively address programming difficulties. Python also offers dynamic ty
11 min read
Logarithm tricks for Competitive Programming
Logarithm: is the inverse function of the exponentiation which means the logarithm value of a given number x is the exponent to another number. [Tex]log_b(x) = y, \to b^{y} = x [/Tex] Below are some tricks using Logarithmic function which can be handy in competitive programming. Checking if a number is a power of two or not:Given an integer N, the
15+ min read
Mastering Bracket Problems for Competitive Programming
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-
4 min read