Ctrl K

Shortest Window Holding a Subsequence

Hard
You are given strings text and pattern. Find the shortest substring of text (a contiguous piece) that contains pattern as a subsequence, meaning all letters of pattern appear in it in the same order, though not necessarily next to each other. If several substrings share the minimum length, return the one that starts furthest left. If no substring fits, return the empty string "".
Example 1
text='abxbcab', pattern='bc' → 'bc'

The window "bxbc" also contains "bc" as a subsequence, but "bc" starting at position 3 is shorter.

Example 2
text='adbaeb', pattern='ab' → 'adb'

Both "adb" and "aeb" fit and have length 3; take the one that starts further left.

Example 3
text='abc', pattern='ca' → ''

No a comes after the c in the text, so no window fits.

Constraints
  • 1 ≤ text.length ≤ 2 · 10⁴
  • 1 ≤ pattern.length ≤ 100
  • text and pattern consist of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsHop Across Safe Tiles MediumAlternate After Rotating MediumTrim and Extend a Word MediumPattern With Dot and Star HardWord Blocks in Any Order Hard
loading Python…
Input
text='abxbcab', pattern='bc'
Expected
'bc'

Run checks the first 3 tests in your browser. Submit checks all 161 tests on the server, hidden ones included.