Leetcode 2904: Shortest and Lexicographically Smallest Beautiful String

grid47
grid47
Exploring patterns and algorithms
Jan 21, 2024 6 min read

You are given a binary string s and a positive integer k. A substring of s is considered ‘beautiful’ if it contains exactly k occurrences of ‘1’. Your task is to return the lexicographically smallest substring of the shortest length that has exactly k ‘1’s. If no such substring exists, return an empty string.
Problem
Approach
Steps
Complexity
Input: The input consists of a binary string `s` and a positive integer `k`. The length of the string `s` is at least 1 and at most 100, and `k` is a positive integer such that `1 <= k <= s.length`.
Example: s = '11010101', k = 3
Constraints:
• 1 <= s.length <= 100
• 1 <= k <= s.length
Output: Return the lexicographically smallest beautiful substring of the shortest length that contains exactly `k` '1's, or an empty string if no such substring exists.
Example: '10101'
Constraints:
• If no beautiful substring exists, return an empty string.
Goal: The goal is to find the lexicographically smallest substring that contains exactly `k` '1's.
Steps:
• 1. Iterate through the binary string `s` while maintaining a count of '1's.
• 2. Whenever the count reaches `k`, check if the current substring is valid and potentially update the result if it is the shortest or lexicographically smaller than any previous valid substring.
• 3. Return the lexicographically smallest substring with the minimum length, or an empty string if no such substring is found.
Goal: The input string `s` is non-empty and its length is at most 100. The integer `k` is between 1 and the length of `s`.
Steps:
• The string `s` has a length between 1 and 100.
• The integer `k` is between 1 and the length of `s`.
Assumptions:
• The input string `s` contains only '0's and '1's.
• The integer `k` is valid, i.e., `1 <= k <= s.length`.
Input: Input: '11010101', k = 3
Explanation: In this case, the valid substrings with exactly 3 '1's are ['11010101', '1010101', '010101', '10101']. The shortest substring is '10101', which is also the lexicographically smallest substring.

Input: Input: '11100', k = 2
Explanation: Here, the valid substrings with exactly 2 '1's are ['11100', '110', '11']. The shortest valid substring is '11'.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus