π©βπ» { A JavaScript developer, who try to solves LeetCode problems using Python and Java )

with the nonlocal keyword, you can use the variable is declared outside the expand function, so it is part of the enclosing scope π
def outer_function():
count = 0
def expand():
nonlocal count # π Refers to the count variable in func scope
count += 1
print(count)
expand() # 1
expand() # 2
outer_function()
in the coin change problem, using BFS, because bfs guarantees finding the minimum number of coins. looking for the shortest path "smallest number of coins" to make the target amount. bfs is suitable, because it's with the smallest number of coins.
you can reverse sort by using sort(reverse=True) or sorted(reverse=True). (sort in descending order)
# reverse sort A
list.sort()
list.reverse()
# reverse sort B
list.sort(reverse=True)
deque vs queue.queue| Feature | collections.deque | queue.Queue |
|---|---|---|
| Thread Safety | Not thread-safe | Thread-safe |
| Performance | Fast O(1) for all operations | Slightly slower due to thread locks |
| Use Case | Single-threaded programs | Multithreaded programs |
| Extra Features | No size limit, can pop from both ends | maxsize, blocking operations |
deque (double-ended queue)deque is the better choice for general-purpose queues in python, especially for non-thread-safe use cases. it allows efficient popping from both ends (O(1) time complexity).
queue.queuequeue.queue is thread-safe and should be used in multithreaded programs to ensure data safety. however, its operations might be a bit slower than deque due to the internal locking mechanisms.
thread safety ensures that resources are accessed in a way that avoids issues when multiple threads are concurrently executing. it's essential in scenarios where resources (like a variable or a data structure) might be accessed simultaneously.
π it's a concept that helps prevent concurrency issues(λμμ± μ΄μ).
- Python's
queue.Queueis thread-safe by design, meaning you donβt need to add locks.- other thread-safe structures include:
queue.LifoQueue(stack-like behavior)queue.PriorityQueuecollections.deque(with manual lock handling for thread safety)
unpacking is a process where elements from an iterable (such as a list, tuple, or dictionary) are assigned to individual variables in a single step
| Type of Unpacking | Example | Description |
|---|---|---|
| Tuple Unpacking | person = ("John", 30, "Engineer") name, age, profession = person | Assigning elements of a tuple to separate variables. |
| List Unpacking | colors = ["red", "green", "blue"] color1, color2, color3 = colors | Assigning elements of a list to separate variables. |
| Dictionary Unpacking | person_info = {"name": "Alice", "age": 25, "city": "New York"} introduce(**person_info) | Passing dictionary key-value pairs as function arguments. |
| Extended Unpacking | numbers = [1, 2, 3, 4, 5] first, *rest, last = numbers | Capturing multiple elements of a list in a variable (rest in this case). |

tuple unpacking is used to assign values from a tuple (or iterable) directly to variables. this is especially useful when working with data structures like queues or lists where multiple values are returned and need to be handled together.
queue = deque([(amount, 0)]) # set deque with tuple
while queue:
remain, count = queue.popleft() # unpacking queue
for-each Loop in javause for loop with the :(in) operator (for (Type element : collection))
for (int num in nums) {}

to solve the group anagrams problem, use a hash map with the sorted string as the key and the list of anagrams as the value. so we don't store duplicates like above example.
defaultdict(list) (helpful to automatically create needed empty datatype for new key)https://docs.python.org/3/library/collections.html#collections.defaultdict
return a new dictionary-like object. defaultdict is automatically create empty value for new keyπ
# use {}
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
result = {}
for str in strs:
sorted_key = ''.join(sorted(str))
if sorted_key not in result:
result[sorted_key] = []
result[sorted_key].append(str)
return list(result.values())
# use defaultdict
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
result = defaultdict(list)
for str in strs:
sorted_key = ''.join(sorted(str))
result[sorted_key].append(str)
return list(result.values())
# set for different types
defaultdict(list)
defaultdict(dict)
defaultdict(tuple)
sorted_key = ''.join(sorted(str))
char[] chars = str.toCharArray();
Arrays.sort(chars);
String sortedStr = new String(chars);
if sortedStr not in mapmap.putIfAbsent(sortedStr, new ArrayList<>());
result.get(sortedStr).add(str);