KatInterview

Tally Slices Whose Letters Are All Different

StringsAuto-graded · 17 test cases
MediumAuto-gradedStringssliding-windowtwo-pointersstrings

Last updated

Count every contiguous slice of a lowercase string in which no letter appears twice, using a linear-time sliding window.

Tally Slices Whose Letters Are All Different

You are given a string text made up of lowercase English letters. A slice is any non-empty run of consecutive characters from text. A slice is all-different if no letter occurs in it more than once.

Return how many all-different slices text has.

Slices are identified by their start and end positions, not by their contents. If two slices have the same characters but sit at different positions, count both.

Constraints

  • 1 <= len(text) <= 100000
  • text contains only the lowercase letters 'a' to 'z'.
  • The answer can be large in general, so do not rely on small fixed-width integer types in languages that have them.

Edge cases

  • A string where every character is the same has exactly len(text) valid slices.
  • A string whose characters are all distinct with length n has n * (n + 1) // 2 valid slices.
  • A one-character string has exactly one valid slice.

Examples

Example 1

Input: count_distinct_letter_slices('abc')

Output: 6

Example 2

Input: count_distinct_letter_slices('aba')

Output: 5

Hints

Hint 1

Enumerating all slices is far too slow for length 100000. Try grouping the slices by the position where they end.

Hint 2

For a fixed end position, if a slice is all-different then so is every shorter slice ending at the same position. So you only need to find the earliest valid start.

Hint 3

Remember the last position of each letter. When a new character arrives, move the earliest valid start to just after that letter's previous position, but never move it backward.