Difference Array Technique
dev.to·11w·
Discuss: DEV

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...

Keyboard Shortcuts

Navigation
Next / previous item
j/k
Open post
oorEnter
Preview post
v
Post Actions
Love post
a
Like post
l
Dislike post
d
Undo reaction
u
Recommendations
Add interest / feed
Enter
Not interested
x
Go to
Home
gh
Interests
gi
Feeds
gf
Likes
gl
History
gy
Changelog
gc
Settings
gs
Browse
gb
Search
/
General
Show this help
?
Submit feedback
!
Close modal / unfocus
Esc

Press ? anytime to show this help