#2904
Shortest and Lexicographically Smallest Beautiful String
MediumStringSliding WindowSliding WindowTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a sliding window technique to efficiently find the shortest beautiful substring. By maintaining a window that expands and contracts, we can count the '1's without needing to recheck the entire substring each time.
⚙️
Algorithm
5 steps- 1Step 1: Initialize two pointers (left and right) and a count for '1's.
- 2Step 2: Expand the right pointer to include characters until the count of '1's equals k.
- 3Step 3: Once k '1's are found, try to contract the left pointer to minimize the substring length while maintaining k '1's.
- 4Step 4: Update the shortest and lexicographically smallest substring if the current one is valid.
- 5Step 5: Continue this process until the right pointer reaches the end of the string.
solution.py16 lines
1def shortest_beautiful_string(s, k):
2 left, right, count = 0, 0, 0
3 shortest = ''
4 n = len(s)
5 while right < n:
6 if s[right] == '1':
7 count += 1
8 while count == k:
9 substring = s[left:right + 1]
10 if (not shortest) or (len(substring) < len(shortest)) or (len(substring) == len(shortest) and substring < shortest):
11 shortest = substring
12 if s[left] == '1':
13 count -= 1
14 left += 1
15 right += 1
16 return shortestℹ
Complexity note: The time complexity is O(n) because each character is processed at most twice (once by the right pointer and once by the left pointer). The space complexity is O(n) due to the substring storage.
- 1Sliding window technique allows for efficient substring examination without redundant checks.
- 2Lexicographical comparison can be efficiently managed during the substring evaluation.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.