Distance between two closest minimum - GeeksforGeeks

31 May, 2021
Given an array of n integers. Find the minimum distance between any two occurrences of the minimum integer in the array.Examples:  
Input : arr[] = {5, 1, 2, 3, 4, 1, 2, 1}
Output : 2
Explanation: The minimum element 1 occurs at 
             indexes: 1, 5 and 7. So the minimum
             distance is 7-5 = 2.

Input : arr[] = {1, 2, 1}
Output : 2
 
Brute Force Approach: The simplest approach is to find all pair of indexes of minimum element and calculate minimum distance. Time Complexity: O(n^2), where n is the total number of elements in the array.Efficient Approach: An efficient approach will be to observe that distance between index j and i will always be smaller than distance between indexes k and i where, k is greater than j. That is we only have to check distance between consecutive pairs of minimum elements and not all pairs. Below is the step by step algorithm:  
Find the minimum element in the array
Find all occurrences of minimum element in the array and insert the indexes in a new array or list or vector.
Check if size of the list of indexes is greater than one or not, i.e. the minimum element occurs atleast twice. If not than return -1.
Traverse the list of indexes and calculate the minimum difference between any two consecutive indexes.
Below is the implementation of above idea:  
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find Distance between// two closest minimum#include <iostream>#include <limits.h>#include <vector> using namespace std; // function to find Distance between// two closest minimumint findClosestMin(int arr[], int n){    int min = INT_MAX;     // find the min element in the array    for (int i = 0; i < n; i++)        if (arr[i] < min)            min = arr[i];     // vector to store indexes of occurrences    // of minimum element in the array    vector<int> indexes;     // store indexes of occurrences    // of minimum element in the array    for (int i = 0; i < n; i++)        if (arr[i] == min)            indexes.push_back(i);     // if minimum element doesnot occurs atleast    // two times, return -1.    if (indexes.size() < 2)        return -1;     int min_dist = INT_MAX;     // calculate minimum difference between    // any two consecutive indexes    for (int i = 1; i < indexes.size(); i++)        if ((indexes[i] - indexes[i - 1]) < min_dist)            min_dist = (indexes[i] - indexes[i - 1]);     return min_dist;} // Driver codeint main(){    int arr[] = { 5, 1, 2, 3, 4, 1, 2, 1 };    int size = sizeof(arr) / sizeof(arr[0]);    cout << findClosestMin(arr, size);    return 0;}
// Java program to find Distance between// two closest minimumimport java.util.Vector; class GFG { // function to find Distance between// two closest minimum    static int findClosestMin(int arr[], int n) {        int min = Integer.MAX_VALUE;         // find the min element in the array        for (int i = 0; i < n; i++) {            if (arr[i] < min) {                min = arr[i];            }        }         // vector to store indexes of occurrences        // of minimum element in the array        Vector<Integer> indexes = new Vector<>();         // store indexes of occurrences        // of minimum element in the array        for (int i = 0; i < n; i++) {            if (arr[i] == min) {                indexes.add(i);            }        }         // if minimum element doesnot occurs atleast        // two times, return -1.        if (indexes.size() < 2) {            return -1;        }         int min_dist = Integer.MAX_VALUE;         // calculate minimum difference between        // any two consecutive indexes        for (int i = 1; i < indexes.size(); i++) {            if ((indexes.get(i) - indexes.get(i - 1)) < min_dist) {                min_dist = (indexes.get(i) - indexes.get(i - 1));            }        }         return min_dist;    } // Driver code    public static void main(String args[]) {        int arr[] = {5, 1, 2, 3, 4, 1, 2, 1};        int size = arr.length;        System.out.println(findClosestMin(arr, size));    }} // This code is contributed by PrinciRaj19992
# Python3 program to find Distance# between two closest minimumimport sys # function to find Distance between# two closest minimumdef findClosestMin(arr, n):         #assigning maximum value in python    min = sys.maxsize              for i in range(0, n):        if (arr[i] < min):            min = arr[i]     # list in python to store indexes    # of occurrences of minimum element    # in the array    indexes = []     # store indexes of occurrences    # of minimum element in the array    for i in range(0, n):        if (arr[i] == min):            indexes.append(i)     # if minimum element doesnot occurs    #  atleast two times, return -1.    if (len(indexes) < 2):        return -1     min_dist = sys.maxsize     # calculate minimum difference between    # any two consecutive indexes    for i in range(1, len(indexes)):        if ((indexes[i] - indexes[i - 1]) < min_dist):            min_dist = (indexes[i] - indexes[i - 1]);     return min_dist; # Driver codearr = [ 5, 1, 2, 3, 4, 1, 2, 1 ]ans = findClosestMin(arr, 8)print (ans) # This code is contributed by saloni1297.
     // C# program to find Distance between// two closest minimumusing System;using System.Collections.Generic;public class GFG {  // function to find Distance between// two closest minimum    static int findClosestMin(int []arr, int n) {        int min = int.MaxValue;          // find the min element in the array        for (int i = 0; i < n; i++) {            if (arr[i] < min) {                min = arr[i];            }        }          // vector to store indexes of occurrences        // of minimum element in the array        List<int> indexes = new List<int>();          // store indexes of occurrences        // of minimum element in the array        for (int i = 0; i < n; i++) {            if (arr[i] == min) {                indexes.Add(i);            }        }          // if minimum element doesnot occurs atleast        // two times, return -1.        if (indexes.Count < 2) {            return -1;        }        int min_dist = int.MaxValue;          // calculate minimum difference between        // any two consecutive indexes        for (int i = 1; i < indexes.Count; i++) {            if ((indexes[i] - indexes[i-1]) < min_dist) {                min_dist = (indexes[i] - indexes[i-1]);            }        }          return min_dist;    }  // Driver code    public static void Main() {        int []arr = {5, 1, 2, 3, 4, 1, 2, 1};        int size = arr.Length;        Console.WriteLine(findClosestMin(arr, size));    }}  // This code is contributed by PrinciRaj19992
<?php// Php program to find Distance between// two closest minimum // function to find Distance between// two closest minimumfunction findClosestMin($arr, $n){    $min = PHP_INT_MAX;     # find the min element in the array    for ($i = 0; $i < $n; $i++)        if ($arr[$i] < $min)            $min = $arr[$i];     // vector to store indexes of occurrences    // of minimum element in the array    $indexes = array() ;     // store indexes of occurrences    // of minimum element in the array    for ($i = 0; $i < $n; $i++)        if ($arr[$i] == $min)            array_push($indexes, $i);     // if minimum element doesnot occurs atleast    // two times, return -1.    if (sizeof($indexes) < 2)        return -1;     $min_dist = PHP_INT_MAX;     // calculate minimum difference between    // any two consecutive indexes    for ($i = 1; $i < sizeof($indexes); $i++)        if (($indexes[$i] -             $indexes[$i - 1]) < $min_dist)            $min_dist = ($indexes[$i] -                         $indexes[$i - 1]);     return $min_dist;} // Driver code$arr = array( 5, 1, 2, 3, 4, 1, 2, 1 );$size = sizeof($arr);echo findClosestMin($arr, $size); // This code is contributed by Ryuga?>
<script>    // Javascript program to find Distance between two closest minimum         // function to find Distance between    // two closest minimum    function findClosestMin(arr, n) {        let min = Number.MAX_VALUE;            // find the min element in the array        for (let i = 0; i < n; i++) {            if (arr[i] < min) {                min = arr[i];            }        }            // vector to store indexes of occurrences        // of minimum element in the array        let indexes = [];            // store indexes of occurrences        // of minimum element in the array        for (let i = 0; i < n; i++) {            if (arr[i] == min) {                indexes.push(i);            }        }            // if minimum element doesnot occurs atleast        // two times, return -1.        if (indexes.length < 2) {            return -1;        }        let min_dist = Number.MAX_VALUE;            // calculate minimum difference between        // any two consecutive indexes        for (let i = 1; i < indexes.length; i++) {            if ((indexes[i] - indexes[i-1]) < min_dist) {                min_dist = (indexes[i] - indexes[i-1]);            }        }            return min_dist;    }         let arr = [5, 1, 2, 3, 4, 1, 2, 1];    let size = arr.length;    document.write(findClosestMin(arr, size));         // This code is contributed by suresh07.</script>
Output:  
2
Time Complexity: O(n) Auxiliary Space: O(n) 
princiraj1992
ankthon
suresh07
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Count pairs with given sum
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Find a triplet that sum to a given value
Find subarray with given sum | Set 1 (Nonnegative Numbers)
Find duplicates in O(n) time and O(1) extra space | Set 1
Remove duplicates from sorted array
Move all negative numbers to beginning and positive to end with constant extra space