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.
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 consecutive or not. After checking put these elements back to original stack.
Implementation:
Try It Yourself
// C++ program to check if successive
// pair of numbers in the stack are
// consecutive or not
#include <bits/stdc++.h>
using namespace std;
// Function to check if elements are
// pairwise consecutive 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
// consecutive or not. We also
// need to make sure that original
// content is retained.
bool result = true;
while (aux.size() > 1) {
// Fetch current top two
// elements of aux and check
// if they are consecutive.
int x = aux.top();
aux.pop();
int y = aux.top();
aux.pop();
if (abs(x - y) != 1)
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(-2);
s.push(-3);
s.push(11);
s.push(10);
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 program to check if successive
// pair of numbers in the stack are
// consecutive or not
import java.util.*;
class GfG {
// Function to check if elements are
// pairwise consecutive in stack
static boolean pairWiseConsecutive(Stack<Integer> s)
{
// Transfer elements of s to aux.
Stack<Integer> aux = new Stack<Integer> ();
while (!s.isEmpty()) {
aux.push(s.peek());
s.pop();
}
// Traverse aux and see if
// elements are pairwise
// consecutive or not. We also
// need to make sure that original
// content is retained.
boolean result = true;
while (aux.size() > 1) {
// Fetch current top two
// elements of aux and check
// if they are consecutive.
int x = aux.peek();
aux.pop();
int y = aux.peek();
aux.pop();
if (Math.abs(x - y) != 1)
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<Integer> ();
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))
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();
}
}
}
# Python3 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
def pairWiseConsecutive(s):
# Transfer elements of s to aux.
aux = []
while (len(s) != 0):
aux.append(s[-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.
result = True
while (len(aux) > 1):
# Fetch current top two
# elements of aux and check
# if they are consecutive.
x = aux[-1]
aux.pop()
y = aux[-1]
aux.pop()
if (abs(x - y) != 1):
result = False
# append the elements to
# original stack.
s.append(x)
s.append(y)
if (len(aux) == 1):
s.append(aux[-1])
return result
# Driver Code
if __name__ == '__main__':
s = []
s.append(4)
s.append(5)
s.append(-2)
s.append(-3)
s.append(11)
s.append(10)
s.append(5)
s.append(6)
s.append(20)
if (pairWiseConsecutive(s)):
print("Yes")
else:
print("No")
print("Stack content (from top)",
"after function call")
while (len(s) != 0):
print(s[-1], end = " ")
s.pop()
# This code is contributed by PranchalK
// C# program to check if successive
// pair of numbers in the stack are
// consecutive or not
using System;
using System.Collections.Generic;
class GfG
{
// Function to check if elements are
// pairwise consecutive 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
// consecutive or not. We also
// need to make sure that original
// content is retained.
bool result = true;
while (aux.Count > 1)
{
// Fetch current top two
// elements of aux and check
// if they are consecutive.
int x = aux.Peek();
aux.Pop();
int y = aux.Peek();
aux.Pop();
if (Math.Abs(x - y) != 1)
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 code
public static void Main()
{
Stack<int> s = new Stack<int> ();
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))
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();
}
}
}
/* This code contributed by PrinciRaj1992 */
<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:
- Initialize a variable with the top element of the stack and pop it out.
- 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".
- If the stack has an odd number of elements, discard the top element.
- If the iteration completes without returning "No", return "Yes".
Below is the implementation:
// 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 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
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
using System;
using System.Collections.Generic;
namespace PairWiseConsecutiveExample {
class GFG {
static string PairWiseConsecutive(Stack<int> s)
{
if (s.Count % 2 != 0) {
// If odd number of elements, pop top element
// and discard it
s.Pop();
}
int prev
= s.Peek(); // Initialize prev with top element
s.Pop(); // Pop top element
while (s.Count > 0) {
int curr = s.Peek();
s.Pop();
if (Math.Abs(curr - prev) != 1) {
// Check if absolute difference between curr
// and prev is not 1
return "No";
}
if (s.Count > 0) {
// If there are more elements, update prev
// with the next element
prev = s.Peek();
s.Pop();
}
}
return "Yes";
}
static void Main(string[] args)
{
Stack<int> s = new Stack<int>(
new int[] { 4, 5, -2, -3, 11, 10, 5, 6, 20 });
Console.WriteLine(
PairWiseConsecutive(s)); // Expected output: Yes
}
}
}
function pairWiseConsecutive(s) {
// If the stack size is odd, discard the top element
if (s.length % 2 !== 0) {
s.pop();
}
let prev = s[s.length - 1]; // Initialize prev with the top element
s.pop(); // Pop the top element
while (s.length > 0) {
const curr = s[s.length - 1]; // Get the current element
s.pop(); // Pop the current element
if (Math.abs(curr - prev) !== 1) {
// Check if the absolute difference between curr and prev is not 1
return "No";
}
if (s.length > 0) {
prev = s[s.length - 1]; // Update prev with the next element if more elements are present
s.pop();
}
}
return "Yes"; // All elements are pairwise consecutive
}
// Driver code
const s = [4, 5, -2, -3, 11, 10, 5, 6, 20];
console.log(pairWiseConsecutive(s));
// THIS CODE IS CONTRIBUTED BY PIYUSH AGARWAL
Output
Yes
Time complexity: O(n).
Auxiliary Space : O(1).