You are given a binary string s
and a positive integer k
.
A substring of s
is beautiful if the number of 1
's 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
.
For example, "abcd"
is lexicographically larger than "abcc"
because the first position they differ is at the fourth character, and d
is greater than c
.
Example 1:
Input: s = "100011001", k = 3
Output: "11001"
Example 2:
Input: s = "1011", k = 2
Output: "11"
Example 3:
Input: s = "000", k = 1
Output: ""
Constraints:
1 <= s.length <= 100
1 <= k <= s.length
s
.k
, the substring is beautiful.def shortest_beautiful_substring_brute_force(s, k):
n = len(s)
min_len = float('inf')
result = ""
for i in range(n):
for j in range(i, n):
sub = s[i:j+1]
ones = sub.count('1')
if ones == k:
if len(sub) < min_len:
min_len = len(sub)
result = sub
elif len(sub) == min_len and sub < result:
result = sub
return result
A sliding window approach can improve efficiency by avoiding redundant calculations.
k
, shrink the window from the left until the count is equal to k
.k
, update the minimum length and lexicographically smallest substring.k
is greater than the number of 1s in s
.def shortest_beautiful_substring(s, k):
n = len(s)
min_len = float('inf')
result = ""
left = 0
ones = 0
for right in range(n):
if s[right] == '1':
ones += 1
while ones > k:
if s[left] == '1':
ones -= 1
left += 1
if ones == k:
length = right - left + 1
sub = s[left:right+1]
if length < min_len:
min_len = length
result = sub
elif length == min_len and sub < result:
result = sub
return result
s
is visited at most twice (once by the right pointer and once by the left pointer).