-4

similar types of question are there on stackoverflow but from the 24 hour format HH:MM ,what are the best ways to find the next earliest time if 12:00 is given then the ans is 21:00

KS HARSHA
  • 67
  • 2
  • 7
  • 2
    Your question is not clear. How is 00:12 the "next earliest time" to 12:00? Why wouldn't it be 01:20? Please explain more clearly what you are trying to do. Provide multiple examples. – Jim Mischel Jun 15 '18 at 21:03
  • 1
    Related: https://stackoverflow.com/questions/44664491/find-maximum-possible-time-hhmm-by-permuting-four-given-digits/ – m69's been on strike for years Jun 15 '18 at 21:23

1 Answers1

0

I think I’d generate all possible times from the digits of the original time (here 12:00), sort them and see which comes after the original one.

With more detail: Generate all unique permutations of the digits. If you don’t know how to generate permutations, search the web, it’s covered in many places. It’s probably easiest to generate all permutations and then filter out duplicates. Validate each permutation and discard those that are not valid times if any. For example there is no such time as 12:63 or 31:14. If using Java, use LocalTime.parse for validation. Sort the times using their natural order. Find the original in the sorted list. Return the subsequent list element.

Edit: The following description does not give you the correct next time in all cases.

It’s possible to go more directly for just finding the next time without finding all times, but it’s a bit complicated. First thing to do is to search the time string from the right for where there’s a smaller digit before a greater one (in your example you will find that 1 is before 2). Among the digits visited so far, choose the next digit higher than the smaller digit found. In your example, the next digit higher than 1 is 2. Put this digit where the lower digit was and reverse the order of the remaining digits. The reverse of 100 is 001, so your result is 20:01,, which I believe is the correct answer. For a different example, 01:20, again 1 is before 2, so put 2 there, reverse 10 into 01 to get 02:01. If you get an invalid time, repeat the process. If there is no smaller digit before a greater one, you have exhausted the possible times of the day. If you want to start over, reverse the entire string: from 21:00 you will get 00:12.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161