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++
#include <bits/stdc++.h>
using namespace std;
int shortestDistance(string S, int N)
{
int minDis = S.length();
for ( int i = 0; i < N; i++)
{
for ( int j = i + 1; j < N; j++)
{
if (S[i] == S[j] and (j - i) < minDis)
{
minDis = j - i;
break ;
}
}
}
if (minDis == S.length())
return -1;
else
return minDis - 1;
}
int main()
{
string S = "geeksforgeeks" ;
int N = 13;
cout << (shortestDistance(S, N));
}
|
Java
import java.io.*;
class GFG{
static int shortestDistance(String S, int N)
{
int minDis = S.length();
for ( int i = 0 ; i < N; i++)
{
for ( int j = i + 1 ; j < N; j++)
{
if (S.charAt(i) == S.charAt(j) &&
(j - i) < minDis)
{
minDis = j - i;
break ;
}
}
}
if (minDis == S.length())
return - 1 ;
else
return minDis - 1 ;
}
public static void main(String[] args)
{
String S = "geeksforgeeks" ;
int N = 13 ;
System.out.println(shortestDistance(S, N));
}
}
|
Python3
def shortestDistance(S, N):
minDis = len (S)
for i in range (N):
for j in range (i + 1 , N):
if (S[i] = = S[j] and (j - i) < minDis):
minDis = j - i
break
if (minDis = = len (S)):
return - 1
else :
return minDis - 1
S = "geeksforgeeks"
N = 13
print (shortestDistance(S, N))
|
C#
using System;
class GFG{
static int shortestDistance( string S, int N)
{
int minDis = S.Length;
for ( int i = 0; i < N; i++)
{
for ( int j = i + 1; j < N; j++)
{
if (S[i] == S[j] && (j - i) < minDis)
{
minDis = j - i;
break ;
}
}
}
if (minDis == S.Length)
return -1;
else
return minDis - 1;
}
public static void Main(String[] args)
{
string S = "geeksforgeeks" ;
int N = 13;
Console.Write(shortestDistance(S, N));
}
}
|
Javascript
<script>
function shortestDistance( S, N)
{
var minDis = S.length;
for ( var i = 0; i < N; i++)
{
for ( var j = i + 1; j < N; j++)
{
if (S.charAt(i) == S.charAt(j) &&
(j - i) < minDis)
{
minDis = j - i;
break ;
}
}
}
if (minDis == S.length)
return -1;
else
return minDis - 1;
}
var S = "geeksforgeeks" ;
var N = 13;
document.write(shortestDistance(S, N));
</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;
int shortestDistance(string s, int n)
{
map< char , int > m;
vector< int > v;
int var;
for ( int i = 0; i < n; i++)
{
if (m.find(s[i]) != m.end())
{
var = i - m[s[i]];
m[s[i]] = i;
v.push_back(var);
}
else
m[s[i]] = i;
}
if (v.size() == 0)
return -1;
sort(v.begin(), v.end());
return v[0] - 1;
}
int main()
{
string s;
s = "geeksforgeeks" ;
int n = 13;
cout << (shortestDistance(s, n));
}
|
Java
import java.io.*;
import java.util.*;
class GFG{
static int shortestDistance(String S, int N)
{
HashMap<Character,
Integer> dic = new HashMap<Character,
Integer>();
ArrayList<Integer> dis = new ArrayList<>();
int var;
for ( int i = 0 ; i < N; i++)
{
if (dic.get(S.charAt(i)) != null )
{
var = i - dic.get(S.charAt(i));
dic.put(S.charAt(i), i);
dis.add(var);
}
else
{
dic.put(S.charAt(i), i);
}
}
if (dis.size() == 0 )
return - 1 ;
else
return Collections.min(dis) - 1 ;
}
public static void main(String[] args)
{
String S = "geeksforgeeks" ;
int N = 13 ;
System.out.println(shortestDistance(S, N));
}
}
|
Python3
def shortestDistance(S, N):
dic = {}
dis = []
for i in range (N):
if S[i] in dic:
var = i - dic[S[i]]
dic[S[i]] = i
dis.append(var)
else :
dic[S[i]] = i
if ( len (dis) = = 0 ):
return - 1
else :
return min (dis) - 1
S = "geeksforgeeks"
N = 13
print (shortestDistance(S, N))
|
C#
using System;
using System.Collections.Generic;
public class GFG {
static int shortestDistance(String S, int N) {
Dictionary< char , int > dic = new Dictionary< char , int >();
List< int > dis = new List< int >();
int var ;
for ( int i = 0; i < N; i++) {
if (dic.ContainsKey(S[i])) {
var = i - dic[S[i]];
dic[S[i]]= i;
dis.Add( var );
}
else {
dic.Add(S[i], i);
}
}
dis.Sort();
if (dis.Count == 0)
return -1;
else
return dis[0]- 1;
}
public static void Main(String[] args) {
String S = "geeksforgeeks" ;
int N = 13;
Console.WriteLine(shortestDistance(S, N));
}
}
|
Javascript
<script>
function shortestDistance( S , N) {
var dic = new Map();
var dis = new Array();
var var1;
for (i = 0; i < N; i++) {
if (dic[S[i]] != null ) {
var1 = i - dic[S[i]];
dic[S[i]] = i;
dis.push(var1);
}
else {
dic[S[i]]= i;
}
}
if (dis.length == 0)
return -1;
else
return dis.reduce( function (previous,current){
return previous < current ? previous:current
}) - 1;
}
var S = "geeksforgeeks" ;
var N = 13;
document.write(shortestDistance(S, N));
</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++
#include <bits/stdc++.h>
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));
}
|
Java
import java.util.*;
class GFG {
static int shortestDistance(String s, int n)
{
int [] visited = new int [ 128 ];
Arrays.fill(visited, - 1 );
int ans = Integer.MAX_VALUE;
for ( int right = 0 ; right < n; right++) {
char c = s.charAt(right);
int left = visited;
if (left != - 1 )
ans = Math.min(ans, right - left - 1 );
visited = right;
}
return ans == Integer.MAX_VALUE ? - 1 : ans;
}
public static void main(String[] args)
{
String s = "geeksforgeeks" ;
int n = 13 ;
System.out.print(shortestDistance(s, n));
}
}
|
Python3
import sys
def shortestDistance(s, n):
visited = [ - 1 for i in range ( 128 )];
ans = sys.maxsize;
for right in range (n):
c = (s[right]);
left = visited[ ord (c)];
if (left ! = - 1 ):
ans = min (ans, right - left - 1 );
visited[ ord (c)] = right;
if (ans = = sys.maxsize):
return - 1 ;
else :
return ans;
if __name__ = = '__main__' :
s = "geeksforgeeks" ;
n = 13 ;
print (shortestDistance(s, n));
|
C#
using System;
public class GFG {
static int shortestDistance( string s, int n)
{
int [] visited = new int [128];
for ( int i = 0; i < 128; i++)
visited[i] = -1;
int ans = int .MaxValue;
for ( int right = 0; right < n; right++) {
char c = s[right];
int left = visited;
if (left != -1)
ans = Math.Min(ans, right - left - 1);
visited = right;
}
return ans == int .MaxValue ? -1 : ans;
}
public static void Main(String[] args)
{
string s = "geeksforgeeks" ;
int n = 13;
Console.Write(shortestDistance(s, n));
}
}
|
Javascript
<script>
function shortestDistance(s , n) {
var visited = Array(128).fill(-1);
var ans = Number.MAX_VALUE;
for ( var right = 0; right < n; right++) {
var left = visited[s.charCodeAt(right)];
if (left != -1)
ans = Math.min(ans, right - left - 1);
visited[s.charCodeAt(right)] = right;
}
return ans == Number.MAX_VALUE ? -1 : ans;
}
var s = "geeksforgeeks" ;
var n = 13;
document.write(shortestDistance(s, n));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Minimum distance between the given two words
Given a list of words followed by two words, the task is to find the minimum distance between the given two words in the list of words. Examples: Input: S = { "the", "quick", "brown", "fox", "quick"}, word1 = "the", word2 = "fox"Output: 3Explanation: Minimum distance between the words "the" and "fox
4 min read
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
Hamming Distance between two strings
You are given two strings of equal length, you have to find the Hamming Distance between these string. Where the Hamming distance between two strings of equal length is the number of positions at which the corresponding character is different. Examples: Input : str1[] = "geeksforgeeks", str2[] = "ge
4 min read
Remove All Adjacent Duplicates in String II
Given a string s and an integer k, the task is to repeatedly delete k adjacent duplicates till no deletions are possible and then return the final string. On deletion of k adjacent duplicates, the left and right sides of the deleted substring is concatenated together. Examples: Input: s = "abcd", k
3 min read
Distance between two closest minimum
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[] =
10 min read
Print all the duplicate characters in a string
Given a string S, the task is to print all the duplicate characters with their occurrences in the given string. Example: Input: S = "geeksforgeeks"Output: e, count = 4 g, count = 2 k, count = 2 s, count = 2 Explanation: g occurs 2 times in the string, k occurs 2 times in the string, s occurs 2 times
8 min read
Sum of minimum and the maximum difference between two given Strings
Given two strings S1 and S2 of the same length. The task is to find the sum of the minimum and the maximum difference between two given strings if you are allowed to replace the character '+' in the strings with any other character.Note: If two strings have the same characters at every index, then t
8 min read
Find minimum difference and maximum difference in given String
Given an input string that contains lowercase alphabets and the '?' symbol, the task is to find the minimum and maximum possible difference by replacing '?' and comparing s[i] with s[i+(n/2)]. Examples: Input: s = "a?b??c"Output: 1 3Explanation: We split the input string in two equal parts s1 and s2
5 min read
Decode a given string by removing duplicate occurrences
Given encoded string str such that 'a' is written 1 time, 'b' is written 2 times, and so on, until 'z' is written 26 times, the task is to decode the given string str. Note: The letter may contain spaces and punctuation marks, so don't ignore those. Examples: Input: str = "bbadddd"Output: badExplana
6 min read
Find all duplicate characters in string in Python
In this article, we will explore various methods to find all duplicate characters in string. The simplest approach is by using a loop with dictionary. Using Loop with DictionaryWe can use a for loop to find duplicate characters efficiently. First we count the occurrences of each character by iterati
3 min read