LeetCode 1184: Distance Between Bus Stops Solution
Master LeetCode problem 1184 (Distance Between Bus Stops), 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.
1184. Distance Between Bus Stops
Problem Explanation
Explanation
To find the shortest distance between two bus stops on a circular route, we can calculate the total distance between all stops either clockwise or counterclockwise, and then calculate the minimum distance between the given start and destination stops by taking the minimum of the two possible distances.
- Calculate the total distance in clockwise direction starting from
starttodestination. - Calculate the total distance in counterclockwise direction starting from
starttodestination. - Return the minimum of the two distances calculated above.
Time complexity: O(n) where n is the number of stops Space complexity: O(1)
Solution Code
class Solution {
public int distanceBetweenBusStops(int[] distance, int start, int destination) {
if (start > destination) {
int temp = start;
start = destination;
destination = temp;
}
int totalDistance = 0;
int clockwiseDistance = 0;
for (int i = 0; i < distance.length; i++) {
totalDistance += distance[i];
if (i >= start && i < destination) {
clockwiseDistance += distance[i];
}
}
int counterclockwiseDistance = totalDistance - clockwiseDistance;
return Math.min(clockwiseDistance, counterclockwiseDistance);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1184 (Distance Between Bus Stops)?
This page provides optimized solutions for LeetCode problem 1184 (Distance Between Bus Stops) 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 1184 (Distance Between Bus Stops)?
The time complexity for LeetCode 1184 (Distance Between Bus Stops) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1184 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1184 in Java, C++, or Python.