« Back
Cheatsheet
- [A] 3Sum - Sort list, find complement, use two pointers on rest.
- [A] Best Time to Buy and Sell Stock - Track prospective new buy prices and max profits along the way.
- [A] Container With Most Water - Narrow two pointers - shorter one gets narrowed.
- [A] Contains Duplicate - Keep a set while iterating.
- [A] Find Minimum in Rotated Sorted Array - Binary search for spot where it's smaller than previous.
- [A] Maximum Product Subarray - Modified Kadane’s, hold the minimum to handle negatives.
- [A] Maximum Subarray - Max at i is either value or current best + value.
- [A] Product of Array Except Self - Product from start, then from end, then multiple w/out.
- [A] Search in Rotated Sorted Array - Binary search for pivot, then for target.
- [A] Two Sum - Find the complements, complements-to-index, find the match.
- [B] Counting Bits - Use DP, bottom-up. Build array, shift by one for previous.
- [B] Missing Number - XOR the array and the range.
- [B] Number of 1 Bits - Add n & 1 while shifting down to zero.
- [B] Reverse Bits - Bit-shift the answer out while shifting the original in.
- [B] Sum of Two Integers - Just give up if this one comes :(
- [DP] Climbing Stairs - Basically Fibonacci.
- [DP] Coin Change - Bottom-up: build up to amount. For each value, iterate denominations and find min.
- [DP] Combination Sum - DFS where the candidate pool shrinks on every iteration of the sub loop.
- [DP] Decode Ways - Keep track of previous two as we iterate, recurrence sums it.
- [DP] House Robber - Recurrence: hr(i) = max(hr(i-1), hr(i-2) + nums[i])
- [DP] House Robber II - Track with and without start and end, take max.
- [DP] Jump Game - Keep extending the max as the you loop through.
- [DP] Longest Common Subsequence - Recurrence: either (i, j) increases the previous or it doesn't and it's one or the other.
- [DP] Longest Increasing Subsequence - DP: longest at i is max of everything it's larger than that came before.
- [DP] Unique Paths - DP, recurrence: val(i,j) = val(i - 1,j) + val(i, j - 1)
- [DP] Word Break - Build a trie using wordDict, iterate string and recurse on new words.
- [G] Alien Dictionary - Build lex-relevant words, then graph, then topological sort.
- [G] Clone Graph - Clone all nodes first via BFS, add in associations after.
- [G] Course Schedule - Build graph while tracking roots. Break down graph while traversing from roots.
- [G] Graph Valid Tree - Build graph, start at zero, traverse it and expect no cycles, tree has n-1 edges.
- [G] Longest Consecutive Sequence - Store numbers in a dict along with before and after. BFS after to find the length.
- [G] Number of Connected Components in an Undirected Graph - Build graph, BFS through to break down the nodes.
- [G] Number of Islands - BFS-explore all island while mutating grid. Un-mutated afterwards.
- [G] Pacific Atlantic Water Flow - Reverse flow from each coast, intersect the results.
- [H] Find Median from Data Stream - Keep two heaps.
- [H] Top K Frequent Elements - Count and put everything in a heap.
- [I] Insert Interval - For overlaps, augment the interval's end continuously.
- [I] Meeting Rooms - Check if overlap.
- [I] Meeting Rooms II - Use heap to track "current" end times.
- [I] Merge Intervals - Sort intervals, add them in - if overlap, edit the last one's end.
- [I] Non-overlapping Intervals - Sort it, remove the one with a longer end.
- [L] Detect Cycle in a Linked List - Could do the slow/fast thing or just a simple hash.
- [L] Merge K Sorted Lists - Put all first elements in a heap, for each one that gets popped, add the next one.
- [L] Merge Two Sorted Lists - Straightforward pointer maintenance.
- [L] Remove Nth Node From End Of List - Give end a head start of n, go through to find the node, then do pointers.
- [L] Reorder List - Find the middle using the slow/fast trick, reverse the LL from the middle, merge.
- [L] Reverse Linked List - Keep previous while iterating.
- [M] Rotate Image - Figure out the loops - it depends on (n % 2). Manually figure out the rotation.
- [M] Set Matrix Zeroes - Check if first row/col should be zero, use those to memo zeros, another to set.
- [M] Spiral Matrix - Keep 4 pointers that narrow on each iteration. Iterate while sane.
- [M] Word Search - Recursive search through each element, mutate the board to mark visited.
- [S] Encode and Decode Strings - Use ord to make characters into ascii, chr to bring them back.
- [S] Group Anagrams - Create dict of 26-tuple to list of strings. Return the values.
- [S] Longest Palindromic Substring - Test center expansions around 2n + 1 centers, O(n^2) time.
- [S] Longest Repeating Character Replacement - Sliding window that increases in size when valid. Never contracts.
- [S] Longest Substring Without Repeating Characters - Iterate through and keep a set of seen-once characters. Keep it up to date.
- [S] Minimum Window Substring - After count, create window that is a superset. Slide and contract if possible.
- [S] Palindromic Substrings - Center expansion.
- [S] Valid Anagram - Compare counts.
- [S] Valid Palindrome - Python's .isalnum() helps.
- [S] Valid Parentheses - Use a stack, on open, push close. On close, check match.
- [T] Add and Search Word - Just a trie.
- [T] Binary Tree Level Order Traversal - BFS with a side array to push order.
- [T] Binary Tree Maximum Path Sum - Recursion while tracking connectable and not connectable max.
- [T] Construct Binary Tree from Preorder and Inorder Traversal - Find sub tree inorder and preorder and build recursively.
- [T] Implement Trie (Prefix Tree) - Implement a trie.
- [T] Invert Binary Tree - BFS or DFS while inverting.
- [T] Kth Smallest Element in a BST - Inorder while passing in remaining values.
- [T] Lowest Common Ancestor of BST - Find both paths, compare lists, and find ancestor.
- [T] Maximum Depth of Binary Tree - BFS or DFS while tracking height.
- [T] Same Tree - Traverse both, DFS or BFS is fine.
- [T] Serialize and Deserialize Binary Tree - Recursively create a raw version, use JSON after that.
- [T] Subtree of Another Tree - BFS with nested double BFS. Alternatively, recursion with same tree helper.
- [T] Validate Binary Search Tree - Check left and right, careful with range.
- [T] Word Search II - Build trie, try each position. Mutating input can track visited.