v9.1.1
Menu

Smallest Window Containing All Features

hardPROSliding WindowSliding Window, Hash MapCV - DSA

Problem Statement

In computer vision, feature matching often requires finding the smallest region in an image that contains all required feature types.

Given a string features representing detected features in a scan line, and a string required containing all feature types that must be present, find the length of the smallest contiguous substring of features that contains all characters in required.

Characters are case-sensitive, and duplicates in required count: the window must contain each character at least as many times as it appears in required (e.g. required = "aa" needs two as).

If no such window exists, return 0.

Applications

  • Finding minimal bounding regions containing specific objects
  • Video keyframe selection
  • Region-of-interest detection

Constraints

  • 1≤len(features)≤1051 \leq len(features) \leq 10^5
  • 1≤len(required)≤1001 \leq len(required) \leq 100
  • Strings contain uppercase and lowercase English letters

Example

Input
features = "ADOBECODEBANC", required = "ABC"
Output
4
Reasoning
  • features is the scan line: 13 detections, one letter each, at positions 00 to 1212. required lists the feature types a window must cover: one A, one B, one C.
  • A window is a contiguous stretch from position ll to rr; its length is r−l+1r - l + 1. It is valid if every required type appears in it at least as often as in required.
  • Some valid windows: ADOBEC (positions 00–55, length 66), CODEBA (55–1010, length 66) and BANC (99–1212, length 44).
  • The As sit at 00 and 1010, the Bs at 33 and 99, the Cs at 55 and 1212. The closest trio is {9,10,12}\{9, 10, 12\}, spanning 44 positions, so nothing shorter works and the output is 4.
  • Notice the answer is a length, not the substring. If required asked for more copies than features holds (two "a"s against a single "a"), no window is valid and the result is 0.

More from CV - DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.