Skip to content

Commit 079e214

Browse files
Jeehay28Jeehay28
authored andcommitted
Add LIS solution in TypeScript
1 parent b13d233 commit 079e214

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Time Complexity: O(n * log n)
2+
// Space Complexity: O(n)
3+
4+
function lengthOfLIS(nums: number[]): number {
5+
const sub: number[] = []; // O(n)
6+
7+
for (const num of nums) { // O(n)
8+
// lower bound binary search: find the first index where element >= target
9+
let left = 0;
10+
let right = sub.length;
11+
const target = num;
12+
13+
while (left < right) { // O(log n)
14+
let mid = Math.floor((left + right) / 2);
15+
if (sub[mid] < target) {
16+
left = mid + 1;
17+
} else {
18+
right = mid;
19+
}
20+
}
21+
22+
// if target is greater than all elements in sub
23+
if (left === sub.length) {
24+
sub.push(target);
25+
} else {
26+
// replace the first element >= target
27+
sub[left] = target;
28+
}
29+
}
30+
31+
return sub.length;
32+
}
33+

0 commit comments

Comments
 (0)