Stack: Check if stack elements are pairwise consecutive

Problem Statement:

Given a stack of integers, you need to check if the stack is pairwise consecutive or not.

The pairs can be increasing and decreasing order.

If the stack has odd number, the element at top is left out.

The function should retain the original stack content.

Example:

Input: [4, 5, 2, 3, 14, 15, 7, 8, 20]
Output: Yes

Solution :

Take a variable with the top element of the stack and pop it

Iterate over the remaining element of the stack and check if the absolute difference between each pair of consecutive elements is equal to 1. If not return No.

If the stack has an odd number, then ignore the top element.

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

Code Solution

#include <iostream>
#include <stack>
using namespace std;

string solution(stack<int> s)
{
	if (s.size() % 2 != 0) 
	{  
		s.pop();
	}

	int prev = s.top();
	s.pop(); 

	while (!s.empty()) 
	{
		int curr = s.top();
		s.pop();
		if (abs(curr - prev) != 1) 
		{ 
			return "No";
		}
		if (!s.empty()) 
		{

			prev = s.top();
			s.pop();
		}
	}
	return "Yes";
}
int main()
{
	stack<int> s({ 4, 5, 2, 3, 14, 15, 7, 8, 20 });

	cout << solution(s)
		<< endl; // expected output: Yes

	return 0;
}

Output

Yes
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *