Scala algorithm: Compute the length of longest valid parentheses
Published
Algorithm goal
Find the longest length of valid parentheses in a string. For example, in '((())()', the maximum length is 6 because '(())()' forms the longest valid parentheses sequence.
Test cases in Scala
Algorithm in Scala
25 lines of Scala (compatible versions 2.13 & 3.0), showing how concise Scala can be!
Explanation
In order to count any length of parentheses, we must first reach a closing parentheses, e.g. if we start with '((', nothing is counted because no parens are reached. It's only when we get to the ')' in '(()' that a parens is counted -- we find that its sibling is '(' and thus we now return '2'.
If we applied this naive algorithm, we would only capture pairs '()'. However if you had another full pair before it, you could now count a length of '4'. This covers cases like '(()()', '(()()()' already! (this is © from www.scala-algorithms.com)
How do we get to the case '(()()())'? Well, when we get to the last ')', we find that the previous length of the longest valid parentheses ('6') allows us to navigate from our current index i = 7 to i = 7 - 6 - 1 = 0, and check if the character at i = 0 is '('. If it is so, then we can add this length 6 with 2 to get 6 + 2 = 8; there is no previous parens before that sequence so nothing more needs to be added
Scala concepts & Hints
Def Inside Def
A great aspect of Scala is being able to declare functions inside functions, making it possible to reduce repetition.
It is also frequently used in combination with Tail Recursion.
foldLeft and foldRight
A 'fold' allows you to perform the equivalent of a for-loop, but with a lot less code.
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!
Pattern Matching
Pattern matching in Scala lets you quickly identify what you are looking for in a data, and also extract it.
Stack Safety
Stack safety is present where a function cannot crash due to overflowing the limit of number of recursive calls.
This function will work for n = 5, but will not work for n = 2000 (crash with java.lang.StackOverflowError) - however there is a way to fix it :-)
In Scala Algorithms, we try to write the algorithms in a stack-safe way, where possible, so that when you use the algorithms, they will not crash on large inputs. However, stack-safe implementations are often more complex, and in some cases, overly complex, for the task at hand.
View
The
.view
syntax creates a structure that mirrors another structure, until "forced" by an eager operation like .toList, .foreach, .forall, .count.