InterviewPrepKit

Home / Coding / Arrays & Hashing

Is Subsequence

easy Original β†—
Solving tips
  • Recognize order-preserving matching: a greedy two-pointer scan works because taking the earliest usable occurrence of each needed character is never worse.
  • Keep one pointer into s, walk t once, advance the pointer on each match, and answer True iff the pointer reaches len(s); O(|t|) time, O(1) space.
  • For the many-queries follow-up, preprocess t into a map letter->sorted positions and binary-search (bisect_right) for the first position strictly after the last match.
  • Pitfall: guard s[i] with i < len(s) once s is exhausted, and use bisect_right (not bisect_left) so you don't reuse the same position.

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(|t|) scan answers one query; the follow-up wants each query in roughly O(|s| log |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.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.