EvalFrame Technical Mock Interviews & Coding Practice

Longest Common Prefix

Easy · String / Scanning · Algorithm problem · all problems

Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string `""`. **Examples:** ```typescript longestCommonPrefix(["flower", "flow", "flight"]) // "fl" longestCommonPrefix(["dog", "racecar", "car"]) // "" longestCommonPrefix(["interspecies", "interstellar", "interstate"]) // "inters" ```

Solve It in the BrowserPractice Explaining It Out Loud

Optimal Approach

  • Time complexity: O(S)
  • Space complexity: O(1)

In the worst case (where all strings are identical), the vertical scanning checks all characters across all strings. Total comparisons equal S, the sum of all characters in all strings.

Follow-Up Questions Interviewers Ask About Longest Common Prefix

  • What is the advantage of Vertical Scanning over Horizontal Scanning?
    Vertical scanning compares column by column across all strings. If a mismatch occurs at index 0 or 1, it short-circuits immediately without needing to read the rest of very long strings.
  • How would you solve this if you needed to do frequent prefix queries on a dynamic dictionary of words?
    Insert all words into a Trie (Prefix Tree). The longest common prefix is the path from the root down to the first node with branching > 1 or where an end-of-word marker is reached.
  • Can this be solved by sorting the strings first?
    Yes! If you sort the array lexicographically, you only need to compare the first string and the last string in the sorted array, because all intermediate strings will share any common prefix between the two extremes.

Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.