Minimum Distance between words[AMAZON]

Problem Statement

You want to find the minimum distance between two words in a given string.

Approach

To find the minimum distance between two words in a string, you can follow these steps:

  1. Split the string into an array of words.
  2. Initialize two variables, minDistance and prevIndex, to keep track of the minimum distance and the index of the previous word encountered.
  3. Iterate through the array of words.
  4. If the current word matches either of the target words, calculate the distance between the current index and the previous index.
  5. If the calculated distance is less than the current minimum distance, update the minDistance variable.
  6. Update the prevIndex variable with the current index.
  7. After iterating through all the words, the minDistance variable will contain the minimum distance between the two target words.

Here's an example implementation in C:

#include <stdio.h>
#include <string.h>

int minDistanceBetweenWords(char str, char word1, char* word2) {
    char* word;
    int minDistance = strlen(str); // initialize with a large value
    int prevIndex = -1;

    // Split the string into words
    word = strtok(str, " ");

    while (word != NULL) {
        if (strcmp(word, word1) == 0 || strcmp(word, word2) == 0) {
            if (prevIndex != -1) {
                int distance = prevIndex - (word - str);
                if (distance < minDistance) {
                    minDistance = distance;
                }
            }
            prevIndex = word - str;
        }

        word = strtok(NULL, " ");
    }

    return minDistance;
}

int main() {
    char str[] = "This is a sample string to demonstrate the minimum distance between words.";
    char word1[] = "sample";
    char word2[] = "minimum";

    int distance = minDistanceBetweenWords(str, word1, word2);
    printf("Minimum distance between '%s' and '%s' is %d\n", word1, word2, distance);

    return 0;
}

This implementation uses the strtok function from the string.h library to split the string into words based on spaces. It then compares each word with the target words and calculates the distance between them.

Note: This implementation assumes that the target words are case-sensitive. If you want to make the comparison case-insensitive, you can use the strcasecmp function instead of strcmp.

I hope this helps! Let me know if you have any further questions.