Skip to content

Commit 0e1fbcd

Browse files
committed
D. J.:
- Added the Binary Search (BS) Solution for Leetcode problem 300
1 parent b42ea71 commit 0e1fbcd

File tree

2 files changed

+37
-3
lines changed

2 files changed

+37
-3
lines changed

awesome_python_leetcode/_300_longest_increasing_subsequence.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,37 @@
1+
import bisect
12
from typing import List
23

34

45
class Solution:
56
"""Base class for all LeetCode Problems."""
67

7-
def lengthOfLIS(self, nums: List[int]) -> int:
8+
def lengthOfLISBS(self, nums: List[int]) -> int:
89
"""
910
Given an integer array nums, return the length of the longest strictly
1011
increasing subsequence.
1112
1213
A subsequence is an array that can be derived from another array by deleting
1314
some or no elements without changing the order of the remaining elements.
1415
"""
16+
# Binary Search Solution: O(n log n)
17+
seq = [nums[0]]
18+
for k in range(1, len(nums)):
19+
if nums[k] > seq[-1]:
20+
seq.append(nums[k])
21+
else:
22+
i = bisect.bisect_left(seq, nums[k])
23+
seq[i] = nums[k]
24+
return len(seq)
25+
26+
def lengthOfLISDP(self, nums: List[int]) -> int:
27+
"""
28+
Given an integer array nums, return the length of the longest strictly
29+
increasing subsequence.
30+
31+
A subsequence is an array that can be derived from another array by deleting
32+
some or no elements without changing the order of the remaining elements.
33+
"""
34+
# DP (LIS) Solution: O(n²)
1535
dp = [1] * (len(nums))
1636
for i in range(len(nums) - 2, -1, -1):
1737
for j in range(i + 1, len(nums)):

tests/test_300_longest_increasing_subsequence.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,21 @@
1313
([7, 7, 7, 7, 7, 7, 7], 1),
1414
],
1515
)
16-
def test_func(nums: List[int], expected: int):
16+
def test_func_bs(nums: List[int], expected: int):
1717
"""Tests the solution of a LeetCode problem."""
18-
length = Solution().lengthOfLIS(nums)
18+
length = Solution().lengthOfLISBS(nums)
19+
assert length == expected
20+
21+
22+
@pytest.mark.parametrize(
23+
argnames=["nums", "expected"],
24+
argvalues=[
25+
([10, 9, 2, 5, 3, 7, 101, 18], 4),
26+
([0, 1, 0, 3, 2, 3], 4),
27+
([7, 7, 7, 7, 7, 7, 7], 1),
28+
],
29+
)
30+
def test_func_dp(nums: List[int], expected: int):
31+
"""Tests the solution of a LeetCode problem."""
32+
length = Solution().lengthOfLISDP(nums)
1933
assert length == expected

0 commit comments

Comments
 (0)