ProgrammingHardAmazon 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 = "ABCABCAB"
Integer n = length(s), p = n
for (each k from 1 to n)
    Boolean ok = true
    for (each i from k to n - 1)
        if (s[i] != s[i - k]) ok = false
    end for
    if (ok)
        p = k
        break
    end if
end for
Print p
  1. A. 8
  2. B. 6
  3. C. 2
  4. D. 3

Correct answer: D. 3

p is the smallest k such that every character equals the one k places before it, i.e. the string's smallest period. ABCABCAB repeats ABC, so p = 3, even though 3 does not divide its length 8.

More Pseudocode and Code Tracing questions

Exams that ask this topic