Skip to content
Related Articles

Related Articles

Print a closest string that does not contain adjacent duplicates
  • Difficulty Level : Easy
  • Last Updated : 26 Jul, 2018

Given a string S, change the smallest number of letters in S such that all adjacent characters are different. Print the resultant string.

Examples :

Input : S = "aab"
Output: acb
Explanation :
Loop will start for i-th character, which 
is second ‘a’. It’s cannot be ‘b’ since it 
matches with third char. So output should
be ‘acb’.

Input : S = "geeksforgeeks"
Output: geaksforgeaks
Explanation :
Resultant string, after making minimal 
changes. S = "geaksforgeaks". We made two 
changes, which is the optimal solution here.

We can solve this problem using greedy approach. Let us consider a segment of length k of consecutive identical characters. We have to make at least [K/2] changes in the segment, to make that there are no identical characters in a row. We can also change the second, fourth etc.. characters of the string that is it should not be equal to the letter on the left side and the letter to the right side.

Traverse the string from starting index (i = 1) and if any two adjacent letters( i & i-1) are equal then initialize (i)th character with ‘a’ and start another loop to make (i)th character different from the left and right letters.



Below is the implementation of above approach :

C++




// C++ program to print a string with no adjacent
// duplicates by doing  minimum changes to original
// string
#include <bits/stdc++.h>
using namespace std;
  
// Function to print simple string
string noAdjacentDup(string s)
{
    int n = s.length();
    for (int i = 1; i < n; i++) 
    {
        // If any two adjacent characters are equal
        if (s[i] == s[i - 1]) 
        {
            s[i] = 'a'; // Initialize it to 'a'
  
            // Traverse the loop until it is different
            // from the left and right letter.
            while (s[i] == s[i - 1] || 
                (i + 1 < n && s[i] == s[i + 1]))             
                s[i]++;
              
            i++; 
        }
    }
    return s;
}
  
// Driver Function
int main()
{
    string s = "geeksforgeeks";
    cout << noAdjacentDup(s);
    return 0;
}

Java




// Java program to print a string with
// no adjacent duplicates by doing 
// minimum changes to original string
import java.util.*;
import java.lang.*;
  
public class GfG{
      
    // Function to print simple string
    public static String noAdjacentDup(String s1)
    {
        int n = s1.length();
        char[] s = s1.toCharArray();
        for (int i = 1; i < n; i++) 
        {
            // If any two adjacent 
            // characters are equal
            if (s[i] == s[i - 1]) 
            {
                // Initialize it to 'a'
                s[i] = 'a'
                  
                // Traverse the loop until it  
                // is different from the left
                // and right letter.
                while (s[i] == s[i - 1] || 
                    (i + 1 < n && s[i] == s[i + 1]))             
                    s[i]++;
              
                i++; 
            }
        }
        return (new String(s));
    }
      
    // Driver function
    public static void main(String argc[]){
  
        String s = "geeksforgeeks";
        System.out.println(noAdjacentDup(s));
          
    }
      
}
  
/* This code is contributed by Sagar Shukla */

Python3




# Python program to print a string with
# no adjacent duplicates by doing minimum 
# changes to original string
  
# Function to print simple string
def noAdjacentDup(s):
  
    n = len(s)
    for i in range(1, n): 
      
        # If any two adjacent characters are equal
        if (s[i] == s[i - 1]): 
          
            s[i] = "a" # Initialize it to 'a'
  
            # Traverse the loop until it is different
            # from the left and right letter.
            while (s[i] == s[i - 1] or
                (i + 1 < n and s[i] == s[i + 1])):             
                s[i] += 1
              
            i += 1
          
    return s
  
# Driver Function
s = list("geeksforgeeks")
print("".join(noAdjacentDup(s)))
  
# This code is contributed by Anant Agarwal.

C#




// C# program to print a string with
// no adjacent duplicates by doing 
// minimum changes to original string
using System;
  
class GfG{
      
    // Function to print simple string
    public static String noAdjacentDup(String s1)
    {
        int n = s1.Length;
          
        char[] s = s1.ToCharArray();
        for (int i = 1; i < n; i++) 
        {
            // If any two adjacent 
            // characters are equal
            if (s[i] == s[i - 1]) 
            {
                // Initialize it to 'a'
                s[i] = 'a'
                  
                // Traverse the loop until it 
                // is different from the left
                // and right letter.
                while (s[i] == s[i - 1] || 
                      (i + 1 < n && s[i] == s[i + 1]))             
                 s[i]++;
              
                i++; 
            }
        }
        return (new String(s));
    }
      
    // Driver function
    public static void Main(String[] argc)
    {
        String s = "geeksforgeeks";
          
        // Function calling
        Console.Write(noAdjacentDup(s));
    }
}
  
/* This code is contributed by parashar */

PHP




<?php
// PHP program to print a 
// string with no adjacent
// duplicates by doing minimum 
// changes to original string
  
// Function to print
// simple string
function noAdjacentDup($s)
{
    $n = strlen($s);
    for ($i = 1; $i < $n; $i++) 
    {
        // If any two adjacent
        // characters are equal
        if ($s[$i] == $s[$i - 1]) 
        {
            // Initialize it to 'a'
            $s[$i] = 'a'
  
            // Traverse the loop 
            // until it is different
            // from the left and
            // right letter.
            while ($s[$i] == $s[$i - 1] || 
                  ($i + 1 < $n && 
                   $s[$i] == $s[$i + 1]))             
                $s[$i]++;
              
            $i++; 
        }
    }
    return $s;
}
  
// Driver Code
$s = "geeksforgeeks";
echo (noAdjacentDup($s));
  
// This code is contributed by 
// Manish Shaw(manishshaw1)
?>

Output :

geaksforgeaks

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 Articles
Page :