Data Structures & AlgorithmsEasyInfosys SP/DSE · Product Company SDE

Problem: Return the longest common prefix of a list of file paths.

Problem: Return the longest common prefix of a list of file paths.
def lcp(words):
    if not words: return ""
    p = words[0]
    for w in words[1:]:
        while not w.startswith(p):
            p = p[:-1]
    return p
print(repr(lcp(["/usr/lib/x", "/usr/local", "/usr/lib"])), repr(lcp(["dog", "cat"])))
What is printed?
  1. A. '/usr/l' ''
  2. B. '/usr/' ''
  3. C. '/usr/lib' ''
  4. D. '/usr/l' 'd'

Correct answer: A. '/usr/l' ''

Shrink the candidate until every word starts with it. "/usr/lib/x" vs "/usr/local" shares "/usr/l"; "/usr/lib" also starts with it. Note the answer is a character prefix, not a path-component prefix (that would be "/usr/"). "dog" and "cat" share nothing. Worst case O(total characters).

More Coding Interview Problems questions

Exams that ask this topic