1396. Laser Grid Cells

Easy1.5 points estimatedGeometryNumber TheoryMaths

A floor is tiled with unit squares whose corners sit at integer coordinates. A laser beam is fired from the point (0, 0) to the point (dx, dy) along a straight segment, where dx and dy may be negative or zero.

Return how many tiles the beam passes through the interior of. A tile counts only if the beam spends some positive length strictly inside it. A beam that touches a tile only along an edge or at a corner does not count, so a beam running exactly along a grid line, or one of zero length (dx = dy = 0), crosses 0 tiles. Note that dx and dy can reach 10^9 in magnitude, so the answer must be computed in 64-bit arithmetic. The result depends only on |dx|, |dy| and their greatest common divisor, so the intended solution runs in O(log(max(|dx|, |dy|))) time and O(1) space.

Example 1

Input:
dx = 4, dy = 6
Output:
8
Explanation:

|4| + |6| - gcd(4, 6) = 10 - 2 = 8 tiles are crossed.

Example 2

Input:
dx = 3, dy = 0
Output:
0
Explanation:

The beam runs along a grid line, so it never enters a tile interior.

Example 3

Input:
dx = -5, dy = 3
Output:
7
Explanation:

Signs do not matter: 5 + 3 - gcd(5, 3) = 7.

Constraints

-109 ≤ dx, dy ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(log(max(|dx|, |dy|)))
Space
O(1)

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…