-3

Given list of 6 digits, return the earliest time that can be formed from those digits. If no legal time can be constructed, return -1.

Example [1, 2, 3, 4, 5, 6]
output: 12:34:56

Example [1, 2, 3, 5, 8, 9]
output: 12:38:59

Example [1, 2, 3, 7, 8, 9]
output: 17:28:39

Example [6, 7, 8, 9, 9, 9]
output: -1

I started by sorting the list. I am not sure how we can detect the case in the second example, to swap the 8 and 5. What algorithm can I use to solve this?

Prune
  • 76,765
  • 14
  • 60
  • 81
  • Why isn't the third example's output `17:28:39`? Can you explain *why* the output for example 2 isn't `12:35:89`? – Scott Hunter Oct 24 '17 at 16:22
  • 2
    please add the code you have attempted to write so far – Adam Jaamour Oct 24 '17 at 16:25
  • @Scott thanks the for the catch. Updated the example – Scott Moore Oct 24 '17 at 16:26
  • 1
    You need to provide the code that you're using that produces this output. @AdamJaamour's comment should be directed to the OP (@ScottMoore) – franklin Oct 24 '17 at 16:27
  • @franklin got confused since they both had the same name, my bad :) – Adam Jaamour Oct 24 '17 at 16:29
  • 1
    your edit doesn't help - SO isn't a code-writing service. People will help you if you have made a start but can't quite get something to work, but they won't answer the entire problem for you. – asongtoruin Oct 24 '17 at 16:34
  • Welcome to Stackoverflow! Please have a look at: https://stackoverflow.com/help/how-to-ask – Maximilian Peters Oct 24 '17 at 17:47
  • Similar: https://stackoverflow.com/questions/44664491/find-maximum-possible-time-hhmm-by-permuting-four-given-digits/ – m69's been on strike for years Oct 24 '17 at 17:59
  • @ScottMoore: The problem is not that you asked a question; the problem is that we have posting guidelines to support the site's mission, and you fell short of those guidelines. Yes, the original posting was unclear about what you wanted, but there is still a lack of apparent solving effort on your part. – Prune Oct 24 '17 at 20:30

2 Answers2

1

Consider the time digits in reverse order, starting with the largest of the "pick list". With each assignment, remove the element from pick.

pick = [1, 2, 3, 5, 8, 9]           // just one of the examples

time[6] = pick[6]
    // pick = [1, 2, 3, 5, 8]
time[5] = largest element of pick that's < 6; if none, return -1
    // pick = [1, 2, 3, 8]
time[4] = pick[4]
    // pick = [1, 2, 3]
time[2] = largest element of pick that's < 6; if none, return -1
    // pick = [1, 2]
time[1] = pick[1]
    // pick = []

Finally, check the hours: if time[2] + 10* time[1] > 23, return -1
Prune
  • 76,765
  • 14
  • 60
  • 81
0

Try scanning from right to left. Then if the concatenated numbers is greater than 60, proceed to scan the tens digit that will satisfy the condition.

Or you can make a variable to hold the tens and ones place, and just use an if-else statement to detect if ones>0 and tens<6.

Jsandesu
  • 105
  • 12