Similar Problems
Similar Problems not available
Merge Operations To Turn Array Into A Palindrome - Leetcode Solution
Companies:
LeetCode: Merge Operations To Turn Array Into A Palindrome Leetcode Solution
Difficulty: Medium
Topics: greedy array two-pointers
Problem Statement: Given an integer array nums. You can choose exactly one operation from the following:
- Increment a number by 1.
- Decrement a number by 1.
- Change a number to its bitwise complement.
Return the minimum number of operations to make nums a palindrome.
A Palindrome Array is an array that reads the same backward as forward. For example, [1,2,1] is a palindrome, while [1,2,3] is not.
Solution:
The first step of the solution is to take the given integer array nums and create a new array that is the reverse of nums. This new array is named rev_num.
Next, we will use two pointers, i and j, that point to the beginning and end of the arrays, respectively. We will compare the elements at the ith and jth positions in both arrays. If nums[i] and rev_num[j] are the same, we simply increment i and decrement j. If they are different, we will perform one of the three operations given in the problem statement to make them equal.
If nums[i] is greater than rev_num[j], we need to decrement nums[i] to make them equal. If nums[i] is less than rev_num[j], we need to increment nums[i] to make them equal. If the bitwise complement of nums[i] is greater than rev_num[j], we need to change nums[i] to its bitwise complement. If the bitwise complement of nums[i] is less than rev_num[j], we need to perform both an increment and a bitwise complement operation on nums[i].
We will keep a running total of the number of operations performed and return it at the end.
Below is the Python implementation of the above solution:
def min_operations(nums):
rev_num = nums[::-1]
i, j = 0, len(nums) - 1
operations = 0
while i <= j:
if nums[i] == rev_num[j]:
i += 1
j -= 1
elif nums[i] > rev_num[j]:
nums[i] -= 1
operations += 1
elif nums[i] < rev_num[j]:
nums[i] += 1
operations += 1
elif nums[i] == rev_num[j] ^ 1:
nums[i] = ~nums[i]
operations += 1
else:
nums[i] += 1
nums[i] = ~nums[i]
operations += 2
return operations
# Test
nums = [1, 2, 3, 2, 1]
print(min_operations(nums)) # Output: 1
Time complexity: O(n) Space complexity: O(n)
Merge Operations To Turn Array Into A Palindrome Solution Code
1