InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Is Subsequence

easy Original ↗ 00:00

Problem

Given two strings s and t, return True if s is a subsequence of t, and False otherwise.

A subsequence keeps characters in their original relative order but may skip any number of characters. Formally, s is a subsequence of t if you can delete zero or more characters from t (without reordering the rest) and obtain s. The empty string is a subsequence of everything.

Follow-up: if a huge number of query strings s1, s2, ..., sk (say k >= 10^9) will each be tested against the same t, how would you preprocess t to answer each query fast?

Examples

  • s = "abc", t = "ahbgdc"True — take a (index 0), b (index 2), c (index 5), in order.
  • s = "axc", t = "ahbgdc"False — after matching a, no x appears anywhere later in t.
  • s = "", t = "xyz"True — the empty string is a subsequence of any string.

Constraints

  • 0 <= len(s) <= 100
  • 0 <= len(t) <= 10^4
  • Both strings consist of lowercase English letters only.

A single O(len(t)) scan answers one query; the follow-up wants each query in roughly O(len(s) · log len(t)) after preprocessing.

Think about it first

Hint 1 To match s inside t, does it ever hurt to take the earliest occurrence in t of the character you currently need?
Hint 2 Keep one pointer into s. Walk t once; when the current t character equals the s character under the pointer, advance the pointer. What does the pointer equal at the end if s fits?
Hint 3 For the follow-up: record, for each letter, the sorted list of its positions in t. To match the next character of a query after position p, binary-search that letter's list for the first position greater than p.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug