How to Validate If A Second Array Is A Subsequence of the First Array

Christa Gammage
2 min readSep 27, 2020

Another popular interview question for the coding interview is to validate if a second array is a subsequence of the first array. For example, if the first array is: [1, 2, 3, 4, 5], and the second array is: [1, 2, 3], your function should return “true.” Let’s tackle this solution in Javascript.

First, you’re going to want to keep track of what index you are in in both the first and the second array. So let’s initialize two variables both at 0, one to track the index of the array and one to track the index of the sequence.

Next, we’re going to make sure that we’re only going to be looping over the arrays while each of them are “truthy.” If one of them doesn’t exit, it’s going to break our code. So let’s throw that statement in there as well.

Let’s stop for a second and think about what we’re looking for exactly. We need to find the array element that is the same as the sequence element. If they are the same, then let’s move on to check the next index in the sequence. And regardless of whether they are the same or not, we want to continue iterating through our array. So let’s incorporate that conditional into our while loop with an If statement.

How will we know when we have found a complete subsequence? When the value of seqIdx is equal to the length of the sequence.

This will return a boolean — if seqIdx is not equal to the length of the sequence, then we clearly did not find all of the elements of the sequence to be present in the array.

--

--