Tuesday, February 7, 2012

Minimize distance between words a, b and c in a document.


Given 3 arrays A,B,C find three indices i,j,k such that the value of I = max((a-b),(b-c),(c-a)) is minimized.


The function I = max((a-b),(b-c),(c-a)) actually minimizes the distance between abc. If the arrays are alread sorted, you can iterate through then incrementing i, j or j in the direction of minimizing I. If we think about it, we can conclude that we must increment the element with minimum value between i, j and k. By doing this, we will make one element going in the direction of others.
Agorithm O(n) time O(1) space:
1. initialize i, j and k to zero
2. checks current minimun value updating it if needed
3. check if i, j and k are at the end, if so stops
4. check which one between i, j and k holds the minimum element. Increment this index. Be cautious to not increment an index if it will go outside the array
5. go to step 2


Lets trace with an example:
A = {1, 10, 100}
B = {99, 101, 150}
C = {5, 11, 98}


i=0, j=0, k=0;
initially a = A[i], b=B[j] and c=C[k]
min = INF.
a = 1, b=99, c=5
now max((a-b),(b-c),(c-a)) = max(98,94,4) = 98, 98 < min => min = 98;
a = 1 is the lowest element, so lets increment i by 1, now i=1


a = A[1], b=B[0] and c=C[0]
now max((a-b),(b-c),(c-a)) = max(89,94,4) = 94, 94 < min => min = 94;
c = 5 is the lowest element, so lets increment k by 1, now k=1


a = A[1], b=B[0] and c=C[1]
now max((a-b),(b-c),(c-a)) = max(89,88,1) = 89, 89 < min => min = 89;
a = 10 is the lowest element, so lets increment i by 1, now i=2


a = A[2], b=B[0] and c=C[1]
now max((a-b),(b-c),(c-a)) = max(1,88,89) = 89, 89 == min => min = 89;
c = 11 is the lowest element, so lets increment k by 1, now k=2


a = A[2], b=B[0] and c=C[2]
now max((a-b),(b-c),(c-a)) = max(1,1,2) = 2, 2 < min => min = 2;
c = 98 is the min, and we can not increase k anymore since k=2 is the max index of array C.


So we are done and the final values of indices which minimize max((a-b),(b-c),(c-a)) are i=2, j=0, k=2
And the min value is 2.


Code output:

i:2, j:0, k:2



No comments:

Post a Comment