call(back)
Algorithms & Data StructureshardSign in to star problems

Document Coverage: The Shortest Window

A document is a list of words and a query is a set of distinct terms. Return the shortest contiguous span of the document that contains every term at least once, as [start, end] indices (inclusive). If several spans are shortest, return the one that starts first; if no span covers the query, return [].

shortestCoverage(["a", "b", "c", "a", "d", "b", "c"], ["a", "b", "c"])  ->  [0, 2]
shortestCoverage(["x", "a", "y", "b", "z", "c", "a", "b", "c"], ["a", "b", "c"])  ->  [5, 7]
shortestCoverage(["a", "b"], ["c"])  ->  []

Hints

Hint 1

Sliding window with a count per term and the number of terms currently satisfied. Advance the right end; whenever every term is satisfied, advance the left end as far as it can go without losing a term.

Hint 2

Record a window only when it is strictly shorter than the best so far — that is what makes ties resolve to the earliest start.

Asked at