KatInterview

Longest Window of Unique Characters

StringsAuto-graded · 27 test cases
MediumAuto-gradedStringssliding-windowhash-maptwo-pointers

Last updated

Tests whether a candidate can apply a sliding window with a character index map to find the longest contiguous run of non-repeating characters.

Problem

You are given a string s. Return the length of the longest contiguous portion of s in which every character appears exactly once.

If s is empty, return 0.

What counts as a valid window

A window is any contiguous slice of s. It is valid when no character in that slice occurs more than once. You want the length of the longest such valid window.

Note that you are looking for a substring (contiguous), not a subsequence (characters may be spread out).

Constraints

  • 0 <= len(s) <= 5 * 10^4
  • s may contain uppercase and lowercase English letters, decimal digits, symbols, and space characters.

Examples

Example 1

Input: longest_unique_window('abcabcbb')

Output: 3

Example 2

Input: longest_unique_window('bbbbb')

Output: 1

Example 3

Input: longest_unique_window('pwwkew')

Output: 3

Hints

Hint 1

Try maintaining a window defined by a left and a right pointer. Grow the window by advancing the right pointer one step at a time, and only move the left pointer when the window becomes invalid.

Hint 2

Store the most recent index at which each character was seen. When the character at `right` already appears somewhere inside the current window, you can jump `left` directly past that earlier occurrence rather than shrinking one step at a time.

Hint 3

Be careful not to move `left` backward. If a character was last seen before the current window started, that occurrence is already outside the window and can be ignored. The string "abba" is a good case to trace through by hand to check this.