Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Check If It Is a Straight Line

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1232" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. Example 1: Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] Output: true Example 2: Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] Output: false Constraints: 2 <= coordinates.length <= 1000 coordinates[i].length == 2 -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4 coordinates contains no duplicate point.

Explanation

Here's the breakdown of the problem and the solution:

  • Approach:

    • Calculate the slope between the first two points.
    • Iterate through the remaining points and check if the slope between the first point and the current point is the same as the initial slope.
    • Handle the case where the first two points have the same x-coordinate (vertical line) separately to avoid division by zero.
  • Complexity:

    • Runtime Complexity: O(n), where n is the number of coordinates.
    • Storage Complexity: O(1)

Code

    def checkStraightLine(coordinates):
    """
    Checks if the given coordinates form a straight line.

    Args:
        coordinates: A list of lists, where each inner list represents a coordinate [x, y].

    Returns:
        True if the coordinates form a straight line, False otherwise.
    """

    x0, y0 = coordinates[0]
    x1, y1 = coordinates[1]

    if x1 == x0:  # Vertical line
        for i in range(2, len(coordinates)):
            x, y = coordinates[i]
            if x != x0:
                return False
        return True
    else:
        slope = (y1 - y0) / (x1 - x0)
        for i in range(2, len(coordinates)):
            x, y = coordinates[i]
            current_slope = (y - y0) / (x - x0) if (x-x0) != 0 else float('inf') if (y-y0) != 0 else 0 #handle vertical line cases if they occur later
            if abs(current_slope - slope) > 1e-6: #using abs and a small error tolerance to deal with floating point comparisons
                return False
        return True

More from this blog

C

Chatmagic blog

2894 posts