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

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.

Constraints:

1 <= strs.length <= 200 0 <= strs[i].length <= 200 strs[i] consists of only lowercase English letters.

Solution

O(min(n) * n)

class Solution {
    public String longestCommonPrefix(String[] strs) {
        var prefix = "";

        // find the min now to make our code ahead a bit simpler
        var min = Integer.MAX_VALUE;
        for (var s : strs) {
            min = Math.min(min, s.length());
        }


        for (var i = 0; i < min; i++) {
            // strs will always have at least one item, so this will never be out of bounds
            var target = strs[0].charAt(i);
            for (var s : strs) {
                if (s.charAt(i) != target) {
                    return prefix;
                }
            }
            prefix += target;
        }

        return prefix;
    }
}

Recent posts from blogs that I like

Sequoia introduces pinning to iCloud Drive

If you have Optimise Mac Storage enabled for iCloud Drive, this new feature lets you pin the files you want to be stored locally and not evicted. Full details.

via The Eclectic Light Company

Notes on running Go in the browser with WebAssembly

Recently I've had to compile Go to WebAssembly to run in the browser in a couple of small projects (#1, #2), and in general spent some time looking at WebAssembly. I find WebAssembly to be an exciting technology, both for the web and for other uses (e.g. with WASI); specifically, it's pretty great t...

via Eli Bendersky

I fixed the strawberry problem because OpenAI couldn't

Remember kids: real winners cheat

via Xe Iaso