# Minimum distance between duplicates in a String

Given a string S and its length N (provided N > 0). The task is to find the minimum distance between same repeating characters, if no repeating characters present in string S return -1

Examples:

Input: S = “geeksforgeeks”, N = 13
Output:
Explanation
The repeating characters in string S = “geeksforgeeks” with minimum distance is ‘e’.
The minimum difference of their indices is 0 (i.e. the character ‘e’ are present at index 1 and 2).

Input: S = “abdfhbih”, N = 8
Output: 2
Explanation
The repeating characters in string S = “abdfhbih” with minimum distance is ‘h’.
The minimum difference of their indices is 2 (i.e. the character ‘h’ are present at index 4 and 7).

Naive Approach: This problem can be solved using two nested loops, one considering an element at each index ‘i’ in string S, next loop will find the matching character same to ith in S.

First, store each difference between repeating characters in a variable and check whether this current distance is less than the previous value stored in same variable. At the end return the variable storing Minimum value. There is one corner case i.e. when there are no repeating characters return -1. Follow the steps below to solve this problem:

• Initialize a variable minDis as N to store the minimum distances of repeating characters.
• Iterate in the range [0, N-1] using the variable i:
• Iterate in the range [i + 1, N-1] using the variable j:
• If S[i] is equal to S[j] and distance between them is less than the minDis, update minDis and then break the loop
• If minDis value is not updated that means no repeating characters, return -1, otherwise return minDis – 1.

Below is the implementation of above approach:

## C++

 `// C++ program for the above approach` `#include ` `using` `namespace` `std;`   `// This function is used to find` `// minimum distance between same` `// repeating characters` `int` `shortestDistance(string S, ``int` `N)` `{` `    `  `    ``// Store minimum distance between same` `    ``// repeating characters` `    ``int` `minDis = S.length();`   `    ``// For loop to consider each element ` `    ``// of string` `    ``for``(``int` `i = 0; i < N; i++) ` `    ``{` `        ``for``(``int` `j = i + 1; j < N; j++)` `        ``{` `            `  `            ``// Comparison of string characters and` `            ``// updating the minDis value` `            ``if` `(S[i] == S[j] and (j - i) < minDis) ` `            ``{` `                ``minDis = j - i;` `                `  `                ``// As this value would be least ` `                ``// therefore break` `                ``break``;` `            ``}` `        ``}` `    ``}` `    `  `    ``// If minDis value is not updated that means` `    ``// no repeating characters` `    ``if` `(minDis == S.length())` `        ``return` `-1;` `    ``else` `    `  `        ``// Minimum distance is minDis - 1` `        ``return` `minDis - 1;` `}`   `// Driver Code` `int` `main()` `{` `    `  `    ``// Given Input` `    ``string S = ``"geeksforgeeks"``;` `    ``int` `N = 13;`   `    ``// Function Call` `    ``cout << (shortestDistance(S, N));` `}`   `// This code is contributed by lokeshpotta20`

## Java

 `// Java program for the above approach` `import` `java.io.*;`   `class` `GFG{` `  `  `// This function is used to find` `// minimum distance between same` `// repeating characters` `static` `int` `shortestDistance(String S, ``int` `N)` `{` `    `  `    ``// Store minimum distance between same` `    ``// repeating characters` `    ``int` `minDis = S.length();` `  `  `    ``// For loop to consider each element` `    ``// of string` `    ``for``(``int` `i = ``0``; i < N; i++)` `    ``{` `        ``for``(``int` `j = i + ``1``; j < N; j++) ` `        ``{` `            `  `            ``// Comparison of string characters and` `            ``// updating the minDis value` `            ``if` `(S.charAt(i) == S.charAt(j) && ` `               ``(j - i) < minDis)` `            ``{` `                ``minDis = j - i;` `                `  `                ``// As this value would be least` `                ``// therefore break` `                ``break``;` `            ``}` `        ``}` `    ``}` `  `  `    ``// If minDis value is not updated that means` `    ``// no repeating characters` `    ``if` `(minDis == S.length())` `        ``return` `-``1``;` `  `  `    ``// Minimum distance is minDis - 1` `    ``else` `        ``return` `minDis - ``1``;` `}`   `// Driver code` `public` `static` `void` `main(String[] args)` `{` `    `  `    ``// Given input` `    ``String S = ``"geeksforgeeks"``;` `    ``int` `N = ``13``;` `  `  `    ``// Function call` `    ``System.out.println(shortestDistance(S, N));` `}` `}`   `// This code is contributed by MuskanKalra1`

## Python3

 `# Python3 implementation of above approach`   `# This function is used to find` `# minimum distance between same` `# repeating characters`     `def` `shortestDistance(S, N):`   `    ``# Store minimum distance between same` `    ``# repeating characters` `    ``minDis ``=` `len``(S)`   `    ``# For loop to consider each element of string` `    ``for` `i ``in` `range``(N):` `        ``for` `j ``in` `range``(i``+``1``, N):` `            ``# Comparison of string characters and ` `            ``# updating the minDis value` `            ``if``(S[i] ``=``=` `S[j] ``and` `(j``-``i) < minDis):` `                ``minDis ``=` `j``-``i` `                ``# As this value would be least therefore break` `                ``break` `    ``# If minDis value is not updated that means` `    ``# no repeating characters` `    ``if``(minDis ``=``=` `len``(S)):` `        ``return` `-``1` `    ``else``:` `        ``# Minimum distance is minDis - 1` `        ``return` `minDis ``-` `1`   `# Driver Code`     `# Given Input` `S ``=` `"geeksforgeeks"` `N ``=` `13`   `# Function Call` `print``(shortestDistance(S, N))`

## C#

 `// C# program for the above approach` `using` `System;`   `class` `GFG{` `  `  `// This function is used to find` `// minimum distance between same` `// repeating characters` `static` `int` `shortestDistance(``string` `S, ``int` `N)` `{` `    `  `    ``// Store minimum distance between same` `    ``// repeating characters` `    ``int` `minDis = S.Length;` `  `  `    ``// For loop to consider each element` `    ``// of string` `    ``for``(``int` `i = 0; i < N; i++)` `    ``{` `        ``for``(``int` `j = i + 1; j < N; j++) ` `        ``{` `            `  `            ``// Comparison of string characters and` `            ``// updating the minDis value` `             ``if` `(S[i] == S[j] && (j - i) < minDis)` `            ``{` `                ``minDis = j - i;` `                `  `                ``// As this value would be least` `                ``// therefore break` `                ``break``;` `            ``}` `        ``}` `    ``}` `  `  `    ``// If minDis value is not updated that means` `    ``// no repeating characters` `    ``if` `(minDis == S.Length)` `        ``return` `-1;` `  `  `    ``// Minimum distance is minDis - 1` `    ``else` `        ``return` `minDis - 1;` `}`   `// Driver code` `public` `static` `void` `Main(String[] args)` `{` `    `  `    ``// Given input` `    ``string` `S = ``"geeksforgeeks"``;` `    ``int` `N = 13;` `  `  `    ``// Function call` `    ``Console.Write(shortestDistance(S, N));` `}` `}`   `// This code is contributed by shivanisinghss2110`

## Javascript

 ``

Output

`0`

Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: This problem can be solved by using Dictionary or Hashing. First, store the last index against the character of dictionary so that it can be subtracted with the last value stored against the same character in dictionary and further store the distance in the list. At the end return the minimum of the list. Follow the steps below to solve this problem:

• Initialize a dictionary dic for holding the last occurrence of character and a list dis to store distance.
• Iterate in the range [0, N-1] using the variable i:
• If character present in dictionary:
• Then, extract its last value dic[S[i]] and update it with current position i.
• Store the difference in a variable var = i – dic[S[i]] and append it to list dis.
• If the character is not present, initialize with the current position.
• If the length of dis is 0 that means no repeating characters, return -1, otherwise return min(dis) – 1.

Below is the implementation of the above approach:

## C++

 `#include ` `using` `namespace` `std;`   `// This function is used to find minimum distance between` `// same repeating characters` `int` `shortestDistance(string s, ``int` `n)` `{`   `  ``// Define a map and an vector` `  ``map<``char``, ``int``> m;` `  ``vector<``int``> v;`   `  ``// Temporary variable` `  ``int` `var;`   `  ``// Traverse through string` `  ``for` `(``int` `i = 0; i < n; i++) ` `  ``{`   `    ``// If character present in map` `    ``if` `(m.find(s[i]) != m.end())` `    ``{`   `      ``// Difference between current position and last` `      ``// stored value` `      ``var = i - m[s[i]];`   `      ``// Updating current position` `      ``m[s[i]] = i;`   `      ``// Storing difference in list` `      ``v.push_back(var);` `    ``}`   `    ``// If character not in map assign it with` `    ``// initial of its position` `    ``else` `      ``m[s[i]] = i;` `  ``}`   `  ``// If no element inserted in vector` `  ``// i.e. no repeating characters` `  ``if` `(v.size() == 0)` `    ``return` `-1;` `  ``sort(v.begin(), v.end());` `  ``return` `v - 1;` `}`   `int` `main()` `{` `  ``string s;` `  ``s = ``"geeksforgeeks"``;` `  ``int` `n = 13;`   `  ``// Function call` `  ``cout << (shortestDistance(s, n));` `}`   `// This code is contributed by Aditya Kumar (adityakumar129)`

## Java

 `// Java implementation of above approach` `import` `java.io.*;` `import` `java.util.*;`   `class` `GFG{`   `// This function is used to find` `// minimum distance between same` `// repeating characters` `static` `int` `shortestDistance(String S, ``int` `N)` `{` `    `  `    ``// Define a hashmap and an arraylist` `    ``HashMap dic = ``new` `HashMap();` `    ``ArrayList dis = ``new` `ArrayList<>();`   `    ``// Temporary variable` `    ``int` `var;`   `    ``// Traverse through string` `    ``for``(``int` `i = ``0``; i < N; i++) ` `    ``{` `        `  `        ``// If character present in dictionary` `        ``if` `(dic.get(S.charAt(i)) != ``null``) ` `        ``{` `            `  `            ``// Difference between current position` `            ``// and last stored value` `            ``var = i - dic.get(S.charAt(i));` `            `  `            ``// Updating current position` `            ``dic.put(S.charAt(i), i);` `            `  `            ``// Storing difference in list` `            ``dis.add(var);` `        ``}`   `        ``// If character not in dictionary assign` `        ``// it with initial of its position` `        ``else` `        ``{` `            ``dic.put(S.charAt(i), i);` `        ``}` `    ``}`   `    ``// If no element inserted in list` `    ``// i.e. no repeating characterss` `    ``if` `(dis.size() == ``0``)` `        ``return` `-``1``;`   `    ``// Return minimum distance` `    ``else` `        ``return` `Collections.min(dis) - ``1``;` `}`   `// Driver code` `public` `static` `void` `main(String[] args)` `{` `    `  `    ``// Given input` `    ``String S = ``"geeksforgeeks"``;` `    ``int` `N = ``13``;`   `    ``// Function call` `    ``System.out.println(shortestDistance(S, N));` `}` `}`   `// This code is contributed by MuskanKalra1`

## Python3

 `# Python3 implementation of above approach`     `# This function is used to find the` `# required the minimum distances of` `# repeating characters` `def` `shortestDistance(S, N):` `    `  `    ``# Define dictionary and list` `    ``dic ``=` `{}` `    ``dis ``=` `[]` `    `  `    ``# Traverse through string` `    ``for` `i ``in` `range``(N):` `        ``# If character present in dictionary` `        ``if` `S[i] ``in` `dic:` `            ``# Difference between current position` `            ``# and last stored value` `            ``var ``=` `i``-` `dic[S[i]]` `            ``# Updating current position` `            ``dic[S[i]] ``=` `i` `            ``# Storing difference in list` `            ``dis.append(var)` `        ``# If character not in dictionary assign ` `        ``# it with initial of its position    ` `        ``else``:` `            ``dic[S[i]] ``=` `i` `    ``# If no element inserted in list` `    ``# i.e. no repeating characters        ` `    ``if``(``len``(dis) ``=``=` `0``):` `        ``return` `-``1` `    ``# Return minimum distance  ` `    ``else``:` `        ``return` `min``(dis)``-``1`     `# Driver code`   `# Given Input` `S ``=` `"geeksforgeeks"` `N ``=` `13`   `# Function Call` `print``(shortestDistance(S, N))`

## C#

 `// C# implementation of above approach`   `using` `System;` `using` `System.Collections.Generic;`   `public` `class` `GFG {`   `    ``// This function is used to find` `    ``// minimum distance between same` `    ``// repeating characters` `    ``static` `int` `shortestDistance(String S, ``int` `N) {`   `        ``// Define a hashmap and an arraylist` `        ``Dictionary<``char``, ``int``> dic = ``new` `Dictionary<``char``, ``int``>();` `        ``List<``int``> dis = ``new` `List<``int``>();`   `        ``// Temporary variable` `        ``int` `var``;`   `        ``// Traverse through string` `        ``for` `(``int` `i = 0; i < N; i++) {`   `            ``// If character present in dictionary` `            ``if` `(dic.ContainsKey(S[i])) {`   `                ``// Difference between current position` `                ``// and last stored value` `                ``var` `= i - dic[S[i]];`   `                ``// Updating current position` `                ``dic[S[i]]= i;`   `                ``// Storing difference in list` `                ``dis.Add(``var``);` `            ``}`   `            ``// If character not in dictionary assign` `            ``// it with initial of its position` `            ``else` `{` `                ``dic.Add(S[i], i);` `            ``}` `        ``}` `dis.Sort();` `        ``// If no element inserted in list` `        ``// i.e. no repeating characterss` `        ``if` `(dis.Count == 0)` `            ``return` `-1;`   `        ``// Return minimum distance` `        ``else` `            ``return`  `dis- 1;` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `Main(String[] args) {`   `        ``// Given input` `        ``String S = ``"geeksforgeeks"``;` `        ``int` `N = 13;`   `        ``// Function call` `        ``Console.WriteLine(shortestDistance(S, N));` `    ``}` `}`   `// This code contributed by umadevi9616`

## Javascript

 ``

Output

`0`

Time Complexity: O(N)
Auxiliary Space: O(N)

Alternate Solution: The following problem could also be solved using an improved two-pointers approach. The idea basically is to maintain a left-pointer for every character and as soon as that particular character is repeated, the left pointer points to the nearest index of the character. While doing this, we can maintain a variable ans that will store the minimum distance between any two duplicate characters. This could be achieved using a visited vector array that will store a current character’s nearest index in the array.

Follow the steps below to solve this problem:

• Initialize a visited vector for storing the last index of any character (left pointer)
• Iterate in the range [0, N-1] :
• If the character is previously visited:
• Find the distance between the characters and check, if the distance between the two is minimum.
• If it’s less than the previous minimum, update its value.
• Update the current character’s last index in the visited array.

If there is no minimum distance obtained(Ii.e., when the value of ans is INT_MAX) that means there are no repeating characters. In this case return -1;

Below is the implementation of the above approach:

## C++

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

## Java

 `// Java Program to find the minimum distance between two` `// repeating characters in a String using two pointers` `// technique` `import` `java.util.*;`   `class` `GFG {`   `    ``// This function is used to find` `    ``// minimum distance between any two` `    ``// repeating characters` `    ``// using two - pointers and hashing technique` `    ``static` `int` `shortestDistance(String s, ``int` `n)` `    ``{`   `        ``// hash array to store character's last index` `        ``int``[] visited = ``new` `int``[``128``];` `        ``Arrays.fill(visited, -``1``);` `        ``int` `ans = Integer.MAX_VALUE;`   `        ``// Traverse through the String` `        ``for` `(``int` `right = ``0``; right < n; right++) {` `            ``char` `c = s.charAt(right);` `            ``int` `left = visited;`   `            ``// If the character is present in visited array` `            ``// find if its forming minimum distance` `            ``if` `(left != -``1``)` `                ``ans = Math.min(ans, right - left - ``1``);`   `            ``// update current character's last index` `            ``visited = right;` `        ``}` `      `  `        ``// Return minimum distance found, else -1` `        ``return` `ans == Integer.MAX_VALUE ? -``1` `: ans;` `    ``}`   `  ``// Driver code` `    ``public` `static` `void` `main(String[] args)` `    ``{` `      `  `        ``// Given Input` `        ``String s = ``"geeksforgeeks"``;` `        ``int` `n = ``13``;`   `        ``// Function Call` `        ``System.out.print(shortestDistance(s, n));` `    ``}` `}`   `// This code is contributed by umadevi9616`

## Python3

 `# Python Program to find the minimum distance between two` `# repeating characters in a String using two pointers` `# technique` `import` `sys`   `# This function is used to find` `# minimum distance between any two` `# repeating characters` `# using two - pointers and hashing technique` `def` `shortestDistance(s, n):`   `    ``# hash array to store character's last index` `    ``visited ``=` `[``-``1` `for` `i ``in` `range``(``128``)];` `    `  `    ``ans ``=` `sys.maxsize;`   `    ``# Traverse through the String` `    ``for` `right ``in` `range``(n):` `        ``c ``=` `(s[right]);` `        ``left ``=` `visited[``ord``(c)];`   `        ``# If the character is present in visited array` `        ``# find if its forming minimum distance` `        ``if` `(left !``=` `-``1``):` `            ``ans ``=` `min``(ans, right ``-` `left ``-` `1``);`   `        ``# update current character's last index` `        ``visited[``ord``(c)] ``=` `right;` `    `  `    ``# Return minimum distance found, else -1` `    ``if``(ans ``=``=` `sys.maxsize):` `        ``return` `-``1``;` `    ``else``:` `        ``return` `ans;`   `# Driver code` `if` `__name__ ``=``=` `'__main__'``:`   `    ``# Given Input` `    ``s ``=` `"geeksforgeeks"``;` `    ``n ``=` `13``;`   `    ``# Function Call` `    ``print``(shortestDistance(s, n));`   `# This code is contributed by umadevi9616`

## C#

 `// C# Program to find the minimum distance between two` `// repeating characters in a String using two pointers` `// technique` `using` `System;`   `public` `class` `GFG {`   `    ``// This function is used to find` `    ``// minimum distance between any two` `    ``// repeating characters` `    ``// using two - pointers and hashing technique` `    ``static` `int` `shortestDistance(``string` `s, ``int` `n)` `    ``{`   `        ``// hash array to store character's last index` `        ``int``[] visited = ``new` `int``;` `        ``for``(``int` `i = 0; i < 128; i++)` `            ``visited[i] = -1;` `        ``int` `ans = ``int``.MaxValue;`   `        ``// Traverse through the String` `        ``for` `(``int` `right = 0; right < n; right++) {` `            ``char` `c = s[right];` `            ``int` `left = visited;`   `            ``// If the character is present in visited array` `            ``// find if its forming minimum distance` `            ``if` `(left != -1)` `                ``ans = Math.Min(ans, right - left - 1);`   `            ``// update current character's last index` `            ``visited = right;` `        ``}` `      `  `        ``// Return minimum distance found, else -1` `        ``return` `ans == ``int``.MaxValue ? -1 : ans;` `    ``}`   `  ``// Driver code` `    ``public` `static` `void` `Main(String[] args)` `    ``{` `      `  `        ``// Given Input` `        ``string` `s = ``"geeksforgeeks"``;` `        ``int` `n = 13;`   `        ``// Function Call` `        ``Console.Write(shortestDistance(s, n));` `    ``}` `}`   `// This code is contributed by umadevi9616`

## Javascript

 ``

Output

`0`

Time Complexity: O(N)
Auxiliary Space: O(N)

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next