Skip to content

Commit a702f10

Browse files
committedAug 11, 2018
Added Efficient LIS (nlog(n))
1 parent 46b13f0 commit a702f10

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-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,28 @@
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+
// Retrieves the smallest number greater or equal to val in sorted arr.
10+
function upperBound(arr, val) {
11+
let lo = 0;
12+
let hi = arr.length;
13+
14+
while (lo < hi) {
15+
const mid = lo + Math.floor((hi - lo) / 2);
16+
if (arr[mid] < val) {
17+
lo = mid + 1;
18+
} else {
19+
hi = mid;
20+
}
21+
}
22+
return hi;
23+
}
24+
25+
const lis = [];
26+
sequence.forEach((val) => { lis[upperBound(lis, val)] = val; });
27+
return lis.length;
28+
}

0 commit comments

Comments
 (0)