Shortest and Lexicographically Smallest Beautiful String - Problem
Find the Shortest Beautiful Substring
You're given a binary string
A substring is beautiful if it contains exactly
1. Find the minimum length of any beautiful substring
2. Among all beautiful substrings with this minimum length, return the lexicographically smallest one
If no beautiful substring exists, return an empty string.
Example: For
You're given a binary string
s containing only '0's and '1's, and a positive integer k. Your task is to find a special substring called a "beautiful substring".A substring is beautiful if it contains exactly
k ones ('1's). Among all beautiful substrings, you need to:1. Find the minimum length of any beautiful substring
2. Among all beautiful substrings with this minimum length, return the lexicographically smallest one
If no beautiful substring exists, return an empty string.
Example: For
s = "100110" and k = 2, the beautiful substrings are "10011", "00110", "0011", "011". The shortest length is 3, and "011" is lexicographically smallest among length-3 beautiful substrings. Input & Output
example_1.py โ Basic Case
$
Input:
s = "100110", k = 2
โบ
Output:
"11"
๐ก Note:
Beautiful substrings with exactly 2 ones: "1001" (length 4), "0011" (length 4), "11" (length 2). The shortest length is 2, and "11" is the only substring of length 2.
example_2.py โ Multiple Same Length
$
Input:
s = "1011", k = 2
โบ
Output:
"01"
๐ก Note:
Beautiful substrings: "10" (length 2), "01" (length 2), "11" (length 2), "101" (length 3), "011" (length 3), "1011" (length 4). Among length-2 substrings, "01" is lexicographically smallest.
example_3.py โ No Solution
$
Input:
s = "000", k = 1
โบ
Output:
""
๐ก Note:
The string contains no 1's, so no beautiful substring with exactly 1 one can be formed.
Constraints
- 1 โค s.length โค 100
- 1 โค k โค s.length
- s consists only of '0' and '1'
- The number of 1's in s is at least k for a solution to exist
Visualization
Tap to expand
Understanding the Visualization
1
Identify Pearl Positions
Mark all positions containing pearls (1's) in the binary string
2
Start Collection
Begin collecting from each pearl position, extending the net until you have k pearls
3
Measure and Compare
For each valid collection, measure its length and lexicographic value
4
Select the Best
Choose the shortest collection, and if tied, the lexicographically smallest
Key Takeaway
๐ฏ Key Insight: By starting our search only from positions containing '1' and using a sliding window approach, we efficiently find the shortest beautiful substring while ensuring lexicographic minimality.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code