LC Templates
Dp
Dp is about managing states.
- Use dictionary, arrays
Bottom up DP
- Find recursive relation
- Recurse on target (target must thus be outer loop since we are building up answers using target-1)
- Find base case
- May need to construct extra row for ease of calculation
- Find edge case
- ie: handle impossible cases, input not big enough for target
Top down
Sliding Window
Template 1
Keep L(left side of window) tracker
- Remove left element if window already size k
- L-R > k
- Increment L
- Add current element
- Check if conditions are met
Alternative way to store window
- dictionary of
{e: ind}
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
d = {}
for i, n in enumerate(nums):
if n in d and i - d[n] <= k:
return True
d[n] = i
return False
Template 2
Keep L tracker
- Update relevant counters
- Update window (while loop)
- Remove left side until constraints are satisfied again
- Update result if needed