Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • DSA
  • Interview Problems on Recursion
  • Practice Recursion
  • MCQs on Recursion
  • Recursion Tutorial
  • Recursive Function
  • Recursion vs Iteration
  • Types of Recursions
  • Tail Recursion
  • Josephus Problem
  • Tower of Hanoi
  • Check Palindrome
Open In App
Next Article:
Flood Fill Algorithm
Next article icon

Flood Fill Algorithm

Last Updated : 11 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

You are given a 2D grid image[][], where each image[i][j] represents the color of a pixel in the image. Also provided is a coordinate(sr, sc) representing the starting pixel (row and column) and a new color value newColor.

Your task is to perform a flood fill starting from the pixel (sr, sc), changing its color and the color of all connected pixels that have the same original color. Two pixels are considered connected if they are adjacent horizontally or vertically (not diagonally) and have the same original color.

Example: 

Input: image = [[1, 1, 1, 0], [0, 1, 1, 1], [1, 0, 1, 1]], sr = 1, sc = 2, newColor = 2

111

Output: [[2, 2, 2, 0], [0, 2, 2, 2], [1, 0, 2,2]]

222

Explanation: Starting from pixel (1, 2) with value 1, flood fill updates all connected pixels (up, down, left, right) with value 1 to 2, resulting in [[2, 2, 2, 0], [0, 2, 2, 2], [1, 0, 2, 2]].

Input: image = [[0, 1, 0], [0, 1, 0]], sr = 0, sc = 1, newColor = 0
Output: [[0, 0, 0], [0, 0, 0]]
Explanation: Starting from pixel (1, 2) with value 1, flood fill updates all connected pixels (up, down, left, right) with value 1 to 0, resulting in [[0, 0, 0], [0, 0, 0]].

[Approach 1] Using Depth-First Search - O(m * n) Time and O(m * n) Space

The idea is to use Depth-First Search (DFS) to explore and update all connected pixels that share the same original color (color of image[sr][sc]). Starting from the given pixel, DFS recursively checks its adjacent pixels in all four directions—up, down, left, and right. If an adjacent pixel matches the original color, it is updated to the new color, and the DFS continues from that pixel. If not, the algorithm backtracks. This process continues until all connected pixels of the same color are filled with the new color, effectively updating the entire connected component.

Step-by-Step Implementation :

  • Store the original color at the starting pixel (sr, sc) as this will help in identifying which connected pixels need to be changed..
  • Define a DFS function that takes the current pixel's row and column as parameters.
  • In the DFS function, if the current pixel is out of bounds or doesn't match the original color, return (backtrack); otherwise, update its color to newColor and continue the recursion.
  • Recursively call DFS for all four adjacent directions:
    • Up: (row - 1, col), Down: (row + 1, col), Left: (row, col - 1), Right: (row, col + 1)
  • Start DFS from the starting pixel (sr, sc).
  • Once DFS completes, return the updated image.
C++
#include <iostream> #include <vector> using namespace std;  // Helper function for Depth-First Search (DFS) void dfs(vector<vector<int>>& image, int x,           int y, int oldColor, int newColor) {          // Base case: check boundary conditions and color mismatch     if (x < 0 || x >= image.size() ||          y < 0 || y >= image[0].size() ||          image[x][y] != oldColor) {     // Backtrack if pixel is out of bounds or color doesn't match         return;      }      // Update the color of the current pixel     image[x][y] = newColor;      // Recursively visit all 4 connected neighbors     dfs(image, x + 1, y, oldColor, newColor);      dfs(image, x - 1, y, oldColor, newColor);      dfs(image, x, y + 1, oldColor, newColor);      dfs(image, x, y - 1, oldColor, newColor);  }  // Main flood fill function vector<vector<int>> floodFill(     vector<vector<int>>& image, int sr,      int sc, int newColor) {      // If the starting pixel already has the new color,     // no changes are needed     if (image[sr][sc] == newColor) {         return image;     }      // Call DFS to start filling from the source pixel     int oldColor = image[sr][sc]; // Store original color     dfs(image, sr, sc, oldColor, newColor);      return image; // Return the updated image }  // Driver code to test the flood fill function int main() {     // Input image (2D grid)     vector<vector<int>> image = {         {1, 1, 1, 0},         {0, 1, 1, 1},         {1, 0, 1, 1}     };          // Starting pixel (row, col)     int sr = 1, sc = 2;          // New color to apply     int newColor = 2;              // Perform flood fill and get the result     vector<vector<int>> result = floodFill(image, sr, sc, newColor);      // Print the updated image     for (auto& row : result) {         for (auto& pixel : row) {             cout << pixel << " ";         }         cout << "\n";     }     return 0; } 
Java
import java.util.*;  class GfG {      // Helper method for DFS traversal     static void dfs(int[][] image, int x, int y,                          int oldColor, int newColor){          // Base case: check for out-of-bound indices or mismatched color         if (x < 0 || x >= image.length ||              y < 0 || y >= image[0].length ||              image[x][y] != oldColor) {             return; // Backtrack if invalid         }          // Change the color of the current pixel         image[x][y] = newColor;          // Recursively call DFS in all four directions         dfs(image, x + 1, y, oldColor, newColor);          dfs(image, x - 1, y, oldColor, newColor);         dfs(image, x, y + 1, oldColor, newColor);          dfs(image, x, y - 1, oldColor, newColor);               }      // Main function to perform flood fill     static int[][] floodFill(int[][] image, int sr, int sc, int newColor){          // If the starting pixel already has the new color, no need          // to process         if (image[sr][sc] == newColor) {             return image;         }          // Call DFS with the original color of the starting pixel         dfs(image, sr, sc, image[sr][sc], newColor);          // Return the updated image         return image;     }      // Driver code to test the flood fill function     public static void main(String[] args) {          // Define the image matrix         int[][] image = {             {1, 1, 1, 0},             {0, 1, 1, 1},             {1, 0, 1, 1}         };          // Starting pixel and the new color         int sr = 1, sc = 2, newColor = 2;          // Perform flood fill         int[][] result = floodFill(image, sr, sc, newColor);          for (int[] row : result) {             for (int pixel : row) {                 System.out.print(pixel + " ");             }             System.out.println();         }     } } 
Python
def dfs(image, x, y, oldColor, newColor):        # Check boundary conditions and color match     if (x < 0 or x >= len(image) or y < 0 or          y >= len(image[0]) or image[x][y] != oldColor):         return      # Change the color     image[x][y] = newColor      # Visit all adjacent pixels     dfs(image, x + 1, y, oldColor, newColor)     dfs(image, x - 1, y, oldColor, newColor)     dfs(image, x, y + 1, oldColor, newColor)     dfs(image, x, y - 1, oldColor, newColor)  def floodFill(image, sr, sc, newColor):        # If the starting pixel already has the new color     if image[sr][sc] == newColor:         return image      # Call DFS with the starting pixel's original color     dfs(image, sr, sc, image[sr][sc], newColor)      return image  if __name__ == "__main__":        # Input initialization     image = [[1, 1, 1, 0],[0, 1, 1, 1],[1, 0, 1, 1]]     sr, sc, newColor = 1, 2, 2      # Perform flood fill     result = floodFill(image, sr, sc, newColor)      for row in result:         print(" ".join(map(str, row))) 
C#
// C# implementation of Flood Fill Algorithm using DFS using System;  class GfG {      // Helper method to perform DFS and fill connected pixels     static void dfs(int[,] image, int x, int y, int oldColor, int newColor){                  // Base case: check if pixel is out of bounds or not         // matching old color         if (x < 0 || x >= image.GetLength(0) ||              y < 0 || y >= image.GetLength(1) ||              image[x, y] != oldColor) {                              return;         }          // Update the current pixel's color         image[x, y] = newColor;          // Recursively call DFS in all 4 directions (up, down, left, right)         dfs(image, x + 1, y, oldColor, newColor);          dfs(image, x - 1, y, oldColor, newColor);          dfs(image, x, y + 1, oldColor, newColor);          dfs(image, x, y - 1, oldColor, newColor);      }      // Main function to trigger the flood fill     static int[,] floodFill(int[,] image, int sr, int sc, int newColor) {                  // If the pixel at (sr, sc) is already the new color, return as is         if (image[sr, sc] == newColor) {             return image;         }          // Call DFS from the starting pixel using its original color         dfs(image, sr, sc, image[sr, sc], newColor);          // Return the modified image         return image;     }      // Driver code     static void Main(string[] args) {                  // Example image (2D grid of pixels)         int[,] image = {             {1, 1, 1, 0},             {0, 1, 1, 1},             {1, 0, 1, 1}         };          // Starting coordinates (sr, sc) and new color to fill         int sr = 1, sc = 2, newColor = 2;          // Call flood fill algorithm         int[,] result = floodFill(image, sr, sc, newColor);          // Print the final filled image         for (int i = 0; i < result.GetLength(0); i++) {                          for (int j = 0; j < result.GetLength(1); j++) {                 Console.Write(result[i, j] + " ");             }                          // move to next line after each row             Console.WriteLine();          }     } } 
JavaScript
function dfs(image, x, y, oldColor, newColor) {      // Base case: Check if (x, y) is out of bounds OR pixel     //  is not of the old color     if ( x < 0 || x >= image.length ||           y < 0 || y >= image[0].length ||           image[x][y] !== oldColor) {         // Backtrack if invalid         return;      }      // Change the color of the current pixel to newColor     image[x][y] = newColor;      // Recursively call DFS in all four directions     dfs(image, x + 1, y, oldColor, newColor);      dfs(image, x - 1, y, oldColor, newColor);      dfs(image, x, y + 1, oldColor, newColor);      dfs(image, x, y - 1, oldColor, newColor);  }  // Main function to trigger flood fill using DFS function floodFill(image, sr, sc, newColor) {     // Edge case: If the starting pixel already has      //the new color, no need to fill     if (image[sr][sc] === newColor) {         return image;     }      // Get the original color of the starting pixel     const oldColor = image[sr][sc];      // Start DFS from the given pixel     dfs(image, sr, sc, oldColor, newColor);      // Return the updated image     return image; }   // Sample input image (2D grid of pixels) const image = [     [1, 1, 1, 0],     [0, 1, 1, 1],     [1, 0, 1, 1] ];  // Starting coordinates (sr, sc) and the color to fill with const sr = 1, sc = 2, newColor = 2;  // Perform flood fill const result = floodFill(image, sr, sc, newColor);  // Print the result result.forEach(row => {         // Print each row as a space-separated string         console.log(row.join(" "));  }); 

Output
2 2 2 0  0 2 2 2  1 0 2 2  

Time Complexity: O(m * n), where m and n are the dimensions of the image, as each pixel is visited once.
Space Complexity: O(m * n), due to the recursion stack in the worst case of all pixels being connected.

[Approach 2] Using Breadth-First Search - O(m * n) Time and O(m * n) Space

The idea is to use Breadth-First Search (BFS) to change all connected pixels with the original color (color of image[sr][sc]) to a new color (newColor). BFS uses a queue to explore all reachable pixels level by level (horizontally and vertically). For each pixel, it checks its adjacent pixels, and if they match the original color, it changes their color and adds them to the queue for further exploration. This process ensures that all connected pixels are filled with the new color.

The BFS approach would work better in general as it does not require overhead of recursion.

Step-by-Step Implementation :

  • Save the color of the starting pixel image[sr][sc] in a variable. This helps us identify which pixels need to be changed.
  • Use a queue (FIFO) to keep track of pixels that need to be processed. Start by adding the starting pixel (sr, sc) to the queue.
  • Start BFS traversl, While the queue is not empty, remove the front pixel, update its color to newColor, and check all four adjacent pixels, if they're within bounds and match the original color, add them to the queue for further processing.
  • Repeat until the queue is empty, Continue the above process until all connected pixels with the original color have been visited and updated.
  • After the BFS traversal, return the updated image with the filled region.
C++
#include <iostream> #include <vector> #include <queue> using namespace std;  vector<vector<int>> floodFill(     vector<vector<int>>& image, int sr,      int sc, int newColor) {      // If the starting pixel already has the new color     if (image[sr][sc] == newColor) {         return image;     }      // Direction vectors for traversing 4 directions     vector<pair<int, int>> directions = {         {1, 0}, {-1, 0}, {0, 1}, {0, -1}};          // Initialize the queue for BFS     queue<pair<int, int>> q;     int oldColor = image[sr][sc];     q.push({sr, sc});          // Change the color of the starting pixel     image[sr][sc] = newColor;      // Perform BFS     while (!q.empty()) {         pair<int, int> front = q.front();         int x = front.first, y = front.second;         q.pop();                  // Traverse all 4 directions         for (const pair<int, int>& direction : directions) {             int nx = x + direction.first;             int ny = y + direction.second;                          // Check boundary conditions and color match             if (nx >= 0 && nx < image.size() &&                  ny >= 0 && ny < image[0].size() &&                  image[nx][ny] == oldColor) {                                  // Change the color and enqueue                 image[nx][ny] = newColor;                 q.push({nx, ny});             }         }     }      return image; }  int main() {          // Define the input 2D image (grid of pixel colors)     vector<vector<int>> image = {         {1, 1, 1, 0},         {0, 1, 1, 1},         {1, 0, 1, 1}     };      // Starting pixel coordinates (row = 1, column = 2)     int sr = 1, sc = 2;      // New color to apply to the connected region     int newColor = 2;      // Call the floodFill function to perform DFS/BFS fill from the     // starting pixel     vector<vector<int>> result = floodFill(image, sr, sc, newColor);      // Print the updated image after flood fill     for (auto& row : result) {         for (auto& pixel : row) {                          // Print each pixel with a space             cout << pixel << " ";           }                  // Move to the next line after printing each row         cout << "\n";       }          return 0;  } 
Java
// Java implementation of Flood Fill Algorithm // using BFS import java.util.*;  class GfG {      // Directions for traversing in 4-neighbor cells     private static final int[][] directions = {         {1, 0}, {-1, 0}, {0, 1}, {0, -1}     };      public static int[][] floodFill(int[][] image,                                     int sr, int sc,                                      int newColor) {          // If the starting pixel already has the new color         if (image[sr][sc] == newColor) {             return image;         }          int oldColor = image[sr][sc];         Queue<int[]> q = new LinkedList<>();         q.offer(new int[]{sr, sc});          // Change the color of the starting pixel         image[sr][sc] = newColor;          while (!q.isEmpty()) {             int[] front = q.poll();             int x = front[0], y = front[1];              for (int[] direction : directions) {                 int nx = x + direction[0];                 int ny = y + direction[1];                  // Check boundary conditions and color match                 if (nx >= 0 && nx < image.length &&                      ny >= 0 && ny < image[0].length &&                      image[nx][ny] == oldColor) {                      // Change the color and enqueue                     image[nx][ny] = newColor;                     q.offer(new int[]{nx, ny});                 }             }         }          return image;     }      public static void main(String[] args) {      // Define the input 2D image as a matrix where      // each element represents a pixel's color     int[][] image = {         {1, 1, 1, 0},         {0, 1, 1, 1},         {1, 0, 1, 1}     };      // sr: starting row index, sc: starting column      // index for the flood fill     int sr = 1, sc = 2;      // newColor: the color that we want to fill the      // connected component with     int newColor = 2;      // Call the floodFill function to apply the      // newColor starting from (sr, sc)     int[][] result = floodFill(image, sr, sc, newColor);      // Print the updated image after flood fill     for (int[] row : result) {                  for (int pixel : row) {                    System.out.print(pixel + " ");           }         // Move to the next line after each row         System.out.println();             }      }  } 
Python
from collections import deque   # Function to perform flood fill using BFS def floodFill(image, sr, sc, newColor):     rows, cols = len(image), len(image[0])           # Store the color at the starting pixel     oldColor = image[sr][sc]            # Return the image if the starting pixel      # already has the new color     if oldColor == newColor:         return image        # Create a queue to manage the BFS traversal     q = deque([(sr, sc)])            # Directions to explore: down, up, right, left     directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]        # Change the color of the starting pixel     image[sr][sc] = newColor            # BFS traversal     while q:           x, y = q.popleft()                    # Explore all four possible directions         for dx, dy in directions:             nx, ny = x + dx, y + dy              # Check if new coordinates are within bounds              # and have the old color             if 0 <= nx < rows and 0 <= ny < cols \                          and image[nx][ny] == oldColor:                                # Change the color and add the pixel to                  # queue for further exploration                 image[nx][ny] = newColor                 q.append((nx, ny))      return image        if __name__ == "__main__":      # Input 2D image represented as a grid of pixels      # (each with an integer color)     image = [         [1, 1, 1, 0],         [0, 1, 1, 1],         [1, 0, 1, 1]     ]      # Starting pixel coordinates (sr, sc) and the new color to apply     sr, sc, newColor = 1, 2, 2       # Perform the flood fill operation     result = floodFill(image, sr, sc, newColor)      # Print the updated image row by row     for row in result:           # Convert each row's integers to strings and join them with spaces         print(" ".join(map(str, row))) 
C#
using System; using System.Collections.Generic;  class GfG {      // BFS-based Flood Fill implementation     static int[,] floodFill(int[,] image,                                     int sr, int sc,                                     int newColor) {                  // Get the original color of the starting pixel         int oldColor = image[sr, sc];                  // If the starting pixel already has the new          // color, return the image         if (oldColor == newColor) {             return image;         }          // Dimensions of the image         int rows = image.GetLength(0);         int cols = image.GetLength(1);          // Queue for BFS         Queue<(int, int)> q = new Queue<(int, int)>();          // Add the starting pixel to the queue         q.Enqueue((sr, sc));          // Change the starting pixel color         image[sr, sc] = newColor;          // Direction vectors for adjacent pixels         int[] dx = { -1, 1, 0, 0 };         int[] dy = { 0, 0, -1, 1 };          // BFS loop         while (q.Count > 0) {             (int x, int y) = q.Dequeue();              // Traverse all 4 directions             for (int i = 0; i < 4; i++) {                 int nx = x + dx[i];                 int ny = y + dy[i];                  // Check boundary conditions and color match                 if (nx >= 0 && nx < rows && ny >= 0                              && ny < cols                             && image[nx, ny] == oldColor) {                                        // Change the color                     image[nx, ny] = newColor;                      // Add the pixel to the queue                     q.Enqueue((nx, ny));                 }             }         }          return image;     }      static void Main(string[] args) {      // Define a 2D array (matrix) representing the image where      // each element is a pixel color     int[,] image = {         {1, 1, 1, 0},         {0, 1, 1, 1},         {1, 0, 1, 1}     };      // sr: starting row, sc: starting column, newColor: the color to apply     int sr = 1, sc = 2, newColor = 2;      // Call the floodFill function to apply the new color to      // connected pixels     int[,] result = floodFill(image, sr, sc, newColor);      // Print the updated image     for (int i = 0; i < result.GetLength(0); i++) {                     for (int j = 0; j < result.GetLength(1); j++) {                     Console.Write(result[i, j] + " ");                          }         Console.WriteLine();                                       } }  } 
JavaScript
function floodFill(image, sr, sc, newColor) {     const oldColor = image[sr][sc];          // If the starting pixel already has the new color, return     if (oldColor === newColor) {         return image;     }      // Dimensions of the image     const rows = image.length;     const cols = image[0].length;      // Queue for BFS     const q = [[sr, sc]];      // Change the starting pixel's color     image[sr][sc] = newColor;      // Direction vectors for 4 adjacent directions     const directions = [ [1, 0], [-1, 0], [0, 1], [0, -1] ];      // BFS loop     while (q.length > 0) {         const [x, y] = q.shift();          for (const [dx, dy] of directions) {             const nx = x + dx;             const ny = y + dy;              // Check boundary conditions and color match             if (                 nx >= 0 && nx < rows &&                  ny >= 0 && ny < cols &&                  image[nx][ny] === oldColor             ) {                 // Change color and add to queue                 image[nx][ny] = newColor;                 q.push([nx, ny]);             }         }     }      return image; }  // Define a 2D array (image) where each element represents a pixel's color const image = [     [1, 1, 1, 0],     [0, 1, 1, 1],     [1, 0, 1, 1] ];  // sr: starting row, sc: starting column, newColor: the color to fill const sr = 1, sc = 2, newColor = 2;  // Call the floodFill function to update the image with the new color const result = floodFill(image, sr, sc, newColor);  // Print the updated image row by row result.forEach(row => {     // Join each row's elements with a space and print the row     console.log(row.join(" ")); }); 

Output
2 2 2 0  0 2 2 2  1 0 2 2  

Time Complexity: O(m * n),as all pixels are visited once in bfs.
Space Complexity: O(m * n), because the queue can hold all pixels in the worst-case scenario.


Next Article
Flood Fill Algorithm

A

Archana choudhary
Improve
Article Tags :
  • Graph
  • Algorithms
  • Matrix
  • Recursion
  • DSA
  • Google
  • BFS
  • DFS
Practice Tags :
  • Google
  • Algorithms
  • BFS
  • DFS
  • Graph
  • Matrix
  • Recursion

Similar Reads

    Queue Data Structure
    A Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
    2 min read
    Introduction to Queue Data Structure
    Queue is a linear data structure that follows FIFO (First In First Out) Principle, so the first element inserted is the first to be popped out. FIFO Principle in Queue:FIFO Principle states that the first element added to the Queue will be the first one to be removed or processed. So, Queue is like
    5 min read
    Introduction and Array Implementation of Queue
    Similar to Stack, Queue is a linear data structure that follows a particular order in which the operations are performed for storing data. The order is First In First Out (FIFO). One can imagine a queue as a line of people waiting to receive something in sequential order which starts from the beginn
    2 min read
    Queue - Linked List Implementation
    In this article, the Linked List implementation of the queue data structure is discussed and implemented. Print '-1' if the queue is empty.Approach: To solve the problem follow the below idea:we maintain two pointers, front and rear. The front points to the first item of the queue and rear points to
    8 min read
    Applications, Advantages and Disadvantages of Queue
    A Queue is a linear data structure. This data structure follows a particular order in which the operations are performed. The order is First In First Out (FIFO). It means that the element that is inserted first in the queue will come out first and the element that is inserted last will come out last
    5 min read
    Different Types of Queues and its Applications
    Introduction : A Queue is a linear structure that follows a particular order in which the operations are performed. The order is First In First Out (FIFO). A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first. In this article, the diff
    8 min read

    Queue implementation in different languages

    Queue in C++ STL
    In C++, queue container follows the FIFO (First In First Out) order of insertion and deletion. According to it, the elements that are inserted first should be removed first. This is possible by inserting elements at one end (called back) and deleting them from the other end (called front) of the dat
    4 min read
    Queue Interface In Java
    The Queue Interface is a part of java.util package and extends the Collection interface. It stores and processes the data in order means elements are inserted at the end and removed from the front. Key Features:Most implementations, like PriorityQueue, do not allow null elements.Implementation Class
    12 min read
    Queue in Python
    Like a stack, the queue is a linear data structure that stores items in a First In First Out (FIFO) manner. With a queue, the least recently added item is removed first. A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first. Operations
    6 min read
    C# Queue with Examples
    A Queue in C# is a collection that follows the First-In-First-Out (FIFO) principle which means elements are processed in the same order they are added. It is a part of the System.Collections namespace for non-generic queues and System.Collections.Generic namespace for generic queues.Key Features:FIF
    6 min read
    Implementation of Queue in Javascript
    A Queue is a linear data structure that follows the FIFO (First In, First Out) principle. Elements are inserted at the rear and removed from the front.Queue Operationsenqueue(item) - Adds an element to the end of the queue.dequeue() - Removes and returns the first element from the queue.peek() - Ret
    7 min read
    Queue in Go Language
    A queue is a linear structure that follows a particular order in which the operations are performed. The order is First In First Out (FIFO). Now if you are familiar with other programming languages like C++, Java, and Python then there are inbuilt queue libraries that can be used for the implementat
    4 min read
    Queue in Scala
    A queue is a first-in, first-out (FIFO) data structure. Scala offers both an immutable queue and a mutable queue. A mutable queue can be updated or extended in place. It means one can change, add, or remove elements of a queue as a side effect. Immutable queue, by contrast, never change. In Scala, Q
    3 min read

    Some question related to Queue implementation

    Implementation of Deque using doubly linked list
    A Deque (Double-Ended Queue) is a data structure that allows adding and removing elements from both the front and rear ends. Using a doubly linked list to implement a deque makes these operations very efficient, as each node in the list has pointers to both the previous and next nodes. This means we
    9 min read
    Queue using Stacks
    Given a stack that supports push and pop operations, your task is to implement a queue using one or more instances of that stack along with its operations.Table of ContentBy Making Enqueue Operation CostlyBy Making Dequeue Operation Costly Queue Implementation Using One Stack and RecursionBy Making
    11 min read
    implement k Queues in a single array
    Given an array of size n, the task is to implement k queues using the array.enqueue(qn, x) : Adds the element x into the queue number qn dequeue(qn, x) : Removes the front element from queue number qn isFull(qn) : Checks if the queue number qn is fullisEmpty(qn) : Checks if the queue number qn is em
    15+ min read
    LRU Cache - Complete Tutorial
    What is LRU Cache? Cache replacement algorithms are efficiently designed to replace the cache when the space is full. The Least Recently Used (LRU) is one of those algorithms. As the name suggests when the cache memory is full, LRU picks the data that is least recently used and removes it in order t
    8 min read

    Easy problems on Queue

    Detect cycle in an undirected graph using BFS
    Given an undirected graph, the task is to determine if cycle is present in it or not.Examples:Input: V = 5, edges[][] = [[0, 1], [0, 2], [0, 3], [1, 2], [3, 4]]Undirected Graph with 5 NodeOutput: trueExplanation: The diagram clearly shows a cycle 0 → 2 → 1 → 0.Input: V = 4, edges[][] = [[0, 1], [1,
    6 min read
    Breadth First Search or BFS for a Graph
    Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
    15+ min read
    Traversing directory in Java using BFS
    Given a directory, print all files and folders present in directory tree rooted with given directory. We can iteratively traverse directory in BFS using below steps. We create an empty queue and we first enqueue given directory path. We run a loop while queue is not empty. We dequeue an item from qu
    2 min read
    Vertical Traversal of a Binary Tree
    Given a Binary Tree, the task is to find its vertical traversal starting from the leftmost level to the rightmost level. If multiple nodes pass through a vertical line, they should be printed as they appear in the level order traversal of the tree.Examples: Input:Output: [[4], [2], [1, 5, 6], [3, 8]
    10 min read
    Print Right View of a Binary Tree
    Given a Binary Tree, the task is to print the Right view of it. The right view of a Binary Tree is a set of rightmost nodes for every level.Examples: Example 1: The Green colored nodes (1, 3, 5) represents the Right view in the below Binary tree. Example 2: The Green colored nodes (1, 3, 4, 5) repre
    15+ min read
    Find Minimum Depth of a Binary Tree
    Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. For example, minimum depth of below Binary Tree is 2. Note that the path must end on a leaf node. For example, the minimum depth of below Bi
    15 min read
    Check whether a given graph is Bipartite or not
    Given a graph with V vertices numbered from 0 to V-1 and a list of edges, determine whether the graph is bipartite or not.Note: A bipartite graph is a type of graph where the set of vertices can be divided into two disjoint sets, say U and V, such that every edge connects a vertex in U to a vertex i
    8 min read

    Intermediate problems on Queue

    Flatten a multilevel linked list using level order traversal
    Given a linked list where in addition to the next pointer, each node has a child pointer, which may or may not point to a separate list. These child lists may have one or more children of their own to produce a multilevel linked list. Given the head of the first level of the list. The task is to fla
    9 min read
    Level with maximum number of nodes
    Given a binary tree, the task is to find the level in a binary tree that has the maximum number of nodes. Note: The root is at level 0.Examples: Input: Binary Tree Output : 2Explanation: Input: Binary tree Output:1Explanation Using Breadth First Search - O(n) time and O(n) spaceThe idea is to traver
    12 min read
    Find if there is a path between two vertices in a directed graph
    Given a Directed Graph and two vertices src and dest, check whether there is a path from src to dest.Example: Consider the following Graph: adj[][] = [ [], [0, 2], [0, 3], [], [2] ]Input : src = 1, dest = 3Output: YesExplanation: There is a path from 1 to 3, 1 -> 2 -> 3Input : src = 0, dest =
    11 min read
    All nodes between two given levels in Binary Tree
    Given a binary tree, the task is to print all nodes between two given levels in a binary tree. Print the nodes level-wise, i.e., the nodes for any level should be printed from left to right. Note: The levels are 1-indexed, i.e., root node is at level 1.Example: Input: Binary tree, l = 2, h = 3Output
    8 min read
    Find next right node of a given key
    Given a Binary tree and a key in the binary tree, find the node right to the given key. If there is no node on right side, then return NULL. Expected time complexity is O(n) where n is the number of nodes in the given binary tree.Example:Input: root = [10 2 6 8 4 N 5] and key = 2Output: 6Explanation
    15+ min read
    Minimum steps to reach target by a Knight | Set 1
    Given a square chessboard of n x n size, the position of the Knight and the position of a target are given. We need to find out the minimum steps a Knight will take to reach the target position.Examples: Input: KnightknightPosition: (1, 3) , targetPosition: (5, 0)Output: 3Explanation: In above diagr
    9 min read
    Islands in a graph using BFS
    Given an n x m grid of 'W' (Water) and 'L' (Land), the task is to count the number of islands. An island is a group of adjacent 'L' cells connected horizontally, vertically, or diagonally, and it is surrounded by water or the grid boundary. The goal is to determine how many distinct islands exist in
    15+ min read
    Level order traversal line by line (Using One Queue)
    Given a Binary Tree, the task is to print the nodes level-wise, each level on a new line.Example:Input:Output:12 34 5Table of Content[Expected Approach – 1] Using Queue with delimiter – O(n) Time and O(n) Space[Expected Approach – 2] Using Queue without delimiter – O(n) Time and O(n) Space[Expected
    12 min read
    First non-repeating character in a stream
    Given an input stream s consisting solely of lowercase letters, you are required to identify which character has appeared only once in the stream up to each point. If there are multiple characters that have appeared only once, return the one that first appeared. If no character has appeared only onc
    15+ 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