Longest Common Prefix - Problem

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 "".

Note: All given inputs are in lowercase letters a-z.

Input & Output

Example 1 — Basic Case
$ Input: strs = ["flower","flow","flight"]
Output: "fl"
💡 Note: The common prefix is "fl". All three strings start with "fl", but at position 2, "flower" and "flow" have 'o' while "flight" has 'i', so the common prefix stops there.
Example 2 — No Common Prefix
$ Input: strs = ["dog","racecar","car"]
Output: ""
💡 Note: There is no common prefix among the input strings. The first characters are 'd', 'r', and 'c' respectively, which are all different.
Example 3 — Complete Match
$ Input: strs = ["test","test","test"]
Output: "test"
💡 Note: All strings are identical, so the entire string "test" is the common prefix.

Constraints

  • 1 ≤ strs.length ≤ 200
  • 0 ≤ strs[i].length ≤ 200
  • strs[i] consists of only lowercase English letters

Visualization

Tap to expand
Longest Common Prefix - Vertical Scanning INPUT String Array: strs[] "flower" f l o w e r "flow" f l o w "flight" f l i g h t Dark blue = common prefix chars ALGORITHM STEPS 1 Initialize Start with column index = 0 2 Scan Column 0 f == f == f (OK, continue) f f f All match! 3 Scan Column 1 l == l == l (OK, continue) l l l All match! 4 Scan Column 2 o != i (STOP!) o != i FINAL RESULT Common prefix found at columns 0 and 1 Extracted prefix: "fl" Output: "fl" Verification: "flower" starts with "fl" OK "flow" starts with "fl" OK "flight" starts with "fl" OK Key Insight: Vertical scanning compares characters column by column across all strings simultaneously. This approach stops immediately when a mismatch is found, making it efficient for cases where the common prefix is short. Time Complexity: O(S) where S = sum of all character lengths. TutorialsPoint - Longest Common Prefix | Vertical Scanning Approach
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
52.0K Views
High Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen