Monotonic-stack

38 articles

dsa1 min read

Gas Station — Greedy Circular

Find starting gas station index to complete circular route. If total gas >= total cost, a solution exists. Track running balance; reset start when negative.

Read →
dsa1 min read

Candy — Two-Pass Greedy

Distribute minimum candies with higher-rated children getting more than neighbors. Two-pass: left-to-right for ascending, right-to-left for descending.

Read →
dsa1 min read

Largest Rectangle in Histogram — Monotonic Stack

Find the area of the largest rectangle in a histogram. Monotonic increasing stack: when a shorter bar is found, pop and compute rectangle area using popped height and current width.

Read →
dsa1 min read

Remove K Digits — Greedy Monotonic Stack

Remove k digits to get smallest number. Monotonic increasing stack: pop larger digits when they appear before a smaller one. Remove remaining from end.

Read →
dsa1 min read

Maximal Rectangle — Histogram per Row

Find the largest rectangle in a binary matrix. Build histogram row by row (reset to 0 on '0'), apply Largest Rectangle in Histogram each row.

Read →