ProgrammingHardAmazon OA · Infosys SP

What will be the output of the following pseudocode? (substring(s, i, 2) is the 2 characters from index i; sorted(t) puts t's letters in alphabetical order)

What will be the output of the following pseudocode? (substring(s, i, 2) is the 2 characters from index i; sorted(t) puts t's letters in alphabetical order)
String s = "ABBAAB"
Integer c = 0
for (each i from 0 to length(s) - 2)
    String t = substring(s, i, 2)
    if (sorted(t) == "AB")
        c = c + 1
    end if
end for
Print c
  1. A. 2
  2. B. 5
  3. C. 4
  4. D. 3

Correct answer: D. 3

The windows of length 2 are AB, BB, BA, AA, AB. Sorting the letters turns BA into AB too, so windows that are anagrams of AB are counted: AB, BA, AB = 3.

More Pseudocode and Code Tracing questions

Exams that ask this topic