Skip to content

Instantly share code, notes, and snippets.

@ritik-agrawal
Created August 7, 2023 05:11
Show Gist options
  • Save ritik-agrawal/0a7bf0864fea2beb69adfaf3dade9633 to your computer and use it in GitHub Desktop.
Save ritik-agrawal/0a7bf0864fea2beb69adfaf3dade9633 to your computer and use it in GitHub Desktop.
LeetCode: isSubsequence, given with two strings return true if `s` is subsequence of `t` .
class Solution {
public boolean isSubsequence(String s, String t) {
var slen = s.length();
var tlen = t.length();
if (slen == 0){
return true;
}
if (tlen < slen){
return false;
}
var sc = 0;
for (int i = 0; i < tlen; i++){
if (sc < slen && s.charAt(sc) == t.charAt(i)){
sc++;
}
}
return (sc == slen);
}
}
@ritik-agrawal
Copy link
Author

Example

A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., ace is a subsequence of abcde while aec is not).

Observation

The above problem has been solved using an algorithm with two different implementations.

Algorithm

  • if the s length is equal to zero then return true.
  • if the t length is less than the s length then return false.
  • A marker that iterates through the s character after it's seen in 't'
  • if the marker is equal to s length then return true else false.

Implementation 1

Using the s.toCharArray(). This implementation beats 54% of the total solutions submitted with a runtime of 2 ms.

Implementation 2

Using s.charAt(i) to iterate through the strings given instead of the array index. This implementation beats 89% of total solutions submitted with a runtime of 1 ms.

Click here for the Leetcode submission page.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment