
241221
to avoid processing redundant duplicate values in problems like 3Sum
π skip duplicates, using conditions and multiple pointers.(indices)
π ensures that you don't include duplicate triplets in the result, such as [[1, 0, -1], [1, 0, -1]]
def threeSum(self, nums: List[int]) -> List[List[int]]: nums.sort() # TC: O(n log n), SC: O(1) result = [] # result are part of the output => do not count toward auxiliary (extra) space. for i in range(len(nums)): # TC: O(n^2) if i > 0 and nums[i] == nums[i - 1]: continue j = i + 1 k = len(nums) - 1 while j < k: currSum = nums[i] + nums[j] + nums[k] if currSum < 0: j += 1 elif currSum > 0: k -= 1 else: result.append([nums[i], nums[j], nums[k]]) while j < k and nums[j] == nums[j + 1]: j += 1 while j < k and nums[k] == nums[k - 1]: k -= 1 j += 1 k -= 1 return result
if i > 0 and nums[i] == nums[i - 1]:
continue
while j < k and nums[j] == nums[j + 1]:
j += 1
while j < k and nums[k] == nums[k - 1]:
k -= 1
results not count toward auxiliary (extra) space?when evaluating space complexity, result is considered as part of the output rather than extra space.
Auxiliary space(보쑰 곡κ°) refers to the additional memory used by the algorithm, excluding the input and output. This typically includes variables, temporary data structures, and extra memory required during execution.
Total space(μ 체 곡κ°) includes both the auxiliary space and the space used by the input and output.
π in a problem 3Sum, the result array holds the triplets, that considered as part of the output. so it doesnβt contribute to auxiliary space. It is simply the memory space used to store the answer, which is part of the final result.
- Construct Binary Tree from Preorder and Inorder Traversal: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
in preorder traversal, the root node is processed before its left and right subtrees.
The order of processing is:
in inorder traversal, the left subtree is processed first, followed by the root node, and then the right subtree.
in a bst, inorder traversal produces the nodes in sorted order.
preorder traversal: Root β Left β Right
inorder traversal: Left β Root β Right
enumerate() is a built-in function that adds a counter to an iterable and returns it as an enumerate object. Itβs often used in loops when you need both the index and the value of items in a list.
for index, value in enumerate(inorder):
print(index, value)
iter(preorder)
iterator is an object that can be iterated (looped) upon, returns one element at a time when you use the next() function.
using iterators can help with efficient memory usage when processing large data or streams.
π to convert an iterable into an iterator in python => use iter().
preorder = [3, 9, 20, 15, 7]
preorder_iter = iter(preorder)
print(next(preorder_iter)) # Output: 3
print(next(preorder_iter)) # Output: 9