Strings String basics

126. Longest Common Prefix

Easy 147 DSA Sheet

You are given a list of lowercase words, words. Return the longest string that every word in the list starts with.

A prefix of a word is its first few letters, from none of them up to all of them: "car", "c" and the empty string are all prefixes of "car". You are looking for the longest string that is a prefix of every word at once. If the words do not even share their first letter, the answer is the empty string "".

Answers are shown in double quotes, so an empty answer shows as "".

Example 1

Input: words = ["carpet", "carpool", "card", "care"]

Output: "car"

Explanation: "carpet" and "carpool" both start with "carp", but "card" and "care" break off after "car". All four words start with "car", and no longer string fits all of them.

Example 2

Input: words = ["night", "nightly", "nightfall"]

Output: "night"

Explanation: The other two words both begin with the whole of "night", so the answer is that entire word.

Example 3

Input: words = ["mango", "melon", "grape"]

Output: ""

Explanation: "mango" and "melon" share their first letter, but "grape" starts with a "g". No letter is shared by all three, so the answer is the empty string.

Check your understanding

Work out the answer for this input before you write any code.

words = ["season", "seas", "seat"]

Constraints

  • 1 ≤ words.length ≤ 105
  • 0 ≤ words[i].length, and all the words together hold at most 106 letters
  • words[i] holds only lowercase English letters

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.