#3674

Minimum Operations to Equalize Array

Easy
ArrayBit ManipulationBrainteaserHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

If all elements are already equal, no operations are needed. Otherwise, one operation can make them equal by replacing the entire array with the AND of all elements.

⚙️

Algorithm

3 steps
  1. 1Step 1: Check if all elements in nums are equal.
  2. 2Step 2: If they are equal, return 0.
  3. 3Step 3: If not, return 1, as one operation can equalize the array.
solution.py4 lines
1def min_operations(nums):
2    if all(x == nums[0] for x in nums):
3        return 0
4    return 1

Complexity note: We only need to check each element once, leading to linear time complexity.

  • 1All elements equal means 0 operations.
  • 2One operation can make the array equal if not already.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.