May Leetcode Challenge - Day 8

Problem

Check If It Is a Straight Line

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.

Solution

Apply formula dx1 * dy2 = dx2 * dy1; dx, dy is absolute different between two points.
Calculate first pairs, then a straight loop for the rest points.

class Solution {
    func checkStraightLine(_ coordinates: [[Int]]) -> Bool {
        if coordinates.count < 2 {
            return true
        }
        let delta = lineAngle(coordinates[0], coordinates[1])
        for i in 2..<coordinates.count {
            let deltaK = lineAngle(coordinates[i], coordinates[i - 1])
            if deltaK != delta {
                return false
            }
        }
        return true
    }
    
    func lineAngle(_ p1: [Int], _ p2: [Int]) -> Delta {
        return Delta(dx: abs(p1[0] - p2[0]), dy: abs(p1[1] - p2[1]))
    }
    
    struct Delta : Equatable {
        var dx: Int
        var dy: Int
        
        static func ==(_ lhs: Delta, _ rhs: Delta) -> Bool {
            return lhs.dx * rhs.dy == lhs.dy * rhs.dx
        }
    }

}