Problem · Array

Minimum Operations to Transform Array

Learn this problem
MediumNutanix logoNutanixFULLTIMEONSITE INTERVIEW

Problem statement

You are given two integer arrays:

  • a with length n
  • b with length n + 1

You may perform the following operations on a:

  • Increment any element by 1.
  • Decrement any element by 1.
  • Copy any current element of a and append the copy to the end of a.

After all operations, the first n positions of a must equal the first n positions of b, and the appended element must equal b[n].

Return the minimum number of operations required.

Function

minimumOperationsToTransformArray(a: int[], b: int[]) → long

Examples

Example 1

a = [1]b = [2,3]return = 3

Increment 1 to 2, copy the value, then increment the copied value to 3. This takes 3 operations.

Example 2

a = [3,3,3]b = [3,3,3,3]return = 1

Copy any existing 3 and append it to the end.

Example 3

a = [5,2,1,4,6]b = [4,1,5,4,6,7]return = 8

The first five positions require 6 total increment/decrement operations. Copying a value costs 1; the best copied value can be adjusted to 7 with one additional operation, for a total of 8.

Constraints

  • a and b are integer arrays.
  • a has length n, and b has length n + 1.

More Nutanix problems

drafts saved locally
public long minimumOperationsToTransformArray(int[] a, int[] b) {
  // write your code here
}
a[1]
b[2,3]
expected3
checking account