Write a Golang program to find pairs with the given sum in an array(O(n2))

Go ProgrammingServer Side ProgrammingProgramming

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

Live Demo

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.
raja
Published on 04-Feb-2021 11:16:04
Advertisements