Find Shortest Covering Substring
Company: Character
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates proficiency in string processing, handling character multiplicities, and designing time- and space-efficient algorithms for substring search.
Constraints
- 1 <= len(source), len(target) <= 100000
- Characters may be uppercase letters, lowercase letters, digits, or symbols.
- Character matching is case-sensitive.
- Duplicate characters in `target` must also appear with the same multiplicity in the chosen substring.
Examples
Input: ("ADOBECODEBANC", "ABC")
Expected Output: "BANC"
Explanation: "BANC" contains A, B, and C, and no shorter valid substring exists.
Input: ("AAABBC", "AABC")
Expected Output: "AABBC"
Explanation: The target needs two 'A' characters, one 'B', and one 'C'. The shortest substring that satisfies this is "AABBC".
Input: ("a", "aa")
Expected Output: ""
Explanation: The source does not contain enough 'a' characters to cover the target.
Input: ("a", "a")
Expected Output: "a"
Explanation: The single character itself is the shortest valid substring.
Input: ("aA$bb$A", "$A")
Expected Output: "A$"
Explanation: Both "A$" and "$A" are valid length-2 answers, but "A$" appears first, so it is returned.
Hints
- Track how many of each character you still need, and update that information as a window expands and shrinks.
- Once a window becomes valid, try moving its left edge rightward while keeping it valid to minimize its length.