Arithmetic Subarrays - Problem

A sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i.

For example, these are arithmetic sequences:

  • [1, 3, 5, 7, 9] (difference = 2)
  • [7, 7, 7, 7] (difference = 0)
  • [3, -1, -5, -9] (difference = -4)

The following sequence is not arithmetic:

  • [1, 1, 2, 5, 7]

You are given an array of n integers, nums, and two arrays of m integers each, l and r, representing the m range queries, where the ith query is the range [l[i], r[i]]. All the arrays are 0-indexed.

Return a list of boolean elements answer, where answer[i] is true if the subarray nums[l[i]], nums[l[i]+1], ..., nums[r[i]] can be rearranged to form an arithmetic sequence, and false otherwise.

Input & Output

Example 1 — Basic Queries
$ Input: nums = [4,6,5,9,3,7], l = [0,0,2], r = [2,3,5]
Output: [true,false,true]
💡 Note: Query 1: [4,6,5] → sorted [4,5,6] with diff=1 (arithmetic). Query 2: [4,6,5,9] → sorted [4,5,6,9] with diffs [1,1,3] (not arithmetic). Query 3: [5,9,3,7] → sorted [3,5,7,9] with diff=2 (arithmetic).
Example 2 — Single Element
$ Input: nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10], l = [0,1,6,4,8,7], r = [4,4,9,7,9,10]
Output: [false,true,true,false,true,true]
💡 Note: Single elements or properly spaced sequences return true. Query [0,4]: [-12,-9,-3,-12,-6] cannot form arithmetic sequence due to duplicate -12.
Example 3 — Edge Case
$ Input: nums = [1,1,1], l = [0,1], r = [2,2]
Output: [true,true]
💡 Note: Query 1: [1,1,1] with diff=0 forms arithmetic sequence. Query 2: [1] single element is trivially arithmetic.

Constraints

  • n == nums.length
  • m == l.length
  • m == r.length
  • 2 ≤ n ≤ 500
  • 1 ≤ m ≤ 500
  • 0 ≤ l[i] < r[i] < n
  • -105 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Arithmetic Subarrays Problem OverviewInput: nums = [4,6,5,9,3,7], queries = [[0,2],[0,3],[2,5]]465937012345Query 1: [0,2] → [4,6,5]456✓ trueQuery 2: [0,3] → [4,6,5,9]4569✗ falseQuery 3: [2,5] → [5,9,3,7]3579✓ trueAlgorithm: Sort each subarray and check equal differencesOutput: [true, false, true]
Understanding the Visualization
1
Input
Array nums and query ranges [l[i], r[i]]
2
Process
For each query, check if subarray can form arithmetic sequence
3
Output
Boolean array indicating which queries are arithmetic
Key Takeaway
🎯 Key Insight: After sorting, arithmetic sequences have constant differences between all consecutive elements
Asked in
Google 15 Facebook 12 Amazon 8
89.2K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen