Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Two pointers

Is one string a subsequence of another

Easy · Target 10 minutes · Two pointers· Type asked at

You're given two strings s and t of lower-case letters. Return true if you can get s by deleting some of the letters of t (or none of them) and keeping the rest in the order they're in, and false if you can't.

Examples

InputOutputWhy
s = "abc", t = "ahbgdc"trueIf you delete the h, the g and the d you're left with abc.
s = "axc", t = "ahbgdc"falseThere's no x anywhere in t so it can't work.
s = "ba", t = "ab"falseBoth letters are there but they're the wrong way round, and you're not allowed to reorder.

Constraints

  • 0 ≤ s.length ≤ 100
  • 0 ≤ t.length ≤ 10⁴
  • s and t hold lower-case letters only

Hints

Hint 1

Say the first letter of s turns up several times in t. Which one of those would you want to match it to?

Hint 2

The earliest one, because that leaves the most of t for the rest of s and there's nothing a later match could do that the earlier one can't.

Hint 3

So you keep i on s and j on t and move j along every time, and you only move i when s[i] = t[j]. If i gets to the end of s the answer's true.

Where people lose marks

  • Checking only that every letter of s turns up somewhere in t. That ignores the order, and ba against ab is the case I'd test it with.
  • Forgetting that the empty string is a subsequence of everything, including another empty string.
  • Reaching for the longest common subsequence DP, which does get the right answer but it's O(|s| × |t|) when one pass is enough.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.