Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return longestIncreasingSubsequence from dpLongestIncreasingSubsequence #1164

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,36 +1,21 @@
import dpLongestIncreasingSubsequence from '../dpLongestIncreasingSubsequence';

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

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

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

// 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(dpLongestIncreasingSubsequence([
0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15,
])).toBe(6);
])).toStrictEqual([0, 2, 6, 9, 11, 15]);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* Complexity: O(n * n)
*
* @param {number[]} sequence
* @return {number}
* @return {number[]}
*/
export default function dpLongestIncreasingSubsequence(sequence) {
// Create array with longest increasing substrings length and
Expand Down Expand Up @@ -49,5 +49,18 @@ export default function dpLongestIncreasingSubsequence(sequence) {
}
}

return longestIncreasingLength;
// Construct the longest increasing subsequence from the back to the front
let rightIndex = lengthsArray.findIndex((item) => item === longestIncreasingLength);
const longestIncreasingSubsequence = [];

while (rightIndex > -1) {
const leftIndex = lengthsArray.findLastIndex((item, idx) => (
item === lengthsArray[rightIndex] - 1 && idx < rightIndex
));

longestIncreasingSubsequence.unshift(sequence[rightIndex]);
rightIndex = leftIndex;
}

return longestIncreasingSubsequence;
}