LeetCode Flashcards
Starting out as an overview of how to solve meta leetcode problems (17 cards)
- Minimum Remove to Make Valid Parentheses
Problem: Remove the minimum number of parentheses to make the string valid (balanced).
- First Pass (Left to Right):
- Initialize a stack or counter.
- Iterate over the string:
- If ‘(‘, push index to stack.
- If ‘)’:
- If stack is not empty, pop (valid pair).
- Else, mark index for removal (unmatched ‘)’).
- Second Pass:
- Remove all unmatched ‘(‘ using indices in the stack.
- Build Result:
- Rebuild the string skipping marked indices.
Time: O(n), Space: O(n)
- Valid Word Abbreviation
Problem: Check if a word matches its abbreviation (e.g., “internationalization” vs “i12iz4n”).
- Use two pointers for word and abbreviation.
- Iterate through abbreviation:
- If digit, parse full number and skip that many characters in word.
- If letter, it must match current char in word.
- Both pointers must reach end.
Time: O(n), Space: O(1)
- Binary Tree Vertical Order Traversal
Problem: Return the vertical order traversal of a binary tree.
- Use BFS with queue storing (node, column index).
- Use defaultdict to map column -> list of node values.
- For children:
- Left: column - 1
- Right: column + 1
- Track min and max columns.
- Output values from min_col to max_col.
Time: O(n), Space: O(n)
- Valid Palindrome II
Problem: Return true if the string can become a palindrome by deleting at most one character.
- Two pointers: left and right.
- Compare characters:
- If equal: move inward.
- If not:
- Try skipping left or right and check if resulting substring is a palindrome.
- Helper: is_palindrome(l, r).
Time: O(n), Space: O(1)
- Kth Largest Element in an Array
Problem: Find the Kth largest element in an unsorted array.
Min-Heap Method:
1. Create min-heap of size k.
2. Iterate array:
- Push element to heap.
- If heap > k, pop smallest.
3. Top of heap is Kth largest.
Time: O(n log k), Space: O(k)
Alternate: QuickSelect (Avg O(n))
Basic Calculator II - Evaluate the expression string containing non-negative integers, ‘+’, ‘-‘, ‘*’, ‘/’, and empty spaces. Return the result following the operator precedence.
- Initialize stack, current number, and current sign (‘+’).
- Iterate through the string:
- If digit, build the number.
- If operator or end of string:
- Based on last sign, push result to stack:
- ’+’ → push number
- ’-‘ → push -number
- ‘*’ → pop, multiply, push result
- ’/’ → pop, divide (truncate toward zero), push result
- Update sign and reset number.
- Based on last sign, push result to stack:
- Return sum of stack.
Time: O(n), Space: O(n)
Subarray Sum Equals K - Given an array of integers and an integer k, return the total number of subarrays whose sum equals to k.
- Initialize hashmap {0: 1} to count prefix sums.
- Track running_sum and result = 0.
- For each num in array:
- Add num to running_sum.
- If running_sum - k in hashmap, add its count to result.
- Increment count of running_sum in hashmap.
Time: O(n), Space: O(n)
Nested List Weight Sum - Given a nested list of integers, return the sum weighted by depth (e.g., [1,[4,[6]]] → 11 + 42 + 6*3 = 27).
- Use DFS helper function with depth parameter.
- For each element in list:
- If integer, add value * depth.
- If list, recurse with depth + 1.
- Return total sum.
Time: O(n), Space: O(d) where d = max depth
Lowest Common Ancestor of a Binary Tree - Given a binary tree and two nodes, return their lowest common ancestor (LCA).
- Use recursive DFS.
- Base case: if node is None or equals p or q, return node.
- Recurse left and right.
- If both sides return non-null, current node is LCA.
- Else, return the non-null side.
Time: O(n), Space: O(h) where h = height of tree
Random Pick with Weight - Given an array of positive integers representing weights, implement a method that randomly picks an index with probability proportional to its weight.
- Preprocess:
- Build prefix sum array of weights.
- For pickIndex():
- Generate random number in [1, total_weight].
- Use binary search to find the first index where prefix sum >= random number.
Time: O(log n) for pickIndex, O(n) preprocessing
Space: O(n)
Two Sum - Given an array of integers and a target, return indices of the two numbers such that they add up to the target.
- Use a hashmap to store num -> index.
- For each element:
- If target - num exists in hashmap, return [index of complement, current index].
- Otherwise, add num to hashmap.
Time: O(n), Space: O(n)
Diameter of Binary Tree - Given the root of a binary tree, return the length of the longest path between any two nodes.
- Use DFS to compute depth of each subtree.
- For each node, update diameter = max(diameter, left_depth + right_depth).
- Return the global max diameter.
Time: O(n), Space: O(h)
Find Peak Element - Given an array, find a peak element where nums[i] > nums[i-1] and nums[i] > nums[i+1].
- Use binary search:
- If mid > mid+1, peak is in left half.
- Else, peak is in right half.
- Return the index when low == high.
Time: O(log n), Space: O(1)
Lowest Common Ancestor of a Binary Tree III - Given two nodes in a binary tree with parent pointers, return their lowest common ancestor.
- Use two pointers p1 and p2.
- Traverse up until both meet:
- If pointer reaches null, redirect to the other node.
- When they meet, it’s the LCA.
Time: O(h), Space: O(1)
Binary Tree Right Side View - Return the rightmost node at each level of a binary tree.
- Use BFS with a queue.
- At each level, record the last node encountered.
- Append it to result list.
Time: O(n), Space: O(n)
Simplify Path - Given a Unix-style file path, simplify it.
- Split path by ‘/’.
- Use a stack:
- Ignore empty, ‘.’.
- ’..’ → pop if not empty.
- Else, push the directory name.
- Join stack with ‘/’ prefix.
Time: O(n), Space: O(n)
Shortest Path in Binary Matrix - Given a binary matrix, return the shortest path from top-left to bottom-right with only 8-directional moves on 0s.
- Use BFS starting from (0, 0).
- Track visited cells.
- For each cell, explore all 8 directions.
- Return path length when reaching bottom-right.
Time: O(n^2), Space: O(n^2)