Prefix Sums & Range Queries · 15 min · free with an account

Challenge: Difference Array

Lesson preview · about 30%

Apply +3 to indexes 1 through 3 and +2 to 2 through 4; return the final array.

Core idea

First make the visible case correct, then test a smallest, duplicate, or adversarial case. Trim whitespace surrounding the complete input before parsing.

Start with the idea

Solve the exact task, not just the visible example: Apply +3 to indexes 1 through 3 and +2 to 2 through 4; return the final array. On input n=5 updates=(1,3,3),(2,4,2), predict the output before opening the answer reveal. The revealed output is a test oracle for this case, while private checks exercise other legal cases. Start by stating the input grammar and output format in your own words. Parse the complete input, including surrounding whitespace, before relying on any convenient positions in the example.

Build the solution around one maintained claim: Mark only where a range update starts and stops, then integrate once. Decide what state represents that claim, how it is initialized, what a single update does, and when the algorithm stops. A range method summarizes intervals so the same information is not recomputed. A static prefix table and an updateable tree make different tradeoffs; define endpoint conventions first. Trace the visible input by hand and record at least two intermediate states, not only the final answer. If the trace cannot justify your predicted output, there is a gap between the idea and the implementation.

Use the Rust sketch as a guide, not a substitute for a complete solve function. The supplied Rust sketch is a starting point. Identify what it stores, how one iteration changes it, and whether it already solves the exact task or only demonstrates a related operation.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Algorithms