ProgrammingHardAccenture · Cognizant

Longest common prefix of the words "flower", "flow" and "flight" is found by comparing characters column by column until a mismatch. The procedure below prints the length of that prefix. What is printed?

Longest common prefix of the words "flower", "flow" and "flight" is found by comparing characters column by column until a mismatch. The procedure below prints the length of that prefix. What is printed?
prefix = first word
for each other word w
    shrink prefix until w starts with prefix
end for
Print length of prefix
  1. A. 4
  2. B. 2
  3. C. 3
  4. D. 0

Correct answer: B. 2

The shared prefix is fl, of length 2, because flow and flight both start with fl but flower's third letter o does not match flight's i. Reading the second word gives 4, counting the words gives 3, and dropping the first letter instead of the last gives 0.

More Pseudocode and Code Tracing questions

Exams that ask this topic