# Scala algorithm: Find kth largest element in a List

Published

## Test cases in Scala

``````assert(kthLargestElement(Nil, 4) == None)
assert(kthLargestElement(List(5, 6, 1, 2, 3, 4), 4) == Some(3))
assert(kthLargestElement(List(5, 6, 7, 1, 2, 3, 4), 4) == Some(4))
``````

## Algorithm in Scala

10 lines of Scala (compatible versions 2.13 & 3.0), showing how concise Scala can be!

## Scala concepts & Hints

1. ### Drop, Take, dropRight, takeRight

Scala's `drop` and `take` methods typically remove or select `n` items from a collection.

``````assert(List(1, 2, 3).drop(2) == List(3))

assert(List(1, 2, 3).take(2) == List(1, 2))

assert(List(1, 2, 3).dropRight(2) == List(1))

assert(List(1, 2, 3).takeRight(2) == List(2, 3))

assert((1 to 5).take(2) == (1 to 2))
``````
2. ### Lazy List

The 'LazyList' type (previously known as 'Stream' in Scala) is used to describe a potentially infinite list that evaluates only when necessary ('lazily').

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

In Scala, the 'Ordering' type is a 'type class' that contains methods to determine an ordering of specific types.

``````assert(List(3, 2, 1).sorted == List(1, 2, 3))

assert(List(3, 2, 1).sorted(Ordering[Int].reverse) == List(3, 2, 1))

assert(Ordering[Int].lt(1, 2))

assert(!Ordering[Int].lt(2, 1))
``````

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

## How our 100 algorithms look

1. A description/goal of the algorithm.
2. An explanation with both Scala and logical parts.
3. A proof or a derivation, where appropriate.
4. Links to Scala concepts used in this specific algorithm, also unit-tested.
5. An implementation in pure-functional immutable Scala, with efficiency in mind (for most algorithms, this is for paid subscribers only).
6. Unit tests, with a button to run them immediately in our in-browser IDE.

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

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

### Explore the 22 most useful Scala concepts

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

## Subscribe to Scala Algorithms

Maximize your Scala with disciplined and consistently unit-tested solutions to 100+ algorithms.

Use it from improving your day-to-day data structures and Scala; all the way to interviewing.