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)
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!
Last Updated :
10 Jan, 2022
Like Article
Save Article