1

Given 2 arrays of integers, A and B, an operation on array B is defined as follows:

B[i] = B[i]+2 and B[j] = B[j]-2, where i != j

  • i and j can be any indices and the above operation can be performed any number of times such that i and j are not equal

  • a valid operation consists of both the addition and subtraction steps, both parts are mandatory

The array is considered equal if the frequency of all the elements is same, the array need not be ordered, find the minimum operations required

Input:
A = [ 2, 10, 14 ]

B = [ 6, 2, 18 ]

Output: 2

Explanation :

1st operation:  select i=0; j=2; 
B[i] += 2 i.e B[0]=8;
B[j] -= 2 i.e B[2] = 16;
B after 1st operation [8,2,16]

2nd operation:  select i=0; j=2; 
B[i] += 2 i.e B[0]=10;
B[j] -= 2 i.e B[2] = 14;
B after 2nd operation [10,2,14]

Order doesnt matter, so we have made the arrays equal return 2;

I am unable get an approach to solve this and couldn't find any similar questions, so posting this here, thanks in advance.

  • What if it isn't possible to make the arrays equal? For example, `A` contains an odd number but `B` doesn't contain any odd numbers, or if `A = [10, 20]`, `B = [12, 22]`? – wLui155 Aug 03 '22 at 17:43
  • You've asked questions before, and some received answers. Any reason why you don't give feedback to them? Are they that bad? – trincot Aug 03 '22 at 18:08

2 Answers2

0

Assuming the arrays are solvable, then sort the arrays (by parity, and then by value), add up the absolute value of the deltas and divide by 4.

E.g.

A = [ 2, 10, 14 ], already sorted
B = [ 6, 2, 18 ], sorted becomes [2, 6, 18]

Sum of absolute value of deltas = 0 + 4 + 4 = 8. 8/4 = 2 so 2 moves.

Dave
  • 7,460
  • 3
  • 26
  • 39
  • That doesn't seem to produce a nice answer when the inputs are with A=[1,1,2,2] and B=[0,1,2,3]. Your calculation produces 1+0+0+1 = 2. 2/4 moves? – Wyck Oct 23 '22 at 05:58
  • @Wyck Right you are. We need to group parities. Same solution, except sort by 1) parity and then 2) value. Gets [2,2,1,1] and [0,2,1,3], with deltas of 2, 0, 0, 2, so 4/4 = 1 move, which is right. – Dave Oct 23 '22 at 15:36
0
A = [2, 10, 14]( % 2 == 0)
B = [2, 6, 18]( % 2 == 0)

another example

A = [1, 2, 5] -> [1, 5]( % 2 == 1) & [2]( % 2 == 0)
B = [1, 3, 4] -> [1, 3]( % 2 == 1) & [4]( % 2 == 0)

Notice that (a + k) mod k == a.

Assuming we already have a sorted array.

We divide the array into k parts, according to the mod k value of the element, then we sum all absolute differences, it's four times the answer.

k = 2
A.sort(key=lambda x: x % k)
B.sort(key=lambda x: x % k)
result = 0
n = len(A)
for i in range(n):
    result += abs(A[i] - B[i])
print(result >> 2)
# A = [1, 2, 5]
# B = [1, 3, 4]
# result = 1
# A = [2, 10, 14]
# B = [6, 2, 18]
# result = 2

O(N log N) because of sorting.

HariHaravelan
  • 1,041
  • 1
  • 10
  • 19
Ji Li
  • 1
  • 1