> For the complete documentation index, see [llms.txt](https://mayanktyagi3111.gitbook.io/interview-prep/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mayanktyagi3111.gitbook.io/interview-prep/hashmap-and-hashset-and-sliding-window/longest-substring-with-at-most-k-distinct-characters.md).

# Longest Substring with At Most K Distinct Characters

Given a string *S*, find the length of the longest substring *T* that contains at most k distinct characters.

#### Example

**Example 1:**

```
Input: S = "eceba" and k = 3
Output: 4
Explanation: T = "eceb"
```

**Example 2:**

```
Input: S = "WORLD" and k = 4
Output: 4
Explanation: T = "WORL" or "ORLD"
```

#### Challenge

O(n) time

```java
class Solution {
    public int lengthOfLongestSubstringKDistinct(String str, int k) {
        if (k == 0 || str.length() == 0)
            return 0;
        HashMap<Character, Integer> map = new HashMap<>();
        int start = 0, unique = 0;
        int maxLen = 0;
        for (int i = 0; i < str.length(); i++) {
            char x = str.charAt(i);
            if (!map.containsKey(x) || map.get(x) == 0)
                unique++;
            map.put(x, map.getOrDefault(x, 0) + 1);
            // Removing characters from start of our window until the number
            // of unique chars > K
            while (unique > k) {
                map.put(str.charAt(start), map.get(str.charAt(start)) - 1);
                if (map.get(str.charAt(start)) == 0) {
                    map.remove(str.charAt(start));
                    unique--;
                }
                start++;
            }
            maxLen = Math.max(maxLen, i - start + 1);
        }
        return maxLen;
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://mayanktyagi3111.gitbook.io/interview-prep/hashmap-and-hashset-and-sliding-window/longest-substring-with-at-most-k-distinct-characters.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
