KatInterview

149. Max Points on a Line

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the maximum number of points that lie on the same straight line, given a set of 2D points. A line can be uniquely determined by two points. A naive approach would be to check every pair of points to define a line and then count how many other points fall on this line. This leads to an O(n³) complexity, which might be too slow given the constraints (n <= 300).

Solution

Max Points on a Line in Python

import math

class Solution:
    def maxPoints(self, points: List[List[int]]) -> int:
        n = len(points)
        # If there are 2 or fewer points, they all lie on a single line.
        if n <= 2:
            return n

        max_points = 0

        # Iterate through each point as an anchor point.
        for i in range(n):
            # Dictionary to store slope -> count of points for lines passing through points[i].
            # Using a tuple (dy_reduced, dx_reduced) as the key is robust and avoids float precision issues.
            slope_map = {}
            local_max = 0
            
            # Iterate through the other points to calculate slopes.
            for j in range(i + 1, n):
                dx = points[j][0] - points[i][0]
                dy = points[j][1] - points[i][1]

                if dx == 0:
                    # Vertical line, slope is considered 'infinity'.
                    # We can use a standard representation like (1, 0) for all vertical lines.
                    slope = (1, 0)
                else:
                    # Reduce the fraction dy/dx to its simplest form.
                    common_divisor = math.gcd(dy, dx)
                    slope = (dy // common_divisor, dx // common_divisor)
                
                slope_map[slope] = slope_map.get(slope, 0) + 1
                local_max = max(local_max, slope_map[slope])

            # The total number of points on a line is the count from the map + the anchor point itself.
            max_points = max(max_points, local_max + 1)
            
        return max_points

Max Points on a Line in Java

class Solution {
    // Helper function to calculate the greatest common divisor
    private int gcd(int a, int b) {
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }

    public int maxPoints(int[][] points) {
        int n = points.length;
        // If there are 2 or fewer points, they all lie on a single line.
        if (n <= 2) {
            return n;
        }

        int maxPoints = 0;

        // Iterate through each point as an anchor point.
        for (int i = 0; i < n; i++) {
            // Map to store slope -> count of points for lines passing through points[i].
            // We use a String key "dy/dx" to avoid floating point issues.
            Map<String, Integer> slopeMap = new HashMap<>();
            int localMax = 0;

            // Iterate through the other points to calculate slopes.
            for (int j = i + 1; j < n; j++) {
                int dx = points[j][0] - points[i][0];
                int dy = points[j][1] - points[i][1];
                
                String slopeKey;
                if (dx == 0) {
                    // Vertical line
                    slopeKey = "inf";
                } else {
                    // Reduce the fraction dy/dx to its simplest form.
                    int commonDivisor = gcd(dy, dx);
                    // Create a canonical string representation for the slope.
                    slopeKey = (dy / commonDivisor) + "/" + (dx / commonDivisor);
                }

                slopeMap.put(slopeKey, slopeMap.getOrDefault(slopeKey, 0) + 1);
                localMax = Math.max(localMax, slopeMap.get(slopeKey));
            }
            // The total number of points on a line is the count from the map + the anchor point itself.
            maxPoints = Math.max(maxPoints, localMax + 1);
        }

        return maxPoints;
    }
}

Max Points on a Line in C++

class Solution {
public:
    // Helper function to calculate the greatest common divisor
    int gcd(int a, int b) {
        while (b) {
            a = a % b;
            swap(a, b);
        }
        return a;
    }

    int maxPoints(vector<vector<int>>& points) {
        int n = points.size();
        // If there are 2 or fewer points, they all lie on a single line.
        if (n <= 2) {
            return n;
        }

        int max_points = 0;

        // Iterate through each point as an anchor point.
        for (int i = 0; i < n; ++i) {
            // Map to store slope -> count of points for lines passing through points[i].
            // We use a string key "dy/dx" to avoid floating point issues and pair hashing.
            unordered_map<string, int> slope_map;
            int local_max = 0; // Max points on a line through points[i]

            // Iterate through the other points to calculate slopes.
            for (int j = i + 1; j < n; ++j) {
                int dx = points[j][0] - points[i][0];
                int dy = points[j][1] - points[i][1];

                string slope_key;
                if (dx == 0) {
                    // Vertical line
                    slope_key = "inf";
                } else {
                    // Reduce the fraction dy/dx to its simplest form.
                    int common_divisor = gcd(dy, dx);
                    // Create a canonical string representation for the slope.
                    slope_key = to_string(dy / common_divisor) + "/" + to_string(dx / common_divisor);
                }

                slope_map[slope_key]++;
                local_max = max(local_max, slope_map[slope_key]);
            }
            // The total number of points on a line is the count from the map + the anchor point itself.
            max_points = max(max_points, local_max + 1);
        }

        return max_points;
    }
};

Max Points on a Line in TypeScript

/**
 * Helper function to calculate the greatest common divisor.
 */
function gcd(a: number, b: number): number {
    while (b) {
        [a, b] = [b, a % b];
    }
    return a;
}

function maxPoints(points: number[][]): number {
    const n = points.length;
    // If there are 2 or fewer points, they all lie on a single line.
    if (n <= 2) {
        return n;
    }

    let maxPoints = 0;

    // Iterate through each point as an anchor point.
    for (let i = 0; i < n; i++) {
        // Map to store slope -> count of points for lines passing through points[i].
        // We use a string key "dy/dx" to avoid floating point issues.
        const slopeMap: Map<string, number> = new Map();
        let localMax = 0;

        // Iterate through the other points to calculate slopes.
        for (let j = i + 1; j < n; j++) {
            const dx = points[j][0] - points[i][0];
            const dy = points[j][1] - points[i][1];

            let slopeKey: string;
            if (dx === 0) {
                // Vertical line
                slopeKey = 'inf';
            } else {
                // Reduce the fraction dy/dx to its simplest form.
                const commonDivisor = gcd(dy, dx);
                // Create a canonical string representation for the slope.
                slopeKey = `${dy / commonDivisor}/${dx / commonDivisor}`;
            }
            
            const count = (slopeMap.get(slopeKey) || 0) + 1;
            slopeMap.set(slopeKey, count);
            localMax = Math.max(localMax, count);
        }

        // The total number of points on a line is the count from the map + the anchor point itself.
        maxPoints = Math.max(maxPoints, localMax + 1);
    }

    return maxPoints;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.