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?- A. '/usr/l' ''
- B. '/usr/' ''
- C. '/usr/lib' ''
- 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
- Problem: Compute the minimum number of characters to add at the end of s so that it becomes a palindrome, using the KMP prefix function…
- Problem: Search a pattern of length m in a text of length n = 10⁶ (m up to 10⁵) and report all match positions. Which method guarantees…
- Problem: Return the longest palindromic substring of s (first one if there is a tie). python def lps(s): best = "" for c in range(len(s))…
- Problem: Check whether a string of brackets ()[]{} is balanced. python def balanced(s): pair = {')': '(', ']': '[', '}': '{'} st = [] for…
- Problem: For each day's temperature, find how many days you must wait for a warmer day (0 if never). python def wait(t): res, st = [0]…
- Problem: Find the largest rectangle that fits under a histogram of bar heights. python def largest(h): st, best = [], 0 for i, x in…