Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SunaDu] Week 6 #901

Merged
merged 5 commits into from
Jan 18, 2025
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions container-with-most-water/dusunax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
'''
# 11. Container With Most Water

use two pointers to find the maximum area.

> **move the shorter line inward:**
> - area is determined by the shorter line.
> - move the shorter line inward => may find a taller line that can increase the area.

## Time and Space Complexity

```
TC: O(n)
SC: O(1)
```

### TC is O(n):
- while loop iterates through the height array once. = O(n)

### SC is O(1):
- using two pointers and max_area variable. = O(1)
'''

class Solution:
def maxArea(self, height: List[int]) -> int:
left = 0
right = len(height) - 1
max_area = 0

while left < right: # TC: O(n)
distance = right - left
current_area = min(height[left], height[right]) * distance
max_area = max(current_area, max_area)

if height[left] < height[right]:
left += 1
else:
right -= 1

return max_area
67 changes: 67 additions & 0 deletions design-add-and-search-words-data-structure/dusunax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
'''
# 211. Design Add and Search Words Data Structure

use trie to perform add and search operations on words.
use recursive dfs to search for words with "." wildcards.

## Time and Space Complexity

### addWord

```
TC: O(n)
SC: O(n)
```

### TC is O(n):
- iterating through each character of the word. = O(n)

### SC is O(n):
- storing the word in the trie. = O(n)

### search

```
TC: O(n)
SC: O(n)
```

### TC is O(n):
- dfs iterates through each character of the word. = O(n)
- if char is "."(wildcard) dfs iterates through all children of the current node. = O(n)

> recursion for the wildcard could involve exploring several paths.
> but time complexity is bounded by the length of the word, so it's still O(n).

### SC is O(n):
- length of the word as recursive call stack. = O(n)
'''
class WordDictionary:
def __init__(self):
self.trie = {}

def addWord(self, word: str) -> None:
node = self.trie
for char in word: # TC: O(n)
if char not in node:
node[char] = {}
node = node[char]
node["$"] = True

def search(self, word: str) -> bool:
def dfs(node, i) -> bool:
if not isinstance(node, dict):
return False
if i == len(word):
return "$" in node if isinstance(node, dict) else False
char = word[i]

if char == ".":
for child in node.values():
if dfs(child, i + 1):
return True
return False
else:
return dfs(node[char], i+1) if char in node else False

return dfs(self.trie, 0)
58 changes: 58 additions & 0 deletions longest-increasing-subsequence/dusunax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
'''
# 300. Longest Increasing Subsequence

use the sub list to store current LIS.
iterate nums's elements and find the position of the current number in the subsequence. (using a binary search helper function)
after the iteration finishes, return the length of the subsequence.

> **helper function explanation:**
> ```py
> position = bisectLeft(sub, num)
> ```
> bisectLeft is doing binary search that finds the leftmost position in a sorted list.
>if the position is the end of the subsequence, append the current number to the subsequence.
>if the position is not the end of the subsequence, replace the number at the position with the current number.

> **python's bisect module:**
> https://docs.python.org/3.10/library/bisect.html

## Time and Space Complexity

```
TC: O(n log n)
SC: O(n)
```

#### TC is O(n log n):
- iterating through the nums list to find the position of the current number. = O(n)
- using a binary search helper function to find the position of the current number. = O(log n)

#### SC is O(n):
- using a list to store the subsequence. = O(n) in the worst case
'''
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
sub = [] # SC: O(n)

for num in nums: # TC: O(n)
pos = self.bisectLeft(sub, num) # bisect.bisect_left(sub, num) = TC: O(log n)
if pos == len(sub):
sub.append(num)
else:
sub[pos] = num

return len(sub)

def bisectLeft(self, list, target) -> int:
low = 0
high = len(list) - 1

while low <= high :
mid = int(low + (high - low) / 2)

if list[mid] < target:
low = mid + 1
else:
high = mid - 1

return low
Comment on lines +46 to +58
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bisectLeft 를 따로 함수로 빼셔서 각 함수들의 목적이 명확해 진 것 같아 넘 좋은것 같아요!

41 changes: 41 additions & 0 deletions valid-parentheses/dusunax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
'''
# 20. Valid Parentheses

use stack data structure to perform as a LIFO

## Time and Space Complexity

```
TC: O(n)
SC: O(n)
```

#### TC is O(n):
- iterating through the string just once to check if the parentheses are valid. = O(n)

#### SC is O(n):
- using a stack to store the parentheses. = the worst case is O(n)
- using a map to store the parentheses. = O(1)

> for space complexity, fixed space is O(1).
> 👉 parentheses_map is fixed and its size doesn't grow with the input size.
> 👉 if the map has much larger size? the space complexity is still O(1).
'''

class Solution:
def isValid(self, s: str) -> bool:
stack = [] # SC: O(n)
parentheses_map = { # SC: O(1)
"(": ")",
"{": "}",
"[": "]"
}
Comment on lines +28 to +32
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

map 을 사용하지 않고 푸는 방법도 도전해도시면 재미있을것 같아요 :)


for char in s: # TC: O(n)
if char in parentheses_map:
stack.append(char)
else:
if len(stack) == 0 or parentheses_map[stack.pop()] != char:
return False

return not stack
Loading