Skip to content

Commit f4f2a5c

Browse files
committed
Update solutions
1 parent 7a21e42 commit f4f2a5c

File tree

43 files changed

+1679
-50
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+1679
-50
lines changed

README.md

Lines changed: 65 additions & 50 deletions
Large diffs are not rendered by default.

src/easy/__init__.py

Whitespace-only changes.
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#! /usr/bin/python3
2+
# -*- coding:utf8 -*-
3+
4+
# Copyright 2025 Robina Li. BSD 3-Clause License All Rights Reserved.
5+
# @file : solution.py
6+
# @desc : Solution for Leetcode
7+
# Reference : https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
8+
9+
from typing import List
10+
import math
11+
12+
class Solution:
13+
def maxProfit(self, prices: List[int]) -> int:
14+
min_, profit = float("inf"), 0
15+
for i in range(len(prices)):
16+
if prices[i] < min_:
17+
min_ = prices[i]
18+
elif prices[i] - min_ > profit:
19+
profit = prices[i]- min_
20+
return profit
21+
22+
if __name__ == '__main__':
23+
solution = Solution()
24+
25+
rtn = solution.maxProfit([7,1,5,3,6,4])
26+
print(5 == rtn)
27+
rtn = solution.maxProfit([7,6,4,3,1])
28+
print(0 == rtn)

src/easy/binary_search/solution.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#! /usr/bin/python3
2+
# -*- coding:utf8 -*-
3+
4+
# Copyright 2025 Robina Li. BSD 3-Clause License All Rights Reserved.
5+
# @file : solution.py
6+
# @desc : Solution for Leetcode
7+
# Reference : https://leetcode.com/problems/binary-search/
8+
9+
from typing import List
10+
import math
11+
12+
class Solution:
13+
def search(self, nums: List[int], target: int) -> int:
14+
if len(nums) == 0:
15+
return -1
16+
left, right = 0, len(nums) -1
17+
while left <= right:
18+
pivot = (left + right) // 2
19+
if nums[pivot] == target:
20+
return pivot
21+
elif nums[pivot] < target:
22+
left = pivot + 1
23+
else:
24+
right = pivot - 1
25+
return -1
26+
27+
if __name__ == '__main__':
28+
solution = Solution()
29+
30+
rtn = solution.search([-1,0,3,5,9,12], 9)
31+
print(4 == rtn)
32+
rtn = solution.search([-1,0,3,5,9,12], 2)
33+
print(-1 == rtn)

src/easy/fibonacci_number/solution.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,30 @@ def fib(self, n: int) -> int:
1515
if n <= 1: return n
1616
return self.fib(n - 1) + self.fib(n - 2)
1717

18+
def __init__(self):
19+
self.cache = dict()
20+
def fib1(self, n: int) -> int:
21+
if n in self.cache:
22+
return self.cache[n]
23+
if n < 2:
24+
rtn = n
25+
else:
26+
rtn = self.fib(n - 1) + self.fib(n - 2)
27+
self.cache[n] = rtn
28+
return rtn
29+
1830
if __name__ == '__main__':
1931
solution = Solution()
2032
rtn = solution.fib(2)
2133
print(1 == rtn)
2234
rtn = solution.fib(3)
2335
print(2 == rtn)
2436
rtn = solution.fib(4)
37+
print(3 == rtn)
38+
39+
rtn = solution.fib1(2)
40+
print(1 == rtn)
41+
rtn = solution.fib1(3)
42+
print(2 == rtn)
43+
rtn = solution.fib1(4)
2544
print(3 == rtn)
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#! /usr/bin/python3
2+
# -*- coding:utf8 -*-
3+
4+
# Copyright 2025 Robina Li. BSD 3-Clause License All Rights Reserved.
5+
# @file : solution.py
6+
# @desc : Solution for Leetcode
7+
# Reference : https://leetcode.com/problems/first-bad-version/
8+
9+
from typing import List
10+
import math
11+
12+
def isBadVersion(version: int) -> bool:
13+
return version >= FIRST_BAD_VERSION
14+
15+
class Solution:
16+
def firstBadVersion(self, n: int) -> int:
17+
left, right = 1, n
18+
while left <= right:
19+
pivit = (left + right) >> 1
20+
if isBadVersion(pivit) == False:
21+
left = pivit + 1
22+
else:
23+
right = pivit - 1
24+
return left
25+
26+
def test_first_bad_version(n, expected):
27+
global FIRST_BAD_VERSION
28+
FIRST_BAD_VERSION = expected # Set the "bad" version globally
29+
solution = Solution()
30+
result = solution.firstBadVersion(n)
31+
print(f"Input n = {n}, First Bad Version = {expected} -> Output = {result}")
32+
assert result == expected, f"❌ Expected {expected}, but got {result}"
33+
print("✅ Test passed\n")
34+
35+
36+
if __name__ == '__main__':
37+
test_first_bad_version(5, 4)
38+
test_first_bad_version(1, 1)
39+
test_first_bad_version(10, 1)
40+
test_first_bad_version(1000, 873)
41+
test_first_bad_version(2, 2)
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
#! /usr/bin/python3
2+
# -*- coding:utf8 -*-
3+
4+
# Copyright 2025 Robina Li. BSD 3-Clause License All Rights Reserved.
5+
# @file : solution.py
6+
# @desc : Solution for Leetcode
7+
# Reference : https://leetcode.com/problems/search-in-a-binary-search-tree/
8+
9+
from typing import List, Optional
10+
import math
11+
12+
class TreeNode:
13+
def __init__(self, val: int = 0, left: Optional['TreeNode'] = None, right: Optional['TreeNode'] = None):
14+
self.val = val
15+
self.left = left
16+
self.right = right
17+
18+
class Solution:
19+
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
20+
# Base case
21+
if not root: return None
22+
if root.val == val: return root
23+
24+
# Recursion relation
25+
if val > root.val:
26+
return self.searchBST(root.right, val)
27+
else:
28+
return self.searchBST(root.left, val)
29+
30+
from collections import deque
31+
32+
def build_tree_from_list(values):
33+
if not values:
34+
return None
35+
root = TreeNode(values[0])
36+
queue = deque([root])
37+
i = 1
38+
while queue and i < len(values):
39+
node = queue.popleft()
40+
if values[i] is not None:
41+
node.left = TreeNode(values[i])
42+
queue.append(node.left)
43+
i += 1
44+
45+
if i < len(values) and values[i] is not None:
46+
node.right = TreeNode(values[i])
47+
queue.append(node.right)
48+
i += 1
49+
return root
50+
51+
52+
def test_search_bst(tree_vals, search_val, expected_val):
53+
root = build_tree_from_list(tree_vals)
54+
solution = Solution()
55+
result = solution.searchBST(root, search_val)
56+
output = result.val if result else None
57+
print(f"Search {search_val} in {tree_vals} → Found: {output}, Expected: {expected_val}")
58+
assert output == expected_val, f"❌ Failed: expected {expected_val}, got {output}"
59+
print("✅ Test passed\n")
60+
61+
if __name__ == "__main__":
62+
test_search_bst([4, 2, 7, 1, 3], 2, 2)
63+
test_search_bst([4, 2, 7, 1, 3], 5, None)
64+
test_search_bst([], 1, None)
65+
test_search_bst([1], 1, 1)
66+
test_search_bst([5, 3, 6, 2, 4], 4, 4)

src/easy/single_number/solution.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#! /usr/bin/python3
2+
# -*- coding:utf8 -*-
3+
4+
# Copyright 2025 Robina Li. BSD 3-Clause License All Rights Reserved.
5+
# @file : solution.py
6+
# @desc : Solution for Leetcode
7+
# Reference : https://leetcode.com/problems/single-number/
8+
9+
from typing import List
10+
import math
11+
12+
class Solution:
13+
def singleNumber(self, nums: List[int]) -> int:
14+
a = 0
15+
for i in nums:
16+
a ^= i
17+
return a
18+
19+
if __name__ == '__main__':
20+
solution = Solution()
21+
22+
rtn = solution.singleNumber([2,2,1])
23+
print(1 == rtn)
24+
rtn = solution.singleNumber([4,1,2,1,2])
25+
print(4 == rtn)
26+
rtn = solution.singleNumber([1])
27+
print(1 == rtn)

src/easy/sqrtx_x/solution.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#! /usr/bin/python3
2+
# -*- coding:utf8 -*-
3+
4+
# Copyright 2025 Robina Li. BSD 3-Clause License All Rights Reserved.
5+
# @file : solution.py
6+
# @desc : Solution for Leetcode
7+
# Reference : https://leetcode.com/problems/sqrtx/
8+
9+
from typing import List
10+
from functools import cache
11+
from math import e, log
12+
13+
class Solution(object):
14+
15+
def mySqrt(self, x: int) -> int:
16+
if x < 2:
17+
return x
18+
left = int(e**(0.5 * log(x)))
19+
right = left + 1
20+
return left if right * right > x else right
21+
22+
def mySqrt1(self, x: int) -> int:
23+
if x < 2:
24+
return x
25+
left, right = 2, x // 2
26+
while left <= right:
27+
pivot = left + (right - left) // 2
28+
num = pivot * pivot
29+
if num > x:
30+
right = pivot - 1
31+
elif num < x:
32+
left = pivot + 1
33+
else:
34+
return pivot
35+
return right
36+
37+
if __name__ == '__main__':
38+
solution = Solution()
39+
40+
rtn = solution.mySqrt(4)
41+
print(2 == rtn)
42+
rtn = solution.mySqrt(8)
43+
print(2 == rtn)
44+
45+
rtn = solution.mySqrt1(4)
46+
print(2 == rtn)
47+
rtn = solution.mySqrt1(8)
48+
print(2 == rtn)
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#! /usr/bin/python3
2+
# -*- coding:utf8 -*-
3+
4+
# Copyright 2025 Robina Li. BSD 3-Clause License All Rights Reserved.
5+
# @file : solution.py
6+
# @desc : Solution for Leetcode
7+
# Reference : https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/
8+
9+
from typing import List
10+
11+
class Solution(object):
12+
def findMin(self, nums: List[int]) -> int:
13+
left, right = 0, len(nums) - 1
14+
while left < right:
15+
pivot = (left + right) >> 1
16+
if nums[pivot] < nums[right]:
17+
right = pivot
18+
elif nums[pivot] > nums[right]:
19+
left = pivot + 1
20+
else:
21+
right -= 1
22+
return nums[left]
23+
24+
if __name__ == '__main__':
25+
solution = Solution()
26+
rtn = solution.findMin([1,3,5])
27+
print(1 == rtn)
28+
rtn = solution.findMin([2,2,2,0,1])
29+
print(0 == rtn)

0 commit comments

Comments
 (0)