Algo Flashcards
- Sliding Window Median
Remember:
- Calc median must check left.size() - nRemovingLeft vs. right.size() - nRemovingRight not just only left.size() and right.size()
- Using 2 priority queues: add to left must compare to move it to right if needed
- LRU Cache
- Using DLinkedList for the rank. When moving rank to top must keep the same instance so that we don’t need to update keyToRanks.put(key, newRank)
- removeElement must update prev and next to null at the end
- Serialize and Deserialize N-ary Tree
Remember to add “+” at the end of the node string as a termination notation, otherwise, when reading digits it read the one of the next node string e.g.
1+0(ended)1+0: two-node with 0 children but when reading it because the first node with “01” = 1 child
- Construct Binary Tree from Inorder and Postorder Traversal
- Use inorderIndices of num -> index to split (start, end) in inorder array
- Only build retVal.right then retVal.left if its size > 0
- Using stack to store postorder
min & max & sum of array of ints
IntStream.of(ints).min().getAsInt()
IntStream.of(ints).max().getAsInt()
IntStream.of(ints).sum()
- Design Search Autocomplete System. Methods:
- AutocompleteSystem(String[] sentences, int[] times) {}
- List input(char c) {}
Using Trie and add times: Map to each node
- Maximum Sum of 3 Non-Overlapping Subarrays
- -> must find indices of arrays, not just the sum
- DP with memorization
- Loop through the cache to trace back e.g. find first, second …
- Using dfs(nums, end,…) instead of dfs(nums, start,…) to get the first match
- Delete Node in a BST
How to implement removeSmallest(TreeNode parent, TreeNode node): int
Go to left most node ultil node.left == null:
parent. left = parent.left == node ? node.right : parent.left;
parent. right = parent.right == node ? node.right : parent.right;
- Stickers to Spell Word
- dfs(int[] target, int[][] stickers, cache)
- remember dfs can return -1. Must check. Do not do like this:
Math.min(retVal, 1 + dfs(newTarget, stickers, cache)
- Longest Valid Parentheses
e. g. ()) -> 2
DP
- Best Time to Buy and Sell Stock IV
max k transactions
- Use int[][] transactions = new int[k][2]; // list of [min-price, max-profit so far]
- Initialize transactions[j][0] = prices[0];
- Start from idx = 1
- Best Meeting Point
- Loop through all rows and columns to collect house rows, house columns
- Find the median of these sets of rows and columns separately
- Remove Invalid Parentheses
return all longest valid strings
- Two options for each open, close: keep or remove
- Remember to check and stop if opens < closes
- Remember to:
resultBuilder.append(ch)
call dfs
remove last char in resultBuilder
- Minimum Window Substring
Input: s = “ADOBECODEBANC”, t = “ABC”
Output: “BANC”
- Calc freqs for t
2. Move pointer idx, increase currentFreqs, try to move left pointer, decrease currentFreqs to make idx - left smallest
- Minimum Window Subsequence
Input: s1 = “abcdebdde”, s2 = “bde”
Output: “bcde”
MUST maintain the order
- build closest array e.g. closest[j][0] the nearest ‘a’ to the left
- go from right to left of s1, find s1[idx] = s2 last char
- go from right to left of s2, find nextId = clostest[nextIdx - 1][ch - ‘a’]
Important notes: - use nextIdx - 1
- check nextIdx - 1 >= 0
- Palindrome Pairs
words[i] + words[j] is a palindrome.
Find all (i, j)
- create suffixes and prefixes set
- for each word check: suffix then prefix
- remember the case: ab, ba will appear twice because of 2. For case word == suffix/prefix, only pick in “check suffix” ignore in “check prefix”
- Data Stream as Disjoint Intervals
e.g. add 1, 1
add 2, 2
add 3, 3
return 1,3
use TreeMap
TreeMap methods, what throws an exception if empty?
- higherKey, lowerKey, floorKey, ceilingKey: null if empty
2. firstKey, lastKey: exception if empty
- LFU Cache
- using Rank i.e DLinkedList with prev, next, keys, freq
- JUST check case by case e.g. key does not exist, new freq does not exist, etc.
do not need to do abstract here - must be fast, this is very long
- Robot Room Cleaner
- use visit(robot, row, col, direction, cache)
2. directions must be consistent e.g. {0, -1} then {1, 0} then {0, 1} then {-1, 0}
- Zigzag Conversion
- if numRows == 1: return
- 2 cases:
a. first + last row
b. normal row
- Largest Divisible Subset
e.g. [1,2,3,4,5,6,7,8,9]
return [1,2,4,8]
- sort nums
- dp to calc largestSubsets[i]
- remember largestSoFar: int and largestNum in this largest so far
- trace back: right -> left
finding = largestSoFar, num = largestNum
find: nums[i] % num == 0 && largestSubsets[i] == finding then update:
*** num = nums[i]
- Prefix and Suffix Search
i. e. search(String prefix, String suffix): return largest idx
- using prefix & suffix Trie having Trie.wordIndices
- in search find prefixIndices and suffixIndices
- remember to reverse suffix before searching
- must use prefixIndices.get(i).equals(…) instead of ==
- Basic Calculator III
e. g. (1+2)/3
- 2 stacks: nums and opts
- remember idx++: not applied for reading operands
- rules:
a. meet num: eval if top = * or /
b. meet + or -: eval if top = + or -
c. meet ): eval ultil seeing (
d. after seeing (, must eval because of this case:
2 * (1+2)
- Sliding Puzzle
e. g. [[1, 2, 3], [4,0,5]] -> 1 swap to make [[1,2,3],[4,5,0]]
- must use BFS instead of normal dfs i.e. using seen to keep track of the path. This dfs with the depth of (mn)! call stack causes 2**(mn)! time complexity
- using int swaps to count the number of steps
- Swim in Rising Water
i. e. with raining, grid[i][j] is the height of the cell
- can only go from cell 1 to cell 2 if the height of 2 cells + water is the same
- use Math.max(top[0], maxHeight of 2 cells) for nei cell
- Sliding Window Maximum
k window, return max in the window for each move
- using dq/queue to achieve O(N)
2. store idx in dq instead of value
- Shortest Subarray with Sum at Least K
with negative nums
Note: use PriorityQueue of sum also works
1. using treeMap.put(preSum, last idx)
2. find floorEntry of currentSum - k, if found
keep trying then remove all keys before this floorKey
3. key here is (for both neg and positive shortest subarray problem): if 1 start point can pair with current idx, we can remove it because the next idx2 if can pair, the length idx2 - start is already > idx - start
- Super Egg Drop
n floors, k eggs –> how many moves
- using dp[moves][eggs] how many floors can be covered with this number of moves & eggs
- dp[moves][eggs] = 1 + dp[moves - 1][eggs] + dp[moves-1][eggs-1]
- remember to catch base case moves - 1 <= 0, eggs = 0 or 1
895. Maximum Frequency Stack pop the max freq, if same freq, pop the last added one e.g. push: 2 1 2 1 pop: 1 2 1 2
Observation: pop val, freq will decrease by 1 so for sure the freq - 1 will exist
- freqToVals: Map>
- maxFreq
- valToFreqs: current freq
- Number of Music Playlists
k: before can repeat the song e.g. k = 2: 1 2 3 1
input: k, songs, goal: playlist size
- dp: dp[songs][goal] = dp[songs - 1][goal - 1] * songs + dp[songs][goal - 1] * (songs - k)
- base cases: songs == goals && songs == k + 1
for: songs == k + 1: e.g. 3 songs, k = 2: always repeat the pattern
1 2 3 1 2 3… doesn’t matter the value of goals