LC 27, 26, 283, 844, 977
LC 27
Remove the elem from a list (array). The intuitive approach is to use list methods like remove, pop. However, noted that the list.remove(val)
only removes the first val
from the list which matches the specified value, and list.pop(N)
takes time O(n)
, where list.pop()
takes time O(1)
.
# lc 704
def remove_element(self, nums: List[int], val: int) -> int:
slow_ind = 0
for fast_ind in range(len(nums)):
if nums[fast_ind] != val:
nums[slow_ind] = nums[fast_ind]
slow_ind += 1
return slow_ind
Logic
- Duo pointers methods: Credit to Carl.
fast_ind
points to the value in the original list,slow_ind
points to the new index that is supposed to be place the old elem.
- Overwrite happens only if the
fast_ind
points to the value that is not removed. Meanwhile, the next index,slow_ind
, is updated.
LC 26
26. Remove Duplicates from Sorted Array
Logic
- Analogue to LC27, but change the overwrite condition to
nums[fast_ind] != nums[fast_ind - 1]
.
Other approaches
- Intuitive but not stable:
nums[:] = list(set(nums))
return len(nums)
- stable:
nums[:] = list(dict.fromkeys(nums))
return len(nums)
LC 283
Logic:
- Analogue to LC 27, consider
0
as the elem to be removed. - After moving forward other elems, use
nums[slow:] = [0] * (len(nums) - slow)
to overwrite the rest of the list.
LC 844
Logic:
- Haven’t figured out how to do this with duo ptr yet.
- The intuition gives:
if nums[fast] == "#":
slow -= 1
else:
keep the same way...
Not sure…
- My approach:
- Since python don’t allow to change string by indexing.
.append(val)
when not “#”, backspace.pop()
when is a backspace
- works like a charm.
- Since python don’t allow to change string by indexing.
LC 977
977. Squares of a Sorted Array
- intuitive:
which gives a time complexitymap(square, nums) nums.sort()
O(n log n)
, thanks to the sorting. - Cases division and merge:
neg_lst = [negative values in nums]
pos_lst = [positive values in nums]
map(square, neg_lst)
map(square, pos_lst)
neg_lst.reverse()
return merge(neg_lst, pos_lst)
Logic:
- merge keep the returned list in non-decreasing order.
Summary:
- Duo ptr is the GOD! hhh
- On other questions, I was just going with the first-site thoughts.
- Study period: EST 13PM - 16PM, 3hrs.
PS:
- Conditions for using duo ptrs:
- Change the treversing order, see LC 977.
- Slow, fast ptr, where two ptr are representing the different states of the system, see LC 27.
- TBD…