Open In App

Minimum days to achieve the String

Last Updated : 19 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string S of length N containing only lowercase alphabets, also given a permutation P of length N containing integers from 0 to N-1. In (i+1)th day you can take the P[i] value of the permutation array and replace S[P[i]] with a ‘?’.

For example on day 1, we can choose the index of the permutation array as i = 0 and replace S[P[0]] with ‘?’.
Similarly on day 2, we can choose the index of the permutation array as i = 1. You can replace S[P[1]] with ‘?’.
Similarly on day 3, we can choose the index of the permutation array as i = 2. You can replace S[P[2]] with ‘?’.

You have to tell the minimum number of days required, such that after it for all index i (0 ? i < N-1), if S[i] != ‘?’, then S[i] != S[i+1].

Examples:

Input: N = 4, S = “aabb”, P[] = {2, 1, 3, 0}
Output: 2
Explanation: On day 1, we replace S[P[0]] with ‘?’. After that String S = “aa?b”. As we can see S still has character ‘a’ at index 0 and 1.On day 2, we replace S[P[1]] with ‘?’. After that String S = “a??b”. As we can see the String has for all index i (0 ? i < N – 1), if S[i] != ‘?’, then S[i] != S[i +1 ].

Input: N = 4, S = “abca”, P[] = {3, 0, 2, 1}
Output: 0
Explanation: We can see that the initial string S = “abca” has for all index i (0 ? i < N – 1), if S[i] != ‘?’, then S[i] != S[i + 1].

Approach: To solve the problem follow the below idea:

<=

The problem can be solved only by observing a few things. Here we have to return the minimum number of days required to change the string so that no two consecutive characters (Except ‘?’)  in the string are similar. The idea here is to iterate the Permutation array and for every value of the permutation array(P[i]), we have to check the string whether the character of the string at the index value same as the value of the permutation array forms a consecutive substring of similar character if it is so then we convert the character of the string into ‘?’ and reduce the number of consecutive similar type character

Follow the steps below to solve the problem:

  • Initialize the variable say, consecutiveCount to store the number of consecutive similar characters or elements.
  • Using a loop count the number of consecutive similar characters and store it in the consecutiveCount variable. If S[i] is the same as S[i+1] or S[i] is the same as S[i-1] then increase the consecutiveCount variable.
  • If there is no consecutive similar type of character, i.e the value of the variable consecutiveCount is 0 then the answer will be 0. 
  • If consecutiveCount != 0: we have to traverse the Permutation array using a loop with a loop variable, i.
  • Initialize the variable say, index to store the value of permutation array, P[i]
  • If S[index] == S[index-1]: Decrease the value of consecutiveCount by 1.
  • If S[index] == S[index+1]: Decrease the value of consecutiveCount by 1.
  • Update S[index] = ‘?’.
  • If consecutiveCount == 0: return (i+1) value because at (i+1)th day we found that there is no consecutive similar type character(Except ‘?’) present in the string.
  • If no such above case happened then return -1 value.

Below is the implementation for the above approach:

C++




// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to solve the problem
int minimumDays(int N, string S, int P[])
{
 
    // consecutiveCount to store the
    // number of consecutive similar
    // type character.
    int consecutiveCount = 0;
 
    // Count the number of consecutive
    // similar type character.
    for (int i = 1; i < N; i++) {
        if (S[i] == S[i - 1]) {
            consecutiveCount++;
        }
    }
 
    // If Count of consecutive similar
    // type character is 0, then answer
    // is also 0.
    if (consecutiveCount == 0) {
        return 0;
    }
 
    // To find Minimum number of days
    // required to get required string.
    // We have to iterate the permutation
    // array P.
 
    for (int i = 0; i < N; i++) {
 
        // Now we check whether we can
        // change the string at s[p[i]].
 
        // Index to store the value of
        // permutation array, P[i].
        int index = P[i];
 
        // If we get two consecutive
        // similar character.
        if (index != 0 && S[index] == S[index - 1]) {
 
            // Reduce the count of consecutive
            // similar character.
            consecutiveCount--;
        }
 
        // If we get two consecutive
        // similar character.
        if (index != N - 1 && S[index] == S[index + 1]) {
 
            // Reduce the count of consecutive
            // similar character.
            consecutiveCount--;
        }
 
        // Update the string value
        // at the index.
        S[index] = '?';
 
        if (consecutiveCount == 0) {
 
            // If at ith day consecutiveCount
            // becomes 0 then, we should
            // return (i+1) as we have
            // taken 0 based indexing.
            return (i + 1);
        }
    }
 
    // If no such above case happened then
    // return -1 value,
    return -1;
}
 
// Driver Code
int main()
{
    int N = 4;
 
    string S = "aabb";
    int P[] = { 2, 1, 3, 0 };
 
    // Function Call
    cout << minimumDays(N, S, P) << endl;
 
    return 0;
}


C




// C program to implement the above approach
#include <stdio.h>
#include <string.h>
 
// Function to solve the problem
int minimumDays(int N, char S[], int P[])
{
    // consecutiveCount to store the number of
    // consecutive similar type character.
    int consecutiveCount = 0;
 
    // Count the number of consecutive similar
    // type character.
    for (int i = 1; i < N; i++) {
        if (S[i] == S[i - 1]) {
            consecutiveCount++;
        }
    }
    // If count of consecutive similar type
    // character is 0 then answer is also 0.
    if (consecutiveCount == 0) {
        return 0;
    }
    // To find Minimum number of days required
    // to get required string. we have to iterate
    // the permutation array P.
 
    for (int i = 0; i < N; i++) {
        // Now we check whether we can change
        // the string at S[p[i]].
 
        // index to store the value of
        // permutation array, P[i].
        int index = P[i];
 
        // If we get two consecutive similar
        // character.
        if (index != 0 && S[index] == S[index - 1]) {
            // Reduce the count of consecutive
            // similar character.
            consecutiveCount--;
        }
 
        // If we get two consecutive similar
        // character.
        if (index != N - 1 && S[index] == S[index + 1]) {
            // Reduce the count of consecutive
            // similar character.
            consecutiveCount--;
        }
        // Update the string value at the index.
        S[index] = '?';
 
        if (consecutiveCount == 0) {
 
            // If at ith day consecutiveCount
            // becomes 0  then. We should return
            // (i+1) as we have taken 0 based
            // indexing.
            return (i + 1);
        }
    }
    // If no such above case happened then return
    // -1 value.
    return -1;
}
// Driver Code
int main()
{
    int N = 4;
 
    char S[] = "aabb";
    int P[] = { 2, 1, 3, 0 };
    printf("%d ", minimumDays(N, S, P));
 
    return 0;
}


Java




import java.util.*;
 
public class Main {
 
  // Function to solve the problem
  static int minimumDays(int N, String S, int P[])
  {
     
    // consecutiveCount to store the
    // number of consecutive similar
    // type character.
    int consecutiveCount = 0;
 
    // Count the number of consecutive
    // similar type character.
    for (int i = 1; i < N; i++) {
      if (S.charAt(i) == S.charAt(i - 1)) {
        consecutiveCount++;
      }
    }
 
    // If Count of consecutive similar
    // type character is 0, then answer
    // is also 0.
    if (consecutiveCount == 0) {
      return 0;
    }
 
    // To find Minimum number of days
    // required to get required string.
    // We have to iterate the permutation
    // array P.
    for (int i = 0; i < N; i++) {
 
      // Now we check whether we can
      // change the string at s[p[i]].
 
      // Index to store the value of
      // permutation array, P[i].
      int index = P[i];
 
      // If we get two consecutive
      // similar character.
      if (index != 0
          && S.charAt(index) == S.charAt(index - 1)) {
 
        // Reduce the count of consecutive
        // similar character.
        consecutiveCount--;
      }
 
      // If we get two consecutive
      // similar character.
      if (index != N - 1
          && S.charAt(index) == S.charAt(index + 1)) {
 
        // Reduce the count of consecutive
        // similar character.
        consecutiveCount--;
      }
 
      // Update the string value
      // at the index.
      S = S.substring(0, index) + "?"
        + S.substring(index + 1);
 
      if (consecutiveCount == 0) {
 
        // If at ith day consecutiveCount
        // becomes 0 then, we should
        // return (i+1) as we have
        // taken 0 based indexing.
        return (i + 1);
      }
    }
 
    // If no such above case happened then
    // return -1 value,
    return -1;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int N = 4;
 
    String S = "aabb";
    int P[] = { 2, 1, 3, 0 };
 
    // Function Call
    System.out.println(minimumDays(N, S, P));
  }
}
 
// This code is contributed by lokeshpotta20.


Python3




# Python code for the above approach
 
#Function to solve the problem
def minimumDays(N, S, P):
     
    # consecutiveCount to store the
    # number of consecutive similar
    # type character.
    consecutiveCount = 0
     
    # Count the number of consecutive
    # similar type character.
    for i in range(1, N):
        if (S[i] == S[i - 1]):
            consecutiveCount += 1
     
    # If Count of consecutive similar
    # type character is 0, then answer
    # is also 0.
    if (consecutiveCount == 0):
        return 0
     
    # To find Minimum number of days
    # required to get required string.
    # We have to iterate the permutation
    # array P.
    for i in range(N):
     
        # Now we check whether we can
        # change the string at s[p[i]].
     
        # Index to store the value of
        # permutation array, P[i].
        index = P[i]
     
        # If we get two consecutive
        # similar character.
        if (index != 0 and S[index] == S[index - 1]):
     
            # Reduce the count of consecutive
            # similar character.
            consecutiveCount -= 1
     
        # If we get two consecutive
        # similar character.
        if (index != N - 1 and S[index] == S[index + 1]):
     
            # Reduce the count of consecutive
            # similar character.
            consecutiveCount -= 1
     
        # Update the string value
        # at the index.
        S = S[:index] + '?' + S[index+1:]
     
        if (consecutiveCount == 0):
     
            # If at ith day consecutiveCount
            # becomes 0 then, we should
            # return (i+1) as we have
            # taken 0 based indexing.
            return (i + 1)
     
    # If no such above case happened then
    # return -1 value,
    return -1
 
# Driver Code
N = 4
S = "aabb"
P = [2, 1, 3, 0]
 
# Function Call
print(minimumDays(N, S, P))
 
# This code is contributed by Prasad kandekar(prasad264)


C#




using System;
class GFG {
 
// Function to solve the problem
static int minimumDays(int N, string S, int[] P)
{
     
    // consecutiveCount to store the
    // number of consecutive similar
    // type character.
    int consecutiveCount = 0;
 
    // Count the number of consecutive
    // similar type character.
    for (int i = 1; i < N; i++) {
    if (S[i] == S[i-1]) {
        consecutiveCount++;
    }
    }
 
    // If Count of consecutive similar
    // type character is 0, then answer
    // is also 0.
    if (consecutiveCount == 0) {
    return 0;
    }
 
    // To find Minimum number of days
    // required to get required string.
    // We have to iterate the permutation
    // array P.
    for (int i = 0; i < N; i++) {
 
    // Now we check whether we can
    // change the string at s[p[i]].
 
    // Index to store the value of
    // permutation array, P[i].
    int index = P[i];
 
    // If we get two consecutive
    // similar character.
    if (index != 0
        && S[index] == S[index - 1]) {
 
        // Reduce the count of consecutive
        // similar character.
        consecutiveCount--;
    }
 
    // If we get two consecutive
    // similar character.
    if (index != N - 1
        && S[index] == S[index + 1]) {
 
        // Reduce the count of consecutive
        // similar character.
        consecutiveCount--;
    }
 
    // Update the string value
    // at the index.
    S = S.Substring(0, index) + "?"
        + S.Substring(index + 1);
 
    if (consecutiveCount == 0) {
 
        // If at ith day consecutiveCount
        // becomes 0 then, we should
        // return (i+1) as we have
        // taken 0 based indexing.
        return (i + 1);
    }
    }
 
    // If no such above case happened then
    // return -1 value,
    return -1;
}
 
// Driver Code
public static void Main()
{
    int N = 4;
 
    string S = "aabb";
    int []P = { 2, 1, 3, 0 };
 
    // Function Call
    Console.WriteLine(minimumDays(N, S, P));
}
}


Javascript




// Function to solve the problem
function minimumDays(N, S, P) {
 
// consecutiveCount to store the
// number of consecutive similar
// type character.
let consecutiveCount = 0;
 
// Count the number of consecutive
// similar type character.
for (let i = 1; i < N; i++) {
if (S[i] == S[i - 1]) {
consecutiveCount += 1;
}
}
 
// If Count of consecutive similar
// type character is 0, then answer
// is also 0.
if (consecutiveCount == 0) {
return 0;
}
 
// To find Minimum number of days
// required to get required string.
// We have to iterate the permutation
// array P.
for (let i = 0; i < N; i++) {
 
 
// Now we check whether we can
// change the string at s[p[i]].
 
// Index to store the value of
// permutation array, P[i].
let index = P[i];
 
// If we get two consecutive
// similar character.
if (index != 0 && S[index] == S[index - 1]) {
 
  // Reduce the count of consecutive
  // similar character.
  consecutiveCount -= 1;
}
 
// If we get two consecutive
// similar character.
if (index != N - 1 && S[index] == S[index + 1]) {
 
  // Reduce the count of consecutive
  // similar character.
  consecutiveCount -= 1;
}
 
// Update the string value
// at the index.
S = S.substring(0, index) + '?' + S.substring(index + 1);
 
if (consecutiveCount == 0) {
 
  // If at ith day consecutiveCount
  // becomes 0 then, we should
  // return (i+1) as we have
  // taken 0 based indexing.
  return (i + 1);
}
}
 
// If no such above case happened then
// return -1 value,
return -1;
}
 
// Driver Code
let N = 4;
let S = "aabb";
let P = [2, 1, 3, 0];
 
// Function Call
document.write(minimumDays(N, S, P));


Output

2





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

Method #2:Using Hashing

Count the number of consecutive identical characters in the given string S. If this count is zero, then the string already has all unique characters, and we can return 0 as the answer.

Iterate over the permutation array P and for each index i in P, perform the following steps:

a. Replace the character at the index P[i] in the string S with a ?.

b. If the resulting string has two consecutive identical characters, then remove one of them.

c. Decrement the count of consecutive identical characters, if necessary.

d. Check if the count of consecutive identical characters has become zero. If it has, then return the current day as the answer.

If none of the iterations in Step 2 result in a zero count of consecutive identical characters, then return -1 as the answer.

C++




#include <iostream>
#include <vector>
#include <unordered_map>
 
using namespace std;
 
int minimumDays(int n, string s, vector<int> p) {
    // Count the frequency of characters in the given string
    unordered_map<char, int> freq;
    for (char ch : s) {
        freq[ch]++;
    }
 
    // Check if all characters are unique in the string
    if (freq.size() == n) {
        return 0;
    }
 
    // Initialize variables for counting the minimum number of days required
    int days = 0;
    string current = s;
    int consecutive_count = 0;
    for (int i = 1; i < n; i++) {
        if (s[i] == s[i - 1]) {
            consecutive_count++;
        }
    }
 
    // Iterate over the permutation array and perform the operations
    for (int index : p) {
        // Check if we can change the character at index in the string
        if (index != 0 && s[index] == s[index - 1]) {
            consecutive_count--;
        }
        if (index != n - 1 && s[index] == s[index + 1]) {
            consecutive_count--;
        }
 
        // Update the string by replacing the character at index with '?'
        s[index] = '?';
 
        // Check if the string contains only unique characters after the update
        freq.clear();
        for (char ch : s) {
            freq[ch]++;
        }
        if (freq.size() == n) {
            return days + 1;
        }
 
        // Update the variables for counting the minimum number of days required
        days++;
        if (consecutive_count == 0) {
            return days;
        }
    }
 
    return -1;
}
 
int main() {
    int N = 4;
    string S = "aabb";
    vector<int> P = {2, 1, 3, 0};
 
    // Function Call
    cout << minimumDays(N, S, P) << endl;
 
    return 0;
}


Java




import java.util.HashMap;
 
public class Main {
 
    public static int minimumDays(int n, String s, int[] p) {
        // Count the frequency of characters in the given string
        HashMap<Character, Integer> freq = new HashMap<>();
        for (char ch : s.toCharArray()) {
            freq.put(ch, freq.getOrDefault(ch, 0) + 1);
        }
 
        // Check if all characters are unique in the string
        if (freq.size() == n) {
            return 0;
        }
 
        // Initialize variables for counting the minimum number of days required
        int days = 0;
        StringBuilder current = new StringBuilder(s);
        int consecutiveCount = 0;
        for (int i = 1; i < n; i++) {
            if (s.charAt(i) == s.charAt(i - 1)) {
                consecutiveCount++;
            }
        }
 
        // Iterate over the permutation array and perform the operations
        for (int index : p) {
            // Check if we can change the character at index in the string
            if (index != 0 && s.charAt(index) == s.charAt(index - 1)) {
                consecutiveCount--;
            }
            if (index != n - 1 && s.charAt(index) == s.charAt(index + 1)) {
                consecutiveCount--;
            }
 
            // Update the string by replacing the character at index with '?'
            current.setCharAt(index, '?');
            s = current.toString();
 
            // Check if the string contains only unique characters after the update
            freq.clear();
            for (char ch : s.toCharArray()) {
                freq.put(ch, freq.getOrDefault(ch, 0) + 1);
            }
            if (freq.size() == n) {
                return days + 1;
            }
 
            // Update the variables for counting the minimum number of days required
            days++;
            if (consecutiveCount == 0) {
                return days;
            }
        }
 
        return -1;
    }
 
    public static void main(String[] args) {
        int N = 4;
        String S = "aabb";
        int[] P = {2, 1, 3, 0};
 
        // Function Call
        System.out.println(minimumDays(N, S, P));
    }
}


Python3




def minimumDays(n, s, p):
    # Count the frequency of characters in the given string
    freq = {}
    for ch in s:
        freq[ch] = freq.get(ch, 0) + 1
 
    # Check if all characters are unique in the string
    if len(freq) == n:
        return 0
 
    # Initialize variables for counting the minimum number of days required
    days = 0
    current = s
    consecutive_count = sum(1 for i in range(1, n) if s[i] == s[i-1])
 
    # Iterate over the permutation array and perform the operations
    for index in p:
        # Check if we can change the character at index in the string
        if index != 0 and s[index] == s[index-1]:
            consecutive_count -= 1
        if index != n-1 and s[index] == s[index+1]:
            consecutive_count -= 1
 
        # Update the string by replacing the character at index with '?'
        s = s[:index] + '?' + s[index+1:]
 
        # Check if the string contains only unique characters after the update
        freq = {}
        for ch in s:
            freq[ch] = freq.get(ch, 0) + 1
        if len(freq) == n:
            return days+1
 
        # Update the variables for counting the minimum number of days required
        days += 1
        if consecutive_count == 0:
            return days
 
    return -1
 
 
# Driver Code
N = 4
S = "aabb"
P = [2, 1, 3, 0]
 
# Function Call
print(minimumDays(N, S, P))


C#




// C# code
using System;
using System.Collections.Generic;
 
public class MainClass
{
    public static int MinimumDays(int n, string s, int[] p)
    {
        // Count the frequency of characters in the given string
        Dictionary<char, int> freq = new Dictionary<char, int>();
        foreach (char ch in s)
        {
            if (freq.ContainsKey(ch))
            {
                freq[ch]++;
            }
            else
            {
                freq[ch] = 1;
            }
        }
 
        // Check if all characters are unique in the string
        if (freq.Count == n)
        {
            return 0;
        }
 
        // Initialize variables for counting the minimum number of days required
        int days = 0;
        char[] current = s.ToCharArray();
        int consecutiveCount = 0;
        for (int i = 1; i < n; i++)
        {
            if (s[i] == s[i - 1])
            {
                consecutiveCount++;
            }
        }
 
        // Iterate over the permutation array and perform the operations
        foreach (int index in p)
        {
            // Check if we can change the character at index in the string
            if (index != 0 && s[index] == s[index - 1])
            {
                consecutiveCount--;
            }
            if (index != n - 1 && s[index] == s[index + 1])
            {
                consecutiveCount--;
            }
 
            // Update the string by replacing the character at index with '?'
            current[index] = '?';
            s = new string(current);
 
            // Check if the string contains only unique characters after the update
            freq.Clear();
            foreach (char ch in s)
            {
                if (freq.ContainsKey(ch))
                {
                    freq[ch]++;
                }
                else
                {
                    freq[ch] = 1;
                }
            }
            if (freq.Count == n)
            {
                return days + 1;
            }
 
            // Update the variables for counting the minimum number of days required
            days++;
            if (consecutiveCount == 0)
            {
                return days;
            }
        }
 
        return -1;
    }
 
    public static void Main(string[] args)
    {
        int N = 4;
        string S = "aabb";
        int[] P = { 2, 1, 3, 0 };
 
        // Function Call
        Console.WriteLine(MinimumDays(N, S, P));
    }
}


Javascript




function minimumDays(n, s, p) {
 
    //  Count the frequency of characters in the given string
    let freq = {};
    for (let ch of s) {
        freq[ch] = (freq[ch] || 0) + 1;
    }
     
    // Check if all characters are unique in the string
    if (Object.keys(freq).length === n) {
        return 0;
    }
     
     
    // Initialize variables for counting the minimum number of days required
    let days = 0;
    let current = s;
    let consecutive_count = [...Array(n-1).keys()].reduce((count, i) => count + (s[i] === s[i+1] ? 1 : 0), 0);
     
    // Iterate over the permutation array and perform the operations
    for (let index of p) {
     
        // Check if we can change the character at index in the string
        if (index !== 0 && s[index] === s[index-1]) {
            consecutive_count -= 1;
        }
        if (index !== n-1 && s[index] === s[index+1]) {
            consecutive_count -= 1;
        }
         
        // Update the string by replacing the character at index with '?'
        s = s.slice(0, index) + '?' + s.slice(index+1);
         
        // Check if the string contains only unique characters after the update
        freq = {};
        for (let ch of s) {
            freq[ch] = (freq[ch] || 0) + 1;
        }
        if (Object.keys(freq).length === n) {
            return days+1;
        }
         
        // Update the variables for counting the minimum number of days required
        days += 1;
        if (consecutive_count === 0) {
            return days;
        }
    }
    return -1;
}
// Driver code
const N = 4;
const S = "aabb";
const P = [2, 1, 3, 0];
 
console.log(minimumDays(N, S, P));


Output

2





Time Complexity: O(N^2 * len(S)) and an auxiliary space of O(N * len(S))



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads