Taro Logo

Max Points on a Line

#37 Most AskedHard
0 views
Topics:
Arrays

Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.

Example 1:

Input: points = [[1,1],[2,2],[3,3]]
Output: 3

Example 2:

Input: points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Output: 4

Constraints:

  • 1 <= points.length <= 300
  • points[i].length == 2
  • -104 <= xi, yi <= 104
  • All the points are unique.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the range and data type of the coordinates, and can the input contain negative numbers, zeros, or duplicate points?
  2. How should we handle duplicate points (i.e., points with identical x and y coordinates) when counting collinear points?
  3. What is the minimum and maximum number of points in the input array, and what should be returned if the array has fewer than three points?
  4. How should we handle vertical lines where the slope is technically undefined due to division by zero?
  5. If there are multiple lines that share the maximum number of collinear points, does it matter which line's count is returned?

Brute Force Solution

Approach

Imagine you have a handful of dots scattered across a large piece of paper and you want to find the straight line that captures the most dots. The brute force strategy works by systematically testing every possible pair of dots, drawing a straight path through them, and counting how many other dots happen to fall exactly on that same path.

Here's how the algorithm would work step-by-step:

  1. Pick any starting dot and pair it with a second dot to establish a specific straight direction.
  2. Once you have your pair, look at every remaining dot on the paper one by one.
  3. Check if each remaining dot lines up perfectly with the original two dots you started with.
  4. Count how many dots align along this exact path and remember this total number.
  5. Reset your count and choose a different pair of dots to establish a brand new direction.
  6. Repeat this process of checking every other dot against the new pair.
  7. Keep testing every possible combination of pairs until you have examined every conceivable straight line you can draw between any two dots.
  8. Look back at all your recorded counts and select the highest number you found, which tells you the most dots that can ever sit on a single straight line together.

Code Implementation

def max_points(points):    max_points_found = 1    total_points = len(points)    if total_points <= 2:        return total_points    # Iterate through every possible starting dot to establish the baseline for our lines    for first_index in range(total_points):        first_point_x, first_point_y = points[first_index]        for second_index in range(first_index + 1, total_points):            second_point_x, second_point_y = points[second_index]            current_line_count = 2            # Check every remaining dot to see if it collinear with our chosen pair            for third_index in range(total_points):                if third_index == first_index or third_index == second_index:                    continue                third_point_x, third_point_y = points[third_index]                if (second_point_y - first_point_y) * (third_point_x - second_point_x) == (third_point_y - second_point_y) * (second_point_x - first_point_x):                    current_line_count += 1            # Update our global maximum if the current line captures more dots than previous            if current_line_count > max_points_found:                max_points_found = current_line_count    return max_points_found

Big(O) Analysis

Time Complexity
O(n³) – The input size n represents the total number of dots on the paper. For every dot we pick as our starting point, we loop through every other dot to form a pair, which drives the first two nested levels of cost. Then, for each chosen pair, we iterate through all remaining dots in the dataset a third time to check for alignment. This results in roughly n times n times n over 6 total checking operations, which ultimately simplifies to a cubic Big O time complexity of O(n³).
Space Complexity
O(N) – The auxiliary space is driven by a hash map used to store the frequency of slopes calculated for each starting dot. As we test every possible pair and examine remaining dots, this hash map grows to store slope values relative to the current starting dot, containing at most N entries. When resetting for a new starting dot, this hash map is cleared and reused, meaning the peak extra memory consumed at any given time scales linearly with the total number of dots N.

Optimal Solution

Approach

Instead of comparing every possible combination of three or more points at once, we can solve this by focusing on one starting point at a time. By measuring the tilt of the path leading from that starting point to every other point, we can easily spot which destinations share the exact same straight line.

Here's how the algorithm would work step-by-step:

  1. Pick any single point to act as your central anchor.
  2. Look at every other point remaining on the board and imagine drawing a straight path from your anchor to each of them.
  3. Measure the precise angle or tilt of each of those individual paths.
  4. Group together all the destination points that share the exact same tilt because they all lie on the exact same straight line passing through your anchor.
  5. Count how many points share that specific tilt and remember the highest count you find.
  6. Repeat this entire process by picking a new anchor point and clearing your counts, until you have tested every single point as an anchor.
  7. Compare the maximum counts you found during each anchor session to determine the absolute highest number of points aligned on a single straight line.

Code Implementation

from collections import defaultdict

class Solution:
    def maxPoints(self, points: list[list[int]]) -> int:
        total_points = len(points)
        if total_points <= 2:
            return total_points

        maximum_aligned_points = 1

        # An anchor point is needed to measure relative slopes to all other points.
        for anchor_index in range(total_points):
            anchor_point = points[anchor_index]
            slope_counts = defaultdict(int)
            duplicates_count = 1
            local_maximum = 0

            for other_index in range(anchor_index + 1, total_points):
                other_point = points[other_index]

                if anchor_point[0] == other_point[0] and anchor_point[1] == other_point[1]:
                    duplicates_count += 1
                    continue

                delta_x = other_point[0] - anchor_point[0]
                delta_y = other_point[1] - anchor_point[1]

                import math
                greatest_common_divisor = math.gcd(delta_x, delta_y)
                simplified_slope = (delta_x // greatest_common_divisor, delta_y // greatest_common_divisor)

                slope_counts[simplified_slope] += 1
                local_maximum = max(local_maximum, slope_counts[simplified_slope])

            # Total points on this line include the anchor and overlapping duplicate coordinates.
            maximum_aligned_points = max(maximum_aligned_points, local_maximum + duplicates_count)

        return maximum_aligned_points

Big(O) Analysis

Time Complexity
O(n²) – For each of the n anchor points chosen in the outer loop, the algorithm iterates through every remaining point in the inner loop to calculate the slope. For the first anchor, we check (n-1) other points, for the second (n-2), and so on down to the last point. This creates a nested iteration resulting in approximately n * (n-1) / 2 slope calculations, which simplifies to Big O of n squared.
Space Complexity
O(n) – For each anchor point chosen in the outer loop, we use a hash map to group and count the slopes formed with every other destination point. In the worst-case scenario where all points lie on different slopes, the hash map stores up to N-1 distinct tilt entries. Since we reset and reuse this hash map for each of the N anchor points, the peak auxiliary memory is consumed by storing these slope frequencies. Thus, the extra memory scales linearly with the number of points, resulting in a space complexity of O(n) where n is the total number of points.

Edge Cases

Fewer than 3 points provided in the input array
How to Handle:
Return the total number of points directly since 0, 1, or 2 points are always collinear.
Duplicate points with identical x and y coordinates
How to Handle:
Track duplicates relative to the current anchor point and add them to every computed slope count.
Vertical lines where the change in x is zero
How to Handle:
Represent the slope as an undefined or infinite value, such as using a string or a distinct tuple, to prevent division by zero errors.
Negative coordinates and mixed sign values
How to Handle:
Normalize the greatest common divisor of the slope's numerator and denominator to always be positive so equivalent negative slopes match.
Floating point precision issues when calculating slopes
How to Handle:
Use the greatest common divisor of differences in x and y to reduce slopes to irreducible fractions instead of using division.
Extremely large coordinate values causing integer overflow
How to Handle:
Cast coordinate differences to 64-bit integers before computing products or greatest common divisors.
All points lying on the exact same horizontal line
How to Handle:
The vertical difference remains zero while the horizontal difference varies, mapping all points to a slope of zero.
Massive inputs with thousands of points
How to Handle:
Optimize the pairwise slope calculation using a nested loop with a hash map per outer iteration to achieve an efficient O(N^2) time complexity.
0/45 completed