Difference Array Technique
dev.to·2h·
Discuss: DEV
Flag this post

Understanding Difference Arrays

Imagine you have a problem. You have a list of numbers. This list is very big. You are given many tasks to update this list.

The task is to add a number to a range of indexes. For example, the first task could be to add 5 to all numbers from index 2 to index 7. If you do this one by one for every number on every task, it will be very slow. Your code will not run fast enough.

We need a faster way. This is where the Difference Array technique helps.

The Problem

Let’s start with a simple example. We have an array of size 6 initialized with 0.

A = [0, 0, 0, 0, 0, 0]

We have two updates to do.

  1. Add 2 to the numbers from index 1 to 3.
  2. Add 4 to the numbers from index 3 to 4.

All indexing in this post is 0-based.

Solutio…

Similar Posts

Loading similar posts...