LeetCode 613: Shortest Distance in a Line Solution

Master LeetCode problem 613 (Shortest Distance in a Line), a easy 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.

613. Shortest Distance in a Line

Problem Explanation

Explanation:

Given a set of points on a straight line and an integer k, we need to find the shortest distance between any two points among the first k points.

Algorithm:

  1. Initialize a variable minDist to store the minimum distance. Set it to maximum possible value initially.
  2. Iterate over all pairs of points among the first k points.
  3. Calculate the distance between each pair of points and update minDist if the calculated distance is smaller.
  4. Finally, return minDist as the shortest distance.

Time Complexity:
The time complexity of this algorithm is O(k^2) as we are iterating over all pairs of points among the first k points.

Space Complexity:
The space complexity is O(1) as we are using only a constant amount of extra space.

:

Solution Code

class Solution {
    public int shortestDistance(int[] points, int k) {
        int minDist = Integer.MAX_VALUE;
        for (int i = 0; i < k - 1; i++) {
            for (int j = i + 1; j < k; j++) {
                int dist = Math.abs(points[j] - points[i]);
                minDist = Math.min(minDist, dist);
            }
        }
        return minDist;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 613 (Shortest Distance in a Line)?

This page provides optimized solutions for LeetCode problem 613 (Shortest Distance in a Line) 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 613 (Shortest Distance in a Line)?

The time complexity for LeetCode 613 (Shortest Distance in a Line) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 613 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 613 in Java, C++, or Python.

Back to LeetCode Solutions