Intersection of Two Arrays 350. j++; LeetCode / Longest Substring with At Most Two Distinct Characters.java / Jump to. HashSet splitSet = new HashSet(); Given a string, find the length of the longest substring T that contains at most k distinct characters. if(counter.containsKey(c)){ 3)Then using that index value backspace the nearby value using substring()[which has to be separated and merged without # character]. This article is contributed by Rahul Agrawal. Can we modify the above program such that cnt[] is not reset every time? By using our site, you This can be done by just isn’t hashmap. } If we apply this brute force, it would take O (n 2) to generate all substrings and O (n) to do a check on each one. edit return s.length(); Attention reader! Substring with Concatenation of All Words 159. Úvodní stránka; Základní informace. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. Examples: If the length of string is n, then there can be n*(n+1)/2 possible substrings. Example 1: Input: s = "aaabb", k = 3 Output: 3 The longest substring is "aaa", as 'a' is repeated 3 times. For example, Given s = “eceba”, T is "ece" which its length is 3. Last Updated : 23 May, 2019. brightness_4 The key idea of the solution is to use two pointers to maintain a "sliding window". } Example: Input: s = "aaabbbccddd", k = 3 Output: 6 Explanation: The longest substring is "aaabbb", as 'a' and 'b' are repeated 3 times. Medium. } Please use ide.geeksforgeeks.org, The above code resets count array “cnt[]” in every iteration of outer loop. Example 2: counter.put(c, counter.get(c)+1); Integrovaná strategie rozvoje BMO 21+ O strategii; Vymezení území Brněnské metropolitní oblasti 21+ 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. But we first need to split the input string by using the characters whose occurrence < k. A simple way is to generate all the substring and check each one whether it has exactly k unique characters or not. When the total kinds of the letter is less than k, we just continue, and count both kind and number of each kind of letter. close, link Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times. int max = 0; LeetCode – Longest Substring with At Least K Repeating Characters (Java), LeetCode – Longest Substring Without Repeating Characters (Java), Longest Substring with At Most K Distinct Characters, Leetcode – Longest Palindromic Substring (Java), LeetCode – Substring with Concatenation of All Words (Java). return max; Exercise (Further Optimization): A hash map can do this. Idea Report. for(char c: counter.keySet()){ The problem is very similar to the Leetcode question 3 (Longest Substring Without Repeating Characters). For example, Given s = “eceba” and k = 2, T is "ece" which its length is 3. Longest Substring with At Most K Distinct Characters 341. Two Sum; 2. See your article appearing on the GeeksforGeeks main page and help other Geeks. for(int i=0; i=k, return the length. splitSet.add(c); Given a string, find the length of the longest substring T that contains at most k distinct characters. Flatten Nested List Iterator 342. 30. Count number of substrings with exactly k distinct characters, Count of substrings of length K with exactly K distinct characters, Find distinct characters in distinct substrings of a string, Count distinct substrings that contain some characters at most k times, Count of Substrings with at least K pairwise Distinct Characters having same Frequency, Count of substrings having all distinct characters, Generate a string of size N whose each substring of size M has exactly K distinct characters, Minimum length substring with exactly K distinct characters, Find the String having each substring with exactly K distinct characters, Count of ungrouped characters after dividing a string into K groups of distinct characters, Count number of distinct substrings of a given length, Replace minimal number of characters to make all characters pair wise distinct, Count number of substrings of a string consisting of same characters, Count of distinct substrings of a string using Suffix Trie, Count of distinct substrings of a string using Suffix Array, Count distinct substrings of a string using Rabin Karp algorithm, Count of Distinct Substrings occurring consecutively in a given String, String with k distinct characters and no same characters adjacent, Count substrings with same first and last characters, Recursive solution to count substrings with same first and last characters, Count of Substrings that can be formed without using the given list of Characters, Count of all unique substrings with non-repeating characters, Count of substrings formed using a given set of characters only, Count of substrings of a given Binary string with all characters same, Count substrings with different first and last characters, Data Structures and Algorithms – Self Paced Course, Ad-Free Experience – GeeksforGeeks Premium, We use cookies to ensure you have the best browsing experience on our website. When the number of kind is larger than k, we need to move the left side of the window, until the number of kind is no more larger than k. if(splitSet.contains(c)){ [380.Insert-Delete-GetRandom-O(1)](Data-Structure/380.Insert-Delete-GetRandom-O(1).md) LC address: https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/. }. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. For example, Given s = “eceba” and k = 2, T is "ece" which its length is 3. Longest Substring with At Most K Distinct Characters. This website contains ALL LeetCode Premium problems for FREE!!. acknowledge that you have read and understood our, GATE CS Original Papers and Official Keys, ISRO CS Original Papers and Official Keys, ISRO CS Syllabus for Scientist/Engineer Exam, Amazon Interview Experience for SDE-1 (Full Time-Referral) 2020, Number of substrings with count of each character as k, Program to print all substrings of a given string, Print all subsequences of a string | Iterative Method, Print all subsequences of a string using ArrayList, Generating all possible Subsequences using Recursion, Subarray/Substring vs Subsequence and Programs to Generate them, Find subarray with given sum | Set 1 (Nonnegative Numbers), Find subarray with given sum | Set 2 (Handles Negative Numbers), Find subarray with given sum with negatives allowed in constant space, Smallest subarray with sum greater than a given value, Find maximum average subarray of k length, Count minimum steps to get the given desired array, Number of subsets with product less than k, Find minimum number of merge operations to make an array palindrome, Find the smallest positive integer value that cannot be represented as sum of any subset of a given array, Write a program to reverse an array or string, Write a program to print all permutations of a given string, Check for Balanced Brackets in an expression (well-formedness) using Stack, Array of Strings in C++ (5 Different Ways to Create), Python program to check if a string is palindrome or not, Different methods to reverse a string in C/C++, Check whether two strings are anagram of each other, C Program to Check if a Given String is Palindrome, Write Interview Given a string, find the length of the longest substring T that contains at most k distinct characters. LeetCode 340. If we apply this brute force, it would take O(n*n) to generate all substrings and O(n) to do a check on each one. This question could be solved with two pointers and more importantly, using the Ordered Dictionary would be able to achieve time complexity. Design Tic-Tac-Toe 349. eval(ez_write_tag([[728,90],'programcreek_com-medrectangle-4','ezslot_2',137,'0','0'])); public int longestSubstring(String s, int k) { This can be very costly for large alphabet size. counter.put(c, 1); # i for start, k for end, j for latest pos contains different character from k: for k in range (1, len (s)): if s [k] == s [k-1]: continue: if j >= 0 and s [j] != s [k]: maxLen = max (k-i, maxLen) # update i: i = j + 1 # update: j = k-1: return max (len (s) -i, maxLen) // Given a string, find the length of the longest substring T that contains at most k distinct characters. Longest Substring with At Least K Repeating Characters. Moving Average from Data Stream 347. max = Math.max(max, longestSubstring(s.substring(i, j), k));