A clear explanation of checking if three points form a boomerang (non-collinear) using the cross product.
Problem Restatement
We are given three points in the 2D plane: points[0], points[1], points[2].
A boomerang is a set of three points that are all distinct and not collinear.
Return true if the three points form a boomerang.
The official constraints state that points.length == 3 and 0 <= points[i][j] <= 100.
Input and Output
| Item | Meaning |
|---|---|
| Input | Three 2D points [[x1,y1],[x2,y2],[x3,y3]] |
| Output | true if points are distinct and non-collinear |
Function shape:
def isBoomerang(points: list[list[int]]) -> bool:
...Examples
Example 1:
points = [[1,1],[2,3],[3,2]]Non-collinear. Answer: True.
Example 2:
points = [[1,1],[2,2],[3,3]]Collinear (all on the line y = x). Answer: False.
Key Insight
Three points are collinear if and only if the cross product of vectors AB and AC is zero.
AB = (B[0] - A[0], B[1] - A[1])
AC = (C[0] - A[0], C[1] - A[1])
cross = AB[0] * AC[1] - AB[1] * AC[0]If cross == 0, points are collinear (or two are identical). If cross != 0, they form a valid boomerang.
Correctness
The cross product of two 2D vectors is zero if and only if they are parallel (or one is zero). Three points are collinear if the vectors from the first point to the other two are parallel.
Using the cross product avoids division and handles all edge cases including identical points.
Edge Cases
- Check the minimum input size allowed by the constraints.
- Verify duplicate values or tie cases if the input can contain them.
- Keep the return value aligned with the exact failure case in the statement.
Complexity
| Metric | Value | Why |
|---|---|---|
| Time | O(1) | Constant computation |
| Space | O(1) | No extra storage |
Common Pitfalls
- Do not optimize away the invariant; the code should still make it clear what condition is being maintained.
- Prefer problem-specific names over one-letter variables once the logic becomes stateful.
Implementation
class Solution:
def isBoomerang(self, points: list[list[int]]) -> bool:
(x1, y1), (x2, y2), (x3, y3) = points
return (x2 - x1) * (y3 - y1) != (x3 - x1) * (y2 - y1)Testing
def run_tests():
s = Solution()
assert s.isBoomerang([[1,1],[2,3],[3,2]]) == True
assert s.isBoomerang([[1,1],[2,2],[3,3]]) == False
assert s.isBoomerang([[0,0],[0,0],[1,1]]) == False
assert s.isBoomerang([[0,0],[1,0],[2,1]]) == True
print("all tests passed")
run_tests()| Test | Expected | Why |
|---|---|---|
| Non-collinear | True | Valid boomerang |
| Collinear diagonal | False | All on y=x |
| Two identical points | False | Cross product is zero |
| Generic non-collinear | True | Valid boomerang |