AlgoExpert: Validate Subsequence, not passing all test cases

Viewed 214

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

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

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

This solution passed all the tests, cheer!

    import java.util.*;

class Program {
  public static boolean isValidSubsequence(List<Integer> array, List<Integer> sequence) {
    // Write your code here.
    int k=0;
    int truecounter=0;
    int totalsize=sequence.size();
    for(int i=0; i<array.size(); i++){
      if(k<totalsize){
        int squencearray_value = sequence.get(k);
        if(squencearray_value == array.get(i)){
          truecounter=truecounter+1;
          k++;
        }
      }else{
        if(truecounter==totalsize)
          return true;
        else 
          return false;
    
      }
      
    }

     if(truecounter==totalsize)
          return true;
        else 
          return false;
    
   // return false;
  }
}
Related