Go: Find a pair with a given sum

A map turns a slow search into a quick lookup.

What to build

A program that finds two numbers in a list that add up to a target.

Requirements

  • Read n and the target, then n numbers.
  • Find the pair of positions i < j (counting from 0) with the smallest j such that the numbers add up to the target; if several i work, use the smallest i.
  • Print i j, or no pair if there is none.

Input

Line 1: n and target. Line 2: n numbers.

Output

One line.

Constraints

1 ≤ n ≤ 100; numbers and target are between -1000 and 1000.

Example

Input:

5 9
2 7 11 15 1

Output:

0 1

Why it works

While walking through the list, the map remembers the index of every number seen so far. For each new number x one lookup of target - x answers whether an earlier partner exists, so no second loop is needed.

Examples

Example 1 · Input
5 9
2 7 11 15 1
Expected output
0 1
Example 2 · Input
3 100
1 2 3
Expected output
no pair

Hints

Hint 1

Walk through the numbers with index j. Before storing a number, look for target - x in a map from value to index.

Hint 2

Store a value only if it is not in the map yet, so you keep the smallest earlier index.

Solution

Show one correct solution (try it yourself first)
package main

import "fmt"

func main() {
	var n, target int
	fmt.Scan(&n, &target)
	seen := make(map[int]int)
	for j := 0; j < n; j++ {
		var x int
		fmt.Scan(&x)
		if i, ok := seen[target-x]; ok {
			fmt.Println(i, j)
			return
		}
		if _, exists := seen[x]; !exists {
			seen[x] = j
		}
	}
	fmt.Println("no pair")
}

▶ Open this solution in the compiler

Lesson: Maps →