LeetCode TIL 250101~05

두선아 DusunaΒ·2025λ…„ 1μ›” 5일

algorithm

λͺ©λ‘ 보기
8/14

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


Solved Problems πŸ“


Key Learnings πŸ€”


what is nonlocal keyword in python

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()

approach to coin change problem (BFS)

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.


reverse sorting in python

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)

queues in python: deque vs queue.queue

Featurecollections.dequequeue.Queue
Thread SafetyNot thread-safeThread-safe
PerformanceFast O(1) for all operationsSlightly slower due to thread locks
Use CaseSingle-threaded programsMultithreaded programs
Extra FeaturesNo size limit, can pop from both endsmaxsize, 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.queue

queue.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.


what is thread safety?

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.Queue is thread-safe by design, meaning you don’t need to add locks.
  • other thread-safe structures include:
    • queue.LifoQueue (stack-like behavior)
    • queue.PriorityQueue
    • collections.deque (with manual lock handling for thread safety)

unpacking tuple in python

what is unpacking?

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 UnpackingExampleDescription
Tuple Unpackingperson = ("John", 30, "Engineer")
name, age, profession = person
Assigning elements of a tuple to separate variables.
List Unpackingcolors = ["red", "green", "blue"]
color1, color2, color3 = colors
Assigning elements of a list to separate variables.
Dictionary Unpackingperson_info = {"name": "Alice", "age": 25, "city": "New York"}
introduce(**person_info)
Passing dictionary key-value pairs as function arguments.
Extended Unpackingnumbers = [1, 2, 3, 4, 5]
first, *rest, last = numbers
Capturing multiple elements of a list in a variable (rest in this case).
  • can't unpack non-iterable object

tuple unpacking

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 java

https://www.w3schools.com/java/java_foreach_loop.asp

use for loop with the :(in) operator (for (Type element : collection))

for (int num in nums) {}

approach to group anagrams problem

wrong answer

  • need to remove duplicates

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.

  • sorting each string and using it as a key.
  • the use of defaultdict(list) (helpful to automatically create needed empty datatype for new key)

what is defaultdict()?

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(str) will return a list like ["a", "b", "c"], list can't be the key of the hashmap.
sorted_key = ''.join(sorted(str))

sorting strings in java

  • sorting and join string
char[] chars = str.toCharArray(); 
Arrays.sort(chars); 
String sortedStr = new String(chars);
  • if sortedStr not in map
map.putIfAbsent(sortedStr, new ArrayList<>());
  • get hashmap element & add append
result.get(sortedStr).add(str);
profile
μ•ˆλ…•ν•˜μ„Έμš”.

0개의 λŒ“κΈ€