Push openers; pop and check match on closers
When to useBrackets/parentheses validation, undo operations
iterative
Stack Applications
stack_applicationsValid Parentheses
valid_parenthesesRemove Adjacent Duplicates in String
remove_adjacent_duplicates_in_stringBackspace String Compare
backspace_string_compareEvaluate Reverse Polish Notation
evaluate_reverse_polish_notationStack Intro
stack_introBaseball Scorekeeping
baseball_scorekeepingAmazon OA — Matching Brackets
amazon_oa_matching_bracketsBasic Calculator Ihard
basic_calculator_i · no slotsBasic Calculator IImedium
basic_calculator_ii · no slotsINITIALIZE
empty stack; map of pairs if needed
const pairs = { ')': '(', ']': '[', '}': '{' };const stack = [];
const pairs = { ')': '(', ']': '[', '}': '{' };const stack = [];
const stack = [];
const stack = [];
const stack = [];
const pairs = { ')': '(', ']': '[', '}': '{' };const stack = [];
const stack = [];
const pairs = { ')': '(', ']': '[', '}': '{' };const stack = [];
—
—
TRAVERSE
for-of input
for (const ch of s) {
for (const ch of s) {
for (const ch of s) {
for (const ch of str) {
for (const token of tokens) {
for (const ch of s) {
for (const op of ops) {
for (const ch of s) {
—
—
[MATCH]
if opener push; if closer pop and verify
if (ch in pairs) {if (stack.pop() !== pairs[ch]) return false;} else {stack.push(ch);}
if (ch in pairs) {if (stack.pop() !== pairs[ch]) return false;} else {stack.push(ch);}
if (stack.length > 0 && stack[stack.length - 1] === ch) {stack.pop();} else {stack.push(ch);}
if (ch === '#') {stack.pop();} else {stack.push(ch);}
if (['+', '-', '*', '/'].includes(token)) {const b = stack.pop();const a = stack.pop();if (token === '+') stack.push(a + b);else if (token === '-') stack.push(a - b);else if (token === '*') stack.push(a * b);else stack.push(Math.trunc(a / b));} else {stack.push(parseInt(token));}
if (ch in pairs) {if (stack.pop() !== pairs[ch]) return false;} else {stack.push(ch);}
if (op === 'X') {stack.push(stack[stack.length - 1] * 2);} else if (op === '+') {stack.push(stack[stack.length - 1] + stack[stack.length - 2]);} else if (op === 'Z') {stack.pop();} else {stack.push(Number(op));}
if (ch in pairs) {if (stack.length === 0 || stack.pop() !== pairs[ch]) return false;} else {stack.push(ch);}
—
—
RETURN
stack.length === 0 (or other final check)
return stack.length === 0;
return stack.length === 0;
return stack.join('');
return build(s) === build(t);
return stack.pop();
return stack.length === 0;
return stack.reduce((sum, n) => sum + n, 0);
return stack.length === 0;
—
—