Skip to content

Latest commit

 

History

History
37 lines (26 loc) · 959 Bytes

File metadata and controls

37 lines (26 loc) · 959 Bytes

Level: Easy

Topic: Array Two Pointers Dynamic Programming

Question

Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

Input: s = "abc", t = "ahbgdc"
Output: true

Intuition

Two Pointers Approach

  • keep a sPointer and a tPointer
  • increment sPointer until sees the same char in t
  • lastly, if all chars in s are found, return true

Code

Time: O(t.length)
Space: O(1)

public boolean isSubsequence(String s, String t) {
    int p1 = 0, p2 = 0;
    while (p1 < s.length() && p2 < t.length()) {
        if (s.charAt(p1) == t.charAt(p2))
            p1++;
        p2++;
    }
    return p1 == s.length();
}