Leetcode 1232: Check If It Is a Straight Line

grid47
grid47
Exploring patterns and algorithms
Jul 6, 2024 5 min read

You are given an array of coordinates, where each coordinate represents a point in the 2D plane. Your task is to check if all the points in the array lie on the same straight line.
Problem
Approach
Steps
Complexity
Input: The input consists of a list of points, where each point is represented by two integers [x, y].
Example: coordinates = [[2, 3], [4, 5], [6, 7], [8, 9], [10, 11]]
Constraints:
• 2 <= coordinates.length <= 1000
• coordinates[i].length == 2
• -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
• coordinates contains no duplicate point.
Output: The output should be a boolean value indicating whether all points lie on the same straight line.
Example: true
Constraints:
• Return 'true' if all points are collinear, otherwise return 'false'.
Goal: The goal is to check if the slope between consecutive points remains the same across the entire list of points.
Steps:
• Calculate the slope between the first two points.
• For each subsequent point, calculate the slope between it and the first point.
• If the slopes are not equal, return false.
• If all slopes are equal, return true.
Goal: The input list contains no duplicate points, and the size of the list is between 2 and 1000.
Steps:
• Ensure no duplicate points in the input array.
Assumptions:
• The input coordinates represent valid points in a 2D plane.
• The points are given in no particular order.
Input: coordinates = [[2, 3], [4, 5], [6, 7], [8, 9], [10, 11]]
Explanation: The points have the same slope between consecutive pairs, meaning they lie on the same straight line, so the output is 'true'.

Input: coordinates = [[1, 1], [2, 3], [3, 5], [4, 7]]
Explanation: The slope between the first two points is different from the slopes between the other points, meaning they do not lie on the same straight line, so the output is 'false'.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus