Skip to content

[Chaedie] Week 1 #625

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 9 commits into from
Dec 13, 2024
21 changes: 21 additions & 0 deletions contains-duplicate/Chaedie.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@


'''
풀이:
중복된 요소가 있는지 찾는 문제입니다.

hash set 으로 중복을 제거하고
기존 nums 의 길이와 중복 제거된 nums_set 의 길이가 같은지 return 했습니다.

시간 복잡도:
O(n) - has set 을 만드는 시간

공간 복잡도:
O(n) - n개의 요소를 set에 담기 때문
'''


class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
nums_set = set(nums)
return len(nums_set) != len(nums)
103 changes: 103 additions & 0 deletions house-robber/Chaedie.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
'''
Solution:
스스로 풀지 못해 학습만 진행했습니다.
다음 기회에 다시 풀어보도록 하겠습니다.
'''
class Solution:
def rob(self, nums: List[int]) -> int:
prev, curr = 0, 0
for num in nums:
prev, curr = curr, max(num + prev, curr)

return curr


# class Solution:
# '''
# 4. 달레의 코드 풀이 - DP, prev, curr
# O(n) time
# O(1) space
# '''

# # 달레의 코드 풀이 - DP, prev, cur

# def rob(self, nums: List[int]) -> int:
# prev, curr = 0, 0
# for num in nums:
# prev, curr = curr, max(num + prev, curr)

# return curr

# '''
# 3. 달레의 코드 풀이 - DP
# [1,2,3,1]
# [1, 2, 3, 1]
# DP:[0, 1, 2, 4, 4]
# MAX(1 + DP[2], DP[1]) = MAX(1 + 2, 4) = 4
# '''
# # 달레의 코드 풀이 - DP
# # def rob(self, nums: List[int]) -> int:
# # dp = [0] * (len(nums) + 1)
# # dp[1] = nums[0]
# # for n in range(2,len(nums) + 1):
# # dp[n] = max(nums[n - 1] + dp[n - 2], dp[n - 1])
# # return dp[-1]
# '''
# 2. 달레의 코드 풀이 - 재귀, 메모이제이션
# time: O(n)
# space: O(n)
# '''
# # 달레의 코드 풀이 - 재귀, 메모이제이션
# # def rob(self, nums: List[int]) -> int:
# # memo = {}

# # def dfs(start):
# # if start in memo:
# # return memo[start]
# # if not start < len(nums):
# # memo[start] = 0
# # else:
# # memo[start] = max(nums[start] + dfs(start + 2), dfs(start + 1))
# # return memo[start]
# # return dfs(0)
# '''
# 1. 달레의 코드 풀이 - 재귀
# time: O(2^n)
# space: O(n)

# F([1,2,3,1]) => MAX(1 + F([3,1], f([2,3,1])))
# F([3,1]) => MAX(3 + F([]), F([1]))
# F([]) => 0
# F([1]) => MAX(1 + F([]), F([])) => MAX(1 + 0, 0) => 1
# F([]) => 0
# F([]) => 0
# F([2,3,1]) => MAX(2 + F([1]), F([3,1]))
# F([1]) => MAX(1 + F([]), F([])) => MAX(1 + 0, 0) => 1
# F([]) => 0
# F([]) => 0
# F([3,1]) => MAX(3 + F([]), F([1]))
# F([]) => 0
# F([1]) => MAX(1 + F([]), F([])) => MAX(1 + 0, 0) => 1
# F([]) => 0
# F([]) => 0
# 재귀가 불필요하게 반복되고 있다.
# 메모이제이션으로 기억해두면 반복은 스킵할 수 있다.
# '''
# # 달레의 코드 풀이 - 재귀
# # def rob(self, nums: List[int]) -> int:

# # def dfs(start):
# # if not start < len(nums):
# # return 0
# # return max(nums[start] + dfs(start + 2), dfs(start + 1))
# # return dfs(0)

# # neetcode 풀이 - DP, 이해안됨...
# # def rob(self, nums: List[int]) -> int:
# # rob1, rob2 = 0, 0
# # # [rob1, rob2, n, n+1, ...]
# # for n in nums:
# # temp = max(n + rob1, rob2)
# # rob1 = rob2
# # rob2 = temp
# # return rob2
46 changes: 46 additions & 0 deletions longest-consecutive-sequence/Chaedie.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"""
Solution:
0. i will use prev, cur pointers in for loop,
so i have to get rid of edge case when len of nums is at most 1
1. use hash set for remove duplicate elements
2. sort list
3. iterate sorted_nums and use two pointers (prev, cur)
compare prev and cur and count if the difference is 1
4. use max method, memorize maxCount
5. return maxCount

Time Complexity:
1. remove duplicate by hash set -> O(n)
2. sort the list -> O(n log n)
3. iterate sorted_nums -> O(n)

so time complexity of this solution will be O(n log n)

Space Complexity:
1. set() -> O(n)
2. sorted_nums -> O(n)
3. count , maxCount -> O(1)

space complexity of this solution will be O(n)
Comment on lines +12 to +24
Copy link
Contributor

Choose a reason for hiding this comment

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

Big O 분석 정성스럽게 해주시는 것 아주 모범적입니다 :) bb

"""


class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
if len(nums) <= 1:
return len(nums)

sorted_nums = sorted(list(set(nums)))

count = 1
maxCount = 1
for i in range(1, len(sorted_nums)):
prev = sorted_nums[i - 1]
cur = sorted_nums[i]
if prev + 1 == cur:
count += 1
maxCount = max(count, maxCount)
else:
count = 1

return maxCount
30 changes: 30 additions & 0 deletions top-k-frequent-elements/Chaedie.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""
Solution:
1. make a dictionary of (index, Frequency)
2. sort the items of dictionary by Frequency
3. return list of Top k Frequent Elements

Time Complexity:
1. iterate nums for counting -> O(n)
2. sort -> O(n log n)
3. iterate list for making return value -> O(n)

So Time complexity of this solution is O(n log n)

Space Complexity:
1. dictionary for counting frequency of nums -> O(n)
2. Timsort's space overhead -> O(n)
3. sorted List -> O(n)

Space complexity of this solution is O(n)
"""


class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
counts = defaultdict(int)
for num in nums:
counts[num] += 1

result = sorted(counts.items(), key=lambda x: x[1], reverse=True)
Copy link
Contributor

Choose a reason for hiding this comment

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

python의 built-in sort 알고리즘을 찾아보니 Timsort라는 것을 사용하는 것 같은데, 이게 merge sort의 일종이라는 것을 알게 되었습니다 (링크)

결과적으로 해당 풀이의 space complexity가 변하진 않겠지만, space complexity 고려에 해당 sort기능의 space complexity인 O(N)이 포함되면 더 좋았을 것 같습니다 :)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

wow 감사합니다.
Timsort의 time complexity 는 검색해서 추가했지만, Space complexity 는 전혀 고려하지 않았습니다.
짚어주셔서 감사합니다..!

return list(map(lambda x: x[0], result[:k]))
31 changes: 31 additions & 0 deletions valid-palindrome/Chaedie.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""
풀이:
1) lower case로 변형합니다.
2) alpha numeric 인 문자만 string 배열에 담아줍니다.
3) string 배열과 string 배열의 역순 배열을 비교해서 return 합니다.

시간 복잡도:
1) s.lower() -> O(n) - 각 요소를 순회하며 lower case로 바꿔줍니다.
2) for char in s: -> O(n) - 각 요소를 순회하면 isalnum() 여부를 확인합니다.
3) string.append(char) -> O(1)
4) string[::-1] -> O(n) - 각 요소를 순회합니다.

결론: O(4n) 이므로 O(n) 입니다.

공간 복잡도:
1) string 배열 - O(n)
2) string[::-1] - O(n)

결론: O(n) 입니다.
"""


class Solution:
def isPalindrome(self, s: str) -> bool:
string = []
s = s.lower()
for char in s:
if char.isalnum():
string.append(char)

return string == string[::-1]
Copy link
Contributor

Choose a reason for hiding this comment

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

이 부분도 최종적인 space complexity에는 영향을 미치지 않지만, string[::-1]의 space complexity까지 고려해주시면 더 좋을 것 같습니다 :)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@obzva 리뷰 감사합니다..!
리뷰사항 반영해서 Commit 했습니다.
감사합니다.

Loading