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: "1"
💡 Note: Beautiful substrings with k=1: "1" at position 1 (length 1), "1" at position 3 (length 1), "01" at positions 0-1 (length 2), "10" at positions 1-2 (length 2), "01" at positions 2-3 (length 2). Shortest length is 1, so return "1".

Constraints

  • 1 ≤ s.length ≤ 100
  • 1 ≤ k ≤ s.length
  • s consists only of '0' and '1'.

Visualization

Tap to expand
Shortest and Lexicographically Smallest Beautiful String INPUT Binary String s: 1 0 0 1 0 2 1 3 1 4 0 5 index s = "100110" k = 2 Beautiful Substring: Has exactly k ones Goal: Shortest, then lex smallest ALGORITHM STEPS 1 Sliding Window Find all substrings with k ones 2 Track Minimum Length Shrink window to minimize 3 Compare Lex Order Among shortest, pick smallest 4 Return Result Output best substring Beautiful Substrings Found: "100110" [0-5] len=6 "10011" [0-4] len=5 "0011" [1-4] len=4 "011" [2-4] len=3 "11" [3-4] len=2 -- BEST FINAL RESULT Shortest Beautiful Substring: 1 0 0 1 1 0 answer Output: "11" Verification: Length: 2 (minimum) OK Count of 1s: 2 = k OK Lex smallest: "11" OK Beautiful Substring Found! Key Insight: Use a sliding window to find all substrings with exactly k ones. Track the minimum length found. Among substrings of minimum length, compare lexicographically to find the smallest one. Shrink window from left when count exceeds k. Time: O(n^2) due to string comparison, Space: O(1). TutorialsPoint - Shortest and Lexicographically Smallest Beautiful String | Optimal Solution
Asked in
Google 15 Microsoft 12 Amazon 8 Apple 6
23.4K Views
Medium Frequency
~18 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen