Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 68f3f67

Browse files
committedAug 10, 2018
Added Efficient LIS (nlog(n))
1 parent 46b13f0 commit 68f3f67

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import longestIncreasingSubsequence from '../longestIncreasingSubsequence';
2+
3+
describe('LongestIncreasingSubsequence', () => {
4+
it('should find longest increasing subsequence length', () => {
5+
// Should be:
6+
// 9 or
7+
// 8 or
8+
// 7 or
9+
// 6 or
10+
// ...
11+
expect(longestIncreasingSubsequence([
12+
9, 8, 7, 6, 5, 4, 3, 2, 1, 0,
13+
])).toBe(1);
14+
15+
// Should be:
16+
// 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
17+
expect(longestIncreasingSubsequence([
18+
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
19+
])).toBe(10);
20+
21+
// Should be:
22+
// -1, 0, 2, 3
23+
expect(longestIncreasingSubsequence([
24+
3, 4, -1, 0, 6, 2, 3,
25+
])).toBe(4);
26+
27+
// Should be:
28+
// 0, 2, 6, 9, 11, 15 or
29+
// 0, 4, 6, 9, 11, 15 or
30+
// 0, 2, 6, 9, 13, 15 or
31+
// 0, 4, 6, 9, 13, 15
32+
expect(longestIncreasingSubsequence([
33+
0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15,
34+
])).toBe(6);
35+
});
36+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Efficient approach to find longest increasing subsequence.
3+
* Complexity: O(n * log(n))
4+
*
5+
* @param {number[]} sequence
6+
* @return {number}
7+
*/
8+
export default function LongestIncreasingSubsequence(sequence) {
9+
if (sequence.length <= 1) {
10+
return sequence.length;
11+
}
12+
13+
function lowerBound(arr, val) {
14+
let lo = 0;
15+
let hi = arr.length;
16+
17+
while (lo < hi) {
18+
const mid = lo + Math.floor((hi - lo) / 2);
19+
if (arr[mid] < val) {
20+
lo = mid + 1;
21+
} else {
22+
hi = mid;
23+
}
24+
}
25+
return hi;
26+
}
27+
28+
const lis = [];
29+
sequence.forEach((val) => { lis[lowerBound(lis, val)] = val; });
30+
return lis.length;
31+
}

0 commit comments

Comments
 (0)
Please sign in to comment.