Traverse through count arrays and one by one pick characters . Below loop takes O ( n ) time considering the MAX is constant .
i = 0 NEW_LINE j = 0 NEW_LINE k = 0 NEW_LINE while ( k < n ) : NEW_LINE INDENT while ( i < MAX and uCount [ i ] == 0 ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT if ( i < MAX ) : NEW_LINE INDENT s [ k ] = chr ( ord ( ' A ' ) + i ) NEW_LINE k += 1 NEW_LINE uCount [ i ] -= 1 NEW_LINE DEDENT while ( j < MAX and lCount [ j ] == 0 ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT if ( j < MAX ) : NEW_LINE INDENT s [ k ] = chr ( ord ( ' a ' ) + j ) NEW_LINE k += 1 NEW_LINE lCount [ j ] -= 1 NEW_LINE DEDENT DEDENT print ( " " . join ( s ) ) NEW_LINE