File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
3766-minimum-operations-to-make-binary-palindrome Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ # time complexity: O(n)
2+ # space complexity: O(n)
3+ from typing import List
4+ import bisect
5+
6+
7+ class Solution :
8+ def minOperations (self , nums : List [int ]) -> List [int ]:
9+ palindromeSet = set ()
10+
11+ for length in range (1 , 14 ):
12+ halfLen = (length + 1 ) // 2
13+ start = 1 << (halfLen - 1 )
14+ end = 1 << halfLen
15+ for half in range (start , end ):
16+ s = bin (half )[2 :]
17+ if length % 2 == 0 :
18+ pal = s + s [::- 1 ]
19+ else :
20+ pal = s + s [- 2 ::- 1 ]
21+ val = int (pal , 2 )
22+ if val <= 5000 :
23+ palindromeSet .add (val )
24+
25+ palindromeSet = sorted (palindromeSet )
26+
27+ result = []
28+ for num in nums :
29+ pos = bisect .bisect_left (palindromeSet , num )
30+
31+ best = float ('inf' )
32+
33+ if pos < len (palindromeSet ):
34+ best = min (best , abs (palindromeSet [pos ] - num ))
35+ if pos > 0 :
36+ best = min (best , abs (palindromeSet [pos - 1 ] - num ))
37+
38+ result .append (best )
39+
40+ return result
41+
42+
43+ nums = [1 , 2 , 4 ]
44+ print (Solution ().minOperations (nums ))
45+ nums = [6 , 7 , 12 ]
46+ print (Solution ().minOperations (nums ))
You can’t perform that action at this time.
0 commit comments