Longest Common Prefix

EasyStringsvertical scan

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an array of strings words, return the longest string that is a prefix shared by **every** string in the array. A *prefix* is a leading run of characters. For example, "co" and "cod" are both prefixes of "code", but "ode" is not. The longest common prefix must appear at the start of every word, character for character, in the same positions. If the strings share no common starting characters, return the empty string "". Comparisons are case-sensitive, so "Go" and "go" do not share the prefix "go".

Examples

Input: words = ["flower", "flow", "flight"]
Output: "fl"
All three words begin with `f` and `l`. The third character differs (`o` vs `o` vs `i`), so the common prefix stops at `"fl"`.
Input: words = ["dog", "racecar", "car"]
Output: ""
The very first characters already disagree (`d`, `r`, `c`), so there is no shared prefix and the result is the empty string.
Input: words = ["interview", "internal", "internet"]
Output: "inter"
Every word starts with `inter`. The sixth characters (`v`, `n`, `n`) are not all equal, so the prefix ends there.

Constraints

  • `1 <= words.length <= 200`
  • `0 <= words[i].length <= 200`
  • Each `words[i]` consists only of lowercase and uppercase English letters.
  • An empty string in the input forces the answer to be `""`.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.