Minimum Operations to Make the Array Alternating LeetCode solution in Python

1
# Runtime: 3233 ms (Top 5.15%) | Memory: 31.6 MB (Top 46.98%)
2
class Solution:
3
def minimumOperations(self, nums: List[int]) -> int:
4
n = len(nums)
5
odd, even = defaultdict(int), defaultdict(int)
6
for i in range(n):
7
if i % 2 == 0:
8
even[nums[i]] += 1
9
else:
10
odd[nums[i]] += 1
11
topEven, secondEven = (None, 0), (None, 0)
12
for num in even:
13
if even[num] > topEven[1]:
14
topEven, secondEven = (num, even[num]), topEven
15
elif even[num] > secondEven[1]:
16
secondEven = (num, even[num])
17
topOdd, secondOdd = (None, 0), (None, 0)
18
for num in odd:
19
if odd[num] > topOdd[1]:
20
topOdd, secondOdd = (num, odd[num]), topOdd
21
elif odd[num] > secondOdd[1]:
22
secondOdd = (num, odd[num])
23
if topOdd[0] != topEven[0]:
24
return n - topOdd[1] - topEven[1]
25
else:
26
return n - max(secondOdd[1] + topEven[1], secondEven[1] + topOdd[1])

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0