Stack & Queue 101
Fundamental · 4 chapters · 7 min read · Use last-in-first-out to match brackets, undo steps and find the next greater value.
Practise this in the app All guides
Stacks, queues and when to use them
Two ways to line things up
A stack is last-in, first-out (LIFO): like a pile of plates, you add and remove from the top. A queue is first-in, first-out (FIFO): like the line at a railway ticket counter, people leave in the order they arrived. In Python a plain list is a good stack (append and pop are O(1)), and collections.deque is the right queue (append and popleft are O(1)). Never use list.pop(0) as a queue in an interview; it is O(n).
Signals for a stack
- Matching or nesting: brackets, tags, nested encodings like
3[a2[c]]. - Undo or cancel the previous item: backspace characters, removing adjacent duplicates, asteroid collisions.
- Expression evaluation: Reverse Polish Notation, basic calculators.
- "Next greater" or "previous smaller" element, daily temperatures, stock spans, the largest rectangle in a histogram. These use a monotonic stack.
- Converting recursion to iteration (depth-first search with an explicit stack).
Signals for a queue
- Processing in arrival order, simulation, "recent calls in the last 3000 ms".
- Breadth-first search, level-by-level traversal, shortest path in an unweighted graph.
- Sliding-window maximum with a monotonic deque.
Mental model
A stack holds the things that are still "open" or "waiting for an answer". When a new element arrives, it may close or answer some of them, always the most recent first. If you can describe what is waiting on your stack in one phrase ("indices of days that have not yet seen a warmer day"), you are using it correctly.
Core patterns with templates
1. Cancel the previous item
def remove_adjacent_duplicates(s):
st = []
for ch in s:
if st and st[-1] == ch:
st.pop()
else:
st.append(ch)
return "".join(st)
The same shape handles backspace (# pops, anything else pushes).
2. Evaluate Reverse Polish Notation
def eval_rpn(tokens):
st = []
for t in tokens:
if t in "+-*/":
b, a = st.pop(), st.pop()
if t == "+":
st.append(a + b)
elif t == "-":
st.append(a - b)
elif t == "*":
st.append(a * b)
else:
st.append(int(a / b))
else:
st.append(int(t))
return st[0]
Pop b first: the right operand is on top. int(a / b) truncates towards zero, unlike //.
3. Monotonic stack for "next warmer day"
def daily_temperatures(t):
ans = [0] * len(t)
st = []
for i, x in enumerate(t):
while st and t[st[-1]] < x:
j = st.pop()
ans[j] = i - j
st.append(i)
return ans
The stack holds indices whose temperatures are decreasing from bottom to top. Example: [73, 74, 75, 71, 69, 72, 76] gives [1, 1, 4, 2, 1, 1, 0].
4. Nested decoding with two stacks
def decode(s):
st, cur, num = [], "", 0
for ch in s:
if ch.isdigit():
num = num * 10 + int(ch)
elif ch == "[":
st.append((cur, num))
cur, num = "", 0
elif ch == "]":
prev, k = st.pop()
cur = prev + cur * k
else:
cur += ch
return cur
5. Queue for BFS
from collections import deque
q = deque([start])
while q:
node = q.popleft()
# visit node, append unvisited neighboursComplexity, mistakes and edge cases
Complexity
| Operation | Stack (list) | Queue (deque) |
|---|---|---|
| push / append | O(1) | O(1) |
| pop top / popleft | O(1) | O(1) |
| peek | st[-1] O(1) | q[0] O(1) |
A monotonic stack is O(n) overall even with a nested while: each index is pushed once and popped at most once.
Common mistakes
- Popping from an empty stack. Always check
if stbeforest[-1]orst.pop(). - Operand order. For
-and/, the second pop is the left operand. - Division semantics. Python's
//floors towards negative infinity (-7 // 2 == -4), but most problems want truncation (-3). Useint(a / b). - Multi-digit numbers. Accumulate
num = num * 10 + digitinstead of reading one character. - Strict versus non-strict comparison in monotonic stacks.
<versus<=decides how equal values are handled; think about duplicates explicitly. - Leftover items. After the loop, elements still on the stack have no answer; make sure their default (0, -1) is right.
- Using a list as a queue.
pop(0)is O(n).
Edge cases
Empty input, a single element, strictly increasing or strictly decreasing sequences (which stress the monotonic stack in opposite ways), all equal values, unbalanced brackets, and nested structures several levels deep.
The histogram trick
For "largest rectangle in a histogram", keep a stack of bar indices with increasing heights. When a shorter bar arrives, pop taller bars; each popped bar's rectangle extends from just after the new stack top to just before the current index. Appending a sentinel bar of height 0 at the end flushes the stack so you do not need special code afterwards.
Variations and practise
How interviewers twist it
- Min-stack. Support
getMinin O(1) by storing(value, current_min)pairs on the stack. - Queue using two stacks. Push onto an input stack; when the output stack is empty, pour everything across. Each element moves at most twice, so operations are O(1) amortised.
- Circular arrays. For "next greater element" on a circular list, loop over indices
0..2n-1and usei % n. - Previous smaller instead of next greater. Reverse the direction or the comparison; the template is otherwise identical.
- Calculators with precedence. Push numbers, applying
*and/immediately to the stack top, and sum the stack at the end. - Asteroid or car-fleet collisions. The stack holds survivors moving one way; each new item may destroy several of them.
How to explain it
Name what the stack holds and its order: "indices of bars with increasing heights" or "characters not yet cancelled". Then say when you pop: "when the current value breaks the order". That gives the interviewer confidence before you write a single line.
Practise
The problems below move from simple cancelling (backspace and adjacent duplicates) to expression evaluation, nested decoding, the monotonic stack, and finally the histogram rectangle. Solve the monotonic-stack problems twice: once by brute force to see the pattern, then with the stack.
Practise
Easy
- 1122. Backspace String Compare
- 1123. Remove All Adjacent Duplicates in String
- 1129. Crate Stack Top Log
- 1134. Deepest Bracket Nesting
- 1135. Fewest Brackets to Add
- 1136. Peel the Outer Bracket Layer
- 1137. Tally With Checkpoints
- 1138. Ticket Window Line
- 1139. Queue Built From Two Stacks
- 1140. Stack Built From One Queue
- 1141. Running Minimum Ledger
- 1142. Nearest Shorter on the Left
- 1143. Chain Reads the Same Both Ways
- 1144. Flip the Front of the Line
- 1145. Shuffle Two Halves of a Queue
- 1146. Counting-Out Circle
- 1147. Requests in the Recent Window
- 1148. Discard and Tuck Deck
- 1149. Is the Postfix Well-Formed
- 1150. Number in Another Base
- 1151. Folder Depth After Commands
- 1152. Sort a Pile With a Spare
- 1153. Pull the Middle Crate
- 1154. Turn a Pile Upside Down
- 1155. Well-Nested Tags
- 1156. Longest Balanced Opening
- 1157. Ring Buffer Log
- 1158. Double-Ended Line
- 1159. Print Shop Finish Times
- 1160. Shuttle Leftover Riders
- 1161. Lifting Books Off the Pile
- 1162. Rolling Window Sums
- 1163. Partner Bracket Index
- 1164. Two Piles, One Shelf
- 1165. Tree to Bracketed Text
- 1166. Word-Level Palindrome
- 1167. Audit a Queue Log
- 1168. Mirror Around a Marker
- 1169. Two-Lane Service Counter
- 1170. Freight Lift Trips
- 1171. Recent Files Panel
- 1172. Spatula Flip Log
- 1173. Three-Peg Disk Moves
- 1174. Cut and Paste Stack Editor
- 1175. Reversible Conveyor Belt
- 1176. Toll Plaza Backlog
- 1177. First Invalid Pile Command
- 1178. Library Return Cart Walk
- 1179. Spotlight Performers
- 1181. Binary Labels in Order
- 1183. Candy Line Handout
- 1185. First Loss in Every Window
- 1186. FIFO Cache Misses
- 1251. Two-Pile Card Battle
- 1262. Pair Sum in a Search Tree
- 1271. Two-Station Assembly Line
- 1292. LIFO Inventory Cost
Medium
- 1124. Evaluate Reverse Polish Notation
- 1125. Daily Temperatures
- 1126. Decode String
- 1130. Stamp Token Check
- 1131. First Solo Letter So Far
- 1132. Chain Merge of Equal Tiles
- 1180. Turnstile With Two Directions
- 1182. Properly Nested Time Blocks
- 1184. Deepest Tag Path
- 1187. Weighted Depth Sum
- 1188. Brackets With Wild Cards
- 1189. Fewest Swaps to Balance
- 1190. Split Into Two Shallow Sets
- 1191. Flip Text Inside Brackets
- 1192. Nested Shell Score
- 1193. Trim Stray Brackets
- 1194. Infix to Postfix
- 1195. Postfix to Bracketed Infix
- 1196. Prefix to Postfix
- 1197. Desk Calculator With Precedence
- 1198. Resolve Chained Conditionals
- 1199. Normalize a Folder Path
- 1200. Self Time per Routine
- 1201. Shrink a Number by Deleting Digits
- 1202. Lex-First Distinct Pick
- 1203. Smallest Code From Rise/Fall
- 1204. Train Cars Through a Siding
- 1205. Colliding Drones
- 1206. Next Taller Tower on a Ring
- 1208. Next Larger Node Down the Chain
- 1210. Total of Window Minimums
- 1212. Dip-Then-Rise Triple
- 1215. Widest Rising Ramp
- 1217. Convoys on a One-Lane Road
- 1219. Prune Overshadowed Nodes
- 1221. Sortable Blocks Count
- 1223. Peak Reading in Every Window
- 1225. Steady Stretch Within Tolerance
- 1226. Strongest Segment Score
- 1227. Subarrays Led by Their Smallest
- 1228. Character at Position on an Expanding Tape
- 1229. Back and Forward Navigation
- 1230. Bulk Raise Stack
- 1231. Queue With Instant Maximum
- 1232. Line With a Middle Lane
- 1233. Grid Snake Score
- 1234. Council Vote of Two Factions
- 1235. Deal Order for a Magic Trick
- 1236. Elevator With Two Buttons
- 1237. Postorder Without Recursion
- 1238. Check a Tree's Preorder Sketch
- 1239. Could This Be a Search Tree Preorder
- 1240. Rebuild a Search Tree From Its Visit Order
- 1241. Tallest-Root Tree
- 1242. Search Tree Stepper
- 1243. Tree From Bracketed Text
- 1244. Cheapest Merge of Adjacent Leaves
- 1245. Smallest Printout From a Robot's Tray
- 1246. Deepest File Path Length
- 1247. Cursor Text Editor
- 1248. Longest Stretch of Busy Days
- 1249. Paint Layers to Match a Skyline
- 1250. Lineup Name From Both Ends
- 1252. Priority-Aware Print Spooler
- 1253. Multi-Teller Bank Line
- 1254. Fewest Knight Hops
- 1255. Dial Lock With Forbidden Codes
- 1256. Chutes Board Fewest Rolls
- 1257. Count Balanced Bracket Slices
- 1258. Locked and Free Brackets
- 1259. Double-Closer Balance
- 1260. Fewest Bracket Flips
- 1261. Rotating Operator Countdown
- 1263. Interleave Two Search Trees
- 1264. Next More Popular Value
- 1265. Time-Slice Scheduler
- 1266. Find the Town Favorite
- 1267. Spot Useless Brackets
- 1268. Is This Formula Well-Formed
- 1269. Versioned Stack
- 1270. Trucks Over a Weight-Limited Bridge
- 1272. Match Buy and Sell Orders
- 1273. Smallest Zero-One Multiple
- 1274. Step Numbers in a Range
- 1275. K-th Number From Two Digits
- 1276. Rotations That Balance a Bracket Ring
- 1277. Toppling Poles
- 1278. Same Shape Bracket Forests
- 1279. Fewest Turns of a Revolving Tray
- 1280. Coaster Ride Earnings
- 1281. Discs in a Narrowing Shaft
- 1282. Bracket Check That Skips Strings
- 1283. Hopping Bug Heading Home
- 1284. Harvest Pair Tokens
- 1285. Letters in Order With Fewest Deletions
- 1286. Nested Transactions Store
- 1287. Block World Commands
- 1288. Riffle Shuffles Until Restored
- 1289. Erase a Pattern Until It's Gone
- 1290. Resolve Variable Scopes
- 1291. Throttle Requests per Window
- 1293. Rooftop Hopping Chain
- 1294. Best Segment With Length Limits
- 1295. Preemptive Task Stack
- 1296. Parking Garage Waitlist
- 1304. Count All-Ones Rectangles
Hard
- 1127. Largest Rectangle in Histogram
- 1128. Basic Calculator
- 1133. Longest Balanced Stretch
- 1207. Most Repeated Pop
- 1209. Cafeteria Plate Racks
- 1211. Rebuild Tree From Dashed Outline
- 1213. Total Strength of All Squads
- 1214. Rounds Until the Row Stops Shrinking
- 1216. Evaluate a Tiny Let-Language
- 1218. Script of Assignments
- 1220. Stack That Gives Up Its Largest
- 1222. Biggest Number From Two Digit Rows
- 1224. Alternating Leaps to the Finish
- 1297. Evaluate a Nested Logic Formula
- 1298. Count Atoms in a Formula
- 1299. Expand Option Groups
- 1300. Parade Line of Sight
- 1301. Shortest Segment Reaching a Target Sum
- 1302. Hop-Limited Best Sum
- 1303. Best Floor for Every Window Size
- 1305. Second Taller to the Right
- 1306. Skyline Under a Single Peak
- 1307. When Does Each Car Catch Up
- 1308. Fewest Buses Between Stops
- 1309. Grid Walk With Limited Wall Breaks
- 1310. Teleport Between Equal Values
- 1311. Outrun the Spreading Fire
- 1312. Flip Windows to All Ones
- 1313. Best Pair Within a Gap
- 1314. Dock Runs With Weight Limits
- 1315. Rubber Stamp Reconstruction
- 1316. All Minimal Bracket Repairs
- 1317. Fence Around the Orchard
- 1318. Windows Framed by Their Peak
- 1319. Robot Squad Under Budget
- 1320. Window Where Every Item Clears the Bar
- 1321. Signal Fires Around a Ring
- 1322. Pick With a Required Letter
- 1323. Downhill Leaps Over Lower Ground
- 1324. Accelerate-and-Reverse Racer
- 1325. Push the Crate to the Dock
- 1326. Collect Every Key in the Vault
- 1327. Cheapest Bracket Fix With Costs
- 1328. Spreadsheet Formula Evaluator
- 1329. Record-Breaking Moments in a Range
- 1330. Peak Reading Over Every Square Patch
- 1331. Battling Robots on a Rail
- 1332. Crew Assignment With Energy Boosts
- 1333. K-th Balanced Bracket String
- 1334. Meeting Rooftop for Two Climbers
- 1335. Clinic Queue With Emergencies
- 1336. Elevator Sweep Scheduler