array manipulation
programming tutorial
data structures
algorithm
coding techniques

How to increment all values in an array interval by a given amount

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

If you need to add a value to every element in an array range, the direct loop is obvious and often perfectly fine for one update. The more interesting case is when there are many interval updates, because then a difference-array technique can reduce each range update from linear time to constant time.

Core Sections

The naive update is simple and correct

For a single update on a normal array, just loop over the interval.

python
1def increment_range(arr: list[int], left: int, right: int, delta: int) -> None:
2    for i in range(left, right + 1):
3        arr[i] += delta
4
5
6values = [0, 0, 0, 0, 0]
7increment_range(values, 1, 3, 2)
8print(values)

This is easy to read and runs in O(r - l + 1) time for one operation. If you only perform a few updates, this may be the best solution because it has minimal complexity in both code and reasoning.

Why repeated range updates get expensive

Suppose you have an array of length n and q updates. If each update touches a long interval, the total runtime can approach O(nq). That becomes wasteful when the update pattern is heavy.

The core insight is that for repeated interval additions, you do not need to change every element immediately. You can record only where the increment starts and where it stops.

Use a difference array for many updates

A difference array stores boundary changes instead of fully updated values. To add delta to every position from left to right:

  • add delta at diff[left]
  • subtract delta at diff[right + 1] if that index exists

After processing all updates, reconstruct the final values with a prefix sum.

python
1def apply_range_updates(length: int, updates: list[tuple[int, int, int]]) -> list[int]:
2    diff = [0] * length
3
4    for left, right, delta in updates:
5        diff[left] += delta
6        if right + 1 < length:
7            diff[right + 1] -= delta
8
9    result = [0] * length
10    running = 0
11    for i in range(length):
12        running += diff[i]
13        result[i] = running
14
15    return result
16
17
18updates = [(1, 3, 2), (2, 4, 3)]
19print(apply_range_updates(5, updates))

This makes each update O(1) and the final reconstruction O(n). For many updates, that is a major improvement.

Start from an existing array, not just zeros

If the array already contains values, build the updates on top of it by reconstructing the accumulated increments and then adding them back to the original array.

python
1def apply_updates_to_existing(arr: list[int], updates: list[tuple[int, int, int]]) -> list[int]:
2    diff = [0] * len(arr)
3
4    for left, right, delta in updates:
5        diff[left] += delta
6        if right + 1 < len(arr):
7            diff[right + 1] -= delta
8
9    result = []
10    running = 0
11    for i, value in enumerate(arr):
12        running += diff[i]
13        result.append(value + running)
14
15    return result
16
17
18base = [10, 10, 10, 10, 10]
19updates = [(1, 3, 2), (0, 2, 1)]
20print(apply_updates_to_existing(base, updates))

This is the more general version you would use in real applications.

When to choose which approach

Use the naive loop when:

  • you only have one or a few updates
  • the intervals are short
  • code simplicity matters more than asymptotic improvement

Use the difference array when:

  • you have many range updates
  • the array is large
  • you only need the final array after all updates

The last point is important. If you need to answer queries between updates, the problem becomes more like a segment tree or Fenwick tree family of problems rather than a pure difference-array pass.

Common Pitfalls

  • Using the naive loop for thousands of large interval updates can create unnecessary O(nq) work.
  • Forgetting the right + 1 boundary check in the difference-array approach causes out-of-bounds errors.
  • Reconstructing the final array incorrectly without a running prefix sum defeats the whole method.
  • Applying the technique when intermediate query results are needed mixes up offline updates with online-query problems.
  • Confusing inclusive intervals with half-open intervals leads to off-by-one mistakes in both the naive and optimized versions.

Summary

  • A direct loop is the simplest solution for a single or small number of interval increments.
  • A difference array turns each range increment into two point updates.
  • After all updates, a prefix sum reconstructs the final values.
  • The optimized approach is O(1) per update and O(n) for the final pass.
  • Choose the technique based on whether you need simplicity for a few updates or efficiency for many updates.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms