Web Toolbar by Wibiya

Pages

Wednesday, January 25, 2012

Given an array with duplicates, find the minimum distance between given x and y.

Solution #1: Below is the code with explanation in comments,

int minDistance(int* arr, int len, int x, int y)
{
    int prevIndex = -1;
    int min = INT_MAX;
    int i=0;
    int first;
    int second;
    int distance;


    for(i=0; i < len; i++)
    {
        if((arr[i] == x) || (arr[i] == y))
        {
            //first time encounter with x or y
            //'first' stores either x or y, depending on
            //which is encountered first
            if(prevIndex == -1)
            {
                first = (arr[i]==x)?x:y;
                second = (arr[i]==x)?y:x;
                prevIndex = i;
            }
            else
            {
                //if arr[i] is same as 'first', reset prevIndex
                if(arr[i] == first)
                    prevIndex = i;
                //if arr[i] is different from 'first', calculate distance
                else
                {
                    distance = i - prevIndex;
                    prevIndex = i;
                    min = MIN(min, distance);

                    //swap first and second
                    int temp = first;
                    first = second;
                    second = temp;
                }
            }
        }
    }
    return min;
}

int main()
{
    int arr[] ={2, 3, 4, 6, 6, 7, 5, 1, 4};

    int len = sizeof(arr)/sizeof(int);

    printf("MIN DISTANCE: %d\n", minDistance(arr, len, 4, 5));
    return 0;
}

No comments: