Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,937 questions

51,874 answers

573 users

How to get all the substrings with exactly k distinct characters from a given string in Python

1 Answer

0 votes
from collections import defaultdict  # handle character frequency mapping

def get_substrings_with_k_distinct(s, k):
    list_of_substrings = [] 
    n = len(s)          

    # Iterate over all possible starting points of substrings
    for i in range(n):
        freq_map = defaultdict(int)  # Dictionary to count character frequencies
        distinct_count = 0           # Counter for distinct characters in current substring

        # Extend the substring from position i to j
        for j in range(i, n):
            char = s[j] # Current character

            # If character is new to the substring, increment distinct count
            if freq_map[char] == 0:
                distinct_count += 1

            freq_map[char] += 1      # Update frequency of the character

            # If we have exactly k distinct characters, store the substring
            if distinct_count == k:
                list_of_substrings.append(s[i:j+1])
            # If we exceed k distinct characters, stop exploring this substring
            elif distinct_count > k:
                break

    return list_of_substrings 

string = "characters"
k = 4

substrings = get_substrings_with_k_distinct(string, k)

print("Number of substrings with exactly k distinct characters = ", len(substrings))

print(f"\nSubstrings with exactly {k} distinct characters in '{string}':")
for sub in substrings:
    print(sub)

 
 
"""
run:
 
Number of substrings with exactly k distinct characters =  9

Substrings with exactly 4 distinct characters in 'characters':
char
chara
charac
harac
aract
ract
acte
cter
ters
 
"""

 



answered Nov 12, 2025 by avibootz
edited Nov 12, 2025 by avibootz

Related questions

...