Magicsheet logo

Check If It Is a Straight Line

Easy
54.9%
Updated 6/1/2025

Check If It Is a Straight Line

What is this problem about?

The "Check If It Is a Straight Line interview question" is a geometry task. You are given an array of coordinates (x,y)(x, y) representing points on a 2D plane. You need to determine if all these points lie on the same straight line.

Why is this asked in interviews?

Companies like Amazon and Palantir use the "Check If It Is a Straight Line coding problem" to assess a candidate's understanding of Slope and linear equations. It evaluates whether you can handle potential edge cases like vertical lines (where the slope is undefined due to division by zero) and how you use cross-multiplication to avoid floating-point issues.

Algorithmic pattern used

This problem follows the Slope Comparison or Cross-Multiplication pattern.

  1. Baseline Slope: Calculate the slope between the first two points (x0,y0)(x_0, y_0) and (x1,y1)(x_1, y_1).
  2. Comparison: For every other point (xi,yi)(x_i, y_i), check if the slope between (x0,y0)(x_0, y_0) and (xi,yi)(x_i, y_i) is the same as the baseline.
  3. Avoid Division: Instead of dy1 / dx1 == dy2 / dx2, use cross-multiplication: dy1 * dx2 == dy2 * dx1. This avoids precision issues and "division by zero" errors for vertical lines.

Example explanation

Points: (1,2), (2,3), (3,4)

  1. dx1=21=1,dy1=32=1dx_1 = 2-1=1, dy_1 = 3-2=1.
  2. Check point 3: dx2=31=2,dy2=42=2dx_2 = 3-1=2, dy_2 = 4-2=2.
  3. Cross-multiply: dy1imesdx2=1imes2=2dy_1 imes dx_2 = 1 imes 2 = 2. dy2imesdx1=2imes1=2dy_2 imes dx_1 = 2 imes 1 = 2.
  4. 2==22 == 2. OK. Result: True.

Common mistakes candidates make

  • Division by Zero: Using dy/dxdy/dx directly, which crashes if dx=0dx=0 (vertical line).
  • Floating Point Errors: Using floating point division, which can lead to 0.333333333334 != 0.333333333333. Always prefer integer cross-multiplication.
  • Checking only adjacent points: While checking only (i,i+1)(i, i+1) and (i+1,i+2)(i+1, i+2) is mathematically sound, using a fixed reference point (0,1)(0, 1) is often easier to implement correctly.

Interview preparation tip

In geometry problems, Cross-Multiplication is your best friend. It transforms division into multiplication, making your code safer and more robust. This is a vital "Math interview pattern" trick.

Similar Questions