Tutte le sfide
Difficile 1 risolta 50.0% di accettazione

Minimum Window Substring

Find the shortest piece of text containing all required characters.

Cosa imparerai

  • Grow and shrink a window over text
  • Track required character counts
  • Find the shortest valid window

Problema

Mostra traduzione

Find the shortest contiguous substring of text that contains every character of pattern, including repeats. If several are equally short, return the leftmost.

Implement min_window(text, pattern).

Input

text: The text to search. pattern: The characters that must appear.

Output

Return the shortest window, or an empty string if none exists.

Vincoli

1 ≤ length of text, pattern ≤ 100,000 (ASCII)

Esempi

Esempio 1
Input:
text = "ADOBECODEBANC"
pattern = "ABC"

Output atteso:
expected = "BANC"
Input:
std::string text = "ADOBECODEBANC";
std::string pattern = "ABC";

Output atteso:
std::string expected = "BANC";
Input:
string text = "ADOBECODEBANC";
string pattern = "ABC";

Output atteso:
string expected = "BANC";

Spiegazione

"BANC" contains A, B and C and nothing shorter does.

Esempio 2
Input:
text = "a"
pattern = "aa"

Output atteso:
expected = ""
Input:
std::string text = "a";
std::string pattern = "aa";

Output atteso:
std::string expected = "";
Input:
string text = "a";
string pattern = "aa";

Output atteso:
string expected = "";

Spiegazione

Two a's are needed but the text has only one: "".

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

The window must cover all needed character counts, not just distinct characters.

Suggerimento 2

Expand until valid, then shrink from the left to remove unnecessary characters while staying valid.

Suggerimento 3

If multiple windows share the same minimum length, keep the earliest one when updating your best answer.

Complessità attesa

O(n) time, O(1) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

# Programmatore Linguaggio Tempo Memoria Voto dell'IA Soluzione
1 Н"Никита "Programmer" Python 835 ms - 5/5 Vedi il codice

Impara dagli altri

Soluzioni della community

Attenzione spoiler: 1 soluzione completa sotto Prova prima a risolverla da solo. Puoi comunque sbirciare il codice degli altri sviluppatori e le revisioni dell'IA. Accedi e risolvi la sfida per partecipare alla discussione.