Transform Array to All Equal Elements - Problem

You are given an integer array nums of size n containing only 1 and -1, and an integer k.

You can perform the following operation at most k times:

  • Choose an index i (0 <= i < n - 1), and multiply both nums[i] and nums[i + 1] by -1.

Note: You can choose the same index i more than once in different operations.

Return true if it is possible to make all elements of the array equal after at most k operations, and false otherwise.

Input & Output

Example 1 — Basic Transformation
$ Input: nums = [1,-1,1], k = 1
Output: true
💡 Note: Apply operation at index 0: multiply nums[0] and nums[1] by -1, getting [-1,1,1]. Then apply operation at index 1: multiply nums[1] and nums[2] by -1, getting [-1,-1,-1]. All elements are now equal.
Example 2 — Insufficient Operations
$ Input: nums = [1,1,-1,-1], k = 1
Output: false
💡 Note: We have 2 positive and 2 negative elements. To make all equal, we need at least 1 operation to group negatives or positives, but the arrangement makes it impossible with just k=1 operations.
Example 3 — Already Equal
$ Input: nums = [-1,-1], k = 0
Output: true
💡 Note: All elements are already equal to -1, so no operations needed.

Constraints

  • 1 ≤ nums.length ≤ 105
  • nums[i] is either 1 or -1
  • 0 ≤ k ≤ 109

Visualization

Tap to expand
Transform Array to All Equal Elements INPUT Array nums: 1 i=0 -1 i=1 1 i=2 Parameters: nums = [1, -1, 1] k = 1 (max operations) n = 3 (array size) Initial Count: Count of 1s: 2 Count of -1s: 1 Goal: Make all equal ALGORITHM STEPS 1 Count -1s negCount = 1 2 Check All 1s Need negCount ops 1 <= 1? YES 3 Check All -1s Need (n-negCount) ops 2 <= 1? NO 4 Return Result Either option works Operation at i=0: [1, -1, 1] --> [−1, 1, 1] nums[0] x -1 = -1 nums[1] x -1 = 1 Wait, need all 1s! FINAL RESULT After 1 operation at i=1: 1 i=0 1 i=1 1 i=2 Output: true All elements equal! Used: 1 operation Verification: Original: [1, -1, 1] Op at i=1: nums[1] x -1 = 1 nums[2] x -1 = -1 Result: [1, 1, -1] Key Insight: Each operation flips TWO adjacent elements. To make all elements equal to 1, we need exactly (count of -1s) operations. To make all -1s, we need (count of 1s) operations. Return true if either count is <= k. Time: O(n), Space: O(1). Mathematical approach avoids simulation! TutorialsPoint - Transform Array to All Equal Elements | Mathematical Analysis
Asked in
Google 15 Amazon 12 Microsoft 8
23.4K Views
Medium Frequency
~15 min Avg. Time
867 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen