How would you like to learn today?
Visualize algorithms in real time, explore them step by step, or challenge yourself with a test.Choose a path to focusโor scroll down to preview all options.
Visualize the algorithm step-by-step with interactive animations in real time.
Read the full explanation, examples, and starter code at your own pace.
Drag and arrange the algorithm steps in the correct execution order.
๐ง Select Active to activate
Follow every state change, comparison, and transformation as the execution unfolds in real time.
๐ Select Passive to activate
Topics: Array, Greedy, Prefix Sum, Difference Array
You are given an integer array nums of even length n and an integer limit.
In one move, you can replace any integer from nums with another integer between 1 and limit (inclusive).
An array is called complementary if for every index i:
nums[i] + nums[n - 1 - i] = constant
That means every mirrored pair in the array must have the same sum.
[1, 2, 3, 4]
Pair sums:
| Pair | Sum |
|---|---|
| 1 + 4 | 5 |
| 2 + 3 | 5 |
โ All pair sums are equal, so the array is complementary.
nums = [1,2,4,3]
limit = 4
1
In 1 move, we can change the array to:
[1,2,2,3]
Now the mirrored pair sums become:
| Pair | Sum |
|---|---|
| 1 + 3 | 4 |
| 2 + 2 | 4 |
โ Every pair has the same sum.
Therefore, the minimum number of moves is:
nums = [1,2,2,1]
limit = 2
2
One possible complementary array:
[2,2,2,2]
Pair sums:
| Pair | Sum |
|---|---|
| 2 + 2 | 4 |
| 2 + 2 | 4 |
Since values cannot exceed limit = 2, this requires 2 moves.
nums = [1,2,1,2]
limit = 2
0
The array already satisfies:
| Pair | Sum |
|---|---|
| 1 + 2 | 3 |
| 2 + 1 | 3 |
โ No changes are needed.
| Constraint | Value |
|---|---|
2 <= n <= 10^5 | โ |
1 <= nums[i] <= limit <= 10^5 | โ |
n is even | โ |
For every mirrored pair:
(nums[i], nums[n - 1 - i])
we try to make all pair sums equal using the minimum moves.
The target sum can range from:
2 <= target sum <= 2 * limit
Efficient solutions use:
to compute the answer in:
๐ฏ Select Challenge to activate
Drag and arrange the algorithm steps in the correct execution order instead of spending time typing code letter by letter.
The algorithm is divided into three logical parts. Carefully rearrange each section in the correct order to form a complete and valid solution.
Understand Below AlgorithmGreen text means the instruction is placed in the correct position.
Red text means the instruction is in the wrong position.
Instructions with the same background color indicate particular blocks start and end.
A tick mark means the instruction is correct and locked.
๐ Locked steps cannot be moved. Only unlocked steps are draggable.
๐ Enable sound for swap feedback and completion effects.