Minimum distance between duplicates in a String | C ++ Program to find the minimum distance between two repeating characters in a string using two pointers technique ; This function is used to find minimum distance between any two repeating characters using two - pointers and hashing technique ; hash array to store character 's last index ; Traverse through the string ; If the character is present in visited array find if its forming minimum distance ; update current character 's last index ; Return minimum distance found , else - 1 ; Driver code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int shortestDistance ( string s , int n ) { vector < int > visited ( 128 , -1 ) ; int ans = INT_MAX ; for ( int right = 0 ; right < n ; right ++ ) { char c = s [ right ] ; int left = visited ; if ( left != -1 ) ans = min ( ans , right - left - 1 ) ; visited = right ; } return ans == INT_MAX ? -1 : ans ; } int main ( ) { string s = " geeksforgeeks " ; int n = 13 ; cout << ( shortestDistance ( s , n ) ) ; }