Here are some interesting and useful tips for navigating through LeetCode. The majority of the code snippets are written in Python.
- Prefix sum (array): of
[1, 2, 3, 4, 5]
is[1, 3, 6, 10, 15]
.
1nums = [1, 2, 3, 4, 5]
2prefix_sum = [nums[0]]
3for i in range(1, len(nums)):
4 prefix_sum.append(prefix_sum[-1] + nums[i])
- Replace an array completely with another
1arr[:] = new_arr
- Use
dict.fromkeys(arr)
to keep the order of elements,set(arr)
doesn’t keep the order!
1list(dict.fromkeys([-1,0,0,0,0,3,3])) # [-1, 0, 3]
2list(set([-1,0,0,0,0,3,3])) # [0, 3, -1]
- “non-decreasing order” = the elements in the array are not strictly ascending like
[1,2,3,4,5]
, it could be[1,1,2,2,3]
.
- In LeetCode, the Runtime result isn’t consistent.
- Brute Force: An algorithm that generates and tests all possibilities until it finds a solution. While not efficient, it assures an answer if one exists.