Given a 24-hour time value, where on some numbers are question marks( ‘?’ ), and two integers L and R. The question mark can be replaced with any number. The task is to find the maximum time such that the absolute difference between hour value and minute value lies in the interval [L, R]. If no possible value of time exists, then print -1.
Input : time = “2?:03”, L = 5, R = 18
Output : 21:03
Explanation : Since, the difference is 21 – 3 = 18 and the time value 21:03 is the largest possible value whose difference lies in the range [5, 18]
Input : time = “??:??”, L = 60, R = 69
Output : -1
Explanation : Since maximum possible difference between hour value and minute value is 59. So, no time value is possible.
We will run two nested loops, one to represent ‘hour’ value from 23 to 0 and another to represent ‘minute’ value from 59 to 0. We keep decreasing ‘hour’ and ‘minute’ value until we get the desired time value.
- Since the maximum time value is desired, so we decrease the ‘hour’ value from 23 to 0 and similarly ‘minute’ value from 59 to 0.
- After decreasing the ‘hour’ and ‘minute’ value, we need to check if the ‘hour’ and ‘minute’ value is valid or not.
- Change in value of ‘hour’ and ‘minute’ is allowed only at those positions which have ‘?’. Changes at other positions will make time value invalid. To ensure this we will call function isValid().
- Keep on decreasing ‘hour’ and ‘minute’ value until a valid time is found whose difference lies in the range [ L, R ].
- If no valid time is found, then print “-1”.
Below is the implementation of the above approach:
Time Complexity: O(1)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.