Is Subsequence [Easy]

17 Aug 2026, Updated: 19 Sep 2026 2 min read
2
The Is Subsequence problem asks whether one string can be formed from another by deleting some characters without changing the relative order of the remaining characters.

Problem

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

A subsequence is formed by deleting zero or more characters from a string without changing the relative order of the remaining characters.

Example(s)

Consider the following example(s) to understand the expected input and output.

Input

s = "abc" t = "ahbgdc"

Output

true

Solution

This solution uses the Two Pointer technique. The i pointer tracks the current character in s, while the j pointer traverses t.

Whenever s[i] matches t[j], we increment i because that character has been successfully matched. The j pointer is incremented after every comparison to continue scanning t.

If i reaches the length of s, all characters of s have been found in the correct order, so we return true. Otherwise, s is not a subsequence of t.
class Solution {
    public boolean isSubsequence(String s, String t) {
        int i = 0, j = 0;

        while (i < s.length() && j < t.length()) {
            if (s.charAt(i) == t.charAt(j)) {
                i++;
            }
            j++;
        }
        return i == s.length();
    }
}

Complexity

The t string is traversed at most once, resulting in a time complexity of O(n), where n is the length of t.

The algorithm uses only two pointers, so the extra space complexity is O(1).
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer • Java • Python • Distributed Systems • AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

💬 Comments

Join the Discussion