A list of numbers is arithmetic when it has at least three numbers and the gap between each number and the next is always the same, such as [2, 4, 6] or [9, 9, 9] or [5, 1, -3].
Given an integer array nums, count how many of its contiguous pieces (subarrays) are arithmetic.
Example 1
Input: nums = [3, 5, 7, 9, 2, 2, 2] Output: 4 Why: [3, 5, 7], [5, 7, 9], [3, 5, 7, 9] and [2, 2, 2]
2 more examples and the constraints
Example 2
Input: nums = [8, 1] Output: 0 Why: fewer than three numbers
Example 3
Input: nums = [10, 7, 4, 1, 1] Output: 3 Why: [10, 7, 4], [7, 4, 1] and [10, 7, 4, 1]; the gap may be negative
Constraints
- 1 ≤ length of nums ≤ 5,000
- −1,000 ≤ nums[i] ≤ 1,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Extend from every startO(n²)
- Count per runO(n)
- Slices ending hereO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 5,000 equal numbers | Verdict |
|---|---|---|---|
| Extend from every start | O(n²) | Re-checks the same gaps | |
| Count per run | O(n) | Passes; mind the seams | |
| Slices ending here | O(n) | Best; one simple loop |
n = length of nums.
Edge cases to test
- Fewer than three numbers. [8, 1] or [1] has no slice; the loop from i = 2 never runs.
- All equal. A gap of 0 counts: [6, 6, 6, 6, 6] has 6 slices.
- Negative gaps. [10, 7, 4, 1] has gap −3 and 3 slices.
- Runs sharing a number. [1, 2, 3, 5, 7, 9]: 3 belongs to both runs, giving 1 + 3 = 4.
Common mistakes
- Counting runs of two numbers, or starting the loop at i = 1.
- Adding 1 per arithmetic index instead of
cur, which misses the longer slices. - Starting the next run at j + 1 and losing slices that begin on the shared border number.
How to talk through it
- 1Clarify. Slices must be contiguous and at least three long? Does a gap of 0 count?
- 2Give the brute force. Extend from each start while the gap holds: O(n²) on one long run.
- 3Count by the last index. Slices ending at i are the ones ending at i − 1, stretched, plus one triple.
- 4Code the one pass. Keep
curandtotal; resetcurwhen the gap breaks. - 5Test out loud. Run [1, 2] for 0, all-equal numbers, and two runs that share a number.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?