Round 1
Questions:
Given two arrays change
and arr
that consist of n and m integers respectively, in a single operation, any element of arr[i]
can be decremented by 1.
In the ith operation, the element at the index change[i]
of arr
, i.e., arr[change[i]]
can be changed. Assume indexing starts from 1.
Regardless of the value of change[i]
, in the ith operation, any element can be decremented. If change[i] > 0
: If arr[change[i]] = 0
, it can be changed to NULL.
Note that it is not necessary to change an element to NULL if it is optimal to do so later. You can choose to do nothing or to decrement any element instead.
Find the minimum number of operations required to change all the elements of the array to NULL or report -1 if it is not possible.
public static int getMinOperations(List<Integer> change, List<Integer> arr) { // Write your code here }
For input change = [1, 0, 1, 3, 2, 1, 0, 3, 1, 1]
and arr = [2, 1, 2]
, the output is 8. One of the possible operations flow can be:
- Decrementing
arr[1]
-[1, 1, 2]
- Decrementing
arr[1]
-[0, 1, 2]
- Decrementing
arr[2]
-[0, 0, 2]
- Decrementing
arr[3]
-[0, 0, 1]
- Change
arr[2]
aschange[5] = 2
-[0, NULL, 1]
- Change
arr[1]
aschange[6] = 1
-[NULL, NULL, 1]
- Decrementing
change[3]
-[NULL, NULL, 0]
- Change
arr[3]
aschange[8] = 3
-[NULL, NULL, NULL]
For case 2:
List<Integer> change = Arrays.asList(0, 0, 0, 2, 1, 3, 2); List<Integer> arr = Arrays.asList(1, 3, 2); System.out.println(getMinOperations(change, arr)); // Output: -1
Candidate's Approach
The candidate would need to implement a method to track the operations performed on the arr
array based on the indices provided in the change
array. The approach would involve:
- Iterating through the
change
array and decrementing the corresponding elements inarr
. - Keeping a count of operations until all elements in
arr
are changed to NULL. - Handling cases where it is impossible to change all elements to NULL and returning -1.
Interviewer's Feedback
No feedback provided.