- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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 the given sum in an array(O(n2))
Examples
Input Array = [4, 1, 6, 8, 7, 2, 3], sum = 11 => (4, 7) or (8, 3)
Approach to solve this problem
- Step 1: Define a method that accepts an array and sum.
- Step 2: Iterate from 0 to n as i.
- Step 3: Again, iterate a for loop from i+1 to n-1 as j.
- Step 4: If arr[i] + arr[j] == sum, then return arr[i] and arr[j].
- Step 5: At the end, print that pair not found.
Program
package main import ( "fmt" ) func findSumPair(arr []int, sum int){ for i:=0; i<len(arr)-1; i++{ for j:=i+1; j<len(arr); j++{ if arr[i]+arr[j] == sum{ fmt.Printf("Pair for given sum is (%d, %d).\n", arr[i], arr[j]) return } } } fmt.Println("Pair not found in the 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 the given array.
Advertisements