ХабрПостыНовостиМегапосты?

Algorithms in Go: Sliding Window Pattern

Most solutions to algorithmic problems can be grouped into a rather small number of patterns. When we start to solve some problem, we need to think about how we would classify them. For example, can we apply fast and slowalgorithmic pattern or do we need to use cyclic sortpattern? Some of the problems have several solutions with different patterns. In this article of series Algorithms in Go we consider an algorithmic pattern that solves an entire class of the problems related to array manipulation.

Let's consider the following problem: we have an array of integers and we need to find out the length of the smallest subarray the sum of which is no less than the target number. If we don't have such a subarray we shall return -1.

We can start with a naive approach and consider every possible subarray in the input:

  1. start with an item at index 0.

  2. grow the subarray by one.

  3. if the accumulated sum is equal or greater to the target number, save the length of the subarray.

  4. continue growing the subarray till we reach the last item.

  5. move the start of the subarray to the next item at index 1 and repeat the procedure.

Let's encode the above algorithm in Go:

for start := 0; start < len(arr); start++ {
	var acc int
	for stop := start; stop < len(arr); stop++ {
		acc += arr[stop]
		if acc >= target {
			minLn = min(minLn, stop-start+1)
		}
	}
}

As Go doesn't have generics (yet), we have to write function min manually.

What about minLn constant? We would like to start with an initial value equal to plus infinity. However, taking into consideration that we are still mere humans, we have to settle down on some finite approximation of infinity. An interesting fact about Go is that we actually can have constants that are "arbitrary" big, for example, this

const inf = 1 << 65 // 2 in power 65

and even this:

const inf = 1 << 165 // 2 in power 165

are perfectly fine constants.

In our use case, however, we will be just fine with the maximum value for an int64. Any of these will do:

minLn := 1 << 63 - 1
minLn := math.MaxInt64

In the following articles, we discuss more deeply subtle differences in Go in regards to integer constants and variables and why we guarded word arbitrary with quotes in the above paragraph.

We also have to check whether we able to accumulate the required sum at all and if not return -1

if minLn == 1<<63 -1 {
		return -1
}
return minLn

A clear advantage of the above implementation is that we visibly cover the whole space of options and can be certain that we get the intended result. The cost of this benefit is time complexity: we have two for loops, so we end up with the quadratic time complexity.

Can we do better than that?

Oh, yes. The Sliding Window Pattern could make the wonder. The basic idea is the following: we start "consuming" the array and accumulate the sum. We stop when the accumulated sum is greater or equal to the target number. And then we try to shrink the subarray from the start to obtain the minimum length of a subarray at this stage. Then we move the end of the subarray to the right i.e. processing the next number in the array) and repeat the whole process.

We can encode the algorithm in Go:

var start, stop, acc int
minLn := 1<<63 - 1

for stop < len(arr) {
   for stop < len(arr) && acc < target {
      acc += arr[stop]
      stop++
   }
   if acc < target {
      break
   }

   for start <= stop && acc-arr[start] >= target {
      acc -= arr[start]
      start++
   }

   ln := stop - start
   minLn = min(ln, minLn)

   acc -= arr[start]
   start++
}

if minLn == 1<<63-1 {
   return -1
}
return minLn

Ok, did we manage to improve the time complexity? Well, we iterate through the whole array and we add each item (and later discard it) exactly once, so now we have a linear time complexity.

Here you can find the code and tests.

In this post, we implemented a solution for the Sliding Window problem. This is one of the most popular algorithmic patterns that solve an entire class of problems. More algorithmic patterns such as Merge Intervals or Dutch National Flag can be found in the series Algorithms in Go.

@aydu
05.12.2020 15:52 UTC
Первоисточник

Комментарии

@unknown-50
08.03.2021 10:15 UTC
0
I like your post. It is good to see you verbalize from the heart and clarity on this important subject can be easily observed…
Responsive web design services
@sashagil
13.03.2021 21:32 UTC
0

Could you please correct this fragment (following up with correspondent corrections below it)?


In our use case, however, we will be just fine with the maximum value for an int64. Any of these will do:

minLn := 1 << 63 - 1

minLn := math.MaxInt64

The first variant is incorrect — and you picked the incorrect one out of two! Worse, you formatted this bad expression later on as 1<<63 - 1 — no spaces around << to kind of stress the fact that as you think this operation has the higher precedence over -.


No it does not. You need parentheses around 1 << 63. Go has C-style precedence of operators and - is one step higher in the precedence order than <<, so your expression yields the same result as 1 << 62 which is not what you meant. Check this table, for example: https://www.tutorialspoint.com/go/go_operators_precedence.htm.


Please correct!

26.06.2021 05:55 UTC
0

Hey sashagil!


Thank you for your comment and interesting observation!


While the precedence order that mentioned is correct to the vast majority of programming languages, it is not the case for Go:


There are five precedence levels for binary operators. Multiplication operators bind strongest, followed by addition operators, comparison operators, && (logical AND), and finally || (logical OR):

    5             *  /  %  <<  >>  &  &^
    4             +  -  |  ^
    3             ==  !=  <  <=  >  >=
    2             &&
    1             ||

The quote above is from Golang spec.


We can verify it in playground:


v := 1<<63 — 1
v1 := (1 << 63) — 1
fmt.Println(v == v1) // true
26.06.2021 06:04 UTC
0

Good to know, thanks — looks like i was fooled by a random "tutorial" page that pops up in search results at the top.