https://leetcode.com/problems/largest-time-for-given-digits

In this problem we are asked to check if some possible permutation of digits creates maximum possible valid time. One way to handle this problem is to just check all possible 4! = 24 permutations: this number is quite small and we can afford it. So, we:

  1. Create out = "", here we will keep our answer.
  2. Check all permutations of A, in python there is special function for it, why not use it: for each permutation check if it is valid time: hour need to be <=23 and minutes need to be <=59, which can be written as P[2] <= 5.
  3. Now, compare new build time with our current maximum and choose best of them. This is all!

Complexity: time complexity is O(1), but more strictrly it is O(k!), we need to check all permutations in any case, where k=4 is size of A. Space complexity is O(1) also, which is more like O(k) to keep our answer and compare it with out.

class Solution:
    def largestTimeFromDigits(self, A):
        out = ""
        for P in permutations(A):
            if P[0]*10 + P[1] <= 23 and P[2] <= 5:
                out = max(out, str(P[0])+str(P[1]) + ":" + str(P[2])+str(P[3]))
        
        return out

If you like the solution, you can upvote it on leetcode discussion section: Problem 0949