Minimum distance between duplicates in a String
Last Updated :
10 Jan, 2022
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: 0
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 <bits/stdc++.h>
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
<script>
// JavaScript program for the above approach
// This function is used to find
// minimum distance between same
// repeating characters
function shortestDistance( S, N)
{
// Store minimum distance between same
// repeating characters
var minDis = S.length;
// For loop to consider each element
// of string
for(var i = 0; i < N; i++)
{
for(var 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
// Given input
var S = "geeksforgeeks";
var N = 13;
// Function call
document.write(shortestDistance(S, N));
// This code is contributed by shivanisinghss2110
</script>
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 <bits/stdc++.h>
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[0] - 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<Character,
Integer> dic = new HashMap<Character,
Integer>();
ArrayList<Integer> 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[0]- 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
<script>
// javascript implementation of above approach
// This function is used to find
// minimum distance between same
// repeating characters
function shortestDistance( S , N) {
// Define a hashmap and an arraylist
var dic = new Map();
var dis = new Array();
// Temporary variable
var var1;
// Traverse through string
for (i = 0; i < N; i++) {
// If character present in dictionary
if (dic[S[i]] != null) {
// Difference between current position
// and last stored value
var1 = i - dic[S[i]];
// Updating current position
dic[S[i]] = i;
// Storing difference in list
dis.push(var1);
}
// 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 characterss
if (dis.length == 0)
return -1;
// Return minimum distance
else
return dis.reduce(function(previous,current){
return previous < current ? previous:current
}) - 1;
}
// Driver code
// Given input
var S = "geeksforgeeks";
var N = 13;
// Function call
document.write(shortestDistance(S, N));
// This code is contributed by gauravrajput1
</script>
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 <bits/stdc++.h>
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[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[c] = 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[c];
// 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[c] = 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[128];
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[c];
// 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[c] = 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
<script>
// javascript 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
function shortestDistance(s , n) {
// hash array to store character's last index
var visited = Array(128).fill(-1);
var ans = Number.MAX_VALUE;
// Traverse through the String
for (var right = 0; right < n; right++) {
var left = visited[s.charCodeAt(right)];
// 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[s.charCodeAt(right)] = right;
}
// Return minimum distance found, else -1
return ans == Number.MAX_VALUE ? -1 : ans;
}
// Driver code
// Given Input
var s = "geeksforgeeks";
var n = 13;
// Function Call
document.write(shortestDistance(s, n));
// This code is contributed by umadevi9616
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Check if edit distance between two strings is one An edit between two strings is one of the following changes. Add a characterDelete a characterChange a characterGiven two strings s1 and s2, find if s1 can be converted to s2 with exactly one edit. Note: Even if the strings are already equal, one edit operation can still be considered valid by "chan
14 min read
Print all the duplicate characters in a string Given a string s, the task is to identify all characters that appear more than once and print each as a list containing the character and its count. Examples:Input: s = "geeksforgeeks"Output: ['e', 4], ['g', 2], ['k', 2], ['s', 2]Explanation: Characters e, g, k, and s appear more than once. Their co
8 min read
Print a closest string that does not contain adjacent duplicates Given a string S, change the smallest number of letters in S such that all adjacent characters are different. Print the resultant string. Examples : Input: S = "aab"Output: acbExplanation: Loop will start for i-th character, which is second âaâ. Itâs cannot be âbâ since it matches with third char. S
9 min read
Character replacement after removing duplicates from a string Given a string. The task is to replace each character of the minimized string with a character present at the index 'IND' of the original string. The minimized string is the string obtained by removing all duplicates from the original string keeping the order of elements the same. IND for any index
7 min read
Minimum cost to construct a string Given a string s (containing lowercase letters only), we have to find the minimum cost to construct the given string. The cost can be determined using the following operations: Appending a single character cost 1 unit A sub-string of a new string(intermediate string) can be appended without any cost
5 min read
Find the duplicate characters in a string in O(1) space Given a string str, the task is to find all the duplicate characters present in a given string in lexicographical order without using any additional data structure. Examples: Input: str = "geeksforgeeks" Output: e g k s Explanation: Frequency of character 'g' = 2 Frequency of character 'e' = 4 Frequ
10 min read