Minimum days to achieve the String
Last Updated :
19 Oct, 2023
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++
#include <bits/stdc++.h>
using namespace std;
int minimumDays( int N, string S, int P[])
{
int consecutiveCount = 0;
for ( int i = 1; i < N; i++) {
if (S[i] == S[i - 1]) {
consecutiveCount++;
}
}
if (consecutiveCount == 0) {
return 0;
}
for ( int i = 0; i < N; i++) {
int index = P[i];
if (index != 0 && S[index] == S[index - 1]) {
consecutiveCount--;
}
if (index != N - 1 && S[index] == S[index + 1]) {
consecutiveCount--;
}
S[index] = '?' ;
if (consecutiveCount == 0) {
return (i + 1);
}
}
return -1;
}
int main()
{
int N = 4;
string S = "aabb" ;
int P[] = { 2, 1, 3, 0 };
cout << minimumDays(N, S, P) << endl;
return 0;
}
|
C
#include <stdio.h>
#include <string.h>
int minimumDays( int N, char S[], int P[])
{
int consecutiveCount = 0;
for ( int i = 1; i < N; i++) {
if (S[i] == S[i - 1]) {
consecutiveCount++;
}
}
if (consecutiveCount == 0) {
return 0;
}
for ( int i = 0; i < N; i++) {
int index = P[i];
if (index != 0 && S[index] == S[index - 1]) {
consecutiveCount--;
}
if (index != N - 1 && S[index] == S[index + 1]) {
consecutiveCount--;
}
S[index] = '?' ;
if (consecutiveCount == 0) {
return (i + 1);
}
}
return -1;
}
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 {
static int minimumDays( int N, String S, int P[])
{
int consecutiveCount = 0 ;
for ( int i = 1 ; i < N; i++) {
if (S.charAt(i) == S.charAt(i - 1 )) {
consecutiveCount++;
}
}
if (consecutiveCount == 0 ) {
return 0 ;
}
for ( int i = 0 ; i < N; i++) {
int index = P[i];
if (index != 0
&& S.charAt(index) == S.charAt(index - 1 )) {
consecutiveCount--;
}
if (index != N - 1
&& S.charAt(index) == S.charAt(index + 1 )) {
consecutiveCount--;
}
S = S.substring( 0 , index) + "?"
+ S.substring(index + 1 );
if (consecutiveCount == 0 ) {
return (i + 1 );
}
}
return - 1 ;
}
public static void main(String[] args)
{
int N = 4 ;
String S = "aabb" ;
int P[] = { 2 , 1 , 3 , 0 };
System.out.println(minimumDays(N, S, P));
}
}
|
Python3
def minimumDays(N, S, P):
consecutiveCount = 0
for i in range ( 1 , N):
if (S[i] = = S[i - 1 ]):
consecutiveCount + = 1
if (consecutiveCount = = 0 ):
return 0
for i in range (N):
index = P[i]
if (index ! = 0 and S[index] = = S[index - 1 ]):
consecutiveCount - = 1
if (index ! = N - 1 and S[index] = = S[index + 1 ]):
consecutiveCount - = 1
S = S[:index] + '?' + S[index + 1 :]
if (consecutiveCount = = 0 ):
return (i + 1 )
return - 1
N = 4
S = "aabb"
P = [ 2 , 1 , 3 , 0 ]
print (minimumDays(N, S, P))
|
C#
using System;
class GFG {
static int minimumDays( int N, string S, int [] P)
{
int consecutiveCount = 0;
for ( int i = 1; i < N; i++) {
if (S[i] == S[i-1]) {
consecutiveCount++;
}
}
if (consecutiveCount == 0) {
return 0;
}
for ( int i = 0; i < N; i++) {
int index = P[i];
if (index != 0
&& S[index] == S[index - 1]) {
consecutiveCount--;
}
if (index != N - 1
&& S[index] == S[index + 1]) {
consecutiveCount--;
}
S = S.Substring(0, index) + "?"
+ S.Substring(index + 1);
if (consecutiveCount == 0) {
return (i + 1);
}
}
return -1;
}
public static void Main()
{
int N = 4;
string S = "aabb" ;
int []P = { 2, 1, 3, 0 };
Console.WriteLine(minimumDays(N, S, P));
}
}
|
Javascript
function minimumDays(N, S, P) {
let consecutiveCount = 0;
for (let i = 1; i < N; i++) {
if (S[i] == S[i - 1]) {
consecutiveCount += 1;
}
}
if (consecutiveCount == 0) {
return 0;
}
for (let i = 0; i < N; i++) {
let index = P[i];
if (index != 0 && S[index] == S[index - 1]) {
consecutiveCount -= 1;
}
if (index != N - 1 && S[index] == S[index + 1]) {
consecutiveCount -= 1;
}
S = S.substring(0, index) + '?' + S.substring(index + 1);
if (consecutiveCount == 0) {
return (i + 1);
}
}
return -1;
}
let N = 4;
let S = "aabb" ;
let P = [2, 1, 3, 0];
document.write(minimumDays(N, S, P));
|
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) {
unordered_map< char , int > freq;
for ( char ch : s) {
freq[ch]++;
}
if (freq.size() == n) {
return 0;
}
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++;
}
}
for ( int index : p) {
if (index != 0 && s[index] == s[index - 1]) {
consecutive_count--;
}
if (index != n - 1 && s[index] == s[index + 1]) {
consecutive_count--;
}
s[index] = '?' ;
freq.clear();
for ( char ch : s) {
freq[ch]++;
}
if (freq.size() == n) {
return days + 1;
}
days++;
if (consecutive_count == 0) {
return days;
}
}
return -1;
}
int main() {
int N = 4;
string S = "aabb" ;
vector< int > P = {2, 1, 3, 0};
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) {
HashMap<Character, Integer> freq = new HashMap<>();
for ( char ch : s.toCharArray()) {
freq.put(ch, freq.getOrDefault(ch, 0 ) + 1 );
}
if (freq.size() == n) {
return 0 ;
}
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++;
}
}
for ( int index : p) {
if (index != 0 && s.charAt(index) == s.charAt(index - 1 )) {
consecutiveCount--;
}
if (index != n - 1 && s.charAt(index) == s.charAt(index + 1 )) {
consecutiveCount--;
}
current.setCharAt(index, '?' );
s = current.toString();
freq.clear();
for ( char ch : s.toCharArray()) {
freq.put(ch, freq.getOrDefault(ch, 0 ) + 1 );
}
if (freq.size() == n) {
return days + 1 ;
}
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 };
System.out.println(minimumDays(N, S, P));
}
}
|
Python3
def minimumDays(n, s, p):
freq = {}
for ch in s:
freq[ch] = freq.get(ch, 0 ) + 1
if len (freq) = = n:
return 0
days = 0
current = s
consecutive_count = sum ( 1 for i in range ( 1 , n) if s[i] = = s[i - 1 ])
for index in p:
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
s = s[:index] + '?' + s[index + 1 :]
freq = {}
for ch in s:
freq[ch] = freq.get(ch, 0 ) + 1
if len (freq) = = n:
return days + 1
days + = 1
if consecutive_count = = 0 :
return days
return - 1
N = 4
S = "aabb"
P = [ 2 , 1 , 3 , 0 ]
print (minimumDays(N, S, P))
|
C#
using System;
using System.Collections.Generic;
public class MainClass
{
public static int MinimumDays( int n, string s, int [] p)
{
Dictionary< char , int > freq = new Dictionary< char , int >();
foreach ( char ch in s)
{
if (freq.ContainsKey(ch))
{
freq[ch]++;
}
else
{
freq[ch] = 1;
}
}
if (freq.Count == n)
{
return 0;
}
int days = 0;
char [] current = s.ToCharArray();
int consecutiveCount = 0;
for ( int i = 1; i < n; i++)
{
if (s[i] == s[i - 1])
{
consecutiveCount++;
}
}
foreach ( int index in p)
{
if (index != 0 && s[index] == s[index - 1])
{
consecutiveCount--;
}
if (index != n - 1 && s[index] == s[index + 1])
{
consecutiveCount--;
}
current[index] = '?' ;
s = new string (current);
freq.Clear();
foreach ( char ch in s)
{
if (freq.ContainsKey(ch))
{
freq[ch]++;
}
else
{
freq[ch] = 1;
}
}
if (freq.Count == n)
{
return days + 1;
}
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 };
Console.WriteLine(MinimumDays(N, S, P));
}
}
|
Javascript
function minimumDays(n, s, p) {
let freq = {};
for (let ch of s) {
freq[ch] = (freq[ch] || 0) + 1;
}
if (Object.keys(freq).length === n) {
return 0;
}
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);
for (let index of p) {
if (index !== 0 && s[index] === s[index-1]) {
consecutive_count -= 1;
}
if (index !== n-1 && s[index] === s[index+1]) {
consecutive_count -= 1;
}
s = s.slice(0, index) + '?' + s.slice(index+1);
freq = {};
for (let ch of s) {
freq[ch] = (freq[ch] || 0) + 1;
}
if (Object.keys(freq).length === n) {
return days+1;
}
days += 1;
if (consecutive_count === 0) {
return days;
}
}
return -1;
}
const N = 4;
const S = "aabb" ;
const P = [2, 1, 3, 0];
console.log(minimumDays(N, S, P));
|
Time Complexity: O(N^2 * len(S)) and an auxiliary space of O(N * len(S))
Share your thoughts in the comments
Please Login to comment...