Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: trekhleb/javascript-algorithms
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: master
Choose a base ref
...
head repository: Bruce-Feldman/javascript-algorithms
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: Add-Efficient-LIS
Choose a head ref
Able to merge. These branches can be automatically merged.
  • 1 commit
  • 2 files changed
  • 1 contributor

Commits on Aug 11, 2018

  1. Copy the full SHA
    5cf8ac2 View commit details
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import longestIncreasingSubsequence from '../longestIncreasingSubsequence';

describe('LongestIncreasingSubsequence', () => {
it('should find longest increasing subsequence length', () => {
// Should be:
// 9 or
// 8 or
// 7 or
// 6 or
// ...
expect(longestIncreasingSubsequence([
9, 8, 7, 6, 5, 4, 3, 2, 1, 0,
])).toBe(1);

// Should be:
// 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
expect(longestIncreasingSubsequence([
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
])).toBe(10);

// Should be:
// -1, 0, 2, 3
expect(longestIncreasingSubsequence([
3, 4, -1, 0, 6, 2, 3,
])).toBe(4);

// Should be:
// 0, 2, 6, 9, 11, 15 or
// 0, 4, 6, 9, 11, 15 or
// 0, 2, 6, 9, 13, 15 or
// 0, 4, 6, 9, 13, 15
expect(longestIncreasingSubsequence([
0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15,
])).toBe(6);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* Efficient approach to find longest increasing subsequence.
* Complexity: O(n * log(n))
*
* @param {number[]} sequence
* @return {number}
*/
export default function LongestIncreasingSubsequence(sequence) {
// Retrieves the smallest number greater or equal to val in sorted arr.
function upperBound(arr, val) {
let lo = 0;
let hi = arr.length;

while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (arr[mid] < val) {
lo = mid + 1;
} else {
hi = mid;
}
}
return hi;
}

const lis = [];
sequence.forEach((val) => { lis[upperBound(lis, val)] = val; });
return lis.length;
}