ProgrammingHardAccenture · Cognizant pattern

What will be the output of the following pseudocode (longest common prefix of a list of strings)?

What will be the output of the following pseudocode (longest common prefix of a list of strings)?
Function lcp(List strs)
    String prefix = strs[0]
    for (each s in strs, skipping the first)
        while (not startsWith(s, prefix))
            prefix = prefix[0 .. length(prefix) - 2]
            if (length(prefix) == 0)
                return ""
            end if
        end while
    end for
    return prefix
End Function

Print lcp({"flower", "flow", "flight"})
  1. A. fl
  2. B. flo
  3. C. f
  4. D. flow

Correct answer: A. fl

Starting with prefix='flower', it shrinks against 'flow' (common prefix becomes 'flow'), then shrinks further against 'flight' (common prefix becomes 'fl', since 'flow' doesn't match 'flight' beyond 'fl').

More Pseudocode and Code Tracing questions

Exams that ask this topic