ProgrammingVery hardTCS NQT · Accenture

The string "bca" may have exactly one swap of two characters made. The procedure below finds the lexicographically smallest string obtainable. What is printed?

The string "bca" may have exactly one swap of two characters made. The procedure below finds the lexicographically smallest string obtainable. What is printed?
best = s
for every pair i < j
    swap s[i] and s[j]; best = min(best, the new string)
    swap back
end for
Print best
  1. A. acb
  2. B. cba
  3. C. bca
  4. D. bac

Correct answer: A. acb

Swapping b and c gives cba, swapping the first two gives cba... the adjacent swap of b and c gives bca unchanged, while the swap of c (index 0) and a (index 2) gives acb, which is the smallest. Choosing the largest result, leaving the string unchanged, and limiting to adjacent swaps give different answers.

More Pseudocode and Code Tracing questions

Exams that ask this topic