ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Data Structures & Algorithms (DSA)• 6 min read

Stacks (LIFO) & Queues (FIFO)

Call stacks, undo buffers, breadth-first queues, and Deque implementations

Stacks and Queues are abstract linear data structures defined by their strict order of item insertion and removal.

LIFO vs FIFO Paradigms

Stack (LIFO - Last-In, First-Out): The last item pushed is the first one popped. Examples: Browser navigation back button, text editor undo history, programming language call stacks.

Queue (FIFO - First-In, First-Out): The first item enqueued is the first one dequeued. Examples: Print spoolers, background task job queues, BFS graph traversal.

Operations: Push/Pop for Stacks; Enqueue/Dequeue for Queues. All execute in O(1) constant time.

Valid Parentheses Problem using a Stack
function isValidParentheses(s) {
  const stack = [];
  const map = { ')': '(', '}': '{', ']': '[' };

  for (const char of s) {
    if (char === '(' || char === '{' || char === '[') {
      stack.push(char); // Push opening brackets
    } else if (map[char]) {
      // Pop matching bracket; if mismatch, invalid!
      if (stack.pop() !== map[char]) return false;
    }
  }

  return stack.length === 0;
}

console.log(isValidParentheses("({[]})")); // true
console.log(isValidParentheses("([)]"));   // false
A classic LeetCode problem solved cleanly in O(n) time using a stack.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which data structure operates on a Last-In, First-Out (LIFO) principle?