Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Stacks, Queues & Deques/Monotonic Stack

Technique

Stack for Matching & Expression Parsing

Use a plain LIFO stack to match nested structures (brackets, tags, decode strings) and evaluate expressions with precedence.

UnlocksMonotonic Stack
0%
mastery
0/13 solved
Practise nextValid Parentheses
IdeaPracticePitfalls

Recognise it

The signal

valid/minimum-remove parentheses

  1. 1Brute force

    Repeatedly find and remove innermost pairs: O(n2).

  2. 2The observation

    Rescanning: the most recent unmatched opener is always on top.

  3. 3Why it works

    The stack holds exactly the unmatched / unevaluated items in order.

Reach for it when

  • +evaluate RPN or infix with + - * / and parentheses
  • +nested encodings like 3[a2[c]]
  • +path simplification, collisions

Not when

  • ×needs next greater/smaller (mono-stack invariant)
  • ×balance counting suffices (one counter)

Practice

Next

Valid Parentheses

0/13 solved
  • Valid ParenthesesAmazon, MetaEasy
  • Backspace String CompareGoogle, MetaEasy
  • Move BracketsCodeforces1000
  • Basic Calculator IIMeta, StripeMedium
  • Decode StringGoogle, AmazonMedium
  • Evaluate Reverse Polish NotationAmazon, LinkedInMedium
  • Minimum Remove to Make Valid ParenthesesMeta, UberMedium
  • Simplify PathMeta, MicrosoftMedium
  • Asteroid CollisionUber, AmazonMedium
  • Design Browser HistoryUber, MetaMedium
  • Asteroid Collision (variant)NutanixOAMedium
  • Array BurstGoldman SachsOAMedium
  • Basic CalculatorUber, StripeHard

Pitfalls

Misconceptions

  • !unary minus and operator precedence handling

Looks like it, isn't

  • Valid Parenthesis String needs Greedy
    Why
    '*' makes stacks branch; track a range [lo, hi] of open counts. source ↗
Go deeperresources

Resources

  • Queue & Stack explore cardLeetCode · course
  • Stack cheatsheetTech Interview Handbook · article
  • Minimum stack / minimum queuecp-algorithms · article
  • Sliding Window (monotonic deque)USACO Guide · course
  • NeetCode RoadmapNeetCode · sheet
TodayReviewPatternsProblems