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] Week8 #971

Merged
merged 5 commits into from
Feb 1, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
35 changes: 35 additions & 0 deletions clone-graph/dusunax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
'''
# 133. Clone Graph
This is the problem for copying nodes, which helps you understand the concept of referencing a node & copying the node (creating a new node from the existing one).

👉 Perform recursion DFS with the correct escape condition and handling of NoneType.
'''

"""
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
"""
from typing import Optional
class Solution:
def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
if node is None:
return None

visited = {}

def DFS(currNode):
if currNode.val in visited:
return visited[currNode.val]

copiedNode = Node(currNode.val)
visited[currNode.val] = copiedNode

for neighbor in currNode.neighbors:
copiedNode.neighbors.append(DFS(neighbor))

return copiedNode

return DFS(node)
27 changes: 27 additions & 0 deletions longest-common-subsequence/dusunax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
'''
# 1143. Longest Common Subsequence

use DP table.

> key: tuple(current index in text1, current index in text2)
> value: LCS of text1[i:] and text2[j:]
'''
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
dp = {}

def helper(i, j):
if i == len(text1) or j == len(text2):
return 0

if (i, j) in dp:
return dp[(i, j)]

if text1[i] == text2[j]:
dp[(i, j)] = 1 + helper(i + 1, j + 1)
else:
dp[(i, j)] = max(helper(i + 1, j), helper(i, j + 1))

return dp[(i, j)]

return helper(0, 0)
32 changes: 32 additions & 0 deletions longest-repeating-character-replacement/dusunax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
'''
# 424. Longest Repeating Character Replacement

use sliding window to find the longest substring with at most k replacements.

## Time and Space Complexity

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

class Solution:
def characterReplacement(self, s: str, k: int) -> int:
freq = [0] * 26 # A~Z, SC: O(1)
left = 0
max_freq = 0
result = 0

for right in range(len(s)): # TC: O(n)
curr_char_index = ord(s[right]) - 65
freq[curr_char_index] += 1
max_freq = max(max_freq, freq[curr_char_index])

if (right - left + 1) - max_freq > k:
freq[ord(s[left]) - 65] -= 1
left += 1

result = max(result, right - left + 1)

return result
4 changes: 4 additions & 0 deletions number-of-1-bits/dusunax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
class Solution:
def hammingWeight(self, n: int) -> int:
binary_string = bin(n).replace('0b', '');
return binary_string.count('1');
53 changes: 53 additions & 0 deletions sum-of-two-integers/dusunax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
'''
# 비트 연산 Bit Manipulation

## 이진수 덧셈 binary addition

이진수에서 두 비트를 더하기

1. XOR: 올림수를 제외한 합
2. AND << 1: 올림수를 계산
3. 1~2를 carry가 0일 때까지 반복

```
while b:
carry = (a & b) << 1 # 올림수를 계산
a = (a ^ b) # 합
b = carry # 캐리가 남아있다면 계속 계산
```

## 32비트 오버플로우 제거

- 0xFFFFFFFF는 모든 비트가 1입니다.

Python의 int는 크기 제한이 없어서 연산 중 비트 수가 자동 확장됩니다.
MASK(0xFFFFFFFF)와 and 연산을 사용해 32비트 오버플로우를 방지합니다.

```
MASK = 0xFFFFFFFF
a = (a ^ b) & MASK # 32비트가 넘어가면 초과 비트가 제거됨
b = carry & MASK
```

## 음수 처리

- 0x7FFFFFFF(2147483647) 이하는 양수(Positive Number).
- 0x80000000(2147483648) 이상이면 음수(Negative Number)

`a > MAX_INT(0x7FFFFFFF)`인 경우, 32비트 환경에서 음수 값임을 의미합니다.

```
~(a ^ MASK) # 32비트 음수 변환
```
'''
class Solution:
def getSum(self, a: int, b: int) -> int:
MASK = 0xFFFFFFFF
MAX_INT = 0x7FFFFFFF

while b:
carry = (a & b) << 1
a = (a ^ b) & MASK
b = carry & MASK

return a if a <= MAX_INT else ~(a ^ MASK) # a가 MAX_INT보다 크면 32비트 환경에서 음수이므로 변환