Smallest character in a string having minimum sum of distances between consecutive repetitions

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:

  1. Create the arrays last[] and first[] having the length equals 26 initialize both the arrays as -1.
  2. Initialize min with some large number.
  3. Traverse the string S and update the first occurrence of the current characters to the current index if it equals to -1.
  4. Find the last occurrence of each character and store it in the array last[].
  5. Traverse the array and update the index having a minimum difference at each corresponding if both the index has non-negative value.
  6. If the minimum index is found at index x, and print the character (x + ‘a’).
  7. Otherwise, print “-1”.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the character
// repeats with minimum distance
char minDistChar(string s)
{
    int n = s.length();
 
    // Stores the first and last index
    int* first = new int[26];
    int* last = new int[26];
 
    // Initialize with -1
    for (int i = 0; i < 26; i++) {
        first[i] = -1;
        last[i] = -1;
    }
 
    // Get the values of last and
    // first occurence
    for (int i = 0; i < n; i++) {
 
        // Update the first index
        if (first[s[i] - 'a'] == -1) {
            first[s[i] - 'a'] = i;
        }
 
        // Update the last index
        last[s[i] - 'a'] = i;
    }
 
    // Initialize min
    int min = INT_MAX;
    char ans = '1';
 
    // Get the minimum
    for (int i = 0; i < 26; i++) {
 
        // Values must not be same
        if (last[i] == first[i])
            continue;
 
        // Update the minimum distance
        if (min > last[i] - first[i]) {
            min = last[i] - first[i];
            ans = i + 'a';
        }
    }
 
    // return ans
    return ans;
}
 
// Driver Code
int main()
{
    string str = "geeksforgeeks";
 
    // Function Call
    cout << minDistChar(str);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for
// the above approach
import java.util.*;
class GFG{
 
// Function to find the character
// repeats with minimum distance
static char minDistChar(char []s)
{
int n = s.length;
 
// Stores the first and last index
int []first = new int[26];
int []last = new int[26];
 
// Initialize with -1
for (int i = 0; i < 26; i++)
{
    first[i] = -1;
    last[i] = -1;
}
 
// Get the values of last and
// first occurence
for (int i = 0; i < n; i++)
{
    // Update the first index
    if (first[s[i] - 'a'] == -1)
    {
    first[s[i] - 'a'] = i;
    }
 
    // Update the last index
    last[s[i] - 'a'] = i;
}
 
// Initialize min
int min = Integer.MAX_VALUE;
char ans = '1';
 
// Get the minimum
for (int i = 0; i < 26; i++)
{
    // Values must not be same
    if (last[i] == first[i])
    continue;
 
    // Update the minimum distance
    if (min > last[i] - first[i])
    {
    min = last[i] - first[i];
    ans = (char) (i + 'a');
    }
}
 
// return ans
return ans;
}
 
// Driver Code
public static void main(String[] args)
{
String str = "geeksforgeeks";
 
// Function Call
System.out.print(minDistChar(str.toCharArray()));
}
}
 
// This code is contributed by shikhasingrajput

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
import sys
 
# Function to find the character
# repeats with minimum distance
def minDistChar(s):
     
    n = len(s)
     
    # Stores the first and last index
    first = []
    last = []
     
    # Intialize with -1
    for i in range(26):
        first.append(-1)
        last.append(-1)
         
    # Get the values of last and
    # first occurence
    for i in range(n):
         
        # Update the first index
        if (first[ord(s[i]) - ord('a')] == -1):
            first[ord(s[i]) - ord('a')] = i
             
        # Update the last index
        last[ord(s[i]) - ord('a')] = i
         
    # Intialize the min
    min = sys.maxsize
    ans = '1'
     
    # Get the minimum
    for i in range(26):
         
        # Values must not be same
        if (last[i] == first[i]):
            continue
         
        # Update the minimum distance
        if (min > last[i] - first[i]):
            min = last[i] - first[i]
            ans = i + ord('a')
             
    return chr(ans)
         
# Driver Code
if __name__ == "__main__":
     
    str = "geeksforgeeks"
 
    # Function call
    print(minDistChar(str))
 
# This code is contributed by dadi madhav

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
using System.Collections.Generic; 
 
class GFG{
   
// Function to find the character
// repeats with minimum distance
static char minDistChar(char []s)
{
    int n = s.Length;
 
    // Stores the first and last index
    int []first = new int[26];
    int []last = new int[26];
 
    // Initialize with -1
    for(int i = 0; i < 26; i++)
    {
        first[i] = -1;
        last[i] = -1;
    }
 
    // Get the values of last and
    // first occurence
    for(int i = 0; i < n; i++)
    {
 
        // Update the first index
        if (first[s[i] - 'a'] == -1)
        {
              first[s[i] - 'a'] = i;
        }
 
        // Update the last index
        last[s[i] - 'a'] = i;
    }
 
    // Initialize min
    int min = int.MaxValue;
    char ans = '1';
 
    // Get the minimum
    for(int i = 0; i < 26; i++)
    {
        // Values must not be same
        if (last[i] == first[i])
            continue;
 
        // Update the minimum distance
        if (min > last[i] - first[i])
        {
            min = last[i] - first[i];
            ans = (char)(i + 'a');
        }
    }
   
    // return ans
    return ans;
}
   
// Driver Code
public static void Main(string[] args)
    String str = "geeksforgeeks";
  
    // Function call
    Console.Write(minDistChar(str.ToCharArray()));
}
}
 
// This code is contributed by rutvik_56

chevron_right


Output: 

g


Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.