Skip to content

Commit dd9d486

Browse files
committed
feat: Solves Validate Subsequence
- AlgoExpert
1 parent c085479 commit dd9d486

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* AlgoExpert
3+
*
4+
* Given two non-empty arrays of integers, write a function that determines
5+
* whether the second array is a subsequence of the first one.
6+
*
7+
* A subsequence of an array is a set of numbers that aren't necessarily adjacent
8+
* in the array but that are in the same order as they appear in the array. For
9+
* instance, the numbers [1, 3, 4] form a subsequence of the array [1, 2, 3, 4],
10+
* and so do the numbers [2, 4]. Note that a single number in an array and the
11+
* array itself are both valid subsequences of the array.
12+
*/
13+
14+
/**
15+
* @param {number[]} array
16+
* @param {number[]} sequence
17+
* @returns {boolean}
18+
*/
19+
function isValidSubsequence(array, sequence) {
20+
// Time: O(n), Space: O(1)
21+
let seqIdx = 0;
22+
let i = 0;
23+
24+
while(i < array.length && seqIdx < sequence.length) {
25+
const arrElement = array[i];
26+
const seqElement = sequence[seqIdx];
27+
28+
if (arrElement === seqElement) {
29+
seqIdx++;
30+
}
31+
32+
i++;
33+
}
34+
35+
return seqIdx === sequence.length;
36+
}

0 commit comments

Comments
 (0)