KatInterview

Longest Distinct Run and First Singleton Position

StringsAuto-graded · 22 test cases
EasyAuto-gradedStringssliding-windowhash-mapstrings

Last updated

Tests a sliding window with last-seen indices plus a frequency count to find the longest repeat-free substring and the earliest character occurring exactly once.

You are given a string text made up of lowercase English letters. Compute two values about it and return them together.

  1. Longest distinct run: the length of the longest contiguous substring in which no letter appears more than once.
  2. First singleton position: the smallest index i such that the letter text[i] occurs exactly once in the entire string. If no letter occurs exactly once, this value is -1.

Return a two-element list [longest_run, first_singleton].

Details

  • A substring is a contiguous block of characters; a subsequence that skips characters does not count.
  • For the empty string, the longest run has length 0 and there is no singleton, so the result is [0, -1].
  • "Occurs exactly once" is judged against the whole string, not just a window.
  • The result must be a list of two integers in the order shown above.

Constraints

  • text contains only lowercase English letters ('a' to 'z').
  • 0 <= len(text) <= 10^5
  • Your solution should run in roughly linear time.

Examples

Example 1

Input: longest_distinct_and_first_singleton('abcabcbb')

Output: [3, -1]

Example 2

Input: longest_distinct_and_first_singleton('leetcode')

Output: [5, 0]

Hints

Hint 1

For the longest run, keep a window [left, right] with no repeated letters and move right one step at a time. Track the most recent index of each letter.

Hint 2

When the new letter was last seen at an index that is at least left, move left to just after that index. If the previous occurrence is before left, it is outside the window and must not move left backward (think of 'abba').

Hint 3

A singleton depends on the whole string, so count every letter first, then scan from the left and return the first index whose letter has count 1, or -1 if none.