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- A. acb
- B. cba
- C. bca
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- The phrase "the cat and the hat" is searched for the whole word "the" (counted as a separate word). The procedure below counts the…
- Strings are run-length compressed. The procedure below counts the number of runs in "aaabbc" (a run is a maximal block of equal…
- The procedure below checks the bracket string "(()())" and prints the maximum nesting depth it reaches. The depth is raised by '(' and…
- The sentence "to be or not to be to" is split into words, and the procedure below prints the most frequent word (ties go to the first word…
- The string "aabbc" is examined by the procedure below, which counts the substrings (contiguous pieces, counted by position) that contain…
- The procedure below counts the positions i in "abbab" where the two-letter window s[i]s[i+1] is "ab" or "ba". What is printed? count = 0…