Foundations: Arrays, Strings, Two Pointers, Prefix Sums

Work through examples, try the reasoning yourself, then put it into practice.

View Slides

Before you start

  • Read a zero-based index and add signed integers.

What you will practice

  • Answer inclusive queries using boundary totals.
  • Trace which input survives an in-place write or a pointer move.
  • Derive when a positive-sum window can discard a start.
In this lesson

Lesson

7 min read

Foundations: Arrays, Strings, Two Pointers, Prefix Sums

A reading at index 2 is the third reading. The boundary at 2 is the gap before that reading. Draw the gaps as well as the values. That distinction will let you answer a range query, write back into an array, or decide what a window contains.

Answer several questions about the same array

A meter records changes [4, -6, 3, 5]. A query [1, 3] asks for the total from index 1 through index 3. Adding those three changes gives 2. Another query, [2, 3], asks you to add 3 and 5 again. What single reading could you store at each gap so that both queries take one subtraction?

Boundary 0 1 2 3 4
Value just crossed — 4 −6 3 5
Total so far 0 4 −2 1 6

Call the last row P. At boundary 4 the total includes everything through index 3. Subtracting the total at boundary 1 removes just the first reading. So the first answer is 6 - 4 = 2. For the second, subtract the total at boundary 2 and get 6 - (-2) = 8. In general, the inclusive query uses P[r+1] - P[l]. Boundary 0 lets the same rule work when the query starts at the first value.

Try it. Return the answers in order for queries [2,2], [0,3], [1,1]. Then change the reading at index 1 from −6 to −4. Which stored totals would need repair?

Check the boundaries

The answers are 3, 6, and −6. Only boundaries 2, 3, and 4 have crossed the changed reading. Each of their totals rises by 2. Precomputing works especially well when the data stays fixed across many queries.

For n readings and q queries, summing each interval directly costs up to nq additions. A prefix table uses n additions, q subtractions, and n+1 stored totals, apart from the returned answers. This is what an O(n + q) time bound counts. One short query alone can cost less to answer directly. Practice range queries.

Write a shorter answer into the original slice

Keep one copy of each value in sorted [2,2,2,5,5,8]. A caller wants the length and the values in the first slots. You could collect [2,5,8] into a fresh slice. Which slots in the original are already free to hold those values?

Next input Decision Accepted prefix after the decision Next output slot
2 at index 0 First value [2] 1
2 at 1, then 2 at 2 Both repeat the last accepted value [2] 1
5 at 3 Write 5 at index 1 [2,5] 2
5 at 4 Already present at the end of the prefix [2,5] 2
8 at 5 Write 8 at index 2 [2,5,8] 3

After reading r items, at most r could have been accepted. The next output slot is therefore at or before the next unread item. Read that item, then make the write. The caller sees length 3 and prefix [2,5,8]. Any values beyond that prefix are allowed. Sorting makes a comparison with the last accepted value sufficient because equal values occur together.

Try it. Trace [-1,-1,0,0,3] until the first write that changes a value. On unsorted [2,5,2], what extra fact would you need to keep just the first occurrence of each value?

Check the writes

Reading 0 at index 2 changes slot 1 from −1 to 0. The accepted prefix becomes [-1,0]. In the unsorted input the final 2 differs from its immediate predecessor. Remembering all previously accepted values, for example in a set, can catch that repeat.

In Go an array has fixed length. A slice refers to a portion of a backing array. Assigning to an indexed slot updates that storage, so the caller can inspect the prefix after the function returns. This scan needs one read per value and a constant number of indices. Practice in-place deduplication.

Compare the next surviving characters

Read "7,É!é7" from both ends. After ignoring punctuation and lowercasing the letters, could it read the same backward? A simple way to check is to build the cleaned sequence and compare it with its reverse. To do the comparisons as you go, keep track of the first and last characters still awaiting a partner.

The outer 7s match. Skip the comma on the left. Now É and é match after lowercasing. The remaining exclamation mark contributes no character. Each step either skips an excluded character or finishes one pair. In "7,É!é8" the first comparison already settles the answer.

The exercise keeps Unicode letters and decimal digits. In Go, indexing a string reads a byte. Use a rune sequence for this trace so that advancing one position crosses an entire code point. That conversion takes linear storage. In Python, iterating over the string already yields code points.

Try it. What does "3..." return? What about "3...4"? Draw the positions compared in each before writing a loop. Practice palindrome comparison.

Check the stopping rule

The first string has one surviving character and passes. Skipping the trailing periods reaches the 3, which needs no partner. The second string fails immediately because its two outer digits differ.

Find the shortest qualifying stretch

Packets have positive sizes [2,1,5,2]. Find the fewest consecutive packets totaling at least 7. Enumerating starts and extending each one will find the answer. Watch what happens to a start once it has already produced a qualifying window.

Right index Sum after entry Qualifying windows recorded, in order Window left for the next entry
0 2 — [2], sum 2
1 3 — [2,1], sum 3
2 8 [2,1,5], length 3 [1,5], sum 6
3 8 [1,5,2], length 3, then [5,2], length 2 [2], sum 2

Record the length before taking the left value out. That start has supplied its shortest qualifying window: every later end would make it longer. When the sum drops below 7, removing another positive value can only reduce it. Wait for the next entry. Each item enters once and leaves at most once, so even the loop inside the scan costs O(n) time in total and O(1) extra space.

Try it. Use target 6 on [1,2,6]. How many qualifying lengths do you record at the last index? What would a single removal miss? Then run the same rule on signed input [1,-2,6].

Check both stopping decisions

The positive case records lengths 3, 2, and 1, with sums 9, 8, and 6. A single removal leaves another qualifying window unexamined. In the signed case the running sums are 1, −1, and 5. The loop never shrinks, yet [6] qualifies. The earlier prefix table still computes any specified signed interval correctly.

In the graded exercise, return 0 if no nonempty window qualifies. Practice minimum size subarray sum.

Choose what to remember

A caller gives you a fixed array and many explicit pairs of endpoints. Another gives you a positive array and asks you to find endpoints with the shortest qualifying length. Explain which work repeats in each problem and which observation lets you stop doing it. For a third caller who wants the first two original positions holding equal readings, it will matter what you remember about earlier values. Continue to Hash Maps.

Test your reasoning in the array and string checkpoint.


Practice sequence

Use the order below for a guided path, or choose an item to revisit. A pass records a successful attempt; try a fresh example later to check what you can reconstruct.

Join Discord