FastPrepLongest Unique Substring Range

Longest Unique Substring Range

Google logoGoogle● MediumINTERNONSITE INTERVIEW
Learn

Problem statement

You are given a nonempty string text. Return [start, end], the zero-based inclusive indices of a longest contiguous substring whose characters are all distinct.

If several longest valid substrings exist, return the one with the smallest start index.

Process the string from left to right in O(text.length) time and use O(1) auxiliary space for the fixed printable-ASCII alphabet.

What the interview report shared

The report described a sliding-window solution and then asked how the approach should change when the input is too large to keep in memory.

Function

longestUniqueSubstringRange(text: String) → int[]

Examples

Example 1

text = "abcabcbb"return = [0,2]

The maximum length is 3. The valid ranges [0,2], [1,3], [2,4], and [3,5] all have that length, so the earliest range is returned.

Example 2

text = "bbbbb"return = [0,0]

Every valid substring contains one b. The earliest one begins and ends at index 0.

Example 3

text = "pwwkew"return = [2,4]

Both wke at [2,4] and kew at [3,5] have maximum length 3. The earlier range is returned.

Example 4

text = "dvdf"return = [1,3]

After the second d, the window moves forward and the substring vdf becomes the unique maximum.

Constraints

  • 1 <= text.length <= 10^6.
  • text contains printable ASCII characters.
  • The returned range uses zero-based inclusive indices.
  • When several ranges have the same maximum length, return the earliest one.

More Google problems

See Google hiring insights
public int[] longestUniqueSubstringRange(String text) {
  // Write your code here.
}
text"abcabcbb"
expected[0,2]
Checking account…