Interview 150

Longest Common Prefix

Problem
LC 14
File
interview150_LC14LongestCommonPrefix.java
Path
pkg5leetcode/interview150/interview150_LC14LongestCommonPrefix.java
Package
pkg5leetcode.interview150
Command
java pkg5leetcode/interview150/interview150_LC14LongestCommonPrefix.java
Approach
Compare characters column-wise across all strings.
Complexity
Time O(n*m), Space O(1)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/interview150/interview150_LC14LongestCommonPrefix.java
1package pkg5leetcode.interview150;2 3/*4 * Longest Common Prefix | LC 145 * APPROACH: Compare characters column-wise across all strings.6 * COMPLEXITY: Time O(n*m), Space O(1)7 */8public class interview150_LC14LongestCommonPrefix {9    static String longestCommonPrefix(String[] strs) {10        if (strs.length == 0) return "";11        for (int i = 0; i < strs[0].length(); i++) {12            char c = strs[0].charAt(i);13            for (int j = 1; j < strs.length; j++) {14                if (i >= strs[j].length() || strs[j].charAt(i) != c)15                    return strs[0].substring(0, i);16            }17        }18        return strs[0];19    }20 21    public static void main(String[] args) {22        check(longestCommonPrefix(new String[]{"flower", "flow", "flight"}).equals("fl"), "case1");23        check(longestCommonPrefix(new String[]{"dog", "racecar", "car"}).equals(""), "case2");24        System.out.println("all tests passed");25    }26 27    static void check(boolean cond, String name) {28        if (!cond) throw new AssertionError("FAILED: " + name);29        System.out.println("  PASS " + name);30    }31}