Home > OS >  AlgoExpert: Validate Subsequence, not passing all test cases
AlgoExpert: Validate Subsequence, not passing all test cases

Time:05-16

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;
}

CodePudding user response:

If you have matched a character in both arrays, you should be moving both pointers instead of just one.

if(array.get(arrayIndex).equals(sequence.get(sequenceIndex))){
    sequenceIndex  ;
}
arrayIndex  ;        

CodePudding user response:

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;
}
  • Related