Transform Array to All Equal Elements - Problem

You're given an array of n integers where each element is either 1 or -1, and you have up to k operations to transform it.

The Operation: Choose any index i (where 0 โ‰ค i < n-1) and multiply both nums[i] and nums[i+1] by -1. This flips the signs of two adjacent elements simultaneously.

Goal: Determine if it's possible to make all elements equal (either all 1s or all -1s) using at most k operations.

Key Insights:

  • You can apply the same operation multiple times on the same index
  • Each operation affects exactly two adjacent elements
  • The strategy depends on the current distribution of 1s and -1s

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1, -1, 1, -1], k = 1
โ€บ Output: false
๐Ÿ’ก Note: We have 4 segments: [1], [-1], [1], [-1]. To make all equal, we need to eliminate 3 boundaries, requiring at least 2 operations. Since k=1 < 2, it's impossible.
example_2.py โ€” Sufficient Operations
$ Input: nums = [1, -1, 1, -1], k = 2
โ€บ Output: true
๐Ÿ’ก Note: With k=2 operations, we can make all elements equal. For example: apply operation at index 1 to get [1, 1, -1, -1], then at index 1 again to get [1, 1, 1, 1].
example_3.py โ€” Already Equal
$ Input: nums = [1, 1, 1], k = 0
โ€บ Output: true
๐Ÿ’ก Note: All elements are already equal, so no operations are needed. Return true regardless of k value.

Constraints

  • 1 โ‰ค n โ‰ค 105
  • nums[i] is either 1 or -1
  • 0 โ‰ค k โ‰ค 109
  • Each operation affects exactly two adjacent elements

Visualization

Tap to expand
Transform Array: [1, -1, 1, -1] with k=2ON1OFF-1ON1OFF-1B1B2B3AnalysisSegments: 4Boundaries: 3Min Operations: โŒˆ3/2โŒ‰ = 2k=2 โ‰ฅ 2 โœ“ Possible!๐ŸŽฏ Key InsightEach operation can eliminate up to 2 segment boundariesby flipping two adjacent elements simultaneously
Understanding the Visualization
1
Initial State
Count how many 'segments' of consecutive same-state switches exist
2
Identify Boundaries
Each transition between segments represents a boundary to eliminate
3
Calculate Minimum Operations
Each tool use can eliminate at most 2 boundaries
4
Check Feasibility
Compare required operations with available tool uses (k)
Key Takeaway
๐ŸŽฏ Key Insight: The minimum operations needed equals โŒˆ(number of segments - 1) / 2โŒ‰, since each operation can eliminate at most 2 boundaries between segments.
Asked in
Google 15 Meta 12 Amazon 8 Microsoft 6
24.6K Views
Medium Frequency
~12 min Avg. Time
892 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