Time Complexity : O(1), since we are sorting fixed size array of 4 elements and there are a fixed 4! = 24 permutations possible for the time array. The checks for valid minute and hour are also constant time.
// Given four digits, find all the valid times that can be formed on a 24 hr clock. Earliest time 00:00 and latest time is 23:59.
// Example : Input: [2, 3, 3, 2] Output: 3
// Explanation: these valid times will be formed with this input : {22:33, 23:23, 23:32} so answer will be 3.
#include<bits/stdc++.h>
using namespace std;
bool isvalidminute(int a, int b){
int x = 10*a+b;
if(x>=0 and x<60) return 1;
return 0;
}
bool isvalidhour(int a, int b){
int x = 10*a+b;
if(x>=0 and x<24) return 1;
return 0;
}
int solution(int A, int B, int C, int D){
vector<int> time;
int count=0;
time.push_back(A);
time.push_back(B);
time.push_back(C);
time.push_back(D);
sort(time.begin(),time.end());
do{
if(isvalidminute(time[2],time[3]) and isvalidhour(time[0],time[1])){
count++;
cout<<time[0]<<" "<<time[1]<<" "<<time[2]<<" "<<time[3]<<endl;
}
}
while(next_permutation(time.begin(),time.end()));
return count;
}
int main() {
cout<<solution(2,3,3,2)<<endl;
return 0;
}