
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Validating Push-Pop Sequence in JavaScript
Problem
JavaScript function that takes in two arrays, pushed and popped, as the first and the second argument. Both these arrays are guaranteed to consist of unique elements.
Our function should return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack, false otherwise.
For example, if the input to the function is −
const pushed = [1, 2, 3, 4, 5]; const popped = [4, 5, 3, 2, 1];
Then the output should be −
const output = true;
Output Explanation
We might do the following sequence −
push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example
The code for this will be −
const pushed = [1, 2, 3, 4, 5]; const popped = [4, 5, 3, 2, 1]; const validateSequence = (pushed = [], popped = []) => { let pushedIndex = 0 let poppedIndex = 0 const stack = [] while (pushedIndex < pushed.length) { if (stack[stack.length - 1] !== popped[poppedIndex]) { stack.push(pushed[pushedIndex++]) } else { stack.pop() poppedIndex += 1 } } while (stack.length) { if (stack.pop() !== popped[poppedIndex++]) { return false } } return true; }; console.log(validateSequence(pushed, popped));
Output
And the output in the console will be −
true
Advertisements