Max Points on a Line

Algorithms
Hard
Google
74.3K views

Given an array of points, find the maximum number of points that lie on the same straight line. This requires using slope and floating-point comparison carefully.

Why Interviewers Ask This

Google asks this problem to evaluate a candidate's ability to handle geometric edge cases and numerical precision issues. They specifically test whether you can move beyond brute-force solutions to optimize time complexity while managing floating-point inaccuracies inherent in slope calculations. It reveals your depth of understanding regarding hash maps, mathematical representations of lines, and robust error handling.

How to Answer This Question

1. Clarify constraints: Ask about input size and coordinate ranges to determine if O(n^2) is acceptable. 2. Identify the core challenge: Recognize that calculating slopes directly introduces floating-point errors, which Google values candidates for catching early. 3. Choose a representation strategy: Propose storing slopes as reduced fractions (dy/dx) using GCD to ensure exact comparisons instead of doubles. 4. Structure the algorithm: Iterate through each point as an anchor, calculate slopes to all subsequent points, and use a hash map to count occurrences of each unique line. 5. Handle edge cases explicitly: Dedicate time to discuss vertical lines (undefined slope), duplicate points, and single-point inputs. 6. Optimize and summarize: Explain how this approach achieves O(n^2) time complexity with O(n) space, demonstrating both efficiency and correctness.

Key Points to Cover

  • Explicitly rejecting floating-point division to prevent precision errors
  • Using Greatest Common Divisor (GCD) to normalize slope representations as integer pairs
  • Implementing O(n^2) time complexity by iterating through every point as an anchor
  • Dedicated logic for handling vertical lines and duplicate coordinates
  • Demonstrating awareness of Google's focus on numerical stability and edge-case robustness

Sample Answer

To solve the Max Points on a Line problem efficiently, I would first clarify that we need to avoid floating-point arithmetic due to precision errors. My approach involves iterating through every point in the array, treat…

Common Mistakes to Avoid

  • Relying on double-precision floats for slopes, which leads to incorrect equality checks due to rounding errors
  • Failing to account for duplicate points in the input array, resulting in undercounted intersections
  • Ignoring vertical lines where the denominator becomes zero, causing division by zero exceptions
  • Attempting to store full line equations rather than just slopes relative to a specific anchor point

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 145 Algorithms questionsBrowse all 145 Google questions