Taro Logo

Longest Substring with At Most K Distinct Characters

#7 Most AskedMedium
0 views
Topics:
StringsTwo PointersSliding Windows

Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct characters.

Example 1:

Input: s = "eceba", k = 2
Output: 3
Explanation: The substring is "ece" which its length is 3.

Example 2:

Input: s = "aa", k = 1
Output: 2
Explanation: The substring is "aa" which its length is 2.

Constraints:

  • 1 <= s.length <= 5 * 104
  • 0 <= k <= 50

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What character set does the string `s` consist of? For example, should we expect only standard ASCII characters, or could it include Unicode / emoji characters?
  2. How should the algorithm behave if `k` is 0, or if `k` is greater than the total number of distinct characters in the entire string?
  3. What should be returned if the input string `s` is empty or `null`?
  4. Is the input string case-sensitive, meaning should 'A' and 'a' be treated as distinct characters?
  5. If multiple longest substrings tie for the maximum length, does it matter which one's length we return since we only need to return the integer length itself?

Brute Force Solution

Approach

The brute force approach to finding the longest stretch of text with a limited variety of symbols is to examine every single possible starting point and ending point in the text. For each and every stretch you look at, you count how many different types of symbols appear inside it to see if it stays within your limit, and you keep track of the longest one that works.

Here's how the algorithm would work step-by-step:

  1. Begin at the very first symbol of your text.
  2. Look at every possible ending point that comes after your starting point, creating every possible slice of text.
  3. For each slice you create, look closely at all the symbols inside it and count how many unique types of symbols are present.
  4. Check if that count of unique symbols is equal to or less than your allowed limit.
  5. If the variety of symbols is within your limit, measure how long this slice is.
  6. Remember this length if it is the biggest one you have found so far.
  7. Move your starting point to the second symbol and repeat the entire process of checking every possible slice from there.
  8. Continue this exhaustive search for every single starting position until you have tested every possible slice in the entire text.
  9. Finally, recall the biggest length you recorded during your search, as that represents your best answer.

Code Implementation

def length_of_longest_substring_k_distinct(input_string, character_limit):
    maximum_length_found = 0

    # Iterate through every possible starting position to evaluate all potential substrings
    for start_position in range(len(input_string)):

        for end_position in range(start_position, len(input_string)):
            current_substring = input_string[start_position:end_position + 1]
            unique_characters_set = set()

            for character in current_substring:
                unique_characters_set.add(character)

            # Validate if the unique symbol count stays within the allowed limit before measuring
            if len(unique_characters_set) <= character_limit:
                current_length = (end_position - start_position) + 1

                # Keep track of the maximum length found so far to ensure we return the optimal result
                if current_length > maximum_length_found:
                    maximum_length_found = current_length

    return maximum_length_found

Big(O) Analysis

Time Complexity
O(n²) – The brute force approach uses nested loops where the outer loop sets every possible starting point and the inner loop creates every possible ending point for a string of length n. For each of the n starting positions, the inner loop examines up to n subsequent ending positions to form slices. Counting the unique symbols inside each slice takes additional time proportional to the length of that slice. This exhaustive testing of roughly n * n/2 possible slices leads to a quadratic total operation count, which simplifies to O(n²).
Space Complexity
O(K) – The brute force approach described relies on counting unique symbols within every possible slice of text. To track these distinct symbols for each slice, we use a hash map or set acting as a frequency counter to store the types of symbols present. Since the problem constrains the maximum number of distinct characters to K, this auxiliary data structure will hold at most K plus one unique elements at any given time. Therefore, the extra memory required is directly bounded by K, resulting in a constant space complexity relative to the input string size N.

Optimal Solution

Approach

Instead of testing every single possible section of the text from scratch, we use a smart sliding window approach that expands and shrinks dynamically. This allows us to keep track of our character variety efficiently without wasting effort rechecking parts we already looked at.

Here's how the algorithm would work step-by-step:

  1. Imagine looking at the text through a moving window frame that starts at the very beginning.
  2. Slowly stretch the right side of your window outward, taking in new characters one by one and keeping count of how many unique types of characters you have collected.
  3. Continue stretching the right side as long as the total number of unique character types stays within your allowed limit.
  4. The moment you encounter one too many unique character types, you have broken the rule.
  5. To fix this, gently slide the left side of your window forward, dropping characters from view until you are safely back under your unique character limit.
  6. Keep track of how wide your window is every time it is valid, updating your record whenever you find a wider view.
  7. Slide the right side forward again to explore new territory, repeating the process of expanding and shrinking until you reach the end of the text.

Code Implementation

def length_of_longest_substring_k_distinct(input_string, allowed_distinct_limit):
    character_frequency_map = {}
    window_start_index = 0
    maximum_substring_length = 0

    if allowed_distinct_limit == 0:
        return 0

    for window_end_index in range(len(input_string)):
        current_character = input_string[window_end_index]
        character_frequency_map[current_character] = character_frequency_map.get(current_character, 0) + 1

        # Shrink window from the left if distinct character count exceeds the allowed limit.
        while len(character_frequency_map) > allowed_distinct_limit:
            left_side_character = input_string[window_start_index]
            character_frequency_map[left_side_character] -= 1
            if character_frequency_map[left_side_character] == 0:
                del character_frequency_map[left_side_character]
            window_start_index += 1

        # Track the maximum valid window width found during the expansion and contraction.
        current_window_width = window_end_index - window_start_index + 1
        if current_window_width > maximum_substring_length:
            maximum_substring_length = current_window_width

    return maximum_substring_length

Big(O) Analysis

Time Complexity
O(n) – Let n be the length of the string. The right pointer traverses the entire string from left to right exactly once, while the left pointer also moves strictly forward without ever backtracking. Each character is added to and removed from our character frequency map at most once as the sliding window adjusts. Although there is a nested movement of the left pointer inside the right pointer loop, the total number of steps taken by both pointers combined is bounded by 2n. This leads to approximately 2n total operations, which simplifies to O(n).
Space Complexity
O(K) – To keep track of how many unique types of characters we have collected within our sliding window, we utilize a hash map or frequency table as an auxiliary data structure. Since the problem limits the number of distinct character types to at most K at any given moment, this hash map will store at most K keys and their corresponding counts. Therefore, the extra memory required grows directly with K rather than the total input string length N, resulting in an auxiliary space complexity of O(K).

Edge Cases

String length is zero or k is zero
How to Handle:
Return zero immediately since no valid substring can be formed.
String length is less than k
How to Handle:
Return the total length of the string because all characters are distinct and within the limit.
k is greater than the number of unique characters in the entire string
How to Handle:
Return the length of the string as the entire string satisfies the condition.
String contains all identical characters
How to Handle:
The sliding window expands to the full string length because the distinct character count remains one.
String consists entirely of distinct characters and k equals one
How to Handle:
The window size collapses to one, and the algorithm correctly returns a maximum length of one.
Extremely large string inputs
How to Handle:
The O(n) sliding window approach ensures linear time complexity and handles large inputs efficiently.
String contains special characters, spaces, or unicode points
How to Handle:
Using a hash map or frequency array sized for the character set correctly tracks all distinct entities.
0/13 completed