FastPrepLongest Substring Without Repeating Characters

Longest Substring Without Repeating Characters

IBM logoIBM● MediumFULLTIMEPHONE SCREEN

Problem statement

Given a string s, return the length of the longest substring of s in which no character appears more than once.

A substring is a run of consecutive characters. Characters are compared exactly: uppercase and lowercase letters are different characters, and spaces, digits, and symbols are characters too.

If s is empty, return 0.

Function

lengthOfLongestSubstring(s: String) → int

Examples

Example 1

s = "hello world"return = 6

The longest substring with no repeated character is " world": a space followed by world, 6 characters in all.

Any longer substring repeats a character. For example, "o world" has 7 characters and repeats o.

Example 2

s = "abba"return = 2

"ab" and "ba" both have length 2. Every substring of length 3 repeats b, so the answer is 2.

When the last a arrives, the window is already "b" after the repeated b, so the first a is no longer inside it.

Example 3

s = "Bob met Tom"return = 7

"Bob met" has 7 different characters: B and b are different, and the space counts once. The next character is a second space, so no longer substring works there, and no other substring is longer than 7.

Constraints

  • 0 <= s.length <= 5 * 10^4
  • s contains only printable ASCII characters: English letters, digits, spaces, and symbols.

More IBM problems

See IBM hiring insights
Saved
public int lengthOfLongestSubstring(String s) {
    // Write your solution here.
}
Checking account…