Valid Boomerang — Easy Problem & Solution
points holds exactly three points [x, y] in the plane. They form a boomerang when all three are different and they do not lie on one straight line.
- Difficulty: Easy
- Topics: Arrays, Math, Geometry
- Asked at: Amazon, Google
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
points holds exactly three points [x, y] in the plane. They form a boomerang when all three are different and they do not lie on one straight line.
Return true if the points form a boomerang.
Example 1
Input: points = [[1,1],[2,3],[3,2]]
Output: true
Example 2
Input: points = [[1,1],[2,2],[3,3]]
Output: false
Explanation: All three lie on the line y = x.
Example 3
Input: points = [[0,0],[0,0],[4,7]]
Output: false
Explanation: Two of the points coincide.
Constraints
points.length == 3points[i].length == 20 <= xi, yi <= 100
How to solve Valid Boomerang
The cross product of p2 - p1 and p3 - p1 is twice the signed area of the triangle. It is zero exactly when the three points are collinear — which includes the case where two of them coincide.
Approach
- Let
(ax, ay) = p2 - p1and(bx, by) = p3 - p1. - Compute
ax * by - ay * bx. - Return
trueif it is non-zero.
Why it works
The cross product of two vectors is zero exactly when one is a scalar multiple of the other (or either is zero). If p3 - p1 is a multiple of p2 - p1, then p3 lies on the line through p1 and p2; if either vector is zero, two points coincide. A non-zero cross product rules out both, which is exactly the boomerang condition. Everything stays in integers, so there is no slope division and no rounding.
Complexity
- Time —
O(1) - Space —
O(1)
Pitfalls
- Comparing slopes with division breaks on vertical lines and on floating-point rounding; cross-multiply instead.
- Do not forget duplicates — the cross product already handles them, a separate equality check is redundant but harmless.
Reference solution
Python
from typing import List
def isBoomerang(points: List[List[int]]) -> bool:
ax = points[1][0] - points[0][0]
ay = points[1][1] - points[0][1]
bx = points[2][0] - points[0][0]
by = points[2][1] - points[0][1]
return ax * by - ay * bx != 0JavaScript
var isBoomerang = function(points) {
var ax = points[1][0] - points[0][0];
var ay = points[1][1] - points[0][1];
var bx = points[2][0] - points[0][0];
var by = points[2][1] - points[0][1];
return ax * by - ay * bx !== 0;
};Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 988 arrays problems · the whole catalogue
Learn the technique: Arrays