Scala algorithm: Find kth largest element in a List
Published
Algorithm goal
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!
Get the full algorithm !
or
'Unlimited Scala Algorithms' gives you access to all the 100 published Scala Algorithms!
Upon purchase, you will be able to Register an account to access all the algorithms on multiple devices.
Explanation
(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.
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').
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!
Ordering
In Scala, the 'Ordering' type is a 'type class' that contains methods to determine an ordering of specific types.