1
+ class Solution :
2
+ def helper (self , output : List [int ], curr_indx : int , pot_vals : List [int ]) -> List [int ] | bool :
3
+ # The check for if there are pot_vals remaining is to check
4
+ # whether multiple "1"s were used
5
+ if curr_indx >= len (output ) :
6
+ return output if not pot_vals else False
7
+
8
+ if output [curr_indx ] :
9
+ return self .helper (output , curr_indx + 1 , pot_vals )
10
+
11
+ len_potvals = len (pot_vals )
12
+ for i in range (len_potvals - 1 , - 1 , - 1 ) :
13
+ # This part is quite inefficient due to it popping and inserting causing many O(n)
14
+ # operations but is somewhat needed in order to keep pot_vals sorted when
15
+ # parsing the potential answers
16
+ if curr_indx + pot_vals [i ] < len (output ) and not output [curr_indx + pot_vals [i ]] :
17
+ curr = pot_vals .pop (i )
18
+ output [curr_indx ] = curr
19
+ output [curr_indx + curr ] = curr
20
+ pot_result = self .helper (output , curr_indx + 1 , pot_vals )
21
+
22
+ # if returns a list, then answer found
23
+ # if returns bool FALSE, then invalid case
24
+ if pot_result :
25
+ return output
26
+
27
+ pot_vals .insert (i , curr )
28
+ output [curr_indx ] = 0
29
+ output [curr_indx + curr ] = 0
30
+
31
+ # Insert the "1" case since it appears once
32
+ output [curr_indx ] = 1
33
+ pot_result = self .helper (output , curr_indx + 1 , pot_vals )
34
+ if pot_result :
35
+ return pot_result
36
+ output [curr_indx ] = 0
37
+
38
+ return False
39
+
40
+
41
+ def constructDistancedSequence (self , n : int ) -> List [int ]:
42
+ output = [0 ] * (n + n - 1 )
43
+ pot_vals = list (range (2 , n + 1 ))
44
+
45
+ return self .helper (output , 0 , pot_vals )
0 commit comments