FastPrepLongest Substring Without Repeating Characters

Longest Substring Without Repeating Characters

Google logoGoogle● MediumINTERNONSITE INTERVIEW
Learn

Problem statement

Given a string s, return the length of its longest contiguous substring whose characters are all distinct.

If s is empty, return 0.

Interview extension

After solving the judged task, explain how to return one longest valid substring itself by tracking the start index whenever the maximum length improves.

Function

lengthOfLongestSubstring(s: String) → int

Examples

Example 1

s = "abcabcbb"return = 3

"abc" is one longest substring whose characters are all distinct.

Example 2

s = "bbbbb"return = 1

Every valid substring contains only one b, so the maximum length is 1.

Example 3

s = ""return = 0

An empty string has no nonempty substring, so the result is 0.

Constraints

  • 0 <= s.length <= 100000
  • s contains printable ASCII characters.
  • The solution should run in O(s.length) time.

More Google problems

See Google hiring insights
public int lengthOfLongestSubstring(String s) {
  // Write your code here.
}
s"abcabcbb"
expected3
Checking account…