Katkat

Find the Longest Substring Without Repeated Characters

NetflixSoftware Engineer · Technical Screen

Last updated

Tests sliding window technique, hash map index tracking, and linear-time constraint optimization on string manipulation.

Problem Statement

Given a string s consisting of printable ASCII characters, return the length of the longest contiguous substring that contains no duplicate characters.

Characters are case-sensitive (e.g., 'a' and 'A' are considered distinct characters).

Function Signature

def length_of_longest_substring(s: str) -> int:
    pass

Input & Output

  • Input: A single string s of length n containing standard ASCII characters.
  • Output: An integer representing the length of the longest substring with all unique characters.

Constraints

  • 0 <= len(s) <= 10^5
  • s consists of English letters, digits, symbols, and spaces.
  • Time complexity must be O(n) to pass within execution time limits.
  • Auxiliary space complexity should be O(min(n, m)) where m is the size of the character set (at most 128 for standard ASCII).

Examples

Example 1

Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with a length of 3.

Example 2

Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with a length of 1.

Example 3

Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with a length of 3. Note that "pwke" is a subsequence, not a contiguous substring.

Edge Cases to Consider

  • An empty string "" should return 0.
  • A string where all characters are identical (e.g., "aaaa") should return 1.
  • A string where all characters are already unique should return len(s).
  • Strings with spaces or non-alphanumeric ASCII characters (e.g., "a b!c a").

Hints

Hint 1

A brute-force check of all substrings takes O(n^3) or O(n^2) time; consider using a sliding window bounded by two pointers [left, right] to achieve linear time.

Hint 2

Instead of incrementing the left boundary by one and clearing visited elements, maintain a map of each character's last seen index to jump the left boundary directly.

Hint 3

Be careful when updating the left pointer: ensure it only moves forward and does not move back to an earlier index when seeing a duplicate that falls outside the current window.

Follow-up questions

  • How would you modify the solution to return the actual substring instead of just its length, while preserving O(1) extra space beyond string references?
  • How does your space and time complexity change if the input contains arbitrary Unicode code points (e.g., emojis and multi-byte characters) instead of standard ASCII?
  • How would you adapt the algorithm if the requirement allowed up to `k` repeated characters instead of zero duplicates?