LeetCode 2904: Shortest and Lexicographically Smallest Beautiful String Solution
Master LeetCode problem 2904 (Shortest and Lexicographically Smallest Beautiful String), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2904. Shortest and Lexicographically Smallest Beautiful String
Problem Explanation
Explanation:
To solve this problem, we can use a sliding window approach. We iterate through the input string s and maintain a window of size k to count the number of ones in each substring. If the count of ones in the window is equal to k, we update the result string to be the lexicographically smallest substring of length k encountered so far. We keep track of the start index of the window and move the window one step at a time. If the count of ones in the window is less than k, we expand the window. If the count exceeds k, we contract the window.
At the end of the iteration, we return the lexicographically smallest substring found or an empty string if no beautiful substring is present in the input string s.
- Time complexity: O(n), where n is the length of the input string
s. - Space complexity: O(1)
:
Solution Code
class Solution {
public String shortestBeautifulString(String s, int k) {
String res = "";
int count = 0, start = 0, minLen = Integer.MAX_VALUE;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '1') {
count++;
}
while (count == k) {
if (i - start + 1 < minLen) {
minLen = i - start + 1;
res = s.substring(start, i + 1);
}
if (s.charAt(start) == '1') {
count--;
}
start++;
}
}
return res;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2904 (Shortest and Lexicographically Smallest Beautiful String)?
This page provides optimized solutions for LeetCode problem 2904 (Shortest and Lexicographically Smallest Beautiful String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2904 (Shortest and Lexicographically Smallest Beautiful String)?
The time complexity for LeetCode 2904 (Shortest and Lexicographically Smallest Beautiful String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2904 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2904 in Java, C++, or Python.