LeetCode Longest Common Prefix Solution in Haskell

LeetCode Longest Common Prefix Solution in Haskell

The Two Sum problem on LeetCode is stated as:

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

My solution below is based on this fantastic answer:

longestCommonPrefix :: [String] -> String
longestCommonPrefix = map head . takeWhile (\(x : xs) -> not (null xs) && all (== x) xs) . transpose

It adopts the 'vertical scanning' approach by using the transpose function to transform the list of strings as follows:

strs = ["flower","flow","flight"]

transpose strs

>>> ["fff","lll","ooi","wwg","eh","rt"]

Each string in the transformed list represents the characters at a particular index in each of the input strings.

The takeWhile then takes elements from the transformed list that satisfy the predicate: all characters in the string must be equal, and the string must not be null (which means empty, not missing, in Haskell).

This is lazily evaluated, so elements will only be drawn from the list while the predicate is true. The rest of the list will not be evaluated.

This leaves us with:

>>> ["fff","lll"]

After mapping the head function to each of the remaining elements, the output is:

>>> "fl"