Codementor Events

LeetCode: Is Subsequence (2ms)

Published May 28, 2022
LeetCode: Is Subsequence (2ms)

I was practising some coding questions on Leetcode and it is interesting how your code can run against other people's code worldwide. You can see the comparison and how close you are to the best. The very good part of doing this is because it helps you to know best practice and better optimise your code. Below is my code for the Subsequence problem in Java.

public class Solution {
    public boolean isSubsequence(String s, String t) {
        int pos = 0;
        int prevPos = 0;
        
        for(int i = 0; i < s.length(); i++) {
            
            if (t.indexOf(s.charAt(i), pos) == -1 || prevPos > t.indexOf(s.charAt(i), pos)) {
                return false;
            }
            
            prevPos = t.indexOf(s.charAt(i), pos);
            pos = prevPos + 1;
        }
        
        return true;
    }
}
Discover and read more posts from Akinyele Olubodun
get started
post commentsBe the first to share your opinion
Show more replies