Magicsheet logo

Arithmetic Subarrays

Medium
25%
Updated 8/1/2025

Asked by 1 Company

Arithmetic Subarrays

What is this problem about?

In the Arithmetic Subarrays interview question, you are given an array of integers and a set of queries. Each query consists of a range [l, r]. For each query, you must determine if the elements in that range can be rearranged to form an arithmetic progression. This Arithmetic Subarrays coding problem combines range queries with sequence verification.

Why is this asked in interviews?

Google uses this problem to see how candidates handle multiple queries efficiently. It tests whether you can identify the properties of an arithmetic progression (min, max, and common difference) to avoid unnecessary sorting for every query, although sorting is often acceptable given the constraints.

Algorithmic pattern used

The Array, Hash Table, Sorting interview pattern is relevant here. To check if a range is arithmetic:

  1. Find the minimum and maximum elements in the range.
  2. Calculate the expected common difference: d = (max - min) / (length - 1).
  3. If d isn't an integer (and max != min), it's not arithmetic.
  4. Check if all expected elements (min, min+d, min+2d, ...) exist in the range using a Set/Hash Table.

Example explanation

Array: [4, 6, 5, 9, 3, 7], Query: range [0, 2] which is [4, 6, 5].

  1. Min: 4, Max: 6, Length: 3.
  2. d = (6-4) / (3-1) = 1.
  3. Elements should be: 4, 5, 6.
  4. Check: 4, 5, and 6 are all in the range. Result: True. Query: range [0, 3] which is [4, 6, 5, 9].
  5. Min: 4, Max: 9, Length: 4.
  6. d = (9-4) / (4-1) = 5/3 (not an integer). Result: False.

Common mistakes candidates make

  • Sorting every time: While O(Q * N log N) might pass, O(Q * N) is better and shows deeper understanding.
  • Division by zero: Failing to handle the case where all elements in the range are the same (max - min = 0).
  • Missing Elements: Forgetting to check if the elements in the range are actually distinct when they are expected to be (if d > 0).

Interview preparation tip

Always consider if you can verify a property without sorting. For arithmetic progressions, the relationship between the min, max, and the set of elements is often enough to validate the sequence in linear time.

Similar Questions