Scala algorithm: Longest common prefix of strings
Published
Algorithm goal
Find the longest common prefix from a list of strings. For example, from a list ['tess', 'tester', 'testing'], the longest common prefix is 'tes' because that is the longest substring that is shared between them.
Test cases in Scala
assert(longestCommonPrefix("test", "teaset", "st").isEmpty)
assert(longestCommonPrefix("test", "tester", "testing").contains("test"))
assert(longestCommonPrefix("tess", "tester", "testing").contains("tes"))
assert(longestCommonPrefix("x", "y").isEmpty)
assert(longestCommonPrefix().isEmpty)
Algorithm in Scala
8 lines of Scala (compatible versions 2.13 & 3.0), showing how concise Scala can be!
Explanation
First, we should find the shortest string in the list because that is the maximum possible longest prefix. Once we find that, we iterate through each of the indices to find the last index that has the same character for all the strings. (this is © from www.scala-algorithms.com)
Scala concepts & Hints
Drop, Take, dropRight, takeRight
Scala's `drop` and `take` methods typically remove or select `n` items from a collection.
For-comprehension
The for-comprehension is highly important syntatic enhancement in functional programming languages.
Option Type
The 'Option' type is used to describe a computation that either has a result or does not. In Scala, you can 'chain' Option processing, combine with lists and other data structures. For example, you can also turn a pattern-match into a function that return an Option, and vice-versa!
Range
The
(1 to n)
syntax produces a "Range" which is a representation of a sequence of numbers.View
The
.view
syntax creates a structure that mirrors another structure, until "forced" by an eager operation like .toList, .foreach, .forall, .count.