Shortest and Lexicographically Smallest Beautiful String — LeetCode 2904 Python Solution

MediumStringSliding Window
Problem
#2904
Reading time
2 min

The problem

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.

Example

Input
s = "100011001", k = 3
Output
"11001"
Explanation
There are 7 beautiful substrings in this example:

Python solution

Python
class Solution:
    def shortestBeautifulSubstring(self, s: str, k: int) -> str:
        n = len(s)
        ans = ""
        for i in range(n):
            for j in range(i + k, n + 1):
                t = s[i:j]
                if t.count("1") == k and (
                    not ans or j - i < len(ans) or (j - i == len(ans) and t < ans)
                ):
                    ans = t
        return ans

Complexity

MeasureComplexity
TimeO(n^3)
SpaceO(n) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2904. Shortest and Lexicographically Smallest Beautiful String is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2904. Shortest and Lexicographically Smallest Beautiful String?
LeetCode 2904. Shortest and Lexicographically Smallest Beautiful String is rated Medium on LeetCode.
What is the time complexity of LeetCode 2904. Shortest and Lexicographically Smallest Beautiful String?
The Python solution on this page runs in O(n^3).
What is the space complexity of LeetCode 2904. Shortest and Lexicographically Smallest Beautiful String?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2904. Shortest and Lexicographically Smallest Beautiful String cover?
LeetCode 2904. Shortest and Lexicographically Smallest Beautiful String is tagged String and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview