Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package com.thealgorithms.strings;

import java.util.HashMap;

public class LongestSubstringKDistinct {

/**
* Returns the length of the longest substring that contains
* at most k distinct characters.
*
* Sliding Window + HashMap
* Time Complexity: O(n)
* Space Complexity: O(k)
*/
public static int longestSubstringKDistinct(String s, int k) {
if (k == 0 || s == null || s.isEmpty()) {
return 0;
}

int left = 0, maxLen = 0;
HashMap<Character, Integer> map = new HashMap<>();

for (int right = 0; right < s.length(); right++) {
char ch = s.charAt(right);
map.put(ch, map.getOrDefault(ch, 0) + 1);

while (map.size() > k) {
char leftChar = s.charAt(left);
map.put(leftChar, map.get(leftChar) - 1);

if (map.get(leftChar) == 0) {
map.remove(leftChar);
}
left++;
}

maxLen = Math.max(maxLen, right - left + 1);
}

return maxLen;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.thealgorithms.strings;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

public class LongestSubstringKDistinctTest {

@Test
void testBasic() {
assertEquals(3, LongestSubstringKDistinct.longestSubstringKDistinct("eceba", 2));
assertEquals(2, LongestSubstringKDistinct.longestSubstringKDistinct("aa", 1));
}

@Test
void testEdgeCases() {
assertEquals(0, LongestSubstringKDistinct.longestSubstringKDistinct("", 2));
assertEquals(0, LongestSubstringKDistinct.longestSubstringKDistinct("abc", 0));
}

@Test
void testLarge() {
assertEquals(4, LongestSubstringKDistinct.longestSubstringKDistinct("aabbcc", 2));
assertEquals(6, LongestSubstringKDistinct.longestSubstringKDistinct("abcabcbb", 3));
}
}
Loading