-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidateSubsequence.js
29 lines (25 loc) · 1006 Bytes
/
ValidateSubsequence.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/* Given two non-empty arrays of integers, write a function that determines whether the second
array is a subsequence of the first one.
A subsequence of an array is a set of numbers that aren't necessarily adjacent in the array
but that are in the same order as they appear in the array. For instance, the numbers [1, 3, 4]
form a subsequence of the array [1, 2, 3, 4], and so do the numbers [2, 4]. Note that a single
number in an array and the array itself are both valid subsequences of the array.
Sample Input
array = [5, 1, 22, 25, 6, -1, 8, 10]
sequence = [1, 6, -1, 10]
Sample Output
true */
function isValidSubsequence(array, sequence) {
if(sequence.length > array.length) {
return false
} else {
let seqIndex = 0
for (const val of array) {
if (val === sequence[seqIndex]) {
seqIndex++
}
}
return seqIndex === sequence.length ? true : false
}
}
console.log(isValidSubsequence([5, 1, 22, 25, 6, -1, 8, 10], [1, 6, -1, 5]))