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 Queue
  • Practice Queue
  • MCQs on Queue
  • Queue Tutorial
  • Operations
  • Applications
  • Implementation
  • Stack vs Queue
  • Types of Queue
  • Circular Queue
  • Deque
  • Priority Queue
  • Stack using Queue
  • Advantages & Disadvantages
Open In App
Next Article:
Why do you do Competitive Programming (CP)?
Next article icon

Queue for Competitive Programming

Last Updated : 18 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 programming.

Table of Content

  • What is a Queue?
  • Why to use Queue?
  • Idea behind a Queue
  • Use Cases of Queue in Competitive Programming
  • Practice Problems on Queues for Competitive Programming

What is a Queue?

A Queue is a linear data structure that follows a First-In, First-Out (FIFO) order. This means that the first element added to the queue is the first element to be removed.


Queue Data Structure


Why to use Queue?

Queues are a useful data structure for several reasons:

  • FIFO Order: Queues ensure that elements are processed in the order they were added, which is crucial for situations where order matters.
  • Dynamic Nature: Queues can grow or shrink dynamically, which can be useful when solving problems related to finding maximum/minimum in subarrays.
  • Breadth-first search algorithm: The breadth-first search algorithm uses a queue to explore nodes in a graph level-by-level. The algorithm starts at a given node, adds its neighbors to the queue, and then processes each neighbor in turn.

Idea behind a Queue

The idea behind a queue is to maintain a sequence of elements where new elements are added at one end and elements are removed from the other end. This is similar to how a line of people waiting for service operates. The person who has been waiting the longest is at the front of the line (first to be served), and new people join the line at the back (last to be served).

Use Cases of Queue in Competitive Programming

1. Min/Max Queue:

Min/max queue is a modified queue which supports finding the minimum and maximum elements in the queue efficiently. In addition to the standard enqueue and dequeue operations, a min/max queue provides operations to retrieve the current minimum or maximum element in the queue in constant time (O(1)).

Method 1: Using Dequeue and Queue

The idea is to use Doubly Ended Queue to store in increasing order if the structure is to return the minimum element and store in decreasing order if the structure is to return the maximum element.

Method 2: Using Dequeue of pairs

This method is used when we want to remove elements without knowing which element we have to remove. This is done by storing element along with the index and keeping track of how many elements we have added or removed.

Implementation:

C++
#include <bits/stdc++.h> using namespace std;  class MinQueue {     // Dequee to implement Min Queue     deque<pair<int, int>> q;     // Data members to store the count of elements added and removed so far     int added, removed; public:      MinQueue() {         added = removed = 0;     }     // Method to return the min element present in the queue     int getMin() {         return q.front().first;     }     // Method to insert element in the queue     void enqueueElement(int ele) {         while (!q.empty() && q.back().first > ele)             q.pop_back();         q.push_back({ele, added++});     }     // Method to remove element from the queue     void dequeueElement() {         if(!q.empty() && q.front().second == removed)         q.pop_front();         removed++;     } };  int main() {     MinQueue minQ;     minQ.enqueueElement(10);     minQ.enqueueElement(5);     cout << minQ.getMin() << "\n";     minQ.enqueueElement(3);     minQ.dequeueElement();     minQ.dequeueElement();     cout << minQ.getMin() << "\n";      return 0; } 
Java
import java.util.ArrayDeque; import java.util.Deque;  class MinQueue {     // Deque to implement Min Queue     private Deque<Pair<Integer, Integer>> q;     // Data members to store the count of elements added and removed so far     private int added, removed;      public MinQueue() {         q = new ArrayDeque<>();         added = removed = 0;     }      // Method to return the min element present in the queue     public int getMin() {         return q.getFirst().getKey();     }      // Method to insert element in the queue     public void enqueueElement(int ele) {         while (!q.isEmpty() && q.getLast().getKey() > ele) {             q.removeLast();         }         q.addLast(new Pair<>(ele, added++));     }      // Method to remove element from the queue     public void dequeueElement() {         if (!q.isEmpty() && q.getFirst().getValue() == removed) {             q.removeFirst();         }         removed++;     }      public static void main(String[] args) {         MinQueue minQ = new MinQueue();         minQ.enqueueElement(10);         minQ.enqueueElement(5);         System.out.println(minQ.getMin());         minQ.enqueueElement(3);         minQ.dequeueElement();         minQ.dequeueElement();         System.out.println(minQ.getMin());     } }  class Pair<K, V> {     private K key;     private V value;      public Pair(K key, V value) {         this.key = key;         this.value = value;     }      public K getKey() {         return key;     }      public V getValue() {         return value;     } } 
Python3
# Python Implementation from collections import deque  class MinQueue:     def __init__(self):         # Deque to implement Min Queue         self.q = deque()         # Data members to store the count of elements added and removed so far         self.added = 0         self.removed = 0      # Method to return the min element present in the queue     def get_min(self):         return self.q[0][0]      # Method to insert element in the queue     def enqueue_element(self, ele):         while self.q and self.q[-1][0] > ele:             self.q.pop()         self.q.append((ele, self.added))         self.added += 1      # Method to remove element from the queue     def dequeue_element(self):         if self.q and self.q[0][1] == self.removed:             self.q.popleft()         self.removed += 1  if __name__ == "__main__":     min_q = MinQueue()     min_q.enqueue_element(10)     min_q.enqueue_element(5)     print(min_q.get_min())     min_q.enqueue_element(3)     min_q.dequeue_element()     min_q.dequeue_element()     print(min_q.get_min())  # This code is contributed by Tapessh(tapeshdua420) 
C#
using System; using System.Collections.Generic;  public class MinQueue {     // Deque to implement Min Queue     private Queue<Tuple<int, int>> q = new Queue<Tuple<int, int>>();     // Data members to store the count of elements added and removed so far     private int added, removed;      public MinQueue()     {         added = removed = 0;     }      // Method to return the min element present in the queue     public int GetMin()     {         return q.Peek().Item1;     }      // Method to insert element in the queue     public void EnqueueElement(int ele)     {         while (q.Count > 0 && q.Peek().Item1 > ele)             q.Dequeue();         q.Enqueue(Tuple.Create(ele, added++));     }      // Method to remove element from the queue     public void DequeueElement()     {         if (q.Count > 0 && q.Peek().Item2 == removed)             q.Dequeue();         removed++;     } }  class Program {     static void Main(string[] args)     {         MinQueue minQ = new MinQueue();         minQ.EnqueueElement(10);         minQ.EnqueueElement(5);         Console.WriteLine(minQ.GetMin());         minQ.EnqueueElement(3);         minQ.DequeueElement();         minQ.DequeueElement();         Console.WriteLine(minQ.GetMin());     } } // This code is contributed by shivamgupta0987654321 
JavaScript
// JS Implementation  class MinQueue {     constructor() {         // Deque to implement Min Queue         this.q = [];         // Data members to store the count of elements added and removed so far         this.added = 0;         this.removed = 0;     }      // Method to return the min element present in the queue     getMin() {         return this.q[0][0]; // The first element of the pair     }      // Method to insert element in the queue     enqueueElement(ele) {         while (this.q.length > 0 && this.q[this.q.length - 1][0] > ele) {             this.q.pop();         }         this.q.push([ele, this.added++]);     }      // Method to remove element from the queue     dequeueElement() {         if (this.q.length > 0 && this.q[0][1] === this.removed) {             this.q.shift();         }         this.removed++;     } }    const minQ = new MinQueue(); minQ.enqueueElement(10); minQ.enqueueElement(5); console.log(minQ.getMin()); minQ.enqueueElement(3); minQ.dequeueElement(); minQ.dequeueElement(); console.log(minQ.getMin());  // This code is contributed by Sakshi 

Output
5 3 

Time Complexity: Since each element is added once and removed once, so both enqueue and dequeue have O(1) time complexity and we can find the min element by accessing the front of the queue so getMin() operation has O(1) time complexity as well.
Auxiliary Space: O(N) to store all elements in the queue.

2. Finding the minimum of all fixed-length subarrays:

If we are given an array of N numbers and we need to find the minimum/maximum of all subarrays of size K, then we can easily solve this my maintaining a min/max queue.

3. Shortest subarray with sum at least K (array can have negative integers as well):

If we are given an array of N integers (positive and negative) and we need to find the smallest length of a subarray whose sum >= K, then we can use a variation of min queue to get the smallest length. Refer this article to know more about using a deque to find the shortest subarray with sum at least K.

4. Graph Algorithms:

Queues are used in multiple graph algorithms like Breadth First Search, Topological Sort, Shortest Path Algorithms like Dijkstra's Algorithm, etc.

5. To Calculate the longest Subarray with maximum absolute difference as K:

We can calculate the longest Subarray with maximum absolute difference using sliding window and two monotonic queues to keep track of the window max and window min.

Practice Problems on Queues for Competitive Programming:

Easy Level Problems on Queues:

Problem

Problem Link

Minimum Cost of Ropes

Solve

Stack using two Queues

Solve

Queue using two Stacks

Solve

Queue Reversal

Solve

Reverse first K elements of Queue

Solve

Generate Binary Numbers

Solve

Queue Operations

Solve

Dequeue Implementations

Solve

Ticket Counter

Solve

Next Right Node

Solve

Queue using Stack

Solve

Medium Level Problems on Queues:

Problem

Problem Link

Maximum of all subarrays of size K

Solve

First non-repeating character in a Stream

Solve

Circular Tour

Solve

First negative integer in every window of size k

Solve

Rotten Oranges

Solve

Steps by Knight

Solve

Print binary tree levels in sorted order

Solve

Restricted Pacman

Solve

Card Rotation

Solve

Interleave the First Half of the Queue with Second Half

Solve

Hard Level Problem on Queues:

Problem

Problem Link

LRU Cache

Solve

Longest subarray in which absolute difference between any two element is not greater than X

Solve

Shortest subarray with sum at least K (including negative numbers)

Solve


Next Article
Why do you do Competitive Programming (CP)?

M

mrityuanjay8vae
Improve
Article Tags :
  • Queue
  • Competitive Programming
  • DSA
  • Data Structures-Queue
Practice Tags :
  • Queue

Similar Reads

  • Stack for Competitive Programming
    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 explo
    7 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
  • 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
  • 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
  • Why do you do Competitive Programming (CP)?
    In the fast-moving world of technology, being good at coding is really important. Competitive Programming (CP) is a way to improve your coding skills. Competitive Programming is like a coding challenge where you solve tough problems against the clock. It's not just about writing code; it's about thi
    5 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
  • 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
  • 10 reasons not to quit Competitive Programming
    Competitive programming, a sport that combines problem-solving skills with coding expertise has experienced a surge, in popularity recently. As participants navigate through challenges and coding competitions, they acquire a set of skills that go beyond just programming. If you're considering giving
    5 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
  • Learning the art of Competitive Programming
    Learning the art of Competitive Programming How to begin with Competitive Programming?Top 10 Algorithms and Data Structures for Competitive ProgrammingHow to prepare for ACM – ICPC?How to prepare for Google Asia Pacific University (APAC) Test ?Remaining Ahead in Competitive Programming:Master in com
    2 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