Skip to content
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
144 changes: 92 additions & 52 deletions 3sum/rivkode.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,43 @@
from typing import List, Tuple, Set

class Solution(object):
def threeSum(self, nums):
result = set()
v_set = {}

for i, v in enumerate(nums):
v_set[v] = i
Comment on lines +8 to +9
Copy link
Member

Choose a reason for hiding this comment

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

혹시 리트코드에서 본 답안 코드를 제출해보셨나요? 이렇게 중복된 값이 여러 번 등장할 때 인덱스를 덮어쓰면 필요한 조합을 놓치거나 잘못된 인덱스를 사용할 수 있을 것 같습니다.

Copy link
Member Author

Choose a reason for hiding this comment

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

image

@DaleSeo 주말 일정으로 늦게 답장을 드립니다. 넵! 제출해보았습니다, pass를 하긴 했었는데 많이 느린 편이네요 .. ㅎㅎ

그러네요 .. set을 사용하게 되면 잘못된 인덱스를 사용할 수 있을 것 같습니다. 답이 pass된 이유는 문제에서 다행히 인덱스와는 크게 관련있지 않고 고유한 조합 return 하면 되기때문이었던 것 같습니다. 항상 set으로 인덱스를 사용한다면 덮어씌워지는 부분을 주의해야겠습니다. 감사합니다~!


n = len(nums)
for i in range(n):
for j in range(i + 1, n):
v = nums[i]
w = nums[j]
target = -(v + w)
if target in v_set:
k = v_set[target]
if k != i and k != j:
triplet = tuple(sorted([v, w, target]))
result.add(triplet)

return list(result)

if __name__ == "__main__":
solution = Solution()
nums = [-1,0,1,2,-1,-4]
result = solution.threeSum(nums)
print(result)









# previous version

# threeSum3()
# Time Complexity O(n ^ 2)
# - when sorting by sorted function(TimSort) for each string it takes O(nlogn)
Expand All @@ -8,58 +46,60 @@
# - when sorting takes O(1)


class Solution:
def threeSum(self, nums: List[int]) -> list[tuple[int, ...]]:

triplets = set()
for i in range(len(nums) - 2):
for j in range(i + 1, len(nums)):
for k in range(j + 1, len(nums)):
if nums[i] + nums[j] + nums[k] == 0:
triplet = [nums[i], nums[j], nums[k]]
triplets.add(tuple(sorted(triplet)))

return list(triplets)

def threeSum2(self, nums: List[int]) -> list[tuple[int, ...]]:
triplets = set()

for i in range(len(nums)):
seen = set()
for j in range(i + 1, len(nums)):
res = -(nums[i] + nums[j])
if res in seen:
triplet = [nums[i], nums[j], res]
triplets.add(tuple(sorted(triplet)))
seen.add(nums[j])

return list(triplets)

def threeSum3(self, nums: List[int]) -> list(tuple[int, ...]):
triplets = set()
nums.sort()

for i in range(len(nums) - 2):
l = i + 1
r = len(nums) - 1

while l < r:
res = nums[l] + nums[r] + nums[i]
if res > 0:
r -= 1
elif res < 0:
l += 1
elif res == 0:
triple = (nums[l], nums[r], nums[i])
triplets.add(triple)
l, r = l + 1, r - 1
else:
raise Exception
return list(triplets)
# class Solution:
# def threeSum(self, nums: List[int]) -> list[tuple[int, ...]]:

if __name__ == "__main__":
nums = [-1,0,1,2,-1,-4]
# triplets = set()
# for i in range(len(nums) - 2):
# for j in range(i + 1, len(nums)):
# for k in range(j + 1, len(nums)):
# if nums[i] + nums[j] + nums[k] == 0:
# triplet = [nums[i], nums[j], nums[k]]
# triplets.add(tuple(sorted(triplet)))

# return list(triplets)

# def threeSum2(self, nums: List[int]) -> list[tuple[int, ...]]:
# triplets = set()

# for i in range(len(nums)):
# seen = set()
# for j in range(i + 1, len(nums)):
# res = -(nums[i] + nums[j])
# if res in seen:
# triplet = [nums[i], nums[j], res]
# triplets.add(tuple(sorted(triplet)))
# seen.add(nums[j])

# return list(triplets)

# def threeSum3(self, nums: List[int]) -> list(tuple[int, ...]):
# triplets = set()
# nums.sort()

# for i in range(len(nums) - 2):
# l = i + 1
# r = len(nums) - 1

# while l < r:
# res = nums[l] + nums[r] + nums[i]
# if res > 0:
# r -= 1
# elif res < 0:
# l += 1
# elif res == 0:
# triple = (nums[l], nums[r], nums[i])
# triplets.add(triple)
# l, r = l + 1, r - 1
# else:
# raise Exception
# return list(triplets)

# if __name__ == "__main__":
# nums = [-1,0,1,2,-1,-4]


# solution = Solution()
# solution.threeSum3(nums)


solution = Solution()
solution.threeSum3(nums)
33 changes: 27 additions & 6 deletions climbing-stairs/rivkode.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,41 @@
# Time Complexity O(n)
# - traversing for loop takes O(n)
# - same with 피보나치
# Space Complexity O(n)
# - appending for loop it takes O(n)

class Solution:
def climbStairs(self, n: int) -> int:
stage = [1, 2, 3]

for i in range(3, 45):
value = stage[i - 1] + stage[i - 2]
stage.append(value)
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""

return stage[n - 1]
map = {1:1, 2:2}


for i in range(3, n + 1):
map[i] = map[i-1] + map[i-2]

return map[n]


# def climbStairs(self, n: int) -> int:
# stage = [1, 2, 3]

# for i in range(3, 45):
# value = stage[i - 1] + stage[i - 2]
# stage.append(value)

# return stage[n - 1]

if __name__ == "__main__":
solution = Solution()
result = solution.climbStairs(5)
print(result)





49 changes: 49 additions & 0 deletions product-of-array-except-self/rivkode.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""

all_multi = 1
zero_count = 0
result = []

for v in nums:
if v == 0:
zero_count += 1
continue
all_multi *= v
all_multi = int(all_multi)

if zero_count == 0:
for v in nums:
if v == 0:
result.append(all_multi)
else:
cur = all_multi / v
result.append(int(cur))
elif zero_count == 1:
Comment on lines +24 to +26
Copy link
Contributor

Choose a reason for hiding this comment

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

안녕하세요, 이쪽에서 보고 왔습니다 ㅎㅎ #1757 (comment)
zero_count를 통해 0을 예외처리하신 이유는 0으로의 나눗셈에서 예외가 발생하기 때문인데 이 문제는 특히 나눗셈을 하지 말라는 설명이 명시된 것처럼 나눗셈 없는 풀이가 가능해요. 결론적으로 나눗셈 없이 푼다면 0을 예외처리하지 않아도 되겠네요. 왜 나눗셈 없이 풀라고 하는 건지 의아했었는데 예외 처리를 제거할 수 있는 이점을 생각하니 덕분에 납득이 됐습니다. 감사합니다!

Copy link
Member Author

@rivkode rivkode Aug 1, 2025

Choose a reason for hiding this comment

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

아하 ..! 사실,, 저는 저 나눗셈이 영어로 무엇인지 잘 몰랐습니다 .. ㅎㅎ divide가 나누다 이고 operation은 실행 동작 이라고만 알았네요 ㅋㅋㅋ 나눗셈 = division operation 도 함께 배우고 갑니다!

저는 처음 output만 보고 0이라는 특이 케이스가 존재해서 이걸 보고 시도하고 풀어봤는데, 지금 돌이켜보니 이게 되네 ? 였네요 ㅎㅎ

친절한 설명 감사합니다!

for v in nums:
if v == 0:
result.append(all_multi)
else:
result.append(0)

if zero_count >= 2:
return [0 for _ in range(len(nums))]

return result


if __name__ == "__main__":
solution = Solution()
# nums = [1,2,3,4]
# nums = [-1,1,0,-3,3]
nums = [1,2,3,4,0,0]
result = solution.productExceptSelf(nums)
print(result)




62 changes: 52 additions & 10 deletions valid-anagram/rivkode.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,68 @@
from typing import List

# Time Complexity O(n log n)
# - when sorting by sorted function(TimSort) for each string it takes O(nlogn)
# - traversing for loop takes O(n)
# - check len first
# - make set for one of list for each values
# - if there's a duplication, then value += 1. This is a number of count.
# - fetch value using set.get() method.
# - minus 1 and check if it is less than 0 which means it's invalid. return false directly.
# Space Complexity O(n)
# - when sorting takes O(n)

class Solution:
def isAnagram(self, s: str, t: str) -> bool:
s_sorted = sorted(s)
t_sorted = sorted(t)

for i in range(len(s_sorted)):
if s_sorted[i] != t_sorted[i]:
return False
return True
"""
:type s: str
:type t: str
:rtype: bool
"""
s_list = list(s)
t_list = list(t)

if len(s_list) != len(t_list):
return False

t_set = {}
for t_val in t_list:
cur = t_set.get(t_val, 0)
cur += 1
t_set[t_val] = cur


flag = True

for s_val in s_list:
if t_set.get(s_val):
cur = t_set.get(s_val)
cur -= 1
t_set[s_val] = cur
if cur < 0:
flag = False
break
else:
flag = False
break

return flag

# previous logic
# s_sorted = sorted(s)
# t_sorted = sorted(t)

# for i in range(len(s_sorted)):
# if s_sorted[i] != t_sorted[i]:
# return False
# return True


if __name__ == "__main__":
solution = Solution()

s = "nagaram"
t = "anagram"
s = "a"
t = "ab"

result = solution.isAnagram(s, t)
print(result)