Calculate Delayed Arrival Time
EasyPrompt
You are given a positive integer arrivalTime denoting the arrival time of a train in hours, and another positive integer delayedTime denoting the amount of delay in hours.
Return the time when the train will arrive at the station.
Note that the time in this problem is in 24-hours format.
Example 1:
Input: arrivalTime = 15, delayedTime = 5
Output: 20
Explanation: Arrival time of the train was 15:00 hours. It is delayed by 5 hours. Now it will reach at 15+5 = 20 (20:00 hours).Example 2:
Input: arrivalTime = 13, delayedTime = 11
Output: 0
Explanation: Arrival time of the train was 13:00 hours. It is delayed by 11 hours. Now it will reach at 13+11=24 (Which is denoted by 00:00 in 24 hours format so return 0).
Constraints:
1 <= arrivaltime < 241 <= delayedTime <= 24
Approaches
2 approaches with complexity analysis and trade-offs.
This approach simulates the passage of time hour by hour. We start with the arrivalTime and increment it for each hour of the delay. We handle the 24-hour clock wrap-around by resetting the time to 0 whenever it reaches 24.
Algorithm
- Initialize a variable
currentTimewitharrivalTime. - Create a loop that iterates
delayedTimetimes. - Inside the loop, increment
currentTimeby 1. - After each increment, check if
currentTimeis equal to 24. If it is, resetcurrentTimeto 0. - After the loop finishes, return the final
currentTime.
Walkthrough
The algorithm initializes a variable, say currentTime, with the given arrivalTime. It then enters a loop that iterates delayedTime times. In each iteration, currentTime is incremented by one. After each increment, we check if currentTime has reached 24. If it has, we reset it to 0, simulating the start of a new day. After the loop completes, currentTime will hold the final arrival time.
class Solution { public int findDelayedArrivalTime(int arrivalTime, int delayedTime) { int currentTime = arrivalTime; for (int i = 0; i < delayedTime; i++) { currentTime++; if (currentTime == 24) { currentTime = 0; } } return currentTime; }}Complexity
Time
O(D) - The time complexity is linear with respect to the `delayedTime` (D), because the loop runs once for each hour of delay.
Space
O(1) - Constant space is used, as we only need a few variables to store the times, regardless of the input size.
Trade-offs
Pros
The logic is very straightforward and easy to understand, as it directly mimics a clock ticking forward.
Cons
This approach is computationally inefficient compared to a direct mathematical formula, especially if
delayedTimewere large.The code is more verbose and complex than necessary for this problem.
Solutions
Solution
class Solution {public int findDelayedArrivalTime(int arrivalTime, int delayedTime) { return (arrivalTime + delayedTime) % 24; }}Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.