Shortest and Lexicographically Smallest Beautiful String - Problem
You are given a binary string s and a positive integer k.
A substring of s is beautiful if the number of 1s in it is exactly k.
Let len be the length of the shortest beautiful substring.
Return the lexicographically smallest beautiful substring of string s with length equal to len.
If s doesn't contain a beautiful substring, return an empty string.
A string a is lexicographically larger than a string b (of the same length) if in the first position where a and b differ, a has a character strictly larger than the corresponding character in b.
Input & Output
Example 1 — Basic Case
$
Input:
s = "100110", k = 2
›
Output:
"11"
💡 Note:
The beautiful substrings with exactly 2 ones are: "1001" (length 4), "0011" (length 4), "0110" (length 4), and "11" (length 2). The shortest length is 2, so return "11".
Example 2 — No Beautiful Substring
$
Input:
s = "000", k = 1
›
Output:
""
💡 Note:
The string contains only zeros, so no substring can have exactly 1 one. Return empty string.
Example 3 — Multiple Same Length
$
Input:
s = "0101", k = 1
›
Output:
"0"
💡 Note:
Beautiful substrings with k=1: "1" at positions 1 and 3, "0" at positions 0 and 2. All have length 1. Lexicographically smallest is "0".
Constraints
- 1 ≤ s.length ≤ 100
- 1 ≤ k ≤ s.length
- s consists only of '0' and '1'.
Visualization
Tap to expand
Understanding the Visualization
1
Input
Binary string s="100110" and k=2
2
Find Beautiful
Locate all substrings with exactly 2 ones
3
Return Best
Return shortest and lexicographically smallest: "11"
Key Takeaway
🎯 Key Insight: Use sliding window to efficiently find minimum length, then compare candidates
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code