Longest Common Prefix

Easystring
Category: Fundamentals
Companies that ask this question:
AmazonGoogleFacebook

Approach

Longest Common Prefix

Problem Statement

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

Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Approach

Vertical Scanning

Compare characters column by column across all strings.

Algorithm:

  1. Take first string as reference
  2. For each character position:
    • Check if all strings have a character at this position
    • Check if all characters match
    • If mismatch or end reached, return prefix so far
  3. Return the complete first string if all match

Complexity

  • Time: O(S) where S = sum of all characters
  • Space: O(1)

Solution

java
1class Solution {
2    public String longestCommonPrefix(String[] strs) {
3        if (strs == null || strs.length == 0) {
4            return "";
5        }
6        
7        for (int i = 0; i < strs[0].length(); i++) {
8            char c = strs[0].charAt(i);
9            
10            for (int j = 1; j < strs.length; j++) {
11                if (i >= strs[j].length() || strs[j].charAt(i) != c) {
12                    return strs[0].substring(0, i);
13                }
14            }
15        }
16        
17        return strs[0];
18    }
19}
Loading visualizer...