algoadvance

Leetcode 2739. Total Distance Traveled

Problem Statement

You are given an integer trips which represents the number of trips a car needs to make.

To complete a single trip, the car starts at milesStart and travels to milesEnd and back to milesStart. It continues this journey for trips number of times.

Write a function totalDistance that calculates the total distance traveled by the car for all the trips.

Function Signature:

int totalDistance(int milesStart, int milesEnd, int trips);

Clarifying Questions

  1. Will milesStart and milesEnd always be positive integers?
    • Assume they are strictly positive integers as the car needs to travel a positive distance.
  2. Is there any upper limit for the inputs?
    • If unspecified, assume no specific upper limit, but the integers are within typical constraints for an int in C++.
  3. What should the function return if trips is 0?
    • If trips is 0, it should return 0 since no trips mean no distance traveled.
  4. Is the direction (round trip) always considered?
    • Yes, we need to consider both the distance to milesEnd and back to milesStart for each trip.

Strategy

  1. Calculate distance per trip: The distance for one round trip is calculated as:
    distance_per_trip = 2 * (milesEnd - milesStart)
    

    This captures the travel from milesStart to milesEnd and back from milesEnd to milesStart.

  2. Calculate total distance: For multiple trips, simply multiply the distance per trip by the number of trips:
    total_distance = distance_per_trip * trips
    
  3. Edge cases: If trips is 0, return 0 as no travel occurs.

Code

Here is the C++ function to accomplish this:

#include <iostream>

int totalDistance(int milesStart, int milesEnd, int trips) {
    // Special case: when 0 trips, distance traveled is 0.
    if (trips == 0)
        return 0;
    
    // Calculate the distance for one round trip.
    int distance_per_trip = 2 * (milesEnd - milesStart);
    
    // Total distance is the distance per trip times the number of trips.
    int total_distance = distance_per_trip * trips;
    
    return total_distance;
}

int main() {
    // Example usage:
    int milesStart = 10;
    int milesEnd = 20;
    int trips = 5;
    
    int result = totalDistance(milesStart, milesEnd, trips);
    
    std::cout << "Total distance traveled: " << result << std::endl; // Should print 100
    
    return 0;
}

Time Complexity

The time complexity of the solution is O(1) since the calculations involve only a few arithmetic operations, making it constant in terms of execution time regardless of input values.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI