Reducing the process time of the sum of numbers code in Go


I wrote this code, but the code test site rejected due to process time. To reduce time, I used Two pointers algorism, and Goroutine(I am not sure I used it correctly). But still that site rejected with the same reason. Is there any improvement solution to pass this? How can I reduce processing time.
Please review my code. Thank you for your support!

Problem description

sequence of N numbers A[1], A[2], … , A[N] exists. The sum of numbers from i to j in this sequence A[i]+A[i+1]+… Write a program to find the number of cases where +A[j-1]+A[j] becomes M.


In the first line, N(1≤N≤10,000) and M(1≤M≤300,000,000) are given. The next line contains A[1], A[2], … , A[N] is given, separated by spaces. Each A[x] is a natural number not exceeding 30,000.


the number of cases on the first line.


  • input 1 :

    4 2

    1 1 1 1

  • output 1:


  • input 2 :

    10 5

    1 2 3 4 2 5 3 1 1 2

  • output 2 :


package main

import "fmt"

func main() {
    var n int //numbers
    var m int //target sum

    c := make(chan []int)
    d := make(chan int)

    fmt.Scanf("%d %d\n", &n, &m)
    arr := make([]int, n)
    go ReadN(arr, n, c)
    go checker(<-c, n, m, d)

func ReadN(arr []int, n int, c chan<- []int) {
    for i := 0; i < n; i++ {
    c <- arr

func checker(arr []int, n, m int, d chan<- int) {
    var start int
    var end int
    var sum int
    var result int

    for start < n {
        if sum > m || end == n {
            sum -= arr[start]
        } else {
            sum += arr[end]
        if sum == m {
    d <- result


You can solve this type of question using prefix-sum algorithm, which can do this in O(n) time and space.
You can also refer to this article.

For practice on this type of questions, refer this

Answered By – Aditya Chudiwal

Answer Checked By – Willingham (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.