Suppose we have an array A with n numbers and another input K, we have to find the index which will be the last to be reduced to zero after performing a given operation. The operation is explained as follows −
Starting from A[0] to A[N – 1], update each element as A[i] = A[i] – K. Now, if A[i] < K then put A[i] = 0 and no further operation will be done on A[i] once it is 0.
We have to repeat the operation until all of the elements are reduced to 0. And return the index which will be the last to become zero.
So, if the input is like A = [4, 3, 6, 8, 3, 10] and K = 4 , then the output will be 5 as operations are like below − Operation 1 − A = {0, 0, 2, 4, 0, 6} Operation 2 − A = {0, 0, 0, 0, 0, 2} Operation 3 − A = {0, 0, 0, 0, 0, 0}
To solve this, we will follow these steps −
n := size of A
idx := -1
for i in range 0 to n, do
A[i] :=(A[i] + k - 1) / k
for i in range 0 to n, do
if A[i] >= x, then
x := A[i]
idx := i
return idx
Example
Let us see the following implementation to get better understanding −
def search_index(A, k): n = len(A) idx = -1 x = -10**9 for i in range(n): A[i] = (A[i] + k - 1) // k for i in range(n): if (A[i] >= x): x = A[i] idx = i return idx arr = [4, 3, 6, 8, 3, 10] K = 4 print(search_index(arr, K))
Input
[4, 3, 6, 8, 3, 10], 4
Output
5