 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write a Golang program to find pairs with the given sum in an array(O(n))
Examples
Input Array = [1, 3, 5, 7, 8, 9], sum = 11 => (3, 8)
Approach to solve this problem
Step 1: Define a method that accepts an array and sum.
Step 2: Define a mapping variable, type map[int]int.
Step 3: Iterate the given array as i.
Step 4: If key in mapping sum-arr[i] is not present, then mapping[arr[i]]=i.
Step 5: If present, then print “pair is found”.
Step 6: At the end, print that “pair not found”.
Program
package main import "fmt" func findSumPair(arr []int, sum int){    mapping := make(map[int]int)    for i:=0; i<len(arr); i++{       if mapping[sum-arr[i]] == 0{          mapping[arr[i]] = i       } else {          fmt.Printf("Pair for given sum is (%d, %d).\n", arr[mapping[sum-arr[i]]], arr[i])          return       }    }    fmt.Println("Pair not found in given array.") } func main(){    findSumPair([]int{4, 3, 6, 7, 8, 1, 9}, 15)    findSumPair([]int{4, 3, 6, 7, 8, 1, 9}, 100) }  Output
Pair for given sum is (7, 8). Pair not found in given array.
Advertisements
 