Similar Self Join Solution


  • 0
    Z

    For the original question:

    SELECT ABS(p1.x - p2.x) AS shortest
    FROM point p1
    JOIN point p2 ON p1.x <> p2.x
    ORDER BY shortest
    LIMIT 1;
    

    For the follow up, we only need to compare adjacent points, because the table is sorted:

    SELECT p2.x - p1.x AS shortest
    FROM point p1
    JOIN point p2 ON p1.id + 1 = p2.id
    ORDER BY shortest
    LIMIT 1;
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.