ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (code(c) gives a letter's character code; strings are indexed from 0)

What will be the output of the following pseudocode? (code(c) gives a letter's character code; strings are indexed from 0)
String s = "ABCADEFB"
Integer last[26] = all -1
Integer start = 0, best = 0
for (each i from 0 to length(s) - 1)
    Integer k = code(s[i]) - code('A')
    if (last[k] >= start)
        start = last[k] + 1
    end if
    last[k] = i
    best = max(best, i - start + 1)
end for
Print best
  1. A. 8
  2. B. 5
  3. C. 7
  4. D. 6

Correct answer: D. 6

best is the longest window with no repeated letter. At the second A the window restarts after the first A (BCADEF), and at the final B after the first B (CADEFB): both 6 letters. 8 ignores the repeats, 7 sets start = last[k] without the +1, and 5 restarts the window at i instead of after the old copy.

More Pseudocode and Code Tracing questions

Exams that ask this topic