ProgrammingHardCapgemini · Infosys pattern

What will be the output of the following pseudocode (length of the longest substring without repeating characters, sliding window)?

What will be the output of the following pseudocode (length of the longest substring without repeating characters, sliding window)?
Function longestUnique(String s)
    Map seen = empty map
    Integer start = 0, best = 0
    for (each i from 0 to length(s) - 1)
        Character ch = s[i]
        if (ch in seen and seen[ch] >= start)
            start = seen[ch] + 1
        end if
        seen[ch] = i
        best = max(best, i - start + 1)
    end for
    return best
End Function

Print longestUnique("abcabcbb")
  1. A. 4
  2. B. 2
  3. C. 3
  4. D. 5

Correct answer: C. 3

The longest substrings without a repeated character here are 'abc', 'bca', 'cab' etc., each of length 3; no window ever grows to length 4 before a repeat forces the window to shrink.

More Pseudocode and Code Tracing questions

Exams that ask this topic