ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (Strings are indexed from 0)

What will be the output of the following pseudocode? (Strings are indexed from 0)
String s = "ABBCCCDDDD"
Integer best = 0, run = 1
for (each i from 1 to length(s) - 1)
    if (s[i] == s[i - 1])
        run = run + 1
    else
        if (run > best)
            best = run
        end if
        run = 1
    end if
end for
Print best
  1. A. 4
  2. B. 3
  3. C. 10
  4. D. 1

Correct answer: B. 3

best is updated only when the character changes. The final run DDDD (length 4) ends with the string, so it is never compared, and best stays at the CCC run: 3. The fix is one more comparison after the loop.

More Pseudocode and Code Tracing questions

Exams that ask this topic