Array
In-place Manipulation (works for string as well)
usually use two pointer: a slow pointer and a fast pointer
If the output has smaller size than the input, loop forward.
If the output has larger size than the input, assign the full size first and then loop backward.
If the output may have smaller or larger size, assign a new array may be easier than in-place manipulation.
Example question:
leetcode 27_Remove Element
Two pointers
One slow, one fast
One loop forward, one loop backward (usually used when we need to check symmetric properties)
Two pointer for two sorted arrays
Example questions:
88_Merge Sorted Array
349_Intersection of Two Arrays
350_Intersection of Two Arrays II
Multiple passes
In some questions, it's hard to compete everything in one pass. In this case, we can use two passes or even more.
Use dynamic programming
update dynamically (usually the question ask for maximum or minimum)
Use hash table/dictionary
If when loop over each element in the array, we need to do a second loop over (at least part of) the array such that these two loops together meets the condition, we can only do one loop and use hash table / set to store the corresponding information.
Example questions:
1_Two Sum
Add Digits and Carry (数组相加要进位)
loop from rightmost to left
set up carry variable to store carry values
typical questions: Q66, Q67
Related to intervals
Sort the interval first
Example questions:
56_Merge Intervals
57_Insert Interval
Notes
When we do loop over the array, it's better to loop over index rather than each element. Because even though we think element is enough at the beginning, we may find we need index later. This happens to me a lot of times!
Last updated