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
52 changes: 52 additions & 0 deletions 3sum/ayosecu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
from typing import List

class Solution:
"""
- Algorithm
- Sort and compares with three pointers: target, left(l), right(r)
- Time Complexity: O(n^2), n = len(nums)
- sort : O(nlogn)
- nested two loops : O(n^2)
- O(nlogn + n^2) => O(n^2)
- Space Complexity: O(n^2) if result included.
- result size : result.append() called in n^2 times (nested two loops)
"""
Comment on lines +4 to +13
Copy link
Contributor

Choose a reason for hiding this comment

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

@ayosecu 님 안녕하세요! 저도 투포인터를 활용하여 문제를 풀었습니다. 개인적으로 알고리즘 문제를 풀 때 tc, sc를 생각해내는 게 항상 어려운데, 이 부분을 잘 정리해주셔서 복습하는 데 도움이 많이 됐습니다!

def threeSum(self, nums: List[int]) -> List[List[int]]:
result = []
nums.sort()

n = len(nums)
for i in range(n - 2):
# skip duplicated numbers
if i > 0 and nums[i] == nums[i - 1]:
continue

target = nums[i]
l, r = i + 1, n - 1
while l < r:
if nums[l] + nums[r] == -target:
result.append([target, nums[l], nums[r]])
# skip duplicated numbers
while l < r and nums[l] == nums[l + 1]:
l += 1
while l < r and nums[r] == nums[r - 1]:
r -= 1
l += 1
r -= 1
elif nums[l] + nums[r] < -target:
l += 1
else:
r -= 1

return result

tc = [
([-1,0,1,2,-1,-4], [[-1,-1,2],[-1,0,1]]),
([0,1,1], []),
([0,0,0], [[0,0,0]])
]

for i, (nums, e) in enumerate(tc, 1):
sol = Solution()
r = sol.threeSum(nums)
print(f"TC {i} is Passed!" if e == r else f"TC {i} is Failed! - Expected: {e}, Result: {r}")
36 changes: 36 additions & 0 deletions climbing-stairs/ayosecu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
class Solution:
"""
- Time Complexity: O(n)
- Space Complexity: O(n)
"""
def climbStairs(self, n: int) -> int:
"""
- DP Formation
- dp[0] = 1
- dp[1] = 1
- dp[2] = dp[1] + dp[0] = 2
- dp[3] = dp[2] + dp[1] = 3
- dp[i] = dp[i - 1] + dp[i - 2]
"""
if n <= 1:
return 1

dp = [1] * (n + 1)

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

return dp[-1]


tc = [
(1, 1),
(2, 2),
(3, 3),
(4, 5)
]

for i, (n, e) in enumerate(tc, 1):
sol = Solution()
r = sol.climbStairs(n)
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")
56 changes: 56 additions & 0 deletions product-of-array-except-self/ayosecu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
from typing import List

class Solution:
"""
- Time Complexity: O(n), n = len(nums)
- Space Complexity: O(n)
"""
def productExceptSelfN(self, nums: List[int]) -> List[int]:
n = len(nums)
prefix, suffix, result = [0] * n, [0] * n, [0] * n

# Calculate prefix and suffix production
prefix[0], suffix[-1] = nums[0], nums[-1]
for i in range(1, n - 1):
prefix[i] = prefix[i - 1] * nums[i]
j = n - i - 1
suffix[j] = suffix[j + 1] * nums[j]

# Update the result
result[0], result[-1] = suffix[1], prefix[-2]
for i in range(1, n - 1):
result[i] = prefix[i - 1] * suffix[i + 1]

return result
Comment on lines +8 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.

저는 두 번째 풀이 방식으로 문제를 풀었는데, 이 풀이는 제가 생각하지 못했던 방법이라 보면서 공부가 되었습니다! 2주차도 고생하셨습니다 👍

Copy link
Contributor Author

Choose a reason for hiding this comment

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

리뷰 너무 감사합니다! 이번주도 고생하셨고, 다음주도 화이팅입니다! 😄


"""
- Time Complexity: O(n), n = len(nums)
- Space Complexity
- O(1), if output space (result) is ignored
- O(n), if output space (result) is considered
"""
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)
result = [1] * n

left = 1
for i in range(n):
result[i] = left
left = result[i] * nums[i]

right = 1
for i in range(n - 1, -1, -1):
result[i] *= right
right *= nums[i]

return result

tc = [
([1, 2, 3, 4], [24, 12, 8, 6]),
([-1, 1, 0, -3, 3], [0, 0, 9, 0, 0])
]

for i, (nums, e) in enumerate(tc, 1):
sol = Solution()
r = sol.productExceptSelf(nums)
print(f"TC {i} is Passed!" if e == r else f"TC {i} is Failed! - Expected: {e}, Result: {r}")
20 changes: 20 additions & 0 deletions valid-anagram/ayosecu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from collections import Counter

class Solution:
"""
- Time Complexity: O(n + m), n = len(s), m = len(t)
- Space Complexity: O(n + m)
"""
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s) == Counter(t)

tc = [
("anagram", "nagaram", True),
("rat", "car", False),
("abc", "dcba", False)
]

for i, (s, t, e) in enumerate(tc, 1):
sol = Solution()
r = sol.isAnagram(s, t)
print(f"TC {i} is Passed!" if e == r else f"TC {i} is Failed! - Expected: {e}, Result: {r}")
47 changes: 47 additions & 0 deletions validate-binary-search-tree/ayosecu.py
Copy link
Contributor

Choose a reason for hiding this comment

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

이 문제는 반복문으로도 풀어보시면 좋을 것 같습니다! 그리고 항상 테스트 케이스를 기록하시는 모습이 인상 깊었고, 그 부분에서 많이 배웠습니다!

Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from typing import Optional

# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right

class Solution:
"""
- Time Complexity: O(n), n = The number of nodes
- Space Complexity: O(H), H = The height of tree
- Stack size of checkVal
- H = logn, if the tree is balanced
- H = n, if the tree is skewed
"""
def isValidBST(self, root: Optional[TreeNode]) -> bool:

def checkVal(node, min_val, max_val):
if not node:
return True

if node.val >= max_val or node.val <= min_val:
return False

return checkVal(node.left, min_val, node.val) and checkVal(node.right, node.val, max_val)

return checkVal(root, float("-inf"), float("inf"))

def doTest():
sol = Solution()
root1 = TreeNode(2)
root1.left = TreeNode(1)
root1.right = TreeNode(3)
result1 = sol.isValidBST(root1)
print(f"TC 1 is Passed!" if result1 == True else f"TC 1 is Failed! - Expected: {True}, Result: {result1}")

root2 = TreeNode(5)
root2.left = TreeNode(1)
root2.right = TreeNode(4)
root2.right.left = TreeNode(3)
root2.right.right = TreeNode(6)
result2 = sol.isValidBST(root2)
print(f"TC 2 is Passed!" if result2 == False else f"TC 2 is Failed! - Expected: {False}, Result: {result2}")

doTest()