Longest Substring With At Most K Distinct Characters

Sliding Window / 2 Pointer Longest and Smallest Window Problems Hard
  • Fun Fact: The core concept of this problem is used in text and data analysis software
  • For example, in social media applications, analyzing the length of the longest substring with at most k distinct characters could help detect, track, or summarize major trends/topic, spam posts or even potential security breaches
  • Similarly, in bioinformatics, this idea could be applicable in DNA sequencing, where the longest substring of a DNA fragment with distinct kinds of nucleotides is important

Given a string s and an integer k.Find the length of the longest substring with at most k distinct characters.

Examples:

Input : s = "aababbcaacc" , k = 2

Output : 6

Explanation : The longest substring with at most two distinct characters is "aababb".

The length of the string 6.

Input : s = "abcddefg" , k = 3

Output : 4

Explanation : The longest substring with at most three distinct characters is "bcdd".

The length of the string 4.

Input : s = "abccab" , k = 4

Constraints

  • 1 <= s.length <= 105
  • 1 <= k <= 26

Hints

  • Use a sliding window approach to find the longest substring with at most k distinct characters.
  • "Use a hash map to store the frequency of each character in the current window. Keep track of the maximum length encountered during the traversal. "

Company Tags

Cloudflare Bungie Nutanix Roche Ernst & Young AMD Boston Consulting Group Riot Games Morgan Stanley Etsy Red Hat Visa Uber IBM Oracle Johnson & Johnson Micron Technology JPMorgan Chase GE Healthcare Salesforce Chewy MongoDB Alibaba Goldman Sachs Reddit Google Microsoft Amazon Meta Apple Netflix Adobe