Golang program to find longest subarray with a given sum using two-pointer approach


In this Golang article, we are going to find longest subarray with a given sum using two-pointer approach with iterative and optimized-iterative method. An array is a collection of elements of the same data type, arranged in a contiguous block of memory, and accessed using an index or a subscript.

Using Two-Pointer Approach With Iterative Method

In this method, we will define a longestSubarray() function using iterative approach that is used to find longest subarray with a given sum using two-pointer approach.

Algorithm

  • Step 1 − First, we need to import the fmt package.

  • Step 2 − Start the main() function. Inside the main() function, initialize an array and provide integer sum value.

  • Step 3 − Now, calls the longestSubarray() function and pass the array & sum to it as argument.

  • Step 4 − Further, the resultant longest subarray value is printed using the fmt.Println() function.

  • Step 5 − Now, create a longestSubarray() function that takes an array of integers and a sum value as input. This function will return the longest sub-array with a given sum.

  • Step 6 − In the longestSubarray() function, check the length of the array. If it is 0, the function returns nil.

  • Step 7 − The function loops through each element of the array with an index end starting from 0. At each iteration, the value of arr[end] is added to currSum.

  • Step 8 − Finally, after comparisons the resultant longest sub array with a given sum is returned back.

Example

Following Is Go Language Program To Find Longest Subarray With A Given Sum Using Two-Pointer Approach With Iterative Method

package main

import "fmt"

func main() {
   arr := []int{10, 50, 20, 70, 10, 90}
   sum := 90
   subarr := longestSubarray(arr, sum)
   fmt.Println("Longest subarray with the sum of", sum, "is", subarr)
}

func longestSubarray(arr []int, sum int) []int {
   n := len(arr)
   if n == 0 {
      return nil
   }

   maxLen := 0
   maxStart, maxEnd := -1, -1
   currSum, start := 0, 0

   for end := 0; end < n; end++ {
      currSum += arr[end]

      for currSum > sum && start <= end {
         currSum -= arr[start]
         start++
      }

      if currSum == sum && end-start+1 > maxLen {
         maxLen = end - start + 1
         maxStart, maxEnd = start, end
      }
   }

   if maxStart == -1 {
      return nil
   }
   return arr[maxStart : maxEnd+1]
}

Output

Longest subarray with the sum of 90 is [20 70]

Using Two-Pointer Approach With Optimized Iterative Method

In this example, we will define a longestSubarrayWithGivenSum() function using iterative approach in optimized manner that is used to find longest sub-array with a given sum using two-pointer approach.

Algorithm

  • Step 1 − First, we need to import the fmt package.

  • Step 2 − Firstly, create a longestSubarrayWithGivenSum() function that takes an array of integers and a target sum value as input. This function will return the longest sub-array with a given sum.

  • Step 3 − The function uses two pointers, left and right, to keep track of the start and end indices.

  • Step 4 − It moves the right pointer to the right while adding each element to currentSum. If currentSum is greater than targetSum, the function moves the left pointer to the right and subtracts each element from currentSum until currentSum becomes less than or equal to targetSum.

  • Step 5 − Finally, after comparisons the resultant longest sub array with a given sum is returned back.

  • Step 6 − Start the main() function. Inside the main() function, initialize an array and provide integer target sum value.

  • Step 7 − Now, calls the longestSubarray() function and pass the array & sum to it as argument.

  • Step 8 − It then prints the longest subarray with the given sum if there is one, or a message indicating that there is no subarray with the given sum.

Example

Following is the go language program to find longest subarray with a given sum using two-pointer approach with optimized iterative method

package main

import "fmt"

func longestSubarrayWithGivenSum(arr []int, targetSum int) []int {
   var result []int
   var left, right, currentSum int

   for right < len(arr) {
      currentSum += arr[right]

      for currentSum > targetSum {
         currentSum -= arr[left]
         left++
      }

      if currentSum == targetSum && (result == nil || len(result) < right-left+1) {
         result = arr[left : right+1]
      }
      right++
   }
   return result
}

func main() {
   arr := []int{10, 40, 20, 30, 10, 50}
   targetSum := 70

   longestSubarray := longestSubarrayWithGivenSum(arr, targetSum)

   if longestSubarray == nil {
      fmt.Println("No subarray found with the given sum")
   } else {
      fmt.Println("Longest subarray with the given sum:", longestSubarray)
   }
}

Output

Longest subarray with the given sum: [10 40 20]

Conclusion

We have successfully compiled and executed a go language program to find longest subarray with a given sum using two-pointer approach with iterative and optimized-iterative method along with two examples. In the first example, we have used the iterative method and in the second example, we have used the optimized-iterative method.

Updated on: 03-Apr-2023

162 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements