Open In App

Check if stack elements are pairwise consecutive

Improve
Improve
Like Article
Like
Save
Share
Report

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 retain the original stack content.
Only following standard operations are allowed on stack.

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

Examples: 

Input : stack = [4, 5, -2, -3, 11, 10, 5, 6, 20]
Output : Yes
Each of the pairs (4, 5), (-2, -3), (11, 10) and
(5, 6) consists of consecutive numbers.
Input : stack = [4, 6, 6, 7, 4, 3]
Output : No
(4, 6) are not consecutive.

Recommended Practice

The idea is to use another stack. 

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

Implementation:

C++





Java





Python3





C#





Javascript




<script>
 
// JavaScript program to check if successive
// pair of numbers in the stack are
// consecutive or not
 
// Function to check if elements are
// pairwise consecutive 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
    // consecutive or not. We also
    // need to make sure that original
    // content is retained.
    var result = true;
    while (aux.length > 1) {
 
        // Fetch current top two
        // elements of aux and check
        // if they are consecutive.
        var x = aux[aux.length-1];
        aux.pop();
        var y = aux[aux.length-1];
        aux.pop();
        if (Math.abs(x - y) != 1)
          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(-2);
s.push(-3);
s.push(11);
s.push(10);
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
20 6 5 10 11 -3 -2 5 4 









Time complexity: O(n). 
Auxiliary Space : O(n).

Without Using Any Auxiliary Stack:

Follow the steps to implement the approach:

  1. Initialize a variable with the top element of the stack and pop it out.
  2. Iterate over the remaining elements of the stack and check if the absolute difference between each pair of consecutive elements is equal to 1. If it is not, return “No”.
  3. If the stack has an odd number of elements, discard the top element.
  4. If the iteration completes without returning “No”, return “Yes”.

Below is the implementation:

C++




// C++ code to implement the above approach
#include <iostream>
#include <stack>
using namespace std;
 
string pairWiseConsecutive(stack<int> s)
{
    if (s.size() % 2
        != 0) { // if odd number of elements, pop top
                // element and discard it
        s.pop();
    }
    int prev = s.top(); // initialize prev with top element
    s.pop(); // pop top element
    while (!s.empty()) {
        int curr = s.top();
        s.pop();
        if (abs(curr - prev)
            != 1) { // check if absolute difference between
                    // curr and prev is not 1
            return "No";
        }
        if (!s.empty()) { // if there are more elements,
                          // update prev with the next
                          // element
            prev = s.top();
            s.pop();
        }
    }
    return "Yes";
}
// Driver code
int main()
{
    stack<int> s({ 4, 5, -2, -3, 11, 10, 5, 6, 20 });
 
    cout << pairWiseConsecutive(s)
         << endl; // expected output: Yes
 
    return 0;
}
// This code is contributed by Veerendra_Singh_Rajpoot


Java




// Java Code to Check  if stack elements are pairwise
// consecutive for the approach Without Using Any Auxiliary Stack
import java.util.Stack;
 
public class GFG {
// function to Check  if stack elements are pairwise consecutive
    static String pairWiseConsecutive(Stack<Integer> s) {
        if (s.size() % 2 != 0) { // if odd number of elements, pop top element and discard it
            s.pop();
        }
        int prev = s.pop(); // initialize prev with top element and pop top element
        while (!s.empty()) {
            int curr = s.pop();
            if (Math.abs(curr - prev) != 1) { // check if absolute difference between curr and prev is not 1
                return "No";
            }
            if (!s.empty()) { // if there are more elements, update prev with the next element
                prev = s.pop();
            }
        }
        return "Yes";
    }
//   Driver Code
    public static void main(String[] args) {
        Stack<Integer> s = new Stack<>();
        s.push(4);
        s.push(5);
        s.push(-2);
        s.push(-3);
        s.push(11);
        s.push(10);
        s.push(5);
        s.push(6);
        s.push(20);
 
        System.out.println(pairWiseConsecutive(s)); // expected output: Yes
    }
}
// This code is contributed by Veerendra_Singh_Rajpoot


Python3




def pair_wise_consecutive(s):
    if len(s) % 2 != 0:
        # If there's an odd number of elements, pop the top element and discard it
        s.pop()
 
    prev = s[-1# Initialize prev with the top element
    s.pop()  # Pop the top element
 
    while s:
        curr = s[-1]
        s.pop()
         
        if abs(curr - prev) != 1:
            # Check if the absolute difference between curr and prev is not 1
            return "No"
 
        if s:
            # If there are more elements, update prev with the next element
            prev = s[-1]
            s.pop()
 
    return "Yes"
 
# Driver code
if __name__ == "__main__":
    s = [4, 5, -2, -3, 11, 10, 5, 6, 20]
    result = pair_wise_consecutive(s)
    print(result)  # expected output: Yes


C#





Javascript





Output

Yes







Time complexity: O(n). 
Auxiliary Space : O(1).

 



Last Updated : 21 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads