Similar Problems

Similar Problems not available

Partition String Into Substrings With Values At Most K - Leetcode Solution

Companies:

LeetCode:  Partition String Into Substrings With Values At Most K Leetcode Solution

Difficulty: Medium

Topics: greedy string dynamic-programming  

Problem Statement:

Given a string s and an integer k, partition s such that every substring of the partition has at most k distinct characters.

Return the maximum number of partitions that can be made.

Example 1:

Input: s = "aaab", k = 2 Output: 2 Explanation: The optimal partition is "aa"-"a"-"b" where each substring contains 2 distinct characters.

Example 2:

Input: s = "eceba", k = 3 Output: 3 Explanation: The optimal partition is "ece"-"b"-"a" where each substring contains 3 distinct characters.

Solution:

The given problem can be solved using the sliding window technique. We can start with a sliding window which contains the first k distinct characters of the string s. We can then iterate through the string s, adding each character to the sliding window and removing the leftmost character until the number of distinct characters in the window is greater than k. At this point, we can add the length of the sliding window to our answer and start a new sliding window which contains the current character as its only element.

Algorithm:

  1. Initialize an empty dictionary freq to keep track of the frequency of each character in the sliding window and a counter count to keep track of the number of distinct characters in the window.
  2. Initialize the answer ans to 0 and a variable start to keep track of the start index of the current sliding window.
  3. Iterate through the string s from left to right using a variable i: a. If the frequency of s[i] is 0, increment count by 1. b. Increment the frequency of s[i] in freq by 1. c. While count > k, decrement the frequency of s[start] in freq by 1 and increment start by 1. If the frequency of s[start] becomes 0, decrement count by 1. d. If count <= k, update the answer by adding the length of the sliding window and increment start to start a new sliding window with s[i] as its only element.
  4. Return the answer.

Python Code:

def maxNumberOfSubstrings(s: str, k: int) -> int: freq = {} count = 0 ans = 0 start = 0

for i in range(len(s)):
    if s[i] not in freq:
        count += 1
    freq[s[i]] = freq.get(s[i], 0) + 1
    
    while count > k:
        freq[s[start]] -= 1
        if freq[s[start]] == 0:
            count -= 1
        start += 1
    
    if count <= k:
        if all(freq[c] <= k for c in freq):
            ans += i - start + 1
            start = i + 1
            freq = {}
            count = 0
            
return ans

Partition String Into Substrings With Values At Most K Solution Code

1