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

Check if the elements of stack are pairwise sorted

Last Updated : 05 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Only following standard operations are allowed on the stack. 

  1. push(X): Enter a element X on top of stack.
  2. pop(): Removes top element of the stack.
  3. empty(): To check if stack is empty.

Examples: 

Input: 4, 5, 6, 7, 8, 9 Output: Yes  Input: 4, 9, 2, 1, 10, 8 Output: No

Approach: The idea is to use another stack.  

  • Create an auxiliary stack aux.
  • Transfer contents of given stack to aux.
  • Traverse aux. While traversing fetch top two elements and check if they are sorted or not.
  • After checking put these elements back to original stack.

Below is the implementation of above approach: 

C++




// C++ program to check if successive
// pair of numbers in the stack are
// sorted or not
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if elements are
// pairwise sorted in stack
bool pairWiseConsecutive(stack<int> s)
{
    // Transfer elements of s to aux.
    stack<int> aux;
    while (!s.empty()) {
        aux.push(s.top());
        s.pop();
    }
 
    // Traverse aux and see if
    // elements are pairwise
    // sorted or not. We also
    // need to make sure that original
    // content is retained.
    bool result = true;
    while (!aux.empty()) {
 
        // Fetch current top two
        // elements of aux and check
        // if they are sorted.
        int x = aux.top();
        aux.pop();
        int y = aux.top();
        aux.pop();
        if (x > y)
            result = false;
 
        // Push the elements to original
        // stack.
        s.push(x);
        s.push(y);
    }
 
    if (aux.size() == 1)
        s.push(aux.top());
 
    return result;
}
 
// Driver program
int main()
{
    stack<int> s;
    s.push(4);
    s.push(5);
    s.push(-3);
    s.push(-2);
    s.push(10);
    s.push(11);
    s.push(5);
    s.push(6);
    // s.push(20);
 
    if (pairWiseConsecutive(s))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
 
    cout << "Stack content (from top)"
            " after function call\n";
    while (s.empty() == false) {
        cout << s.top() << " ";
        s.pop();
    }
 
    return 0;
}
 
 

Java




// Java program to check if successive
// pair of numbers in the stack are
// sorted or not
import java.util.Stack;
 
class GFG {
 
// Function to check if elements are
// pairwise sorted in stack
    static boolean pairWiseConsecutive(Stack<Integer> s) {
        // Transfer elements of s to aux.
        Stack<Integer> aux = new Stack<>();
        while (!s.empty()) {
            aux.push(s.peek());
            s.pop();
        }
 
        // Traverse aux and see if
        // elements are pairwise
        // sorted or not. We also
        // need to make sure that original
        // content is retained.
        boolean result = true;
        while (!aux.empty()) {
 
            // Fetch current top two
            // elements of aux and check
            // if they are sorted.
            int x = aux.peek();
            aux.pop();
            int y = aux.peek();
            aux.pop();
            if (x > y) {
                result = false;
            }
 
            // Push the elements to original
            // stack.
            s.push(x);
            s.push(y);
        }
 
        if (aux.size() == 1) {
            s.push(aux.peek());
        }
 
        return result;
    }
 
// Driver program
    public static void main(String[] args) {
 
        Stack<Integer> s = new Stack<>();
        s.push(4);
        s.push(5);
        s.push(-3);
        s.push(-2);
        s.push(10);
        s.push(11);
        s.push(5);
        s.push(6);
        // s.push(20);
 
        if (pairWiseConsecutive(s)) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
 
        System.out.println("Stack content (from top)"
                + " after function call");
        while (s.empty() == false) {
            System.out.print(s.peek() + " ");
            s.pop();
        }
 
    }
 
}
 
 

Python 3




# Python program to check if successive
# pair of numbers in the stack are
# sorted or not
 
# using deque as stack
from collections import deque
 
# Function to check if elements are
# pairwise sorted in stack
def pairWiseConsecutive(s):
 
    # Transfer elements of s to aux.
    aux = deque()
    while len(s) > 0:
        aux.append(s.pop())
 
    # Traverse aux and see if
    # elements are pairwise
    # sorted or not. We also
    # need to make sure that original
    # content is retained.
    result = True
    while len(aux) != 0:
 
        # Fetch current top two
        # elements of aux and check
        # if they are sorted.
        x = aux.pop()
        y = aux.pop()
        if x > y:
            result = False
 
        # Push the elements to original
        # stack.
        s.append(x)
        s.append(y)
 
    if len(aux) == 1:
        s.append(aux.pop())
 
    return result
 
 
# Driver Code
if __name__ == "__main__":
    s = deque()
    s.append(4)
    s.append(5)
    s.append(-3)
    s.append(-2)
    s.append(10)
    s.append(11)
    s.append(5)
    s.append(6)
 
    if pairWiseConsecutive(s):
        print("Yes")
    else:
        print("No")
 
    print("Stack content (from top) after function call")
    while len(s) > 0:
        print(s.pop(), end=" ")
 
# This code is contributed by
# sanjeev2552
 
 

C#




// C# program to check if successive
// pair of numbers in the stack are
using System;
using System.Collections.Generic;
public class GFG{
 
// Function to check if elements are
// pairwise sorted in stack
    static bool pairWiseConsecutive(Stack<int> s) {
        // Transfer elements of s to aux.
        Stack<int> aux = new Stack<int>();
        while (!(s.Count==0)) {
            aux.Push(s.Peek());
            s.Pop();
        }
 
        // Traverse aux and see if
        // elements are pairwise
        // sorted or not. We also
        // need to make sure that original
        // content is retained.
        bool result = true;
        while (!(aux.Count==0)) {
 
            // Fetch current top two
            // elements of aux and check
            // if they are sorted.
            int x = aux.Peek();
            aux.Pop();
            int y = aux.Peek();
            aux.Pop();
            if (x > y) {
                result = false;
            }
 
            // Push the elements to original
            // stack.
            s.Push(x);
            s.Push(y);
        }
 
        if (aux.Count == 1) {
            s.Push(aux.Peek());
        }
 
        return result;
    }
 
// Driver program
    public static void Main() {
 
        Stack<int> s = new Stack<int>();
        s.Push(4);
        s.Push(5);
        s.Push(-3);
        s.Push(-2);
        s.Push(10);
        s.Push(11);
        s.Push(5);
        s.Push(6);
        // s.push(20);
 
        if (pairWiseConsecutive(s)) {
            Console.WriteLine("Yes");
        } else {
            Console.WriteLine("No");
        }
 
        Console.WriteLine("Stack content (from top)"
                + " after function call");
        while (!(s.Count == 0)) {
            Console.Write(s.Peek() + " ");
            s.Pop();
        }
 
    }
 
}
 
 

Javascript




<script>
  
// JavaScript program to check if successive
// pair of numbers in the stack are
// sorted or not
 
// Function to check if elements are
// pairwise sorted in stack
function pairWiseConsecutive(s)
{
    // Transfer elements of s to aux.
    var aux = [];
    while (s.length!=0) {
        aux.push(s[s.length-1]);
        s.pop();
    }
 
    // Traverse aux and see if
    // elements are pairwise
    // sorted or not. We also
    // need to make sure that original
    // content is retained.
    var result = true;
    while (aux.length!=0) {
 
        // Fetch current top two
        // elements of aux and check
        // if they are sorted.
        var x = aux[aux.length-1];
        aux.pop();
        var y = aux[aux.length-1];
        aux.pop();
        if (x > y)
            result = false;
 
        // Push the elements to original
        // stack.
        s.push(x);
        s.push(y);
    }
 
    if (aux.length == 1)
        s.push(aux[aux.length-1]);
 
    return result;
}
 
// Driver program
var s = [];
s.push(4);
s.push(5);
s.push(-3);
s.push(-2);
s.push(10);
s.push(11);
s.push(5);
s.push(6);
// s.push(20);
if (pairWiseConsecutive(s))
    document.write( "Yes" + "<br>");
else
    document.write( "No" + "<br>");
document.write( "Stack content (from top)"+
        " after function call<br>");
while (s.length!=0) {
    document.write( s[s.length-1] + " ");
    s.pop();
}
 
 
</script>
 
 
Output
Yes Stack content (from top) after function call 6 5 11 10 -2 -3 5 4 

Complexity Analysis:

  • Time Complexity: O(N)
  • Auxiliary Space: O(N) 


Next Article
Check if stack elements are pairwise consecutive

B

barykrg
Improve
Article Tags :
  • Data Structures
  • DSA
  • Stack
  • cpp-stack
  • Technical Scripter 2018
Practice Tags :
  • Data Structures
  • Stack

Similar Reads

  • 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
  • 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 elements of Linked List are present in pair
    Given a singly linked list of integers. The task is to check if each element in the linked list is present in a pair i.e. all elements occur even no. of times. Examples: Input: 1 -> 2 -> 3 -> 3 -> 1 -> 2Output: YesInput: 10 -> 20 -> 30 -> 20Output: No Method : Using MapWe wil
    5 min read
  • Check if Queue Elements are pairwise consecutive | Set-2
    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 o
    8 min read
  • Check if a given array is pairwise sorted or not
    An array is considered pairwise sorted if each successive pair of numbers is in sorted (non-decreasing) order. In case of odd elements, last element is ignored and result is based on remaining even number of elements. Examples: Input : arr[] = {10, 15, 9, 9, 1, 5}; Output : Yes Pairs are (10, 15), (
    5 min read
  • Check if the two given stacks are same
    Given two Stacks, the task is to check if the given stacks are same or not.Two stacks are said to be same if they contains the same elements in the same order.Example: Approach: Take a flag variable and set it to true initially, flag = true. This variable will indicate whether the stacks are same or
    6 min read
  • Check if an array of pairs can be sorted by swapping pairs with different first elements
    Given an array arr[] consisting of N pairs, where each pair represents the value and ID respectively, the task is to check if it is possible to sort the array by the first element by swapping only pairs having different IDs. If it is possible to sort, then print "Yes". Otherwise, print "No". Example
    11 min read
  • Check if a Linked List is Pairwise Sorted
    Given a linked list. The task is to check if the linked list is pairwise sorted or not. A Linked List is considered pairwise sorted if each successive pair of numbers is in sorted (non-decreasing) order. In the case of odd number of nodes, the last node is ignored and the result is based on the rema
    6 min read
  • Check if all array elements are present in a given stack or not
    Given a stack of integers S and an array of integers arr[], the task is to check if all the array elements are present in the stack or not. Examples: Input: S = {10, 20, 30, 40, 50}, arr[] = {20, 30}Output: YesExplanation:Elements 20 and 30 are present in the stack. Input: S = {50, 60}, arr[] = {60,
    5 min read
  • Check if an Array can be Sorted by picking only the corner Array elements
    Given an array arr[] consisting of N elements, the task is to check if the given array can be sorted by picking only corner elements i.e., elements either from left or right side of the array can be chosen. Examples: Input: arr[] = {2, 3, 4, 10, 4, 3, 1} Output: Yes Explanation: The order of picking
    5 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