My code can be viewed in my github: Proverbs Github.
The following difficulty is defined by myself.
add-digits(easy)
- Time complexity: It is hard to tell, I think it should be O(num_of_digits).
- Space complexity: O(1).
add-two-numbers-ii(medium)
It is easy if we can modify the structure of the linked lists: we can reverse and add these two linked lists and then reverse back.
Without changing the structure, we should first align these two linked lists and then concatenate the remaining part.
A trick is to ignore the carry numbers when adding two linked list and to handle carry numbers after concatenation.
- Time complexity: O(n).
- Space complexity: O(n).
binary-tree-vertical-order-traversal(medium)
BFS. It is easy to use map to handle negative index although it may increase time complexity.
The best way is to use doubly linked list or calculate the left-most depth and the right-most depth using dfs.
- Time complexity: O(nlogn), but can be optimized to O(n).
- Space complexity: O(nlogn).
intersection-of-two-arrays(easy)
If the result should be in order according to nums1, we can binary serach nums2. Or we can use map directly.
- Time complexity: O(nlogn).
- Space complexity: O(n).
max-stack(hard)
Again, I made some mistake using iterator. And finally, I replace iterator with linked list.
Use linked list as the underlying data structure of stack. At the same time, we should maintain a priority_queue to retrieve the max element.
A trick is to use lazy delete because we cannot find the corresponding element in the other data structure when removing from either priority_queue or stack.
- Time complexity: O(nlogn).
- Space complexity: O(n).
word-search-ii(medium)
DFS in the trie and board
at the same time.
However, in the worst case, it is the same as brute force because the number of nodes in the trie can be the same as total number of letters of all words.
- Time complexity: O(lengthwidthn*m) where m is the average length of letters.
- Space complexity: O(nm+lengthwidth).
pour-water(hard)
The simplest way is to do as shown in the description.
However, we can find that for the left side, the only thing we need to do is to find the right-most smallest number in the non-decreasing sequence left to index K
.
This can be maintained using a priority_queue.
The key point is to store the left-most position the priority_queue has reached which is mono-decreasing.
For the right side, it is the same as the left side.
- Time complexity: O(VlogN).
- Space complexity: O(N).