Table of contents
1.
Introduction
2.
Problem Statement
2.1.
Example
3.
Algorithm
4.
Implementation in C++
5.
Implementation in Java
6.
Complexity Analysis
7.
Frequently Asked Questions
7.1.
What is Stack?
7.2.
What is the difference between Queue and Stack?
7.3.
What are the different operations that a Stack class provides?
7.4.
What are the disadvantages of a Stack?
7.5.
What are the different applications of Stack?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Check if stack elements are pairwise consecutive

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

We know Stack is the linear data structure that follows the LIFO (Last In First Out) principle, which means that the elements that come last will be accessed first. It is an essential data structure as most questions like Next Greater Element, Largest Rectangular Area In A Histogram, Stock Span Problem, etc., are solved using a stack.

In this article, we will discuss a famous interview problem: "Check if stack elements are pairwise consecutive." This problem requires basic knowledge of stacks with their implementation.

If you don't know about the implementation of Stack, don't worry; we have the most straightforward implementation of the problem: “Check if stack elements are pairwise consecutive.”


So, let's begin with the problem statement.

Problem Statement

The problem statement of “check if stack elements are pairwise consecutive” is that we have given a stack with an integer value. We have to check whether the Stack elements are pairwise consecutive or not? If the Stack contains consecutive pairwise elements, return true or print "Yes" and print the Stack from the top; otherwise, return false or print "No."

Also, If the Stack contains even elements, check all the pairs, and if the Stack contains odd elements, leave the Stack's top element. 

Example

Let's see some examples of the problem: “Check if stack elements are pairwise consecutive” to understand it better.

Input:

6,5,4,3,9,10

 

Output:

Yes

 

Check if stack elements are pairwise consecutive

Here the Stack contains even elements, and (6,5), (4,3), (9,10) all are consecutive. So, the output will be Yes.
 

Input:

5,4,-2,-3,8

 

Output:

Yes

 

Check if stack elements are pairwise consecutive

Here the Stack contains odd elements, so we leave 8 as it was top of the Stack, and (5,4), (-2,-3) are pairwise consecutive. So the output will be Yes.


Input:

2,4,6,7,11,10

 

Output:

No

 

Here (2,4) are not consecutive, so that the output will be No.


Let's see the approach or algorithm used to solve the problem “check if stack elements are pairwise consecutive.”

Algorithm

Let us have a look at the algorithm to solve the problem.

  • Create a stack and push the elements into the Stack.
  • Again, Create another auxiliary stack.
  • Traverse through the whole Stack, while the Stack is not empty, and push the elements into the auxiliary Stack and pop from the top of the original Stack.
  • Again, traverse through the auxiliary Stack, pop the top 2 elements, and store them into two variables.
  • Check whether the absolute difference of the elements of the auxiliary Stack is less than 1 or not? If it is less than 1, return false.
  • If the returned value is true, then print" Yes," or if it is false, print "No."


Below is the implementation of the above algorithm that we have used in the problem “Check if stack elements are pairwise consecutive” in C++ and Java.

Implementation in C++

Let's see how we can implement the above algorithm in C++.

#include <bits/stdc++.h>
using namespace std;
int main()
{
    stack<int> s;
    s.push(6);
    s.push(5);
    s.push(4);
    s.push(3);
    s.push(9);
    s.push(10);
 
    stack<int> res;
    while (!s.empty()) {
        res.push(s.top());
        s.pop();
    }
    if(res.size()%2!=0)
        res.pop();
    bool result = true;
    while (res.size() > 1){
        int x = res.top();
        res.pop();
        int y = res.top();
        res.pop();
        if (abs(x - y) != 1)
          result = false;
        s.push(x);
        s.push(y);

    }

    if (result==true)
        cout <<"Yes"<<"\n";
    else
        cout <<"No"<<"\n";
 
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Input:

6,5,4,3,9,10
You can also try this code with Online C++ Compiler
Run Code

 

Output:

Yes
You can also try this code with Online C++ Compiler
Run Code

Implementation in Java

Let's see how we can implement the above algorithm in Java.

import java.util.*;
class Check{
static boolean ispairWiseConsecutive(Stack<Integer> s)
{
    Stack<Integer> res = new Stack<Integer> ();
    while (!s.isEmpty()) {
        res.push(s.peek());
        s.pop();
    }
 
    boolean result = true;
    while (res.size() > 1) {
        int x = aux.peek();
        res.pop();
        int y = res.peek();
        res.pop();
        if (Math.abs(x - y) != 1)
        result = false;
        s.push(x);
        s.push(y);
    }
 
    if (res.size() == 1)
        s.push(res.peek());
 
    return result;
}
public static void main(String[] args)
{
    Stack<Integer> s = new Stack<Integer> ();
    s.push(6);
    s.push(5);
    s.push(4);
    s.push(3);
    s.push(9);
    s.push(10);
    if (ispairWiseConsecutive(s))
        System.out.println("Yes");
    else
        System.out.println("No");
 
    System.out.println("Stack content (from top) after function call");
    while (s.isEmpty() == false)
    {
    System.out.print(s.peek() + " ");
    s.pop();
    }
 
}
}
You can also try this code with Online Java Compiler
Run Code

 

Input:

6,5,4,3,9,10
You can also try this code with Online Java Compiler
Run Code

 

Output:

Yes
Stack content (from top) after function call
10 9 3 4 5 6
You can also try this code with Online Java Compiler
Run Code

Complexity Analysis

Let us have a look at the time and space complexity.

Time Complexity: The time complexity will be O(N) as the Stack contains N elements and we traversed through the whole elements.

Space complexity: The space complexity will be O(N) as we have used the Stack to store N elements.


In the above, we have learned about the algorithm used to solve the problem "Check if stack elements are pairwise consecutive." Now, let's see some FAQs related to them.

Check out this problem - Queue Implementation

Must Read Stack Operations

Frequently Asked Questions

What is Stack?

Stack is also a linear data structure, but it follows the LIFO (Last In First Out) principle, which means that the element which comes last will be accessed first.

What is the difference between Queue and Stack?

Both are the linear data structures, but Queue follows FIFO (First In First Out) principle, whereas Stack follows the LIFO (Last In First Out) principle.

What are the different operations that a Stack class provides?

Stack class provides different operations like-

  • Push()
  • Pop()
  • Top()
  • Size()
  • Empty()

What are the disadvantages of a Stack?

The Following disadvantages are-

  • The memory of the Stack is limited.
  • The total size of the Stack is defined before.
  • If the number of elements is large, there may be a chance of stack overflow.

What are the different applications of Stack?

The different applications are as follows-

  • Balancing of Symbol
  • Conversion (Infix to Postfix/Prefix and vice-versa).
  • In Graph Algorithms (Topological Sorting)
  • In memory management.
  • Reversal of String.
  • Many algorithms like (Stock Span Problem, Tower Of Hanoi, Largest Rectangular Area In a Histogram).

Conclusion

This article discusses the problem “check if stack elements are pairwise consecutive.” with their examples and implementation. We had also seen some FAQs related to them.

After reading about the above problem, "Check if stack elements are pairwise consecutive," are you not feeling excited to read/explore more articles on Data Structures and Algorithms? Don't worry; Coding Ninjas has you covered. See Next Greater ElementStackOnline Stock ProblemCheck for Balanced Parentheses in an Expression, and Stack to learn.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! 
Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass