You are given a list of lists where each sublist contains two integers representing distances traveled by a car on different days. Each sublist is structured as [forward_distance, backward_distance]
. Write a function that calculates the total distance traveled by the car over all the days, considering both the forward and backward distances.
Without additional constraints, I’ll assume:
The approach is straightforward and involves simple iteration and arithmetic, ensuring clarity and keeping the solution efficient.
Here’s the implementation in Python:
def total_distance_traveled(distances):
total_distance = 0
for day in distances:
forward_distance, backward_distance = day
total_distance += forward_distance + backward_distance
return total_distance
# Example usage
distances = [
[10, 5],
[20, 10],
[15, 10]
]
print(total_distance_traveled(distances)) # Output: 70
The time complexity of this solution is (O(n)), where (n) is the number of days (sublists) in the input list. This is because we need to iterate through each sublist exactly once to compute the total distance. The space complexity is (O(1)), since we are only using a fixed amount of extra space regardless of the input size.
You can run the code with different input examples to see the function in action and verify correctness.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?