Skip to content
Advertisement

AlgoExpert: Validate Subsequence, not passing all test cases

AlgoExpert Question Prompt

Question: Validate Subsequence on AlgoExpert. Given two non-empty arrays of integers write a function that determines whether the second array is a subsequence of the first one.

My code is not passing all test cases, what am I doing wrong?

public static boolean isValidSubsequence(List<Integer> array, List<Integer> sequence) {
    int arrayIndex = 0;
    int sequenceIndex = 0;
    
    while(arrayIndex < array.size() && sequenceIndex < sequence.size()){
        if(array.get(arrayIndex).equals(sequence.get(sequenceIndex))){
            sequenceIndex++;
        } else {
            arrayIndex++;
        }
    }
    if(sequenceIndex == (sequence.size())){
        return true;
    }
    return false;
}

Advertisement

Answer

Thanks for everyone’s help! Updated Solution:

  public static boolean isValidSubsequence(List<Integer> array, List<Integer> sequence) {
    int arrayIndex = 0;
    int sequenceIndex = 0;
    
    while(arrayIndex < array.size() && sequenceIndex < sequence.size()){
        if(array.get(arrayIndex).equals(sequence.get(sequenceIndex))){
            sequenceIndex++;
            arrayIndex++;       
    } else {
            arrayIndex++;
        }
    if(sequenceIndex == (sequence.size())){
        return true;
    }
}
            return false;
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement