Check If Target Array Can Be Formed

You are given two integer arrays arr1 and arr2 of size n.

You also have an array updates of size m.

Initially, the array is arr1.

Then, m update operations (sequential) are performed in order. In the jth operation, some index cj is chosen, and the value at that index is replaced with updates[j].

So the operation is: arr1[cj] = updates[j]

The values in updates are known, but the chosen indices c1, c2, ..., cm are unknown.

Your task is to determine whether it is possible to choose indices for all operations such that, after applying all updates in order, the final array becomes exactly arr2.

Return true if it is possible, otherwise return false.

Notes:

  • In each operation, you can choose any valid index.
  • Updates must be applied in the given order.
  • The same index can be chosen multiple times.
  • Only the values being written are known.
  • The positions where they were written are not known.

Example 1:

Input: arr1 = [1, 2, 3], arr2 = [1, 5, 3], updates = [5]

Output: true

Explanation:

Choose index 1 for the only operation.

After writing 5, the array becomes [1, 5, 3], which matches arr2.

Example 2:

Input: arr1 = [4, 4, 4, 4], arr2 = [4, 7, 4, 7], updates = [7, 7]

Output: true

Explanation:

Write the first 7 at index 1 and the second 7 at index 3.

The final array becomes [4, 7, 4, 7].

Now Your Turn!

Pick the correct output for the given input

Input: arr1 = [2, 1, 2], arr2 = [3, 1, 2], updates = [2, 3]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= n <= 2 * 105
  • 1 <= m <= 2 * 105
  • arr1.length == arr2.length == n
  • updates.length == m
  • 1 <= arr1[i] <= 109
  • 1 <= arr2[i] <= 109
  • 1 <= updates[j] <= 109

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
bool canObtainFinalarr1ay(vector<int>& arr1, vector<int>& arr2, vector<int>& updates) {
// Your code goes here
}
};
Test Case

Input:

Arr1
Arr2
Updates