Tech Interview RoomStudy guides

Strings

Longest common prefix of an array of strings. Compare horizontal, vertical, sort-based and stream solutions.

Beginner · 2 min read · Lesson 3 of 4 in Strings

Problem

["flower", "flow", "flight"] → "fl"; ["dog", "racecar", "car"] → "".

Pattern

Column-by-column comparison with early exit, or reduce the problem pairwise (the prefix of all strings is the prefix of the prefix so far and the next string).

Approach 1: Horizontal scanning (O(S), S = total characters)

Start with the first string and shrink it while the next string does not start with it.

java
class PrefixHorizontal {
    static String lcp(String[] words) {
        if (words.length == 0) return "";
        String prefix = words[0];
        for (int i = 1; i < words.length; i++)
            while (!words[i].startsWith(prefix)) prefix = prefix.substring(0, prefix.length() - 1);
        return prefix;
    }
}

Approach 2: Vertical scanning, character by character (O(S), stops at the first mismatch) — optimal in practice

java
class PrefixVertical {
    static String lcp(String[] words) {
        if (words.length == 0) return "";
        for (int i = 0; i < words[0].length(); i++) {
            char c = words[0].charAt(i);
            for (int j = 1; j < words.length; j++)
                if (i == words[j].length() || words[j].charAt(i) != c) return words[0].substring(0, i);
        }
        return words[0];
    }
}

Approach 3: Sort, then compare only the first and last strings (O(S log n))

After lexicographic sorting, the first and last strings are the most different; their common prefix is everyone's.

java
import java.util.Arrays;

class PrefixSort {
    static String lcp(String[] words) {
        if (words.length == 0) return "";
        String[] w = words.clone();
        Arrays.sort(w);
        String first = w[0], last = w[w.length - 1];
        int i = 0;
        while (i < first.length() && i < last.length() && first.charAt(i) == last.charAt(i)) i++;
        return first.substring(0, i);
    }
}

Approach 4: Java 8 streams reduce

java
import java.util.Arrays;

class PrefixStreams {
    static String lcp(String[] words) {
        return Arrays.stream(words).reduce(PrefixStreams::common).orElse("");
    }
    private static String common(String a, String b) {
        int i = 0;
        while (i < a.length() && i < b.length() && a.charAt(i) == b.charAt(i)) i++;
        return a.substring(0, i);
    }
}

class PrefixDemo {
    public static void main(String[] args) {
        for (String[] w : new String[][] {{"flower", "flow", "flight"}, {"dog", "racecar", "car"}, {"interview", "internet", "interval"}}) {
            System.out.println("[" + PrefixHorizontal.lcp(w) + "] [" + PrefixVertical.lcp(w) + "] [" + PrefixSort.lcp(w) + "] [" + PrefixStreams.lcp(w) + "]");
        }   // [fl] x4, [] x4, [inter] x4
    }
}

Feasible → optimal

Horizontal and vertical scanning are both O(S) in the worst case; vertical stops at the first mismatching column, so it is fastest when the prefix is short. Sorting costs O(S log n) but is a neat trick. A trie helps when many prefix queries run against the same set.

Follow-up questions interviewers ask

Try answering each one before you open it.

Related (same pattern): implement a trie (prefix tree) for autocomplete.

Each node holds children (an array of 26 or a Map<Character, Node>) and an end flag. Insert and search are O(word length); startsWith(prefix) walks the prefix and then collects words below it. The longest common prefix of all words is the path from the root while each node has exactly one child and is not a word end.

Related (same pattern): implement strStr / indexOf (first occurrence of a needle).

Naive O(n·m) by comparing at every position; KMP builds a prefix-function table to skip re-comparisons, O(n + m); Rabin-Karp uses a rolling hash, O(n + m) on average. In Java, String.indexOf is the practical answer.