Skip to content

[bhyun-kim, 김병현] Week 4 solutions #88

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

Merged
merged 5 commits into from
May 26, 2024
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
65 changes: 65 additions & 0 deletions counting-bits/bhyun-kim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
"""
338. Counting Bits
https://leetcode.com/problems/counting-bits/description/

Solution 1:
- Convert the number to binary string
- Sum the number of 1s in the binary string
- Append the sum to the output list
- Return the output list

Time complexity: O(nlogn)
Copy link
Member

Choose a reason for hiding this comment

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

빨리 제출하셨으니, 혹시 $O(n)$으로 해결할 수 있는 방법이 있을지도 고민해보시면 좋을 것 같습니다.

Copy link
Contributor

Choose a reason for hiding this comment

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

확실히 이 문제는 보통 nlog(n)으로 먼저 푸시는 분들이 많군요.

Copy link
Member

@DaleSeo DaleSeo May 23, 2024

Choose a reason for hiding this comment

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

네, $O(n log n)$ 코드도 OA에서는 통과할 수 있는 충분히 좋은 솔루션으로 생각합니다. 하지만 on-site나 화상 인터뷰에서는 면접관의 성향의 따라서 시간이 되는 경우 지원자가 최적 알고리즘을 찾도록 압박하는 경우도 있어서 피드백 드렸습니다.

Copy link
Contributor

Choose a reason for hiding this comment

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

그렇군요. 즉석에서 풀려고 하면 쉽지 않을 것 같으니 여러가지 풀이를 연습해야겠습니다.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Dynamic Programming을 이용해서 $O(n)$ 솔루션으로 고쳐봤습니다.

- The for loop runs n times
- The sum function runs O(logn) times

Space complexity: O(n)
- The output list has n elements

class Solution:
def countBits(self, n: int) -> List[int]:
output = []
for i in range(n + 1):
_str = str(bin(i))[2:]
_sum = sum(map(int, _str.strip()))
output.append(_sum)

return output
"""

"""
Solution 2
We can solve this problem with dynamic programming.
1. Initialize output with n elements
2. The first element is 0 because iteration starts from zero.
3. Iterate from 1 to n+1
4. The last digit of each number is 0 for even number 1 for odd number
So add (i & 1) to the output
5. The digits except the last one can be found when the number is divided by two.
Instead for division by two, we can use one step of bit shift to the right.

0 = 00000
1 = 00001
2 = 00010
3 = 00011
4 = 00100
5 = 00101
6 = 00110
7 = 00111

Time complexity: O(n)
- The for loop runs n times

Space complexity: O(n)
- The output list has n elements
"""

from typing import List

class Solution:
def countBits(self, n: int) -> List[int]:
output = [0] * (n+1)

for i in range(1, n+1):
output[i] = output[i >> 1] + (i & 1)

return output
46 changes: 46 additions & 0 deletions group-anagrams/bhyun-kim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"""
49. Group Anagrams
https://leetcode.com/problems/group-anagrams/description/

Solution:
- Create a hash table and a list of counters
- For each string in the input list:
- Sort the string
- If the sorted string is in the hash table:
- Append the string to the corresponding counter list
- Else:
- Add the sorted string to the hash table
- Create a new counter list and append the string
- Return the list of counters

Time complexity: O(nmlogm)
- The for loop runs n times
- The sorted function runs O(mlogm) times
- m is the length of the longest string in the input list

Space complexity: O(n)
- The output list has n elements
- The hash table has n elements
- The list of counters has n elements
"""

from typing import List


class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:

hash_table = dict()
output = []

for s in strs:
count_s = ''.join(sorted(s))
if count_s in hash_table:
idx = hash_table[count_s]
output[idx].append(s)
else:
hash_table[count_s] = len(output)
output.append([s])

return output

29 changes: 29 additions & 0 deletions missing-number/bhyun-kim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""
268. Missing Number
https://leetcode.com/problems/missing-number/description/

Solution:
- Sort the input list
- For each index in the input list:
- If the index is not equal to the element:
- Return the index
- Return the length of the input list

Time complexity: O(nlogn+n)
- The sort function runs O(nlogn) times
- The for loop runs n times

Space complexity: O(1)
- No extra space is used
"""
from typing import List


class Solution:
def missingNumber(self, nums: List[int]) -> int:
nums.sort()
for i in range(len(nums)):
if i != nums[i]:
return i

return len(nums)
31 changes: 31 additions & 0 deletions number-of-1-bits/bhyun-kim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""
191. Number of 1 Bits
https://leetcode.com/problems/number-of-1-bits/

Solution:
- Create a counter
- For each bit in the input number:
- If the bit is 1:
- Increment the counter
- Return the counter

Time complexity: O(1)
- The while loop runs 32 times

Space complexity: O(1)
- No extra space is used
"""


class Solution:
def hammingWeight(self, n: int) -> int:
output = 0

i = 1 << 31
while i > 0:
if (n & i) != 0:
output += 1

i = i >> 1

return output
26 changes: 26 additions & 0 deletions reverse-bits/bhyun-kim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""
190. Reverse Bits
https://leetcode.com/problems/reverse-bits/description/

Solution:
- Convert the number to binary string
- Reverse the binary string
- Convert the reversed binary string to integer
- Return the integer

Time complexity: O(1)
- The bin function runs once
- The reversed function runs once
- The int function runs once

Space complexity: O(1)
- No extra space is used

"""


class Solution:
def reverseBits(self, n: int) -> int:
n_bin = bin(n)[2:].zfill(32)
n_bin = "".join(reversed(n_bin))
return int(n_bin, base=2)