LeetCode #3724 — MEDIUM

Minimum Operations to Transform Array

Move from brute-force thinking to an efficient approach using array strategy.

Solve on LeetCode
The Problem

Problem Statement

You are given two integer arrays nums1 of length n and nums2 of length n + 1.

You want to transform nums1 into nums2 using the minimum number of operations.

You may perform the following operations any number of times, each time choosing an index i:

  • Increase nums1[i] by 1.
  • Decrease nums1[i] by 1.
  • Append nums1[i] to the end of the array.

Return the minimum number of operations required to transform nums1 into nums2.

Example 1:

Input: nums1 = [2,8], nums2 = [1,7,3]

Output: 4

Explanation:

Step i Operation nums1[i] Updated nums1
1 0 Append - [2, 8, 2]
2 0 Decrement Decreases to 1 [1, 8, 2]
3 1 Decrement Decreases to 7 [1, 7, 2]
4 2 Increment Increases to 3 [1, 7, 3]

Thus, after 4 operations nums1 is transformed into nums2.

Example 2:

Input: nums1 = [1,3,6], nums2 = [2,4,5,3]

Output: 4

Explanation:

Step i Operation nums1[i] Updated nums1
1 1 Append - [1, 3, 6, 3]
2 0 Increment Increases to 2 [2, 3, 6, 3]
3 1 Increment Increases to 4 [2, 4, 6, 3]
4 2 Decrement Decreases to 5 [2, 4, 5, 3]

Thus, after 4 operations nums1 is transformed into nums2.

Example 3:

Input: nums1 = [2], nums2 = [3,4]

Output: 3

Explanation:

Step i Operation nums1[i] Updated nums1
1 0 Increment Increases to 3 [3]
2 0 Append - [3, 3]
3 1 Increment Increases to 4 [3, 4]

Thus, after 3 operations nums1 is transformed into nums2.

Constraints:

  • 1 <= n == nums1.length <= 105
  • nums2.length == n + 1
  • 1 <= nums1[i], nums2[i] <= 105
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given two integer arrays nums1 of length n and nums2 of length n + 1. You want to transform nums1 into nums2 using the minimum number of operations. You may perform the following operations any number of times, each time choosing an index i: Increase nums1[i] by 1. Decrease nums1[i] by 1. Append nums1[i] to the end of the array. Return the minimum number of operations required to transform nums1 into nums2.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Greedy

Example 1

[2,8]
[1,7,3]

Example 2

[1,3,6]
[2,4,5,3]

Example 3

[2]
[3,4]
Step 02

Core Insight

What unlocks the optimal approach

  • Notice that <code>nums2</code> has exactly one extra element compared to <code>nums1</code>. That extra element must be produced by an append operation.
  • Suppose we choose index <code>j</code> in <code>nums1</code> to append. Then <code>nums1[j]</code> must eventually become both <code>nums2[j]</code> and <code>nums2.back()</code>.
  • The cost for index <code>j</code> is: adjust <code>nums1[j]</code> so that one copy matches <code>nums2[j]</code> and the appended copy matches <code>nums2.back()</code>.
  • For each <code>j</code>, compute this adjustment cost, add the cost of transforming all other positions, and take the minimum.
  • Use prefix sums.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3724: Minimum Operations to Transform Array
class Solution {
    public long minOperations(int[] nums1, int[] nums2) {
        long ans = 1;
        int n = nums1.length;
        boolean ok = false;
        int d = 1 << 30;
        for (int i = 0; i < n; ++i) {
            int x = Math.max(nums1[i], nums2[i]);
            int y = Math.min(nums1[i], nums2[i]);
            ans += x - y;
            d = Math.min(d, Math.min(Math.abs(x - nums2[n]), Math.abs(y - nums2[n])));
            ok = ok || (nums2[n] >= y && nums2[n] <= x);
        }
        if (!ok) {
            ans += d;
        }
        return ans;
    }
}
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n log n)
Space
O(1)

Approach Breakdown

EXHAUSTIVE
O(2ⁿ) time
O(n) space

Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.

GREEDY
O(n log n) time
O(1) space

Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.

Shortcut: Sort + single pass → O(n log n). If no sort needed → O(n). The hard part is proving it works.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.

Using greedy without proof

Wrong move: Locally optimal choices may fail globally.

Usually fails on: Counterexamples appear on crafted input orderings.

Fix: Verify with exchange argument or monotonic objective before committing.