LeetCode 612: Shortest Distance in a Plane Solution
Master LeetCode problem 612 (Shortest Distance in a Plane), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
612. Shortest Distance in a Plane
Problem Explanation
Explanation:
To find the shortest distance in a plane between two points given as arrays of points, we can calculate the Euclidean distance between each pair of points and find the minimum distance.
-
Iterate through all pairs of points and calculate the Euclidean distance using the formula:
$distance = \sqrt{(x2 - x1)^2 + (y2 - y1)^2}$ -
Keep track of the minimum distance found so far.
Time Complexity:
The time complexity of this approach is O(n^2), where n is the number of points given.
Space Complexity:
The space complexity of this approach is O(1) as we are not using any extra space.
:
Solution Code
class Solution {
public double shortestDistance(int[][] points) {
double minDistance = Double.MAX_VALUE;
for (int i = 0; i < points.length; i++) {
for (int j = i + 1; j < points.length; j++) {
double distance = Math.sqrt(Math.pow(points[j][0] - points[i][0], 2) + Math.pow(points[j][1] - points[i][1], 2));
minDistance = Math.min(minDistance, distance);
}
}
return minDistance;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 612 (Shortest Distance in a Plane)?
This page provides optimized solutions for LeetCode problem 612 (Shortest Distance in a Plane) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 612 (Shortest Distance in a Plane)?
The time complexity for LeetCode 612 (Shortest Distance in a Plane) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 612 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 612 in Java, C++, or Python.