Valid Boomerang Problem
Description
LeetCode Problem 1037.
Given an array points where points[i] = [x_i, y_i] represents a point on the X-Y plane, return true if these points are a boomerang.
A boomerang is a set of three points that are all distinct and not in a straight line.
Example 1:
Input: points = [[1,1],[2,3],[3,2]]
Output: true
Example 2:
Input: points = [[1,1],[2,2],[3,3]]
Output: false
Constraints:
points.length == 3points[i].length == 20 <= x_i, y_i <= 100
Solution
Approach: Cross Product
Three points fail to be a boomerang exactly when they lie on one line, and that includes the case where two of them are the same point. Both can be caught with a single test.
Take the vectors from the first point to the other two: (x2 - x1, y2 - y1) and (x3 - x1, y3 - y1). Their cross product
(x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)
is twice the signed area of the triangle the points form. It is zero when the triangle is flat, that is, when the points are collinear or two of them coincide (one vector is then zero).
Comparing slopes with division would need special cases for vertical lines and would bring in floating point. The cross product uses only integer multiplication, so it has neither problem.
Complexity: O(1) time and space.
class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
(x1, y1), (x2, y2), (x3, y3) = points
# Cross product of (p2 - p1) and (p3 - p1): zero means collinear (or two points coincide).
return (x2 - x1) * (y3 - y1) != (y2 - y1) * (x3 - x1)