Tuesday, November 19, 2024
Google search engine
HomeData Modelling & AISmallest character in a string having minimum sum of distances between consecutive...

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++




// 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 occurrence
    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 = "neveropen";
 
    // Function Call
    cout << minDistChar(str);
 
    return 0;
}


Java




// 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 occurrence
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 = "neveropen";
 
// Function Call
System.out.print(minDistChar(str.toCharArray()));
}
}
 
// This code is contributed by shikhasingrajput


Python3




# 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 = []
     
    # Initialize with -1
    for i in range(26):
        first.append(-1)
        last.append(-1)
         
    # Get the values of last and
    # first occurrence
    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
         
    # Initialize 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 = "neveropen"
 
    # Function call
    print(minDistChar(str))
 
# This code is contributed by dadi madhav


C#




// 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 occurrence
    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 = "neveropen";
  
    // Function call
    Console.Write(minDistChar(str.ToCharArray()));
}
}
 
// This code is contributed by rutvik_56


Javascript




<script>
 
// JavaScript program for the above approach
 
   
// Function to find the let acter
// repeats with minimum distance
function minDistChar(s)
{
    let n = s.length;
 
    // Stores the first and last index
    let first = new Array(26);
    let last = new  Array(26);
 
    // Initialize with -1
    for(let i = 0; i < 26; i++)
    {
        first[i] = -1;
        last[i] = -1;
    }
 
    // Get the values of last and
    // first occurrence
    for(let 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
    let min = 100000;
    var  ans = 'g';
 
    // Get the minimum
    for(let 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 = String.fromCharCode(i + 97);
        }
    }
   
    // return ans
    return ans;
}
   
// Driver Code
 
str = "neveropen";
 
// Function call
document.write(minDistChar(str));
 
 
</script>


Output: 

g

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 neveropen!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments