algoadvance

Leetcode 2651. Calculate Delayed Arrival Time

Problem Statement

You are given a scheduled arrival time of a train in 24-hour format (0-23). The train can be delayed by a certain amount of hours. Write a function that returns the delayed arrival time in the same 24-hour format.

Example:

Constraints:

Clarifying Questions

  1. Is the delayed time always a positive integer?
    • Yes, as per the problem constraints.
  2. What is the range of the arrival time?
    • Arrival time is always between 0 and 23 (inclusive).
  3. Should we account for wrap-around beyond midnight?
    • Yes, the 24-hour format should wrap around if the delayed time exceeds 24 hours.

Strategy

To solve this problem, we need to calculate the new arrival time after the delay in a 24-hour format. We can achieve this by adding the delayed hours to the scheduled arrival time and taking the result modulo 24. This handles the wrap-around for times greater than or equal to 24 hours.

Steps:

  1. Calculate the sum of arrivalTime and delayedTime.
  2. Take this sum modulo 24.
  3. Return the result.

Time Complexity

The time complexity is O(1), as the operations required (addition and modulo) take constant time.

Code

Here is the implementation in C++:

#include <iostream>

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

int main() {
    int arrivalTime = 22;
    int delayedTime = 5;
    
    std::cout << "Delayed arrival time: " << findDelayedArrivalTime(arrivalTime, delayedTime) << std::endl;
    
    return 0;
}

This code defines the function findDelayedArrivalTime that computes the new arrival time considering the delay and handles the 24-hour wrap-around using the modulo operator. The main function demonstrates how to use this function with an example input and prints the result.

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