- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 given sum in an array(O(nlogn))
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: Sort the given array, declare low:=0 and high:=size-1 variables.
Step 3: Iterate a for loop until low <= high.
Step 4: If arr[low]+arr[high] == sum, then print the elements.
Step 5: If arr[low]+arr[high] < sum, then low++. If arr[low]+arr[high] > sum, then high--.
Step 5: At the end, print “pair not found”.
Program
package main import ( "fmt" "sort" ) func findSumPair(arr []int, sum int){ sort.Ints(arr) low := 0 high := len(arr) - 1 for low <= high{ if arr[low] + arr[high] == sum{ fmt.Printf("Pair for given sum is (%d, %d).\n", arr[low], arr[high]) return } else if arr[low] + arr[high] < sum { low++ } else { high-- } } 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 (6, 9). Pair not found in given array.
- Related Articles
- Write a Golang program to find pairs with the given sum in an array(O(n2))
- Write a Golang program to find pairs with the given sum in an array(O(n))
- Write a Golang program to find duplicate elements in a given array
- Write a Golang program to calculate the sum of elements in a given array
- Write a Golang program to find the element with the minimum value in an array
- Write a Golang program to reverse an array
- Write a Golang program to find the sum of digits for a given number
- Write a Golang program to find the frequency of an element in an array
- Write a Golang program to search an element in an array
- Write a Golang program to find the frequency of each element in an array
- Write a Golang program to find prime numbers in a given range
- Write a Golang program to find duplicate elements in a given range
- Write a Golang program to search an element in a sorted array
- Write a Golang program to sort an array using Bubble Sort
- Golang Program to Check if An Array Contains a Given Value

Advertisements