Parcels roll along a warehouse conveyor, each labelled with a one-character destination code. A truck can serve at most k different destinations, and it must take an unbroken stretch of the belt. Which stretch is the longest it can load?
Write longestWithKDistinct(text, k). text is the belt as a string, one character per parcel. Return { length, substring } for the longest substring of text that contains at most k distinct characters.
Rules:
If several substrings share the longest length, return the one that starts first.
If k is 0 or text is empty, return { length: 0, substring: "" }. If text has at most k distinct characters, the answer is the whole string.
Count characters as code points, so an emoji like 😀 is one character, and length counts code points. Upper and lower case are different characters.
If text is not a string, or k is not a non-negative integer, throw a TypeError.
text can be 200,000 characters long, so restarting from every position will not finish in time. Aim for O(n).