Facebook Pixel

2651. Calculate Delayed Arrival Time

Problem Description

You are given two positive integers representing times related to a train schedule:

  • arrivalTime: the originally scheduled arrival time of a train (in hours)
  • delayedTime: the number of hours the train is delayed

Your task is to calculate and return the actual arrival time of the train after accounting for the delay.

The time system uses a 24-hour format (0-23 hours). This means:

  • Valid times range from 0 to 23
  • After 23:00 (11 PM), the next hour is 0:00 (midnight)
  • If the delay causes the arrival time to go past 23:00, it wraps around to the next day

For example:

  • If a train is scheduled to arrive at 13:00 (1 PM) and is delayed by 5 hours, it arrives at 18:00 (6 PM)
  • If a train is scheduled to arrive at 22:00 (10 PM) and is delayed by 5 hours, it arrives at 3:00 (3 AM the next day), since 22 + 5 = 27, and 27 % 24 = 3

The solution uses the modulo operator % 24 to handle the wraparound when the sum exceeds 23 hours, ensuring the result stays within the valid 24-hour range.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

The key insight is recognizing that time in a 24-hour format is cyclical - it repeats every 24 hours. When we add hours to a time and exceed 23, we don't get invalid times like 25:00 or 30:00; instead, we start counting from 0 again.

Think of a clock face: when the hour hand moves past 23 (11 PM), it doesn't go to 24 - it returns to 0 (midnight). This is exactly how modular arithmetic works.

To find the delayed arrival time, we naturally want to add the delay to the original arrival time: arrivalTime + delayedTime. However, this sum might exceed 23, giving us an invalid hour in the 24-hour format.

The modulo operation % 24 perfectly handles this wraparound behavior:

  • If the sum is less than 24, the modulo operation returns the sum itself (e.g., 18 % 24 = 18)
  • If the sum equals or exceeds 24, it returns only the remainder after dividing by 24 (e.g., 27 % 24 = 3, 48 % 24 = 0)

This single operation elegantly captures the cyclical nature of time, automatically handling all cases including multiple day wraparounds. For instance, if a train scheduled at 20:00 is delayed by 30 hours, (20 + 30) % 24 = 50 % 24 = 2, correctly giving us 2:00 AM.

Learn more about Math patterns.

Solution Approach

The implementation is straightforward and uses a single mathematical operation to solve the problem:

class Solution:
    def findDelayedArrivalTime(self, arrivalTime: int, delayedTime: int) -> int:
        return (arrivalTime + delayedTime) % 24

Step-by-step breakdown:

  1. Add the delay to the arrival time: We compute arrivalTime + delayedTime to get the raw delayed time. This represents the total number of hours from the start of the current day (0:00).

  2. Apply modulo 24: We use the modulo operator % 24 on the sum to ensure the result falls within the valid 24-hour range (0-23).

Why this works:

The modulo operation divides the total hours by 24 and returns only the remainder:

  • For sums less than 24: The remainder is the sum itself, so no change occurs
  • For sums of 24 or more: The remainder represents the hour in the next day(s)

Examples walkthrough:

  • arrivalTime = 15, delayedTime = 5:

    • Sum: 15 + 5 = 20
    • Result: 20 % 24 = 20 (8 PM same day)
  • arrivalTime = 22, delayedTime = 5:

    • Sum: 22 + 5 = 27
    • Result: 27 % 24 = 3 (3 AM next day)
  • arrivalTime = 23, delayedTime = 25:

    • Sum: 23 + 25 = 48
    • Result: 48 % 24 = 0 (midnight, day after next)

Time Complexity: O(1) - Only performs constant-time arithmetic operations
Space Complexity: O(1) - Uses no additional space beyond the input variables

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through a concrete example to illustrate how the solution handles time wraparound.

Example: A train scheduled to arrive at 22:00 (10 PM) is delayed by 5 hours

Step 1: Calculate the raw delayed time

  • Original arrival time: 22 (representing 22:00 or 10 PM)
  • Delay: 5 hours
  • Raw calculation: 22 + 5 = 27

Step 2: Identify the problem

  • The value 27 is outside our valid 24-hour range (0-23)
  • In real life, there's no such thing as "27 o'clock"
  • We need to determine what time 27 hours from midnight actually represents

Step 3: Apply the modulo operation

  • Calculate: 27 % 24
  • This means: "How many hours remain after removing complete 24-hour cycles?"
  • Division: 27 ÷ 24 = 1 with remainder 3
  • The quotient (1) tells us we've passed through one complete day
  • The remainder (3) gives us our answer: 3:00 AM

Step 4: Verify the result

  • Starting at 22:00, let's count forward 5 hours:
    • 22:00 → 23:00 (1 hour)
    • 23:00 → 0:00 (2 hours, midnight wraparound)
    • 0:00 → 1:00 (3 hours)
    • 1:00 → 2:00 (4 hours)
    • 2:00 → 3:00 (5 hours)
  • Final arrival time: 3:00 AM the next day ✓

The modulo operation elegantly handles this wraparound in a single calculation: (22 + 5) % 24 = 3.

Solution Implementation

1class Solution:
2    def findDelayedArrivalTime(self, arrivalTime: int, delayedTime: int) -> int:
3        """
4        Calculate the actual arrival time after a delay, using 24-hour format.
5      
6        Args:
7            arrivalTime: Original arrival time in 24-hour format (0-23)
8            delayedTime: Number of hours delayed
9      
10        Returns:
11            The new arrival time in 24-hour format (0-23)
12        """
13        # Add the delay to the original arrival time and use modulo 24
14        # to handle time wrapping around to the next day(s)
15        new_arrival_time = (arrivalTime + delayedTime) % 24
16      
17        return new_arrival_time
18
1class Solution {
2    /**
3     * Calculates the actual arrival time after a delay, considering a 24-hour format.
4     * 
5     * @param arrivalTime The originally scheduled arrival time (0-23)
6     * @param delayedTime The number of hours delayed
7     * @return The actual arrival time in 24-hour format (0-23)
8     */
9    public int findDelayedArrivalTime(int arrivalTime, int delayedTime) {
10        // Add the delay to the original arrival time and use modulo 24
11        // to handle cases where the time exceeds 24 hours (wraps to next day)
12        return (arrivalTime + delayedTime) % 24;
13    }
14}
15
1class Solution {
2public:
3    /**
4     * Calculates the actual arrival time after a delay, considering a 24-hour clock format.
5     * 
6     * @param arrivalTime - The originally scheduled arrival time (0-23)
7     * @param delayedTime - The number of hours delayed
8     * @return The new arrival time after delay, wrapped around 24-hour format
9     */
10    int findDelayedArrivalTime(int arrivalTime, int delayedTime) {
11        // Add the delay to the original arrival time and use modulo 24
12        // to handle cases where the sum exceeds 23 (wraps to next day)
13        return (arrivalTime + delayedTime) % 24;
14    }
15};
16
1/**
2 * Calculates the actual arrival time after a delay, considering a 24-hour clock format.
3 * 
4 * @param arrivalTime - The originally scheduled arrival time (0-23 hours)
5 * @param delayedTime - The number of hours the arrival is delayed
6 * @returns The new arrival time after the delay, wrapped around 24-hour format
7 */
8function findDelayedArrivalTime(arrivalTime: number, delayedTime: number): number {
9    // Add the delay to the original arrival time and use modulo 24 
10    // to handle cases where the time goes past midnight (24:00)
11    return (arrivalTime + delayedTime) % 24;
12}
13

Time and Space Complexity

Time Complexity: O(1)

  • The solution performs a single addition operation arrivalTime + delayedTime and a single modulo operation % 24
  • Both arithmetic operations execute in constant time regardless of the input values
  • No loops, recursion, or variable-length data structure operations are involved

Space Complexity: O(1)

  • The solution uses only a fixed amount of extra space
  • No additional data structures are created
  • Only the input parameters and the return value are stored, which require constant space
  • The space usage does not scale with the input size

Learn more about how to find time and space complexity quickly.

Common Pitfalls

1. Integer Overflow in Other Languages

While Python handles large integers gracefully, in languages like C++ or Java, adding two large integers could cause overflow before the modulo operation is applied.

Pitfall Example:

// C++ code that might overflow
int findDelayedArrivalTime(int arrivalTime, int delayedTime) {
    return (arrivalTime + delayedTime) % 24;  // Could overflow if sum exceeds INT_MAX
}

Solution: Use long/long long or apply modulo properties:

int findDelayedArrivalTime(int arrivalTime, int delayedTime) {
    // Option 1: Use larger data type
    return static_cast<int>(((long long)arrivalTime + delayedTime) % 24);
  
    // Option 2: Apply modulo properties
    return ((arrivalTime % 24) + (delayedTime % 24)) % 24;
}

2. Forgetting to Handle Negative Time Values

The problem states positive integers, but in real-world scenarios or variations, you might encounter negative delays (early arrivals).

Pitfall Example:

# This fails for negative delays
def findDelayedArrivalTime(arrivalTime, delayedTime):
    return (arrivalTime + delayedTime) % 24
  
# findDelayedArrivalTime(5, -7) returns -2, not 22

Solution: Handle negative values explicitly:

def findDelayedArrivalTime(arrivalTime, delayedTime):
    result = (arrivalTime + delayedTime) % 24
    return result if result >= 0 else result + 24
    # Or more concisely: return (arrivalTime + delayedTime) % 24 + 24) % 24

3. Misunderstanding the Modulo Operation with Different Languages

Different programming languages handle modulo of negative numbers differently. Python's modulo always returns non-negative results for positive divisors, but languages like C++ and Java can return negative remainders.

Pitfall Example:

// Java: -2 % 24 returns -2, not 22
public int findDelayedArrivalTime(int arrivalTime, int delayedTime) {
    return (arrivalTime + delayedTime) % 24;  // Wrong for negative sums
}

Solution: Add 24 and take modulo again to ensure positive result:

public int findDelayedArrivalTime(int arrivalTime, int delayedTime) {
    return ((arrivalTime + delayedTime) % 24 + 24) % 24;
}

4. Not Validating Input Constraints

Assuming the inputs are always valid without checking can lead to unexpected behavior.

Pitfall Example:

def findDelayedArrivalTime(arrivalTime, delayedTime):
    # What if arrivalTime is 25 or -1?
    return (arrivalTime + delayedTime) % 24

Solution: Add input validation:

def findDelayedArrivalTime(arrivalTime, delayedTime):
    if not (0 <= arrivalTime <= 23):
        raise ValueError(f"Invalid arrival time: {arrivalTime}")
    if delayedTime < 0:
        raise ValueError(f"Delay cannot be negative: {delayedTime}")
  
    return (arrivalTime + delayedTime) % 24
Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

What data structure does Breadth-first search typically uses to store intermediate states?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More