O(n) time and O(1) space easy to understand Java solution, 14ms

  • 0

    The first string is the longest common prefix so far. The variable endIdx keeps track of the maximum index to be compared. The while loop finds the first index of a non-common character up to endIdx exclusive.

    public class Solution {
        public String longestCommonPrefix(String[] strs) {
            int len = strs.length;
            if (len == 0) return "";
            String prefix = strs[0];
            int endIdx = prefix.length();
            for (int i = 1; i < strs.length; i++) {
                String str = strs[i];
                int ptr = 0;
                while (ptr < endIdx && ptr < str.length() && prefix.charAt(ptr) == str.charAt(ptr)) ptr++;
                endIdx = ptr;
            return prefix.substring(0, endIdx);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.