# Scala algorithm: Find indices of tuples that sum to a target (Two Sum)

Published

## Algorithm goal

Find indices of tuples that sum to a target. Assume no duplicates on input.

## Test cases in Scala

``````assert(twoSum(Array.empty, 0).isEmpty, "Empty array has no result")
assert(
indexArray(Array(-1, 2)) == Map(-1 -> 0, 2 -> 1),
"We can map numbers to their indices"
)
assert(twoSum(Array(-1, 0, 1, 3, -3, -4), 0) == Set(Set(0, 2), Set(3, 4)))
``````

## Algorithm in Scala

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

## Explanation

The normal approach to this problem is to check for all pairings of values, however that is O(n^2).

In the faster version, we can put the values into a map, and then look up 'target - num' to find if there is a match for the other number for the target number (because 'num1 + num2 = target', then 'num2 = target - num1'. (this is Â© from www.scala-algorithms.com)

This takes to O(n) which is a good fast solution. We also use Sets to represent the indices since they may be out of order.

## Scala concepts & Hints

1. ### For-comprehension

The for-comprehension is highly important syntatic enhancement in functional programming languages.

``````val Multiplier = 10

val result: List[Int] = for {
num <- List(1, 2, 3)
anotherNum <-
List(num * Multiplier - 1, num * Multiplier, num * Multiplier + 1)
} yield anotherNum + 1

assert(result == List(10, 11, 12, 20, 21, 22, 30, 31, 32))
``````
2. ### 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

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