51.7k views
5 votes
Write a function that given a vector of integers calculates the minimum distance between duplicate values. For example, [2,3,3] would be 1, [2,3,4] would be -1, and [2, 3, 2, 1, 4, 3] would be 2.

User Tushariyer
by
8.4k points

1 Answer

4 votes

Final answer:

To calculate the minimum distance between duplicate values in a given vector of integers, you can use a combination of a loop and a hashmap or dictionary.

Step-by-step explanation:

To calculate the minimum distance between duplicate values in a given vector of integers, you can use a combination of a loop and a hashmap or dictionary. Here's a step-by-step approach:

  1. Create an empty hashmap or dictionary to store the value and its index in the vector.
  2. Initialize a variable called 'minDistance' with a very large number (e.g., 'inf').
  3. Iterate through the vector and for each element:
    1. If the element is already in the hashmap/dictionary, calculate the distance between the current index and the index stored in the hashmap/dictionary. If the calculated distance is smaller than 'minDistance', update 'minDistance' with the new value.
    2. If the element is not in the hashmap/dictionary, add it along with its index.
  4. If 'minDistance' remains unchanged (i.e., still set to 'inf') after the loop, it means there were no duplicate values in the vector. In this case, return -1. Otherwise, return 'minDistance'.

Let's take the example of the vector [2, 3, 2, 1, 4, 3] to understand how it works:

  1. Initialize the hashmap/dictionary as empty.
  2. Initialize 'minDistance' as 'inf'.
  3. Iterate through the vector:
    1. At index 0, '2' is not in the hashmap/dictionary. Add '2' with index 0 to the hashmap/dictionary.
    2. At index 1, '3' is not in the hashmap/dictionary. Add '3' with index 1 to the hashmap/dictionary.
    3. At index 2, '2' is already in the hashmap/dictionary. Calculate the distance between the current index (2) and the index stored in the hashmap/dictionary (0). Update 'minDistance' to 2.
    4. At index 3, '1' is not in the hashmap/dictionary. Add '1' with index 3 to the hashmap/dictionary.
    5. At index 4, '4' is not in the hashmap/dictionary. Add '4' with index 4 to the hashmap/dictionary.
    6. At index 5, '3' is already in the hashmap/dictionary. Calculate the distance between the current index (5) and the index stored in the hashmap/dictionary (1). As the calculated distance is 4, which is greater than 'minDistance' (2), 'minDistance' remains unchanged.
  4. Return 'minDistance', which is 2.

Therefore, for the given vector [2, 3, 2, 1, 4, 3], the minimum distance between duplicate values is 2.

User Franco Torres
by
8.2k points