#C10228. Minimum Substring with All Characters

    ID: 39410 Type: Default 1000ms 256MiB

Minimum Substring with All Characters

Minimum Substring with All Characters

You are given two strings s and t which consist of lowercase letters (and may contain spaces). Your task is to determine the length of the smallest contiguous substring of s that contains all the characters present in t (including duplicate characters). If no such substring exists, print 0.

For example, given s = "ADOBECODEBANC" and t = "ABC", the smallest substring covering all characters is "BANC", and its length is 4.

Hint: A sliding window (or two pointers) approach can be used to solve this problem efficiently. The window expands until it contains all required characters, and then shrinks optimally to find the minimum window size. Mathematically, if we denote a valid window by indices i and j, we want to minimize the window length j - i + 1 such that for every character c in t, \[ \text{count}_\text{window}(c) \geq \text{count}_\text{t}(c) \]

inputFormat

The input is read from stdin and consists of two lines:

  • The first line contains the string s.
  • The second line contains the string t.

outputFormat

Output a single integer to stdout which is the length of the smallest substring of s containing all characters of t (including duplicates). If no such substring exists, output 0.

## sample
ADOBECODEBANC
ABC
4