LeetCode in Swift: Max Points on a Line

Problem Statement

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

Original LeetCode problem page

My Solution in Swift

The basic idea is to calculate gradient of every pair of points, and group points with same gradient. The final answer is then the size of the largest group. This results in an O(n2) algorithm. However, we could do it in a smarter way. When we have considered all possible pairs involving a given point, we don’t have to consider that point again. Also, when the current largest group size is x, we don’t have to consider the rest points.count – x number of points anymore. Although this improves the best case to O(n), on average, the algorithm is still in O(n2).

With proper implementation (pre-specify Dictionary capacity and keep the capacity when resetting), my Swift code runs pretty fast. It is actually faster than my friend’s C++ implementation compiling with -Ofast optimisation flag.

Try It Yourself

1: each links to a blog post of mine that is dedicated to the problem
2: total execution time of a solution on my MacBook Pro (Late 2013, 2.6 GHz Intel Core i7, 16 GB 1600 MHz DDR3). Each solution is compiled with following command:

$ swiftc -O -sdk `xcrun --show-sdk-path --sdk macosx` json.swift main.swift -o mySolution

The total execution time is the average of 10 runs.
3: these test cases are semi-automatically :P retrieved from LeetCode Online Judge system and are kept in JSON format
4: each Xcode project includes everything (my Swift solution to a problem, its JSON test cases and a driver code to test the solution on those test cases)

Problem1Time2Test Cases3My Xcode Project4
Max Points on a Line3.648ms Save  (420) Save  (422)

More Problems Solved in Swift

My full list of LeetCode problems attempted using Swift