Longest Substring with K Distinct Characters
Find the Longest Substring with K Distinct Characters
Hey there, Python coding enthusiast! Here's a fun challenge for you: Imagine you're a secret agent, and you need to send a magical message using a one-of-a-kind crystal ball. This magical crystal ball only contains letters which can form words. However, the magic is a bit quirky - it can only handle a limited command, let's say, a specific number of distinct characters at any time.
Your mission, should you choose to accept it, is to write a function that can help determine the longest magical command we can form using exactly 'K' distinct characters!
How to Solve This Magic Riddle:
You must write a function longest_substring_with_k_distinct that takes a string and a number K and returns the longest substring that contains exactly K distinct characters. Can you crack this mystery?
Example Spells:
Here are some examples to help guide your wizardry:
Example 1:
input_string = "araaci" k = 2 # Longest substrings with 2 distinct characters are "araa" and "raac", both with length 4 result = longest_substring_with_k_distinct(input_string, k) print(result) # Output: 4
Example 2:
input_string = "araaci" k = 1 # Longest substring with 1 distinct character is "aa", with length 2 result = longest_substring_with_k_distinct(input_string, k) print(result) # Output: 2
Example 3:
input_string = "cbbebi" k = 3 # Longest such substring is "cbbeb" or "bbebi", both with length 5 result = longest_substring_with_k_distinct(input_string, k) print(result) # Output: 5
Put on your wizard's hat and get coding!
Inputs
Arg 1:
"araaci"Arg 2:
2Expected Output
4Actual Output