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:
Check if Queue Elements are pairwise consecutive
Next article icon

Check if Queue Elements are pairwise consecutive | Set-2

Last Updated : 27 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Queue of integers. The task is to check if consecutive elements in the queue are pairwise consecutive.

Examples: 

Input: 1 2 5 6 9 10 Output: Yes  Input: 2 3 9 11 8 7 Output: No

Approach : 

  • Take a variable n to store size of queue.
  • Push an element to the queue which acts as marker.
  • Now, If size of queue is odd, start popping a pair while n > 2. Also, while popping these pairs, check for their difference and decrease n by 2, if there difference is not equal to 1, set flag to false.
  • If size of queue is even, start popping a pair while n > 1. Also, while popping these pairs, check for their difference and decrease n by 2, if their difference is not equal to 1, set flag to false.
  • Finally, check flag, if it is true, it means elements in the queue are pairwise sorted, else not.

Below is the implementation of above approach: 

C++




// C++ program to check if successive
// pair of numbers in the queue are
// consecutive or not
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if elements are
// pairwise consecutive in queue
bool pairWiseConsecutive(queue<int> q)
{
    // Fetching size of queue
    int n = q.size();
 
    // Pushing extra element to the queue
    // which acts as marker
    q.push(INT_MIN);
 
    // Result flag
    bool result = true;
 
    // If number of elements in the
    // queue is odd pop elements while
    // its size is greater than 2.
    // Else, pop elements while its
    // size is greater than 1
    if (n % 2 != 0) {
 
        while (n > 2) {
            int x = q.front();
            q.pop();
            q.push(x);
            n--;
 
            int y = q.front();
            q.pop();
            q.push(y);
            n--;
 
            if (abs(x - y) != 1) {
                result = false;
            }
        }
 
        // Popping the last element of queue
        // and pushing it again.
        // Also, popping the extra element
        // that we have pushed as marker
        q.push(q.front());
        q.pop();
        q.pop();
    }
 
    else {
        while (n > 1) {
            int x = q.front();
            q.pop();
            q.push(x);
            n--;
 
            int y = q.front();
            q.pop();
            q.push(y);
            n--;
 
            if (abs(x - y) != 1) {
                result = false;
            }
        }
 
        // popping the extra element that
        // we have pushed as marker
        q.pop();
    }
 
    return result;
}
 
// Driver program
int main()
{
    // Pushing elements into the queue
    queue<int> q;
    q.push(4);
    q.push(5);
    q.push(-2);
    q.push(-3);
    q.push(11);
    q.push(10);
    q.push(5);
    q.push(6);
    q.push(8);
 
    if (pairWiseConsecutive(q))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
 
    return 0;
}
 
 

Java




import java.util.LinkedList;
import java.util.Queue;
 
// Java program to check if successive
// pair of numbers in the queue are
// consecutive or not
public class GFG {
 
// Function to check if elements are
// pairwise consecutive in queue
    static boolean pairWiseConsecutive(Queue<Integer> q) {
        // Fetching size of queue
        int n = q.size();
 
        // Pushing extra element to the queue
        // which acts as marker
        q.add(Integer.MAX_VALUE);
 
        // Result flag
        boolean result = true;
 
        // If number of elements in the
        // queue is odd pop elements while
        // its size is greater than 2.
        // Else, pop elements while its
        // size is greater than 1
        if (n % 2 != 0) {
 
            while (n > 2) {
                int x = q.peek();
                q.remove();
                q.add(x);
                n--;
 
                int y = q.peek();
                q.remove();
                q.add(y);
                n--;
 
                if (Math.abs(x - y) != 1) {
                    result = false;
                }
            }
 
            // Popping the last element of queue
            // and pushing it again.
            // Also, popping the extra element
            // that we have pushed as marker
            q.add(q.peek());
            q.remove();
            q.remove();
        } else {
            while (n > 1) {
                int x = q.peek();
                q.remove();
                q.add(x);
                n--;
 
                int y = q.peek();
                q.remove();
                q.add(y);
                n--;
 
                if (Math.abs(x - y) != 1) {
                    result = false;
                }
            }
 
            // popping the extra element that
            // we have pushed as marker
            q.remove();
        }
 
        return result;
    }
 
// Driver program
    static public void main(String[] args) {
        // Pushing elements into the queue
        Queue<Integer> q = new LinkedList<>();
        q.add(4);
        q.add(5);
        q.add(-2);
        q.add(-3);
        q.add(11);
        q.add(10);
        q.add(5);
        q.add(6);
        q.add(8);
 
        if (pairWiseConsecutive(q)) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
 
    }
}
// This code is contributed by Rajput-Ji
 
 

Python3




# Python3 program to check if successive
# pair of numbers in the queue are
# consecutive or not
import sys, queue
 
# Function to check if elements are
# pairwise consecutive in queue
def pairWiseConsecutive(q):
     
    # Fetching size of queue
    n = q.qsize()
 
    # Pushing extra element to the
    # queue which acts as marker
    q.put(-sys.maxsize);
 
    # Result flag
    result = bool(True)
 
    # If number of elements in the
    # queue is odd pop elements while
    # its size is greater than 2.
    # Else, pop elements while its
    # size is greater than 1
    if (n % 2 != 0):
        while (n > 2):
            x = q.queue[0]
            q.get()
            q.put(x)
            n -= 1
 
            y = q.queue[0]
            q.get()
            q.put(y)
            n -= 1
 
            if (abs(x - y) != 1):
                result = bool(False)
 
        # Popping the last element of queue
        # and pushing it again.
        # Also, popping the extra element
        # that we have pushed as marker
        q.put(q.queue[0])
        q.get()
        q.get()
         
    else:
        while (n > 1):
            x = q.queue[0]
            q.get()
            q.put(x)
            n -= 1
 
            y = q.queue[0] 
            q.get()
            q.put(y)
            n -= 1
 
            if (abs(x - y) != 1):
                result = bool(False)
     
        # popping the extra element that
        # we have pushed as marker
        q.get()
 
    return result
 
# Driver code
 
# Pushing elements into the queue
q = queue.Queue()
q.put(4)
q.put(5)
q.put(-2)
q.put(-3)
q.put(11)
q.put(10)
q.put(5)
q.put(6)
q.put(8)
 
if (bool(pairWiseConsecutive(q))):
    print("Yes")
else:
    print("No")
 
# This code is contributed by divyeshrabadiya07
 
 

C#




// C# program to check if successive
// pair of numbers in the queue are
// consecutive or not
using System;
using System.Collections.Generic;
 
class GFG
{
 
    // Function to check if elements are
    // pairwise consecutive in queue
    static Boolean pairWiseConsecutive(Queue<int> q)
    {
        // Fetching size of queue
        int n = q.Count;
 
        // Pushing extra element to the queue
        // which acts as marker
        q.Enqueue(int.MaxValue);
 
        // Result flag
        Boolean result = true;
 
        // If number of elements in the
        // queue is odd pop elements while
        // its size is greater than 2.
        // Else, pop elements while its
        // size is greater than 1
        if (n % 2 != 0)
        {
            while (n > 2)
            {
                int x = q.Peek();
                q.Dequeue();
                q.Enqueue(x);
                n--;
 
                int y = q.Peek();
                q.Dequeue();
                q.Enqueue(y);
                n--;
 
                if (Math.Abs(x - y) != 1)
                {
                    result = false;
                }
            }
 
            // Popping the last element of queue
            // and pushing it again.
            // Also, popping the extra element
            // that we have pushed as marker
            q.Enqueue(q.Peek());
            q.Dequeue();
            q.Dequeue();
        } else
        {
            while (n > 1)
            {
                int x = q.Peek();
                q.Dequeue();
                q.Enqueue(x);
                n--;
 
                int y = q.Peek();
                q.Dequeue();
                q.Enqueue(y);
                n--;
 
                if (Math.Abs(x - y) != 1)
                {
                    result = false;
                }
            }
 
            // popping the extra element that
            // we have pushed as marker
            q.Dequeue();
        }
 
        return result;
    }
 
    // Driver Code
    static public void Main(String[] args)
    {
        // Pushing elements into the queue
        Queue<int> q = new Queue<int>();
        q.Enqueue(4);
        q.Enqueue(5);
        q.Enqueue(-2);
        q.Enqueue(-3);
        q.Enqueue(11);
        q.Enqueue(10);
        q.Enqueue(5);
        q.Enqueue(6);
        q.Enqueue(8);
 
        if (pairWiseConsecutive(q))
        {
            Console.WriteLine("Yes");
        }
        else
        {
            Console.WriteLine("No");
        }
    }
}
 
// This code is contributed by Rajput-Ji
 
 

Javascript




// Javascript program to check if successive
// pair of numbers in the queue are
// consecutive or not
 
 
// Function to check if elements are
// pairwise consecutive in queue
function pairWiseConsecutive(q) {
    // Fetching size of queue
    let n = q.length;
 
    // Pushing extra element to the queue
    // which acts as marker
    q.push(Number.MIN_VALUE);
 
    // Result flag
    let result = true;
 
    // If number of elements in the
    // queue is odd pop elements while
    // its size is greater than 2.
    // Else, pop elements while its
    // size is greater than 1
    if (n % 2 != 0) {
 
        while (n > 2) {
            let x = q[0];
            q.shift();
            q.push(x);
            n--;
 
            let y = q[0];
            q.shift();
            q.push(y);
            n--;
 
            if (Math.abs(x - y) != 1) {
                result = false;
            }
        }
 
        // Popping the last element of queue
        // and pushing it again.
        // Also, popping the extra element
        // that we have pushed as marker
        q.push(q[0]);
        q.shift();
        q.shift();
    }
 
    else {
        while (n > 1) {
            let x = q[0];
            q.shift();
            q.push(x);
            n--;
 
            let y = q[0];
            q.shift();
            q.push(y);
            n--;
 
            if (Math.abs(x - y) != 1) {
                result = false;
            }
        }
 
        // popping the extra element that
        // we have pushed as marker
        q.shift();
    }
 
    return result;
}
 
// Driver program
// Pushing elements into the queue
let q = [];
q.push(4);
q.push(5);
q.push(-2);
q.push(-3);
q.push(11);
q.push(10);
q.push(5);
q.push(6);
q.push(8);
 
if (pairWiseConsecutive(q))
    console.log("Yes");
else
    console.log("No");
     
// This code is contributed by adityamaharshi21
 
 
Output
Yes

Complexity Analysis:

  • Time Complexity: O(n) 
  • Auxiliary Space: O(1)


Next Article
Check if Queue Elements are pairwise consecutive

B

barykrg
Improve
Article Tags :
  • Data Structures
  • DSA
  • Queue
  • cpp-queue
  • Sorting Quiz
Practice Tags :
  • Data Structures
  • Queue

Similar Reads

  • Check if Queue Elements are pairwise consecutive
    Given a Queue of integers. The task is to check if consecutive elements in the queue are pairwise consecutive. Examples: Input : 1 2 5 6 9 10 Output : Yes Input : 2 3 9 11 8 7 Output : No Approach: Using two stacks : Transfer all elements of the queue to one auxiliary stack aux.Now, transfer the ele
    7 min read
  • Check if stack elements are pairwise consecutive
    Given a stack of integers, write a function pairWiseConsecutive() that checks whether numbers in the stack are pairwise consecutive or not. The pairs can be increasing or decreasing, and if the stack has an odd number of elements, the element at the top is left out of a pair. The function should ret
    10 min read
  • Query to check if a range is made up of consecutive elements
    Given an array of n non-consecutive integers and Q queries, the task is to check whether for the given range l and r, the elements are consecutive or not.Examples: Input: arr = { 2, 4, 3, 7, 6, 1}, Q = { (1, 3), (3, 5), (5, 6) } Output: Yes, No, No Explanation: Array elements from (1, 3) = {2, 4, 3}
    15+ min read
  • Check if array elements are consecutive
    Given an unsorted array of numbers, the task is to check if the array consists of consecutive numbers. Examples: Input: arr[] = [5, 2, 3, 1, 4]Output: YesExplanation: Array has consecutive numbers from 1 to 5. Input: arr[] = [83, 78, 80, 81, 79, 82]Output: YesExplanation: Array has consecutive numbe
    15+ min read
  • Check if an array can be split into subsets of K consecutive elements
    Given an array arr[] and integer K, the task is to split the array into subsets of size K, such that each subset consists of K consecutive elements. Examples: Input: arr[] = {1, 2, 3, 6, 2, 3, 4, 7, 8}, K = 3 Output: true Explanation: The given array of length 9 can be split into 3 subsets {1, 2, 3}
    5 min read
  • Check if the elements of stack are pairwise sorted
    Given a stack of integers, write a function pairWiseSorted() that checks whether numbers in the stack are pairwise sorted or not. The pairs must be increasing, and if the stack has an odd number of elements, the element at the top is left out of a pair. The function should retain the original stack
    6 min read
  • Count consecutive pairs of same elements
    Given an array arr[], the task is to count the number of pairs formed by consecutive elements in which both of the elements in a pair are same.Examples: Input: arr[] = {1, 2, 2, 3, 4, 4, 5, 5, 5, 5} Output: 5 (1, 2), (4, 5), (6, 7), (7, 8) and (8, 9) are the valid index pairs where consecutive eleme
    4 min read
  • Check if K Consecutive even numbers present or not
    Given an array, arr[] of integers and an integer K, the task is to print true if there are K consecutive even numbers present else return false. Input: arr[] = {1, 2, 4, 6, 7, 8}, K = 3Output: trueExplanation: There are K = 3 consecutive even elements (2, 4, 6) present in the array. Input: arr[] = {
    10 min read
  • Find missing element in a sorted array of consecutive numbers
    Given an array arr[] of n distinct integers. Elements are placed sequentially in ascending order with one element missing. The task is to find the missing element.Examples: Input: arr[] = {1, 2, 4, 5, 6, 7, 8, 9} Output: 3Input: arr[] = {-4, -3, -1, 0, 1, 2} Output: -2Input: arr[] = {1, 2, 3, 4} Out
    7 min read
  • Checking for Consecutive K-Length Subsequence
    Given an array arr[] of size N, the elements are non-decreasing order, the task is to determine if it's possible to form one or more subsequences such that elements in each subsequence are a consecutive increasing sequence of K length at least. Examples: Input: arr = {1, 2, 3, 3, 4, 4, 5, 5}, K = 3O
    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