Distance Between Bus Stops

Problem Description

Ah, the classic dilemma of navigating public transport! Ever found yourself on a bus, staring out the window, wondering if you should have taken that left turn back there? Welcome to the “Distance Between Bus Stops” problem, where we calculate the distance between two bus stops on a circular route.

Imagine you’re on a bus that goes around in circles (literally). You start at one bus stop, and you want to know how far you have to travel to reach another bus stop. But wait! There’s a twist! You can either go clockwise or counterclockwise. It’s like choosing between a scenic route or the express lane—except both routes are equally confusing!

Code Solution


class Solution {
 public:
  int distanceBetweenBusStops(vector& distance, int start,
                              int destination) {
    int clockwise = 0;
    int counterclockwise = 0;

    if (start > destination)
      swap(start, destination);

    for (int i = 0; i < distance.size(); ++i) {
      if (i >= start && i < destination)
        clockwise += distance[i];
      else
        counterclockwise += distance[i];
    }

    return min(clockwise, counterclockwise);
  }
};

Approach

The code takes a vector of distances between bus stops and two indices representing the start and destination stops. It calculates the total distance in both clockwise and counterclockwise directions. If the start index is greater than the destination, it swaps them to simplify calculations. Finally, it returns the minimum of the two distances. Simple, right? Just like deciding whether to take the bus or walk!

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(n), where n is the number of bus stops.
Space Complexity O(1), as we are using a constant amount of space for our variables.

Real-World Example

Picture this: You're at a bus stop, and your friend is at another stop. You both want to meet up for coffee. You could take the long way around (clockwise) or the shortcut (counterclockwise). This problem helps you figure out the quickest way to get to your friend without getting lost in the maze of bus stops!

Similar Problems

If you enjoyed this problem, you might also like these:

  • 2-Sum Solution in C++
  • 3-Sum Solution in C++
  • 4-Sum Solution in C++