LeetCode 1037. Valid Boomerang Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1037. Valid Boomerang

Description

Given an array points where points[i] = [xi, yi] 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 == 3
  • points[i].length == 2
  • 0 <= xi, yi <= 100

Solutions

Solution 1: Slope Comparison

Let the three points be (x1, y1), (x2, y2), and (x3, y3). The formula for calculating the slope between two points is y2 - y1x2 - x1.

To ensure that the three points are not collinear, the condition y2 - y1x2 - x1y3 - y2x3 - x2 must be satisfied. By transforming the equation, we get (y2 - y1) · (x3 - x2) ≠ (y3 - y2) · (x2 - x1).

Note:

  1. When the slope between two points does not exist, i.e., x1 = x2, the transformed equation still holds.
  2. If there are precision issues with division in slope comparison, it can be converted to multiplication.

Time complexity is O(1).

PythonJavaC++GoTypeScriptRust
class Solution: def isBoomerang(self, points: List[List[int]]) -> bool: (x1, y1), (x2, y2), (x3, y3) = points return (y2 - y1) * (x3 - x2) != (y3 - y2) * (x2 - x1)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !