Sunday, March 27, 2011

WAP to Find Minimum Distance Between Two Elements in An Array, Containg Duplicate As Well

Given an unsorted array and two numbers, find the minimum distance between them. For example, if the array is {1,2, 10, 2, 3, 5, 2, 1, 5} distance between 2 and 5 is 1.

Data Structure :Array

Algorithm:take variables current=-1 & min=INT_Max
so we start from last element say its index is last which is array size -1 & check it with a & b if its equal to any of these then check current !=- && a[current]!=a[last] if its true then compare min with min & current-last & update the min e.g min=minimum(min,current-last)
set current=n; repeat until we run out of loop

#include
#include
int min(int a,int b)
{ if( a
#include

void minDistance (int* pArray, int size, int num1, int num2, int* firstIndex, int* secIndex)
{
int curDst=0, minDst=INT_MAX, index1=0, index2=0;
int moveFirst=1, moveSec = 1;



while ((index1 index2)
{
moveFirst = 0;
moveSec = 1;
curDst = index1 - index2;
if (curDst < minDst)
{
minDst = curDst;
*firstIndex = index2-1;
*secIndex = index1-1;
}
}
else
{
moveFirst = 1;
moveSec = 0;
curDst = index2 - index1;
if (curDst < minDst)
{
minDst = curDst;
*firstIndex = index1-1;
*secIndex = index2-1;
}
}
}
}


int main ()
{
int array [] = {2,2,4,1,8,3,2,5,6,7,5,6,6,4,7,5};
int index1=0, index2=0;
minDistance (array, 16, 6, 2, &index1, &index2);
printf ("Index1 = %d, Index2 = %d\n", index1, index2);
printf ("Minimum distance b|w given num = %d\n", index2-index1);
return 0;
}

Time Complexity O(N)
Space Complexity O(1)
RUN Here https://ideone.com/EL8CX

No comments :