Showing 7 of 7 flashcards
Difficulty: HARD
LC: 853
Frequency: 25
Type: coding
Car Fleet — Given target and cars’ position/speed, count fleets arriving (cars that catch up merge and go same speed); e.g., target=12, position=[10,8,0,5,3], speed=[2,4,1,1,3] → 3.
class Solution: def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: pairs = sorted(zip(position, speed), key=lambda x: x[0], reverse=True) fleets = 0 current_time = 0.0 for pos, sp in pairs: time = (target - pos) / sp if time > current_time: fleets += 1 current_time = time return fleets
Trick: V V VTricky; Don't use stack; Time=Distance/Speed; sort; reverse order; set curr_time; if ith car reaches after curr_time; add +1 fleet and update current_time
Note: Done
Tags: Stack
Difficulty: MEDIUM
LC: 739
Frequency: 24
Type: coding
Daily Temperatures — For each day, return days until a warmer temperature (0 if none); e.g., [73,74,75,71,69,72,76,73] → [1,1,4,2,1,1,0,0].
from collections import deque ## Think This: You want the stack to be always decreasing order, if not, pop and make it one. class Solution: def dailyTemperatures(self, temperatures: List[int]) -> List[int]: # Initialize a stack to keep track of temperatures and their indices. stack = deque([]) # Initialize the result list with 0s, each representing the number of days to wait. res = [0] * len(temperatures) # Iterate through the list of temperatures along with their indices. for index, current_temp in enumerate(temperatures): # While the stack is not empty and the current temperature is higher than # the temperature at the top of the stack (last recorded temperature), # pop the stack and calculate the number of days waited for a warmer temperature. while stack and stack[-1][0] < current_temp: _, index_of_cooler_day = stack.pop() res[index_of_cooler_day] = index - index_of_cooler_day # Push the current temperature and its index onto the stack. # This is done for each temperature as we might need to compare # it with future temperatures. stack.append((current_temp, index)) # Return the result list containing the number of days to wait for a warmer temperature. return res
Trick: ## Think This: You want the stack to be always decreasing order, if not, pop and make it one. Monotonic Decreasing Stack: Neetcode video: if no cooler temp present than curr: push else pop and update all of them
Note: Done
Tags: Stack
Difficulty: MEDIUM
LC: 150
Frequency: 22
Type: coding
Evaluate Reverse Polish Notation — Evaluate postfix expression using stack with operators +,-,,/ (truncate toward zero); e.g., ["2","1","+","3",""] → 9.
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] for token in tokens: if token not in "+-/*": stack.append(int(token)) continue number_2 = stack.pop() number_1 = stack.pop() result = 0 if token == "+": result = number_1 + number_2 elif token == "-": result = number_1 - number_2 elif token == "*": result = number_1 * number_2 else: result = int(number_1 / number_2) stack.append(result) return stack.pop()
Trick: Keep pushing to stack till operand found; pop two numbers and resolve and add it back continue;
Note: Done
Tags: Stack
Difficulty: MEDIUM
LC: 22
Frequency: 23
Type: coding
Generate Parentheses — Generate all valid parentheses strings with n pairs; e.g., n=3 → ["((()))","(()())","(())()","()(())","()()()"].
class Solution: def generateParenthesis(self, n): result = [] self.generate(n, "", result, 0, 0) return result def generate(self, n, partial, result, o_count, c_count): if len(partial) == 2 * n and o_count == c_count: result.append(partial) return if c_count < o_count: self.generate(n, partial + ")", result, o_count, c_count + 1) if len(partial) < 2 * n: self.generate(n, partial + "(", result, o_count + 1, c_count)
Trick: generate(curr_bracket_list, open_count, close_count) -> if open<n -> add; if close<open -> add; final results
Note: Done
Tags: Stack
Difficulty: HARD
LC: 84
Frequency: 26
Type: coding
Largest Rectangle in Histogram — Given bar heights, return max rectangle area in histogram; e.g., [2,1,5,6,2,3] → 10.
class Solution(object): def largestRectangleArea(self, heights): maxArea = 0 stack = [] # (start_index, height) — monotonic INCREASING by height for i, h in enumerate(heights): start = i # If current bar is smaller, it ends rectangles of taller bars on stack while stack and stack[-1][1] > h: idx, height = stack.pop() maxArea = max(maxArea, height * (i - idx)) # width = i - idx start = idx # current bar can extend left to where popped bar started # Push current bar with its leftmost start stack.append((start, h)) # Remaining bars extend to the end of the histogram n = len(heights) for idx, height in stack: maxArea = max(maxArea, height * (n - idx)) return maxArea
Note: Done
Tags: Stack
Difficulty: EASY
LC: 155
Frequency: 21
Type: coding
Min Stack — Design stack supporting push/pop/top/getMin all in O(1); e.g., push 2,0,3,0 then getMin=0, pop, getMin=0, pop, getMin=0, pop, getMin=2.
from collections import deque class MinStack: def __init__(self): self.stack = deque() def push(self, val: int) -> None: if not self.stack: self.stack.append((val, val)) else: current_min = self.stack[-1][1] # Always push the new value along with the updated minimum. self.stack.append((val, min(val, current_min))) def pop(self) -> None: self.stack.pop() def top(self) -> int: return self.stack[-1][0] def getMin(self) -> int: return self.stack[-1][1]
Trick: Simple Stack/Deque; Use a tuple (Val, Min_value(sofar))
Note: Done
Tags: Stack
Difficulty: EASY
LC: 20
Frequency: 20
Type: coding
Valid Parentheses — Check if brackets (), {}, [] are properly opened/closed and nested; e.g., "({[]})" → true, "(]" → false.
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stack=[] for c in s: if c == '{': stack.append('}') elif c == '(': stack.append(')') elif c=='[': stack.append(']') else: if len(stack)==0: return False elif(stack.pop()!=c): return False return len(stack)==0
Trick: Simple List as Stack; append(); pop(); use hashmap for pair brackets
Note: Done
Tags: Stack
We use cookies to improve your experience. By clicking “Accept” you consent to the use of cookies. Read our Privacy Policy.