Learn to implement and use stack and queue data structures for solving problems.
Opening
( { [
Closing
) } ]
const bracketPairs = {
'(': ')',
'{': '}',
'[': ']'
};
const openBrackets = new Set(['(', '{', '[']);
const closeBrackets = new Set([')', '}', ']']);
function isValidBracketSequence(sequence) {
const stack = [];
for (let i = 0; i < sequence.length; i++) {
const char = sequence[i];
// Skip non-bracket characters
if (!openBrackets.has(char) &&
!closeBrackets.has(char)) {
continue;
}
// Handle logic here
}
return stack.length === 0;
}
// Inside the for loop from step 2
if (openBrackets.has(char)) {
// If it's an opening bracket, push to stack
stack.push(char);
} else {
// Handle closing brackets
}
// Inside the else block from step 3
// If stack is empty, no matching open bracket
if (stack.length === 0) {
return false;
}
// Get the last open bracket
const lastOpen = stack.pop();
// Check if brackets match
if (bracketPairs[lastOpen] !== char) {
return false;
}
function isValidBracketSequence(sequence) {
const stack = [];
for (let i = 0; i < sequence.length; i++) {
const char = sequence[i];
// Skip non-bracket characters
if (!openBrackets.has(char) &&
!closeBrackets.has(char)) {
continue;
}
if (openBrackets.has(char)) {
// If it's an opening bracket, push to stack
stack.push(char);
} else {
// If stack is empty, no matching open bracket
if (stack.length === 0) {
return false;
}
// Get the last open bracket
const lastOpen = stack.pop();
// Check if brackets match
if (bracketPairs[lastOpen] !== char) {
return false;
}
}
}
// Valid only if all brackets were matched
return stack.length === 0;
}
Now that you've learned how to validate bracket sequences using a stack, try implementing a queue with a twist.
Create a queue data structure using two stacks. Your implementation should include these methods:
enqueue(element)
: Add element to the queuedequeue()
: Remove and return the front elementpeek()
: Return (without removing) the front elementisEmpty()
: Return true if queue is emptyclass StackQueue {
constructor() {
this.stackNewest = []; // for enqueue
this.stackOldest = []; // for dequeue
}
enqueue(value) {
// Your code here
}
dequeue() {
// Your code here
}
peek() {
// Your code here
}
isEmpty() {
// Your code here
}
}
If you want more practice with stacks and queues, check out these LeetCode problems: