Skip to Content

Longest Substring with At Most K Distinct Characters

Home | Coding Interviews | Arrays and Strings | Longest Substring with At Most K Distinct Characters

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

public class Solution {
    public int lengthOfLongestSubstringKDistinct(String S, int K) {
        int[] charCount = new int[256];
        char[] chS = S.toCharArray();
        int distinctNum = 0, leftIndex = 0, maxLen = 0;
        for (int rightIndex = 0; rightIndex < chS.length; rightIndex++) {
            if (charCount[chS[rightIndex]]++ == 0) distinctNum++;
            if (distinctNum > K) {
                while (--charCount[chS[leftIndex++]] > 0);
                distinctNum--;
            }
            maxLen = Math.max(maxLen, rightIndex - leftIndex + 1);
        }
        return maxLen;
    }
}

Posted by Jamie Meyer 8 months ago

Related Problems

Given a string s, find the length of the longest substring without repeating characters.

Given an integer array nums, you need to find one continuous subarray such that if you only sort this subarray in non-decreasing order, then the whole array will be sorted in non-decreasing order.

Return the shortest such subarray and output its length.

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval.

Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary).

Return intervals after the insertion.

Note that you don't need to modify intervals in-place. You can make a new array and return it.