#3724

Minimum Operations to Transform Array

Medium
ArrayGreedyHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

We can directly calculate the necessary increments and decrements by focusing on the last element of nums2 and matching it with an element from nums1. This reduces unnecessary operations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Append the last element of nums2 to nums1.
  2. 2Step 2: For each element in nums2, calculate the difference with the corresponding element in nums1.
  3. 3Step 3: Sum the absolute differences to get the total operations needed.
solution.py4 lines
1def minOperations(nums1, nums2):
2    nums1.append(nums2[-1])
3    ops = sum(abs(nums1[i] - nums2[i]) for i in range(len(nums2)))
4    return ops

Complexity note: The complexity is linear since we only traverse the arrays once after appending the last element.

  • 1The last element of nums2 must be appended.
  • 2Directly matching elements reduces unnecessary operations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.