Smallest Window Containing All Features
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
- Strings contain uppercase and lowercase English letters
Example
features = "ADOBECODEBANC", required = "ABC"
4
featuresis the scan line: 13 detections, one letter each, at positions to .requiredlists the feature types a window must cover: oneA, oneB, oneC.- A window is a contiguous stretch from position to ; its length is . It is valid if every required type appears in it at least as often as in
required. - Some valid windows:
ADOBEC(positions –, length ),CODEBA(–, length ) andBANC(–, length ). - The
As sit at and , theBs at and , theCs at and . The closest trio is , spanning positions, so nothing shorter works and the output is4. - Notice the answer is a length, not the substring. If
requiredasked for more copies thanfeaturesholds (two "a"s against a single "a"), no window is valid and the result is0.