Minimum Window Subsequence

50 min · minWindow()

A long activity log contains the events you need in the right order, but they're spread apart. How little of the log can you keep without losing that ordered trail?

You're given two lowercase strings, s1 and s2.

A contiguous substring is one unbroken slice of a string. A subsequence keeps characters in their original order but may skip characters between them.

Return the shortest contiguous substring W of s1 in which s2 appears as a subsequence. If no such window exists, return "".

A few ground rules:

  • You may skip characters inside W while matching s2, but you can't reorder them.
  • If several shortest windows have the same length, return the one with the leftmost starting index in s1.
  • The returned window must contain consecutive characters from s1.

Constraints

  • 1 <= s1.length <= 2_000
  • 1 <= s2.length <= 100
  • s1 and s2 contain only lowercase English letters.

Hints

Anchor a starting point

Fix a start in s1, then walk right while matching the next needed character from s2. The first end that completes s2 is the best end for that fixed start.

Store the latest beginning

A prefix is a slice that starts at index 0. For each prefix of s2, track the latest index in s1 where a matching subsequence could have started. A later start gives a shorter window for the same end.

Update prefixes backward

When s1[i] matches s2[j], extend the answer for prefix j - 1. Visit j from right to left so the same character from s1 can't satisfy two positions in s2.

Follow-up

Could you return the exact indices in s1 that matched each character of s2, not just the surrounding window? What extra information would your states need to remember?

Visible cases

Examples

Example 1

ready
Input
s1 = "abcdebdde"
s2 = "bde"
Expected
"bcde"
Why
both 'bcde' and 'bdde' work at length 4, so the leftmost one wins

Example 2

ready
Input
s1 = "jmeqksfrsdcmsiwvaovztaqenprpvnbstl"
s2 = "u"
Expected
""
Why
the required character never appears, so no window exists

Example 3

ready
Input
s1 = "abcab"
s2 = "ac"
Expected
"abc"
Why
a and c appear in order inside the shortest slice 'abc'

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite