LAUNCH SALE 50% off every pass

See plans →

Start from the invariant.

66 of 66 templates

Sliding window

Sliding window

Maintain a valid contiguous interval.

Interview essentials
Free pattern

When to use it

Find the longest contiguous array segment whose sum is at most a limit. Every value must be nonnegative.

What stays true

After shrinking, sum equals the total in [left, right] and is at most the limit. Removing another left value cannot produce a longer valid segment ending here.

Time
O(n)
Extra space
O(1)
sliding_window.go
package main

func longestWindow(nums []int64, limit int64) int {
	if limit < 0 {
		return 0
	}
	left, best := 0, 0
	var total int64
	for right, value := range nums {
		total += value
		for total > limit {
			total -= nums[left]
			left++
		}
		if right-left+1 > best {
			best = right - left + 1
		}
	}
	return best
}

This file declares package main. Add your input/output entry point, or move the helpers into your package.

nums = [2, 1, 3, 1], limit = 4 → 2. Both [2, 1] and [3, 1] have length 2.

Keep the sum at most 4

Extend

  1. 2(active)
  2. 1(active)
  3. 3
  4. 1

[2, 1] sums to 3 and has length 2.

1 / 4

Templates

Esc
↑↓Move ↵Open Ctrl↵New tab >Actions ?Shortcuts

Keyboard shortcuts

Anywhere

Open search
CtrlKor /
Show these shortcuts
?
Close a window or menu
Esc

In search

Move through results
↑or ↓
Open the result
↵
Open in a new tab, or a problem on its judge
Ctrl↵
List actions only
>
Remove the filter
⌫

Go to

Learn
GthenL
Practice
GthenP
Assessments
GthenA
System design
GthenS
Companies
GthenC
My profile
GthenM
Today's quest
GthenT
Home
GthenH

Report a bug

Page