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
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read