[Question]
  [
[Originally posted (and deleted) by *@Tlink*](/q/163907), which was most likely [inspired from this StackOverflow question](https://stackoverflow.com/q/48751320).  
Since it was a shame it got deleted, because it seemed like a good challenge in general, I figured I'd repost it with proper formatting and rules. (I've tried contacting *@Tlink* and get his/her permission to post it, but (s)he doesn't respond any more, which is why I decided to post it myself now.)
**Input:** Six digits.
**Output:** Either the first or last valid time in the 24-hour format (`00:00:00` through `23:59:59`). (You can choose yourself whether you output the first or last valid time.)
**Example:**
When the inputs are `1,8,3,2,6,4`, the following times can be created:
```
12:36:48    12:38:46    12:46:38    12:48:36
13:26:48    13:28:46    13:46:28    13:48:26
14:26:38    14:28:36    14:36:28    14:38:26
16:23:48    16:24:38    16:28:34    16:28:43
16:32:48    16:34:28    16:38:24    16:38:42
16:42:38    16:43:28    16:48:23    16:48:32
18:23:46    18:24:36    18:26:34    18:26:43
18:32:46    18:34:26    18:36:24    18:36:42
18:42:36    18:43:26    18:46:23    18:46:32
21:36:48    21:38:46    21:46:38    21:48:36
23:16:48    23:48:16
```
So we'll output either `12:36:48` or `23:48:16` in this case, being the first / last respectively.
## Challenge rules:
* State whether you output the first or last valid time in your answer.
* I/O is flexible. Input can be six separated integers; a string containing the six digits; an integer list/array; a single (possibly octal) number; etc. Output can be a correctly ordered list/array of digits; a String in the format `HH:mm:ss`/`HHmmss`/`HH mm ss`; every digit printed with new-line delimiter; etc. Your call.
* You are allowed to take the digits in any order you'd like, so they can already be sorted from lowest to highest or vice-versa.
* If no valid time can be created with the given digits (i.e. `2,5,5,5,5,5`), make so clear in any way you'd like. Can return `null`/`false`; `"Not possible"`; crash with an error; etc. (You cannot output an invalid time like `55:55:52`, or another valid time like `00:00:00`.) Please state how it handles inputs for which no valid time can be created.
* You are not allowed to output all possible valid times. Only the earliest/latest should be outputted/returned.
* `24` for hours (i.e. `24:00:00`), or `60` for minutes/seconds (i.e. `00:60:60`) are not valid. The ranges are `[00-23]` for hours and `[00-59]` for minutes and seconds.
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.  
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.
## Test cases:
```
Input:          Earliest output:     Latest output:
1,2,3,4,6,8     12:36:48             23:48:16
2,5,5,5,5,5     None possible        None possible
0,0,0,1,1,1     00:01:11             11:10:00
1,1,2,2,3,3     11:22:33             23:32:11
9,9,9,9,9,9     None possible        None possible
2,3,5,5,9,9     23:59:59             23:59:59
1,2,3,4,5,6     12:34:56             23:56:41
0,0,0,0,0,0     00:00:00             00:00:00
1,5,5,8,8,8     18:58:58             18:58:58
1,5,5,5,8,8     15:58:58             18:58:55
1,1,1,8,8,8     18:18:18             18:18:18
```
  
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~186~~ 174 bytes
```
D[7]={0,1,10,100,1e3,1e4,1e5};G(O,L,F,T,I,M,E){if(!F)O=L<24e4&L%10000<6e3&L%100<60?L:1e9;else{for(T=1e9,I=0;I++<F;M=G(O/10,L*10+E,F-1),T=T>M?M:T,O=(O/10)+E*D[F])E=O%10;O=T;}}
```
[Try it online!](https://tio.run/##LU7BbsIwDL3zFR4SU0KNltDSbaSBy1qE1KqX3lgPVRdYpK1Mhe1S9dszk@1ZL3rWs1/cLk5t69zL4bHWg0CJkh5BNCExIq5GtWMl5phhhXssMOWDPbK7jJc6T5aRie7zGa0IkcQm/NNJLLb5WppnZT4uZjiee1ZpanGvhdoHQZKpQlPqA/2Wz6UIUswWkmOlq02xLdYVltq7PEjnL4es5qkuKViVulLj6Gx3hc/Gduwmmv7UIrTvTQ9z0j@HmsMwAcLNtcpLOgGYBQ1SgYXELykIAsu9fcNXT/NHNp1dYLGB2dtrN0XwgbZG2LHmerbsv@coMCb64lxNfEpvrt99B0JNRufkMoxWsZNP4TKO3MrjFw "C (gcc) – Try It Online")
-12 bytes thanks to Kevin Cruijssen
Probably not optimal, but it works. Oddly enough for some reason with 7 arguments the gcc implementation on TIO requires that you actually supply them or it segfaults. On my machine that is unnecessary however. 
Format: G(X,0,6) -> Y where X is the 6-digit number whose digits are to be used and Y is the 6 digit number which when taken as a time (by inserting : appropriately) is minimal.
[Answer]
# [Haskell](https://www.haskell.org/), ~~114~~ ~~96~~ 86 bytes
```
import Data.List
f l=minimum[x|x@[a,b,c,d,e,f]<-permutations l,a:[b]<"24",c<'6',e<'6']
```
Now with less strict output. Takes input as a string of digits and compares permutations against limits with list comparison. With minutes and seconds only the first digit is checked. Crashes and burns if no permutation is a valid time.
[Try it online!](https://tio.run/##FcSxCsIwEADQ3a84gtDlLFhLEUnBwdE/CB2uNcHDXBqSFDr47xHf8N6UP9b7Wlnimgo8qFD75FwODvwoHFg2Mft3vxvCGRd8oUU36VO0SbZChdeQwSPdzDxp1fUKF90MDdr/UxXiACPExKHAERyo8/XSDb2qPw "Haskell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~131~~ ~~115~~ ~~112~~ ~~109~~ ~~105~~ 88 bytes
```
lambda s:min(d for d in permutations(s)if(2,4)>d[:2]>d[4]<6>d[2])
from itertools import*
```
[Try it online!](https://tio.run/##PUxJbsMwDLz7FbwYkgofbMUyXKPpE/qB1AenkhAB1gKJAZrXu1QKZEAMh5wh0wNvMcjDnr@PffNXvUFZvAtcg40ZNLgAyWR/xw1dDIUX4SyX3Sg@9WWRK/G4fkzU5Coam6MHhyZjjHsB51PM@HbUTzSFCxvkaZxm1jGpKkj0fT8MAwmyqEi8P1EzJ6Weol6p6T9MqBul5nlm69IA5gcxpOwCAmt1q5cXsdZyvyVOVleEaMD8/piErzz7iggpluKuu2HHHw "Python 2 – Try It Online")
I/O are lists of integers
Throws an error if no times are possible
---
Alternative:
# [Python 2](https://docs.python.org/2/), 88 bytes
```
lambda s:max(d*((2,4)>d[:2]>d[4]<6>d[2])for d in permutations(s))
from itertools import*
```
[Try it online!](https://tio.run/##RU7LisMwDLz3K3QJdkoOiRuHbNjuJ@wPtDm4tUMN8QNbhfbrU7kL20GMRpoRKD7xFrzYluN5W5W7aAV5curB9Z5z0fT1jz5NYibu5@@BmpjrJSTQYD1Ek9wdFdrgM891vVtScGDRJAxhzWBdDAn3WzmgyZ9YJw79MLKGCVlAom3brutIkEVF4uuNkjlI@RblSg5/YULZSDmOI5unHWB6EkNM1iOrdKWnf2LVwp2KnJymvAfmcTURP/HfgBBDzvayGra9AA "Python 2 – Try It Online")
Returns the latest time
Returns an empty tuple for invalid times
---
Saved
* -21 bytes, thanks to ovs
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~20~~ 15 bytes
Input as sorted string.  
Output is the smallest time as a string.  
In case of no solution, an empty list is the output.
```
œʒ2ô•3Èñ•2ô‹P}н
```
[Try it online!](https://tio.run/##MzBNTDJM/V9TVvn/6ORTk4wOb3nUsMj4cMfhjUAazNsZUHth7/9KpcP7FXTtFA7vV9L5b2hkbGJmwWVkCgJcBgYGhoaGXIaGRkbGxlyWYMBlZGxqCqRAKk3NQEqAgMvQ1NTCwgJEmYIoQ0MgDwA "05AB1E – Try It Online")
[Answer]
# JavaScript (ES6), ~~93~~ ~~89~~ 88 bytes
Expects an array of 6 digits, sorted from lowest to highest. Returns either the 6-digit string of the first valid time, or `false` if no solution exists.
```
f=(a,t='')=>t<24e4&/..([0-5].){2}/.test(t)?t:a.some((v,i)=>s=f(a.filter(_=>i--),t+v))&&s
```
[Try it online!](https://tio.run/##fY/LboMwEEX3fEVWxFYHg1@IWCX9kCiqrNSOqGioYotN1W@nTBRaRJLq3uXRPTPvtrfhcG4@Y3bq3tww@JpYiPV6TettfBbKqTRnjOyKTO8Z/RLfOYsuRBLpSzSWhe7DEdJDM@Kh9sQy37TRnclrvW2yjEJ86ilN0zAculPoWsfa7kg82XEQIEFBCdWe0lWer7gwsjSqShakAD3lSnrbBrfECsBwzBUrClNww3lyo0Y56uWk5kaMdrkkN/Cb/9Q4hff9YUIavRmbPPhaQzn7Whld3n/nktk72NtNdFeYabMyGnuf1HNSPyIxi81Lhx8 "JavaScript (Node.js) – Try It Online")
### Commented
We recursively try all permutations of the input until we find one that passes a hybrid test using both arithmetic and a regular expression.
```
f = (                       // f = recursive function taking
  a, t = ''                 // a[] = input array and t = current time
) =>                        //
  t < 24e4 &                // if t is less than 240000
  /..([0-5].){2}/.test(t) ? // and it matches "hhMmSs" with M and S in [0-5]:
    t                       //   return t
  :                         // else:
    a.some((v, i) =>        //   for each digit v at position i in a[]:
      s = f(                //     save in s the result of a recursive call with:
        a.filter(_ => i--), //       a copy of a[] with the current digit removed
        t + v               //       the current digit appended to t
      )                     //     end of recursive call
    ) && s                  //   end of some(); if truthy, return s
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 17 bytes
Takes input as a string of digits and outputs the first valid time; loops infinitely if there's no valid time.
```
á
@øXr':}a@ÐX ¤¯8
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=4QpA+FhyJzp9YUDQWCCkrzg=&input=IjAwMDExMSI=)
> 
> **Warning:** Extremely slow - add `*1000` after the second `X` to speed it up somewhat. And don't forget that an invalid input will create an infinite loop and may crash your browser.
> 
> 
> 
---
## Explanation
```
                   :Implicit input of string U
á                  :Get all permutations of U
\n                 :Reassign that array to U
      }a           :Loop until true and then return the argument that was passed
        @          :By default that argument is an integer X which increments on each loop so first we'll pass X through a function
         ÐX        :  new Date(X)
            ¤      :  Get the time
             ¯8    :  Slice to the 8th character to get rid of the timezone info
@                  :The function that tests for truthiness
  Xr':             :  Remove all colons in X
 ø                 :  Does U contain the resulting string?
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~77~~ ~~74~~ ~~69~~ ~~65~~ 62 bytes
```
$
:
6+Lv$`(.)(.*):
$%`$2:$1$%'
O`
0L`([01].|2[0-3])([0-5].){2}
```
[Try it online!](https://tio.run/##K0otycxLNPz/X4XListM26dMJUFDT1NDT0vTiktFNUHFyErFUEVVncs/gcvAJ0Ej2sAwVq/GKNpA1zhWE8jTNY3V06w2qv3/39DC2MjMBAA "Retina – Try It Online") Outputs the earliest time, or the empty string if no time can be found. Edit: Saved ~~5~~ 8 bytes thanks to @TwiNight. Explanation:
```
$
:
6+Lv$`(.)(.*):
$%`$2:$1$%'
```
Generate all the permutations. The `:` works its way though the string as the permutations are generated, ending up at the start.
```
O`
```
Sort the times into order.
```
0L`([01].|2[0-3])([0-5].){2}
```
Output the first valid time.
[Answer]
# [Red](http://www.red-lang.org), 157 124 bytes
Thanks to Kevin Cruijssen for reminding me to read the descritions more carefully!
```
func[s][a: 0:0:0 loop 86400[b: to-string a a: a + 1 if b/1 =#"0"[insert b"0"]if s = sort replace/all copy b":"""[return b]]]
```
[Try it online!](https://tio.run/##VY3LCsMgEEX3@YqLXZZSzYtUyE90Ky400RIIUdQs@vWpzaLYO5vhzOVMMPPxNLOQleWH3bdJRCkUB@V5sDrnMfQtpUJzJHeLKSzbCwq5onAFw2Kh7wzjhVAili2akKDzLvMhYkR0GQTjVzWZu1pXTM6/c4MTQkQwaQ8btJTy8NmcYEFY3bT9QKofqLtvCkApZYwVgLG6bpoCPM6Ujqbr/gA9Uzryj2Egxwc "Red – Try It Online")
Takes a sorted string as input. Returns `none` if it's not possible to make time.
## Explanation:
```
f: func[s][                                    ; the argument is a sorted string of digits
    a: 0:0:0                                   ; time object, set to 00:00:00 h 
    loop 86400 [                               ; loop through all seconds in 24 h
        b: to-string a                         ; convert the time to string 
        a: a + 1                               ; add 1 second to the current time   
        if b/1 = #"0" [                        ; prepend "0" if necessary
            insert b "0"                       ; (Red omits the leading 0)
        ]
        if s = sort replace/all copy b ":" ""[ ; compare the input with the sorted time
            return b                           ; return it if they are equal 
        ]
    ]
]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 78 bytes
```
lambda s:min(x for x in range(62**3)if x%100<60>x/100%100<s==sorted('%06d'%x))
```
[Try it online!](https://tio.run/##TY5BDsIgEEX3PcVsGqAxEVoh1ViP4AXURbWgJC00wAJPX6G68GcyeTP8H2Z@h5c19aK66zL2033owR8mbXAEZR1E0AZcb54Si7qqGqIVxJJRehT0FLcJ1sF3nbcuyAGjkooBlZGQJed9zl8Qq5udaNEG1TwrAaWUMZYgPaVKsF@VPQ3nK@QUF19zUt5w3rYtuh0KCO6dOsxOmwDfX6EEhUftA/4d4wkhBcj4kHP4M59tgNl6r@@jRMsH "Python 2 – Try It Online")
Arnauld saved a byte. Thanks!
Expects a list like `['1','2','3','4','6','8']` in sorted order:
> 
> You are allowed to take the digits in any order you'd like, so they can already be sorted from lowest to highest or vice-versa.
> 
> 
> 
Outputs an integer like `123648` for 12:36:48. I hope that's acceptable.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
Œ!s€2Ḍf«¥“ç;;‘Ṃ
```
[Try it online!](https://tio.run/##y0rNyan8///oJMXiR01rjB7u6Ek7tPrQ0kcNcw4vt7Z@1DDj4c6m////G@qYAqEFCAIA "Jelly – Try It Online")
[Posted after a request.](https://codegolf.stackexchange.com/questions/164439/the-time-anagram/164452?noredirect=1#comment397995_164452) The approach is the same as the one of the other answer, however this answer was developed independently.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~39~~ 23 bytes
Pretty sure there's a shorter way to do this, but I wanted to try using Date objects in Japt. 
```
á ®¬ò q':Ãf@T<ÐXiSiKÅ
Ì
á                     // Get all permutations of the input array.
  ®¬ò q':Ã            // [1,2,3,4,5,6] -> "12:34:56"
          f@          // Filter the results, keeping those that
            T<        // are valid dates
              ÐXiSiKÅ // when made into a date object.
Ì                     // Return the last remaining item, if any.
```
Takes input as a sorted array of numbers, returns the latest valid time or empty output if none exists.  
Lost 10 ~~pounds~~ bytes thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy).
[Try it here](https://ethproductions.github.io/japt/?v=1.4.5&code=4SCurPIgcSc6w2ZAVDzQWGlTaUvFCsw=&input=WzEsMiwzLDQsNiw4XQ==).
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~68 67 62 56~~ 55 bytes
```
->*b{b.permutation.find{|a,b,c,d,e|c<6&&e<6&&a*9+b<22}}
```
[Try it online!](https://tio.run/##JYvLCoMwEEX3foUr09o0mLSRWGx/RKQkPqgLH8QIFuO3pxN7GIbD3Dt6UV/XPt31FatNkanR/WKk6caBtN1Qb1ZihStc48ZWeRpFjV8yzi4qZ2zfXYEou91TgTBi3AOSJAmlFAQiGJDswHdunB/iv3j6LwP@wrkQApWkl9NmVxuEwBQWK26LeCXVR@rZZ6foYcZ3dybzqE1ZBrv7AQ "Ruby – Try It Online")
Input: **Sorted** array of digits (as integers).
Output: Array of digits or `nil` if no solution found
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
I'm almost certain this is not the shortest approach... will look at this again later :)
```
Œ!s2Ḍ<ẠʋÐṀ“ð<<‘ṢḢ
```
**[Try it online!](https://tio.run/##AToAxf9qZWxsef//xZIhczLhuIw84bqgyovDkOG5gOKAnMOwPDzigJjhuaLhuKL///9bOSwxLDUsOSwyLDVd "Jelly – Try It Online")**
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 63 bytes
```
FirstCase[Permutations@#,{a:0|1|2,b_,c_,_,d_,_}/;a*b-4<6>d>=c]&
```
[Try it online!](https://tio.run/##RYzLCoMwEEX3@Q1BWhnxLbZWCRS6FroUkfiiLlSI6Sr67akxbeXAhcO9MwNhr3YgrK@J6JKTePR0Zncyt3nW0uHNtmYaZ6wBJ1d7cRYXqhLqEkpotlitmBiV6d/CtEmTutDFOUYZ7UeWa2baYa3QsfGcKLMwR4g74IIHPoQQrYC4C8EPqTZIHIlUNd5T6gX@qFtvv/zq73MA4fFqR7VyGkkODQ6VqBahVXwA "Wolfram Language (Mathematica) – Try It Online")
Takes a **sorted** list of digits as input. Returns `Missing[NotFound]` for invalid inputs.
### Explanation
```
Permutations@#
```
Find all of the permutations of the input. Since the input is sorted, it is guaranteed that all valid times are in increasing order.
```
FirstCase[ ... ]
```
Find the first list that matches...
```
{a:0|1|2,b_,c_,_,d_,_}
```
The first element, labeled `a`, is 0, 1, or 2, and label the second, third, and fifth elements `b`, `c`, and `d` respectively...
```
... /;a*b-4<6>d>=c
```
... such that `a*b` is less than 10, and `d` and `c` are less than 6, with `d >= c`.
The trick is that for all numbers `00` to `24`, the product of the two digits is at most 9, and the possible invalid numbers `25` to `29` (since we force the first digit to be 0, 1, or 2) have the product of least 10.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 37 bytes
```
j\:hf&&<shT24<s@T1 60<seT60mcs`Md2S.p
```
[**Test suite**](https://pyth.herokuapp.com/?code=j%5C%3Ahf%26%26%3CshT24%3Cs%40T1+60%3CseT60mcs%60Md2S.p&test_suite=1&test_suite_input=1%2C2%2C3%2C4%2C6%2C8%0A2%2C5%2C5%2C5%2C5%2C5%0A0%2C0%2C0%2C1%2C1%2C1%0A1%2C1%2C2%2C2%2C3%2C3%0A9%2C9%2C9%2C9%2C9%2C9%0A2%2C3%2C5%2C5%2C9%2C9%0A1%2C2%2C3%2C4%2C5%2C6%0A0%2C0%2C0%2C0%2C0%2C0%0A1%2C5%2C5%2C8%2C8%2C8%0A1%2C5%2C5%2C5%2C8%2C8%0A1%2C1%2C1%2C8%2C8%2C8&debug=0)
Explanation:
```
j\:hf&&<shT24<s@T1 60<seT60mcs`Md2S.pQ # Code with implicit variables
   h                                   # The first element of
                                   .pQ # The list of all permutations of the input list
                                  S    # Sorted
                           mcs`Md2     # Mapped to three two digit long strings
    f                                  # Filtered on whether
       <shT24                          #  The first number is less than 24
      &      <s@T1 60                  #  AND the second number is less than 60
     &               <seT60            #  AND the third number is less than 60
j\:                                    # Joined by a colon
```
[Answer]
## [Perl 5](https://www.perl.org/) with `-palF`, 73 bytes
```
$"=",";($_)=grep@F~~[sort/./g]&/([01]\d|2[0-3])([0-5]\d){2}/,glob"{@F}"x6
```
[Try it online!](https://tio.run/##LYtRC4IwFEbf9zOGhIK23buuTULwyT9hEkUigbShPgSmP721ReflcOD7bDcO5FzES57yUxxdkrIfO1vV29ZMZpzFXvTtTsSNhPZ8f2MjM9UmPjPynSy4irQfzI0vVb3yV@4coDrkmiEFmJQSABgAolKs@MFQEXmFJeVh4mFApLUOoiCAf4UDgKJj8TF2fpjn5DJ7Heov "Perl 5 – Try It Online")
Outputs like `HHmmss` and outputs a blank line for invalid entries.
Every answer I've made recently has used `glob`ing for permutations... Weird!
[Answer]
## Bash + GNU sed, 83, 72, 69 bytes
* Accepts input as 6 separate arguments;
* Returns the earliest time (if found);
* Returns nothing (empty output) if no valid combination exist.
`seq 0 86399|sed "s/^/date +%T -ud@/e;h;`printf s/%d//\; $@`/\w/d;x;q"`
**How it works**
Pre-generate all the possible time strings, for the timestamps in range 0 to 86399, using GNU-sed **e**(xecute) command + `date`.
`%seq 0 86399|sed "s/^/date +%T -ud@/e;h;"`
```
00:00:00
00:00:01
...
23:59:59
```
Generate `sed` script with 6 sequential substitution commands,
for an each input digit.
`%echo sed `printf s/%d//\; $@`` 
```
sed s/1//;s/2//;s/3//;s/4//;s/6//;s/8//;
```
Then, apply substitutions, remove any input lines which have at least one digit left, print the first matching line (original time string is extracted from the hold space with `x`).
```
%echo 23:45:12|sed 's/1//;s/2//;s/3//;s/4//;s/6//;s/8//;'
:5:2 //non-matching, delete
%echo 12:36:48|sed 's/1//;s/2//;s/3//;s/4//;s/6//;s/8//;'
:: //matching, print and stop
```
**Test**
```
%./timecomb 1 2 3 4 6 8
12:36:48
%./timecomb 2 5 5 5 5 5
%./timecomb 0 0 0 1 1 1
00:01:11
%./timecomb 1 1 2 2 3 3
11:22:33
%./timecomb 9 9 9 9 9 9
%./timecomb 2 3 5 5 9 9
23:59:59
%./timecomb 1 2 3 4 5 6
12:34:56
%./timecomb 0 0 0 0 0 0
00:00:00
%./timecomb 1 5 5 8 8 8
18:58:58
%./timecomb 1 5 5 5 8 8
15:58:58
%./timecomb 1 1 1 8 8 8
18:18:18
```
[Try It Online !](https://tio.run/##S0oszvj/vzi1UMFAwcLM2NKypjg1RUGpWD9OPyWxJFVBWzVEQbc0xUE/1TrDOqGgKDOvJE2hWF81RV8/xlpBxSFBP6ZcP8W6wrpQ6f///wYKIGgIggA)
[Answer]
# [Kotlin](https://kotlinlang.org), ~~396~~ ~~391~~ 389 bytes
No clue how to make this smaller. I'm thinking it is double of what's possible. Produces earliest time.
Thanks to Kevin for 7 bytes!
```
fun p(d:Array<Int>)={val s=Array(6,{0})
val f=Array(6,{1>0})
val t=Array(3,{0})
val o=Array(3,{60})
fun r(i:Int){if(i>5){var l=0>1
var e=!l
for(p in 0..2){t[p]=s[p*2]*10+s[p*2+1]
l=l||(e&&t[p]<o[p])
e=e&&t[p]==o[p]}
if(t[0]<24&&t[1]<60&&t[2]<60&&l)for(p in 0..2)o[p]=t[p]}
else
for(p in 0..5)if(f[p]){f[p]=0>1
s[i]=d[p]
r(i+1)
f[p]=1>0}}
r(0)
if(o[0]>23)0
else "${o[0]}:${o[1]}:${o[2]}"}()
```
[Try it online!](https://tio.run/##lVhrb9vIFf3OXzEbFLaU0JKoFxwlMhokaWNgES8aF8Ui8IcxOZII87UcKrLg@Len5955kIyToJUFazRzH2fum7ormywtvo2fi7e1ko1KxKasRbNLtYjLRIltmW1EvJNZpoqtWgW7pqn0ajymQzob6UbGd@oeJDgfxWU@/muvdJOWhR5Hy/l89jK43ilxneZKvCnktpZ5EFzV6TYtIPQoqlKT1oEsEpGoTOHLUNwexd@vgesuFIddGu/EQWqRg1Jk6Z0CV1roKq0JbV3mBu4nAnL1RdWbrDwIB2IUfEqLWIm0YRlS6J3M@eu2bJzCUNyqWO4172ulcggmRSDflmXS3h96xVYVqp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8CUdn9O5x@BH7B6j8QN3j8IPzkPzEKWLSrDDmcjnAP25lxaDiYyamEKQ6waFI1g@@/Rc "Kotlin – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~31~~ 30 bytes
```
Y@3Xy[X1]X*!Y*t[4XX]6*<!AY)1Y)
```
[Try it online!](https://tio.run/##y00syfmf8D/SwTiiMjrCMDZCSzFSqyTaJCIi1kzLRtExUtMwUvO/S8j/aEMdEx0zHQsdIx3jWK5oBQMdEDQEwVgFLqCsKRha6FhAuCBoAeMaQWWBMJYLAA "MATL – Try It Online")
Input is 6 integers, output is the minimum hour, minutes, and seconds in an array. Crashes for inputs where no such time is possible.
*(-1 byte thanks to @Luis Mendo.)*
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 43 bytes
```
*.permutations.first:{24e4>.join&&6>.[2&4]}
```
[Try it online!](https://tio.run/##RYzLCoMwEEX3@YpBJGgZQo0x2Ir@SCniwoClPojpQkq/PWW0Vs5mDnfunVr71L5fgBso/UlMre1frnHdOMzCdHZ217dUrarEY@wGznUlbpKr@8cXbG4WCGuEAMoKAgQThXUMZrQsSlBiigo15jGySGK2Q3pGIiFI6ZBrISW94J@tm67Nn@7LGepjamVL6TUnDs0OJba08F8 "Perl 6 – Try It Online")
Expects a sorted input array. Returns `Nil` for invalid input.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╝a╣=→aá≈#8(⌂≈58
```
[Run and debug it](https://staxlang.xyz/#p=bc61b93d1a61a0f72338287ff73538&i=%22123468%22%0A%22255555%22%0A%22000111%22%0A%22112233%22%0A%22999999%22%0A%22235599%22%0A%22123456%22%0A%22000000%22%0A%22155888%22%0A%22155588%22%0A%22111888%22&a=1&m=2)
It takes a string of sorted digits for input. It returns the first permutation that satisfies a few criteria.
* lexicographically less than "24"
* all three pairs of characters are lexicographically less than "6"
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~58~~ 47 bytes
```
+,V^2`[0-5][6-9]{2}
G`([01].|2[0-3])([0-5].){2}
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8F9bJyzOKCHaQNc0NtpM1zK22qiWyz1BI9rAMFavxggobhyrqQGW1tMEyv3/b2BoZGxiygWmLMGUBZgyB1NmYMoMTJmBKQA "Retina – Try It Online")
Input is 6 digits in sorted order. Output is 6 digits representing earliest valid time, or empty string if no valid time exists.
EDIT: I was an idiot, -9 bytes
## Explanation
**Algorithm**
For brevity, let's define a low digit as 0-5, and a high digit as 6-9.
First, rearrange the digits so that "low-ness" or "high-ness" of each position is correct. The correct arrangement, for each number of high digits in the input:
```
# of highs  arrangment
0           LLLLLL
1           LLLLLH
2           LLLHLH
3           LHLHLH
4+          Not possible
```
Since the any rearrangement would fail the final check in the input has 4+ high digits, we can ignore that case completely.
Then, sort the lows and the highs individually. Combine with the rearrangement, this gives the lowest value that satisfies the minute and second constraints. So this gives the earliest valid time, if one exists.
Finally, check if that we have valid time. If not, discard the string.
---
**Program**
```
+,V^2`[0-5][6-9]{2}
```
Matches `LHH` and swaps the first two digits in that (becomes `HLH`), and repeat that until no more `LHH` exists. This gives the correct arrangement.
Actually, I lied. No sorting is needed because 1) swapping only happens between adjacent digits and only between a low and a high; and 2) the input is sorted. So the lows and the highs individually are already in sorted order.
```
G`([01].|2[0-3])[0-5].[0-5].
```
Only keeps the string if it is a valid time
]