-
LeetCode 15: 3Sum
link Time: , space: . Sorting helps in two ways: Time: , space: sorting’s worst-case, . Instead of sorting, we could use one set to de-duplicate first elements and a second set to to find the (second, third) pair in a single scan. Time: , space: .
-
LeetCode 121: Best Time to Buy and Sell Stock
link Profit is (sell-buy). For each possible buy, we find the best sell (max day’s price) in the future. Time: , space: . Going through the days in sequence, we keep track of the best_buy; therefore, the minimum price seen so far. Everyday we consider selling and to compute the max_profit for that day we…
-
LeetCode 45: Jump Game II
link Time: , space: . For a sub-problem nums[0:j] find furthest reachable index given 1, 2, …, j jumps. Keep extending the sub-problem to nums[0:n]. Now, find the least jump_count to reach the last index. With one jump, the furthest we can go is nums[0]. We keep moving to indices (1, 2, …, n-1) in…
-
LeetCode 670: Maximum Swap
link A swap cannot increase numbers like below: We need an increasing pair. Those two numbers will be candidate for swap. We can improve the right. Given the improved right, now we can also improve the left. Time: , space: .
-
LeetCode 1404: Number of Steps to Reduce a Number in Binary Representation to One
link Time: , space: . Observations Or, more concisely:
-
LeetCode 455: Assign Cookies
link If we cannot satisfy the least greedy kid with the smallest cookie, we cannot satisfy any other kid with that cookie. Time: , space: . Although does not improve worst case, to reduce waste, we can match more than one compatible (cookie, kid)-pairs at once. To improve space complexity we could trade heap for…
-
LeetCode 2384: Largest Palindromic Number
link For a digit, instances of it can be placed at the two ends of a palindrome. If there is one instance of the digit still left, it can be the center. In both cases, we should pick largest digit first. The palindrome cannot have leading zeros. We have a leading zero if pal_half‘s first…