Arithmetic Slices solution explained

Arithmetic Slices asks how many contiguous pieces of an array, each at least three long, have the same difference between every pair of neighbors. Walk the array once and keep a counter of how many such pieces end at the current position: it grows by one while the step repeats and drops to zero when it changes. Adding that counter to a running total gives the answer in O(n) time and O(1) memory.

By Published 7 min read

The problem, in plain terms

Call a stretch of the array arithmetic if it has at least three values and each value differs from the one before it by the same amount. Count every such stretch, including ones that sit inside longer ones. Stretches are contiguous: you may not skip values. The step can be positive, negative or zero.

Case A: [1, 3, 5, 7, 4, 4, 4, 4]
  steps:  2  2  2 -3  0  0  0
  run 1: 1 3 5 7  ->  1 3 5 | 3 5 7 | 1 3 5 7    (3 slices)
  run 2: 4 4 4 4  ->  same shape                 (3 slices)
  answer: 6

Case B: [2, 9]                  answer: 0
Case C: [10, 7, 4, 1, -2]       one run of 5 values, answer: 6
Three cases, made up for this page

Confirm that length three is the minimum, that stretches inside a longer stretch count separately, and whether the answer could exceed a 32-bit integer for long inputs. A single run of n equal steps produces about n²/2 slices, so for very long arrays a 64-bit total is the safe choice in languages with fixed-size integers.

Why interviewers like it

It is a gentle DP problem that rewards a precise state. The question to ask is not how many slices exist so far but how many end exactly here. Once you phrase it that way, the update is one line, and the interviewer can move to the harder subsequence version or to proving the counting formula. It is also a quick check on off-by-one discipline, since the minimum length of three shows up in the indexes.

Brute force: extend from every start

For each start i, fix the step a[i + 1] - a[i] and walk right while each new step matches. Every position you reach that is at least two past the start closes a valid slice. This is O(n²) in the worst case, a constant array. An even slower version checks every (start, end) pair from scratch in O(n³), which is the reference the faster code was tested against.

def count_slices_quadratic(a):
    total = 0
    for i in range(len(a) - 2):
        step = a[i + 1] - a[i]
        j = i + 2
        while j < len(a) and a[j] - a[j - 1] == step:
            total += 1  # a[i..j] is a valid slice
            j += 1
    return total
Python: extend each start while the step repeats, O(n²)

Optimal: count the slices that end here

Let ending be the number of valid slices that end at position i. If the step into i equals the step into i - 1, then every slice that ended at i - 1 can be stretched by one to end at i, and there is one new slice of length exactly three, (i - 2, i - 1, i). So ending grows by one. If the step changes, nothing can end here, and ending resets to 0. The answer is the sum of ending over all positions.

def count_slices(a):
    total = ending = 0
    for i in range(2, len(a)):
        if a[i] - a[i - 1] == a[i - 1] - a[i - 2]:
            ending += 1
            total += ending
        else:
            ending = 0
    return total
Python: one pass, O(n) time, O(1) memory
function countSlices(a) {
  let total = 0;
  let ending = 0;
  for (let i = 2; i < a.length; i++) {
    if (a[i] - a[i - 1] === a[i - 1] - a[i - 2]) {
      ending += 1;
      total += ending;
    } else {
      ending = 0;
    }
  }
  return total;
}
JavaScript: the same running count
i   value   same step?   ending   total
2     5        yes          1        1
3     7        yes          2        3
4     4        no           0        3
5     4        no           0        3
6     4        yes          1        4
7     4        yes          2        6
Case A traced

The formula view gives the same total and is a nice cross-check. A run with k equal steps contributes 1 + 2 + ... + (k - 1). In Case A each run has three equal steps, so each contributes 1 + 2 = 3. In Case C there are four equal steps, so 1 + 2 + 3 = 6. Some interviewers ask for this closed form after the loop; deriving it from the ending counter is a strong answer.

Complexity summary

n array elements
ApproachTimeExtra memoryNote
Check every (start, end) pairO(n³)O(1)Test oracle
Extend from every startO(n²)O(1)Fine first answer
Count slices ending hereO(n)O(1)Expected answer
Run lengths plus formulaO(n)O(1)Same result, nice to mention
n array elements. Scroll sideways on a small screen.

Edge cases to try

  • Fewer than three values: 0, and the loop must not read a[-1] or a[i - 2] out of range.
  • All values equal: every stretch of length three or more counts, since the step is 0.
  • Two runs that share an endpoint, like [1, 2, 3, 2, 1]: the 3 belongs to both, and the answer is 2.
  • Negative steps, like Case C.
  • A single long run: the total grows quadratically, so watch the integer type.

Mistakes to avoid

  • Counting only maximal runs instead of every slice inside them.
  • Adding 1 per matching step instead of adding the running ending counter.
  • Forgetting to reset the counter when the step changes, so an old run leaks into a new one.
  • Starting the loop at index 1, which reads a[-1]: it silently wraps to the last value in Python and is undefined in JavaScript.
  • Mixing this up with the subsequence version, where values may be skipped.

Follow-ups

  • Return the longest slice instead of the count. Track the longest run of equal steps and add one for the values.
  • Count arithmetic subsequences, not slices. Values can now be skipped, so neighbors no longer decide anything. The usual approach keeps, for every index, a map from difference to how many sequences end there with that step; Longest Arithmetic Subsequence builds the same kind of table for the length.
  • A stream of values. The one-pass version already works on a stream: keep the last two values, the ending counter and the total.
  • Floating-point input. Equality of differences becomes fragile; ask whether a tolerance is expected.

How to explain it out loud

Fictional example

Counting what ends at each index
Candidate
Instead of counting all slices at once, I will count how many end at each index and add those up.
Candidate
If the step into this index matches the previous step, every slice that ended one position back can be stretched to here, plus there is one new slice of length three. So the count goes up by one.
Interviewer
And when the step changes?
Candidate
Nothing can end here, so it goes back to zero. One pass, constant memory. A run with k equal steps adds up to k minus one times k over two, which matches.

Longest Arithmetic Subsequence drops the contiguity rule and needs a table keyed by difference. Wiggle Subsequence is another scan over neighboring differences, looking for alternation instead of repetition. Count Square Submatrices with All Ones uses the same count-what-ends-here idea on a grid. Maximum Subarray is the classic running value that resets when it stops helping.

Practicing it with Natively

Arithmetic Slices is quick to code, so the score often comes from how clearly you derive the counter and the closed form. During practice on Mac or Windows, Natively can read the problem from a screenshot and suggest the ending-here state, and it transcribes your attempt so you can see where your explanation got vague. The AI interview assistant page explains the setup.

Questions people ask

How do you solve Arithmetic Slices?

Walk the array from index 2. If the step into the current value equals the previous step, increase a counter of slices ending here by one and add it to the total; otherwise reset the counter to 0. The total is the answer.

What is the time complexity of Arithmetic Slices?

O(n) time and O(1) memory for the one-pass solution. Extending from every start is O(n²), and checking every start and end pair from scratch is O(n³).

Is there a formula for Arithmetic Slices?

Yes. A run with k equal neighboring steps contains (k - 1) × k / 2 slices of length three or more. Summing that over every maximal run gives the same answer as the one-pass counter.

What is the difference between Arithmetic Slices and arithmetic subsequences?

Slices are contiguous, so only neighboring differences matter. Subsequences may skip values, which needs a table per index keyed by the difference instead of a single counter.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP