Smallest character in a string having minimum sum of distances between consecutive repetitions
Last Updated :
27 May, 2022
Given a string S of size N consisting of lowercase alphabets only, the task is to find the smallest character having a minimum sum of distances between its consecutive repetition. If string S consists of distinct characters only, then print “-1”.
Examples:
Input: str = “aabbaadc”
Output: b;
Explanation:
For all the characters in the given string, the sum of the required distances are as follows:
Indices of ‘a’ = {0, 1, 4, 5}
=> Sum of the distances of its next repetition = abs(0 – 1) + abs(4 – 1) + abs(5 – 4) = 5
Indices of ‘b’ = {2, 3}
=> Sum of the distances of its next repetition = abs(2 – 3) = 1
‘c’, ‘d’ has no repetition
From the above distances the minimum sum of distance obtained is 1, for the character ‘b’.
Therefore, the required answer is ‘b’.
Input: str = “abcdef”
Output: -1
Explanation:
All the characters in the given string are distinct.
Naive approach: The simplest approach is to traverse the given string and for each character, find the sum of the shortest distances individually. Print the smallest character with the minimum shortest distance.
Time Complexity: O(N*26), where N is the length of the given string.
Auxiliary Space: O(N)
Efficient Approach: The idea is to traverse the string once and find the first and last indices for every character as the sum of the difference between the index between the same characters is the difference between the first and the last character. Follow the below steps to solve the problem:
- Create the arrays last[] and first[] having the length equals 26 initialize both the arrays as -1.
- Initialize min with some large number.
- Traverse the string S and update the first occurrence of the current characters to the current index if it equals to -1.
- Find the last occurrence of each character and store it in the array last[].
- Traverse the array and update the index having a minimum difference at each corresponding if both the index has non-negative value.
- If the minimum index is found at index x, and print the character (x + ‘a’).
- Otherwise, print “-1”.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
char minDistChar(string s)
{
int n = s.length();
int * first = new int [26];
int * last = new int [26];
for ( int i = 0; i < 26; i++) {
first[i] = -1;
last[i] = -1;
}
for ( int i = 0; i < n; i++) {
if (first[s[i] - 'a' ] == -1) {
first[s[i] - 'a' ] = i;
}
last[s[i] - 'a' ] = i;
}
int min = INT_MAX;
char ans = '1' ;
for ( int i = 0; i < 26; i++) {
if (last[i] == first[i])
continue ;
if (min > last[i] - first[i]) {
min = last[i] - first[i];
ans = i + 'a' ;
}
}
return ans;
}
int main()
{
string str = "geeksforgeeks" ;
cout << minDistChar(str);
return 0;
}
|
Java
import java.util.*;
class GFG{
static char minDistChar( char []s)
{
int n = s.length;
int []first = new int [ 26 ];
int []last = new int [ 26 ];
for ( int i = 0 ; i < 26 ; i++)
{
first[i] = - 1 ;
last[i] = - 1 ;
}
for ( int i = 0 ; i < n; i++)
{
if (first[s[i] - 'a' ] == - 1 )
{
first[s[i] - 'a' ] = i;
}
last[s[i] - 'a' ] = i;
}
int min = Integer.MAX_VALUE;
char ans = '1' ;
for ( int i = 0 ; i < 26 ; i++)
{
if (last[i] == first[i])
continue ;
if (min > last[i] - first[i])
{
min = last[i] - first[i];
ans = ( char ) (i + 'a' );
}
}
return ans;
}
public static void main(String[] args)
{
String str = "geeksforgeeks" ;
System.out.print(minDistChar(str.toCharArray()));
}
}
|
Python3
import sys
def minDistChar(s):
n = len (s)
first = []
last = []
for i in range ( 26 ):
first.append( - 1 )
last.append( - 1 )
for i in range (n):
if (first[ ord (s[i]) - ord ( 'a' )] = = - 1 ):
first[ ord (s[i]) - ord ( 'a' )] = i
last[ ord (s[i]) - ord ( 'a' )] = i
min = sys.maxsize
ans = '1'
for i in range ( 26 ):
if (last[i] = = first[i]):
continue
if ( min > last[i] - first[i]):
min = last[i] - first[i]
ans = i + ord ( 'a' )
return chr (ans)
if __name__ = = "__main__" :
str = "geeksforgeeks"
print (minDistChar( str ))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static char minDistChar( char []s)
{
int n = s.Length;
int []first = new int [26];
int []last = new int [26];
for ( int i = 0; i < 26; i++)
{
first[i] = -1;
last[i] = -1;
}
for ( int i = 0; i < n; i++)
{
if (first[s[i] - 'a' ] == -1)
{
first[s[i] - 'a' ] = i;
}
last[s[i] - 'a' ] = i;
}
int min = int .MaxValue;
char ans = '1' ;
for ( int i = 0; i < 26; i++)
{
if (last[i] == first[i])
continue ;
if (min > last[i] - first[i])
{
min = last[i] - first[i];
ans = ( char )(i + 'a' );
}
}
return ans;
}
public static void Main( string [] args)
{
String str = "geeksforgeeks" ;
Console.Write(minDistChar(str.ToCharArray()));
}
}
|
Javascript
<script>
function minDistChar(s)
{
let n = s.length;
let first = new Array(26);
let last = new Array(26);
for (let i = 0; i < 26; i++)
{
first[i] = -1;
last[i] = -1;
}
for (let i = 0; i < n; i++)
{
if (first[s[i] - 'a' ] == -1)
{
first[s[i] - 'a' ] = i;
}
last[s[i] - 'a' ] = i;
}
let min = 100000;
var ans = 'g' ;
for (let i = 0; i < 26; i++)
{
if (last[i] == first[i])
continue ;
if (min > last[i] - first[i])
{
min = last[i] - first[i];
ans = String.fromCharCode(i + 97);
}
}
return ans;
}
str = "geeksforgeeks" ;
document.write(minDistChar(str));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...