Skip to content

Commit 78370c1

Browse files
authored
Merge pull request DaleStudy#1206 from ayosecu/main
[ayosecu] WEEK 02 solutions
2 parents d0df82d + 5cb62e7 commit 78370c1

File tree

5 files changed

+211
-0
lines changed

5 files changed

+211
-0
lines changed

3sum/ayosecu.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
from typing import List
2+
3+
class Solution:
4+
"""
5+
- Algorithm
6+
- Sort and compares with three pointers: target, left(l), right(r)
7+
- Time Complexity: O(n^2), n = len(nums)
8+
- sort : O(nlogn)
9+
- nested two loops : O(n^2)
10+
- O(nlogn + n^2) => O(n^2)
11+
- Space Complexity: O(n^2) if result included.
12+
- result size : result.append() called in n^2 times (nested two loops)
13+
"""
14+
def threeSum(self, nums: List[int]) -> List[List[int]]:
15+
result = []
16+
nums.sort()
17+
18+
n = len(nums)
19+
for i in range(n - 2):
20+
# skip duplicated numbers
21+
if i > 0 and nums[i] == nums[i - 1]:
22+
continue
23+
24+
target = nums[i]
25+
l, r = i + 1, n - 1
26+
while l < r:
27+
if nums[l] + nums[r] == -target:
28+
result.append([target, nums[l], nums[r]])
29+
# skip duplicated numbers
30+
while l < r and nums[l] == nums[l + 1]:
31+
l += 1
32+
while l < r and nums[r] == nums[r - 1]:
33+
r -= 1
34+
l += 1
35+
r -= 1
36+
elif nums[l] + nums[r] < -target:
37+
l += 1
38+
else:
39+
r -= 1
40+
41+
return result
42+
43+
tc = [
44+
([-1,0,1,2,-1,-4], [[-1,-1,2],[-1,0,1]]),
45+
([0,1,1], []),
46+
([0,0,0], [[0,0,0]])
47+
]
48+
49+
for i, (nums, e) in enumerate(tc, 1):
50+
sol = Solution()
51+
r = sol.threeSum(nums)
52+
print(f"TC {i} is Passed!" if e == r else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

climbing-stairs/ayosecu.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution:
2+
"""
3+
- Time Complexity: O(n)
4+
- Space Complexity: O(n)
5+
"""
6+
def climbStairs(self, n: int) -> int:
7+
"""
8+
- DP Formation
9+
- dp[0] = 1
10+
- dp[1] = 1
11+
- dp[2] = dp[1] + dp[0] = 2
12+
- dp[3] = dp[2] + dp[1] = 3
13+
- dp[i] = dp[i - 1] + dp[i - 2]
14+
"""
15+
if n <= 1:
16+
return 1
17+
18+
dp = [1] * (n + 1)
19+
20+
for i in range(2, n + 1):
21+
dp[i] = dp[i - 1] + dp[i - 2]
22+
23+
return dp[-1]
24+
25+
26+
tc = [
27+
(1, 1),
28+
(2, 2),
29+
(3, 3),
30+
(4, 5)
31+
]
32+
33+
for i, (n, e) in enumerate(tc, 1):
34+
sol = Solution()
35+
r = sol.climbStairs(n)
36+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
from typing import List
2+
3+
class Solution:
4+
"""
5+
- Time Complexity: O(n), n = len(nums)
6+
- Space Complexity: O(n)
7+
"""
8+
def productExceptSelfN(self, nums: List[int]) -> List[int]:
9+
n = len(nums)
10+
prefix, suffix, result = [0] * n, [0] * n, [0] * n
11+
12+
# Calculate prefix and suffix production
13+
prefix[0], suffix[-1] = nums[0], nums[-1]
14+
for i in range(1, n - 1):
15+
prefix[i] = prefix[i - 1] * nums[i]
16+
j = n - i - 1
17+
suffix[j] = suffix[j + 1] * nums[j]
18+
19+
# Update the result
20+
result[0], result[-1] = suffix[1], prefix[-2]
21+
for i in range(1, n - 1):
22+
result[i] = prefix[i - 1] * suffix[i + 1]
23+
24+
return result
25+
26+
"""
27+
- Time Complexity: O(n), n = len(nums)
28+
- Space Complexity
29+
- O(1), if output space (result) is ignored
30+
- O(n), if output space (result) is considered
31+
"""
32+
def productExceptSelf(self, nums: List[int]) -> List[int]:
33+
n = len(nums)
34+
result = [1] * n
35+
36+
left = 1
37+
for i in range(n):
38+
result[i] = left
39+
left = result[i] * nums[i]
40+
41+
right = 1
42+
for i in range(n - 1, -1, -1):
43+
result[i] *= right
44+
right *= nums[i]
45+
46+
return result
47+
48+
tc = [
49+
([1, 2, 3, 4], [24, 12, 8, 6]),
50+
([-1, 1, 0, -3, 3], [0, 0, 9, 0, 0])
51+
]
52+
53+
for i, (nums, e) in enumerate(tc, 1):
54+
sol = Solution()
55+
r = sol.productExceptSelf(nums)
56+
print(f"TC {i} is Passed!" if e == r else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

valid-anagram/ayosecu.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from collections import Counter
2+
3+
class Solution:
4+
"""
5+
- Time Complexity: O(n + m), n = len(s), m = len(t)
6+
- Space Complexity: O(n + m)
7+
"""
8+
def isAnagram(self, s: str, t: str) -> bool:
9+
return Counter(s) == Counter(t)
10+
11+
tc = [
12+
("anagram", "nagaram", True),
13+
("rat", "car", False),
14+
("abc", "dcba", False)
15+
]
16+
17+
for i, (s, t, e) in enumerate(tc, 1):
18+
sol = Solution()
19+
r = sol.isAnagram(s, t)
20+
print(f"TC {i} is Passed!" if e == r else f"TC {i} is Failed! - Expected: {e}, Result: {r}")
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
from typing import Optional
2+
3+
# Definition for a binary tree node.
4+
class TreeNode:
5+
def __init__(self, val=0, left=None, right=None):
6+
self.val = val
7+
self.left = left
8+
self.right = right
9+
10+
class Solution:
11+
"""
12+
- Time Complexity: O(n), n = The number of nodes
13+
- Space Complexity: O(H), H = The height of tree
14+
- Stack size of checkVal
15+
- H = logn, if the tree is balanced
16+
- H = n, if the tree is skewed
17+
"""
18+
def isValidBST(self, root: Optional[TreeNode]) -> bool:
19+
20+
def checkVal(node, min_val, max_val):
21+
if not node:
22+
return True
23+
24+
if node.val >= max_val or node.val <= min_val:
25+
return False
26+
27+
return checkVal(node.left, min_val, node.val) and checkVal(node.right, node.val, max_val)
28+
29+
return checkVal(root, float("-inf"), float("inf"))
30+
31+
def doTest():
32+
sol = Solution()
33+
root1 = TreeNode(2)
34+
root1.left = TreeNode(1)
35+
root1.right = TreeNode(3)
36+
result1 = sol.isValidBST(root1)
37+
print(f"TC 1 is Passed!" if result1 == True else f"TC 1 is Failed! - Expected: {True}, Result: {result1}")
38+
39+
root2 = TreeNode(5)
40+
root2.left = TreeNode(1)
41+
root2.right = TreeNode(4)
42+
root2.right.left = TreeNode(3)
43+
root2.right.right = TreeNode(6)
44+
result2 = sol.isValidBST(root2)
45+
print(f"TC 2 is Passed!" if result2 == False else f"TC 2 is Failed! - Expected: {False}, Result: {result2}")
46+
47+
doTest()

0 commit comments

Comments
 (0)