How to find the minimum distance between two numbers in an array with C

1 Answer

0 votes
#include <stdio.h>
#include <limits.h>

/*
 * Find the minimum distance between two numbers in an array.
 *
 * Parameters:
 *   arr      - input array
 *   size     - number of elements in the array
 *   number1  - first target number
 *   number2  - second target number
 *
 * Returns:
 *   Minimum distance between number1 and number2.
 *   Returns -1 if no valid pair exists.
 *
 * Time Complexity: O(n)
 * Space Complexity: O(1)
 */
int min_distance(const int arr[], int size, int number1, int number2)
{
    int lastIndex = -1;
    int minDistance = INT_MAX;

    for (int i = 0; i < size; ++i)
    {
        /* Process only occurrences of the target values */
        if (arr[i] == number1 || arr[i] == number2) {
            /*
             * If we've previously seen one of the target values
             * and the current value is the other target value,
             * update the minimum distance.
             */
            if (lastIndex != -1 && arr[i] != arr[lastIndex]) {
                int distance = i - lastIndex;

                if (distance < minDistance) {
                    minDistance = distance;
                }
            }

            /* Remember the most recent occurrence */
            lastIndex = i;
        }
    }

    return (minDistance == INT_MAX) ? -1 : minDistance;
}

int main(void)
{
    const int arr[] = {2, 3, 7, 3, 3, 4, 8, 8, 8, 11, 9, 1, 3};

    const int size = sizeof(arr) / sizeof(arr[0]);

    int result = min_distance(arr, size, 3, 8);

    if (result >= 0) {
        printf("Minimum distance between 3 and 8: %d\n", result);
    }
    else {
        printf("No valid pair found.\n");
    }

    return 0;
}


/*
run:

Minimum distance between 3 and 8: 2

*/

 



answered Aug 24, 2022 by avibootz
edited Oct 21 by avibootz
...