A tile strip is a row of coloured tiles, written as a string with one character per colour, such as "rrgbbgrr". A designer wants a stretch of the strip that uses exactlyk colours, no more and no fewer.
Write two functions that take a string s and a positive integer k:
longestWithKDistinct(s, k) returns the longest substring of s that contains exactly k distinct characters. If several are equally long, return the one that starts first. If no substring has exactly k distinct characters, return null.
countWithKDistinct(s, k) returns how many substrings of s contain exactly k distinct characters. Substrings at different positions count separately, even when they hold the same text.
Rules:
Treat each s[i] as one character. Comparison is exact: "A" and "a" are different colours.
A substring is a non-empty run of consecutive characters.
Throw a TypeError if s is not a string, and a RangeError if k is not an integer of at least 1.
s can have 200,000 characters. Checking every start and end is O(n²) and will not finish in time; aim for O(n).
longestWithKDistinct("rrgbbgrr", 2); // "gbbg"longestWithKDistinct("rrgbbgrr", 1); // "rr": "rr" and "bb" tie, and "rr" starts firstlongestWithKDistinct("rrgbbgrr", 4); // null: the strip has only 3 colourscountWithKDistinct("rrgbbgrr", 1); // 11countWithKDistinct("abab", 2); // 6: every substring of length 2 or more
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
2
code listings
6
edge cases
What's inside
The full problem, with examples
Tests that check your solution
Step-by-step
Approach
Solution
Complexity
Edge cases
Follow-up questions
Card worldwide
UPI and net banking in India
One-time payment, nothing renews
Private, and saved in this browser as you type. All your notes are on My lists.