Created
June 3, 2020 03:08
-
-
Save d-beloved/12d1d4fc8694a09f950adf5b0aed5dff to your computer and use it in GitHub Desktop.
A function to check if a second array is a subsequence of the first one
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isValidSubsequence(array, sequence) { | |
/* | |
On getting two non-empty integer arrays, for example [1, 4, 5, 2, 9, 13, 11] | |
A second array [4, 2, 11] can be said to be a subsequence of the first one because it contains all the element | |
present in the first one in the same order those appear in the first one, even though they are not adjacent. | |
The algorithm below works by comparing the two array, looping through the first one once and then checking for | |
each value if it is equal to the element in the subsequence array, once a match is found, it's on to the next | |
element in the subsequence. Note that if no match is found, the lenght of the subsequence array will never be same | |
as the value of variable "Seq" | |
Space and time complexity => O(n) time | O(1) space | |
*/ | |
let seq = 0; | |
for (const value of array) { | |
if (sequence[seq] === value) { | |
seq++ | |
} | |
} | |
return seq === sequence.length; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment