#3576
Transform Array to All Equal Elements
MediumArrayGreedyGreedyArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Use a greedy approach to fix mismatches as we traverse the array. Count the operations needed to make all elements equal.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a counter for operations needed.
- 2Step 2: Traverse the array and whenever a mismatch occurs (1 followed by -1), increment the operation counter and flip the next element.
- 3Step 3: After traversal, check if the total operations are within k.
solution.py7 lines
1def canTransform(nums, k):
2 ops = 0
3 for i in range(len(nums) - 1):
4 if nums[i] != nums[i + 1]:
5 ops += 1
6 nums[i + 1] *= -1
7 return ops <= kℹ
Complexity note: The linear complexity comes from a single pass through the array to count operations.
- 1Mismatches can be fixed in pairs.
- 2The number of operations needed can be counted in a single pass.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.