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

## 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

1. ### Def Inside Def

A great aspect of Scala is being able to declare functions inside functions, making it possible to reduce repetition.

``````def exampleDef(input: String): String = {
def surroundInputWith(char: Char): String = s"\$char\$input\$char"
surroundInputWith('-')
}

assert(exampleDef("test") == "-test-")
``````

It is also frequently used in combination with Tail Recursion.

2. ### foldLeft and foldRight

A 'fold' allows you to perform the equivalent of a for-loop, but with a lot less code.

``````def foldMutable[I, O](initialState: O)(items: List[I])(f: (O, I) => O): O =
items.foldLeft(initialState)(f)
``````
3. ### 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!

``````assert(Option(1).flatMap(x => Option(x + 2)) == Option(3))

assert(Option(1).flatMap(x => None) == None)
``````
4. ### Pattern Matching

Pattern matching in Scala lets you quickly identify what you are looking for in a data, and also extract it.

``````assert("Hello World".collect {
case character if Character.isUpperCase(character) => character.toLower
} == "hw")
``````
5. ### 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.

``````def sum(from: Int, until: Int): Int =
if (from == until) until else from + sum(from + 1, until)

def thisWillSucceed: Int = sum(1, 5)

def thisWillFail: Int = sum(1, 300)
``````
6. ### View

The `.view` syntax creates a structure that mirrors another structure, until "forced" by an eager operation like .toList, .foreach, .forall, .count.

# Scala Algorithms: The most comprehensive library of algorithms in standard pure-functional Scala

### Study our 89 Scala Algorithms: 6 fully free, 89 published & 0 upcoming

Fully unit-tested, with explanations and relevant concepts; new algorithms published about once a week.

### Explore the 21 most useful Scala concepts

To save you going through various tutorials, we cherry-picked the most useful Scala concepts in a consistent form.

## Register now (free)

Register with GitHub

This gives you access to free test cases & hints for all our 89 published algorithms as well as our installation-free Scala IDE.

You can then choose to subscribe to "Scala Algorithms Unlimited", which gets you access to every current and upcoming algorithm solution. We use Stripe so your data is safe.

We will e-mail you at most once per week with new algorithms and relevant content.
Your data is protected and unsubscribing is straightforward. 