991. Range GCD Table

A music teacher records the beat length of each note in a piece as an array nums (positions start at 0). To find the longest common grid on which a passage can be notated, she needs the greatest common divisor of the beat lengths in a passage.

Each query queries[j] = [l, r] asks for the greatest common divisor of nums[l], nums[l+1], ..., nums[r], both ends included. Return an array with the answer to every query, in the same order as the queries. The array itself never changes between queries, and every number is positive.

Example 1

Input:
nums = [12,18,30,8,24]queries = [[0,2],[1,4],[3,3],[2,4]]
Output:
[6,2,8,2]
Explanation:

gcd(12,18,30) = 6; gcd(18,30,8,24) = 2; a single element 8 is its own gcd; gcd(30,8,24) = 2.

Example 2

Input:
nums = [7,14,21,5], queries = [[0,2],[2,3]]
Output:
[7,1]
Explanation:

7, 14 and 21 are all multiples of 7, so the first range gives 7; 21 and 5 are coprime, so the second gives 1.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109
  • 1 ≤ queries.length ≤ 105
  • 0 ≤ l ≤ r < nums.length

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 400 msC++ 100 msJava 200 msJavaScript 200 msTypeScript 200 ms

Expected complexity

Time
O((n + q) log n) with gcd cost ignored
Space
O(n log n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…