Skip to the code
cf.
+25 XP

#692 Shared Grid Unit for Column Ranges

medium

A layout tool wants to snap a group of neighboring columns to a common grid. The largest grid unit that divides every width in the group is the greatest common divisor (gcd) of their widths. widths is fixed, and many groups are asked about.

Write gridUnits(widths, queries) where each query is [left, right] (inclusive). Return the gcd of widths[left] to widths[right] for each query, in order.

Example 1

Input: widths = [12,18,24,9,30], queries = [[0,2],[2,4],[1,1]]
Output: [6,3,18]

The gcd of 12, 18, 24 is 6; of 24, 9, 30 it is 3; one column is its own unit.

Example 2

Input: widths = [8,16], queries = [[0,1]]
Output: [8]

8 divides 16, so the unit is 8.

Constraints

  • 1 <= widths.length <= 10^5
  • 1 <= widths[i] <= 10^9
  • 0 <= queries.length <= 10^5
  • 0 <= left <= right < widths.length
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).