Monday, November 25, 2024
Google search engine
HomeData Modelling & AIShortest string possible after removal of all pairs of similar adjacent characters

Shortest string possible after removal of all pairs of similar adjacent characters

Given a string S, the task is to find the resultant smallest string possible, formed by repeatedly removing pairs of adjacent characters which are equal.

Examples:

Input: S = “aaabccddd”
Output: abd
Explanation: Following sequence of removal of pairs of adjacent characters minimizes the length of the string: 
aaabccddd ? abccddd ? abddd ? abd.

Input: S = aa
Output: Empty String
Explanation: Following sequence of removal of pairs of adjacent characters minimizes the length of the string: 
aa ? “”.

Approach: The main idea to solve the given problem is to recursively delete all pairs of adjacent characters which are equal, one by one. Follow the steps to solve the given problem:

  • Initialize an empty string, say ans, to store the string of minimum length after deleting all pairs of equal adjacent characters.
  • Initialize a string, say pre, to store the updated string after every removal of equal adjacent characters.
  • Now, iterate until the string ans and pre are unequal and perform the following steps:
    • Update the value of the string ans by removing the first adjacent same character using the function removeAdjacent().
    • If the value of the string ans is the same as the string pre, then break out of the loop. Otherwise, update the value of string pre as the string ans.
  • After completing the above steps, print the string ans as the resultant string.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to delete pair of adjacent
// characters which are equal
string removeAdjacent(string s)
{
     
    // Base Case
    if (s.length() == 1)
        return s;
 
    // Stores the update string
    string sb = "";
 
    // Traverse the string s
    for(int i = 0; i < s.length() - 1; i++)
    {
        char c = s[i];
        char d = s[i + 1];
 
        // If two unequal pair of
        // adjacent characters are found
        if (c != d)
        {
            sb = sb + c;
 
            if (i == s.length() - 2)
            {
                sb = sb + d;
            }
        }
 
        // If two equal pair of adjacent
        // characters are found
        else
        {
            for(int j = i + 2;
                    j < s.length(); j++)
 
                // Append the remaining string
                // after removing the pair
                sb = sb + s[j];
 
            return sb;
        }
    }
 
    // Return the final String
    return sb;
}
 
// Function to find the shortest string
// after repeatedly removing pairs of
// adjacent characters which are equal
void reduceString(string s)
{
     
    // Stores the resultant String
    string result = "";
 
    // Keeps track of previously
    // iterated string
    string pre = s;
 
    while (true)
    {
         
        // Update the result after
        // deleting adjacent pair of
        // characters which are similar
        result = removeAdjacent(pre);
 
        // Termination Conditions
        if (result == pre)
            break;
 
        // Update pre variable with
        // the value of result
        pre = result;
    }
 
    if (result.length() != 0)
        cout << (result) << endl;
 
    // Case for "Empty String"
    else
        cout << "Empty String" << endl;
}
 
// Driver code   
int main()
{
    string S = "aaabccddd";
     
    reduceString(S);
     
    return 0;
}
 
// This code is contributed by divyesh072019


Java




// Java program for the above approach
 
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
    // Function to delete pair of adjacent
    // characters which are equal
    static String removeAdjacent(String s)
    {
        // Base Case
        if (s.length() == 1)
            return s;
 
        // Stores the update string
        StringBuilder sb = new StringBuilder("");
 
        // Traverse the string s
        for (int i = 0;
             i < s.length() - 1; i++) {
            char c = s.charAt(i);
            char d = s.charAt(i + 1);
 
            // If two unequal pair of
            // adjacent characters are found
            if (c != d) {
                sb.append(c);
 
                if (i == s.length() - 2) {
                    sb.append(d);
                }
            }
 
            // If two equal pair of adjacent
            // characters are found
            else {
                for (int j = i + 2;
                     j < s.length(); j++)
 
                    // Append the remaining string
                    // after removing the pair
                    sb.append(s.charAt(j));
 
                return sb.toString();
            }
        }
 
        // Return the final String
        return sb.toString();
    }
 
    // Function to find the shortest string
    // after repeatedly removing pairs of
    // adjacent characters which are equal
    public static void reduceString(String s)
    {
        // Stores the resultant String
        String result = "";
 
        // Keeps track of previously
        // iterated string
        String pre = s;
 
        while (true) {
            // Update the result after
            // deleting adjacent pair of
            // characters which are similar
            result = removeAdjacent(pre);
 
            // Termination Conditions
            if (result.equals(pre))
                break;
 
            // Update pre variable with
            // the value of result
            pre = result;
        }
 
        if (result.length() != 0)
            System.out.println(result);
 
        // Case for "Empty String"
        else
            System.out.println("Empty String");
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String S = "aaabccddd";
        reduceString(S);
    }
}


Python3




# Python program for the above approach
 
# Function to delete pair of adjacent
# characters which are equal
def removeAdjacent(s):
     
    # Base Case
    if (len(s) == 1):
        return s
 
    # Stores the update string
    sb = ""
 
    # Traverse the string s
    for i in range(len(s)-1):
        c = s[i]
        d = s[i + 1]
 
        # If two unequal pair of
        # adjacent characters are found
        if (c != d):
            sb = sb + c
 
            if (i == len(s) - 2):
                sb = sb + d
 
        # If two equal pair of adjacent
        # characters are found
        else:
            for j in range(i + 2,len(s)):
 
                # Append the remaining string
                # after removing the pair
                sb = sb + s[j]
 
            return sb
 
    # Return the final String
    return sb
 
# Function to find the shortest string
# after repeatedly removing pairs of
# adjacent characters which are equal
def reduceString(s):
     
    # Stores the resultant String
    result = ""
 
    # Keeps track of previously
    # iterated string
    pre = s
 
    while True:
         
        # Update the result after
        # deleting adjacent pair of
        # characters which are similar
        result = removeAdjacent(pre)
 
        # Termination Conditions
        if (result == pre):
            break
 
        # Update pre variable with
        # the value of result
        pre = result
 
    if (len(result)!= 0):
        print(result)
 
    # Case for "Empty String"
    else:
        print("Empty String")
 
# Driver code
S = "aaabccddd"
reduceString(S)
     
# This code is contributed by shinjanpatra


C#




// C# program for the above approach
using System;
class GFG {
     
    // Function to delete pair of adjacent
    // characters which are equal
    static string removeAdjacent(string s)
    {
          
        // Base Case
        if (s.Length == 1)
            return s;
      
        // Stores the update string
        string sb = "";
      
        // Traverse the string s
        for(int i = 0; i < s.Length - 1; i++)
        {
            char c = s[i];
            char d = s[i + 1];
      
            // If two unequal pair of
            // adjacent characters are found
            if (c != d)
            {
                sb = sb + c;
      
                if (i == s.Length - 2)
                {
                    sb = sb + d;
                }
            }
      
            // If two equal pair of adjacent
            // characters are found
            else
            {
                for(int j = i + 2;
                        j < s.Length; j++)
      
                    // Append the remaining string
                    // after removing the pair
                    sb = sb + s[j];
      
                return sb;
            }
        }
      
        // Return the final String
        return sb;
    }
      
    // Function to find the shortest string
    // after repeatedly removing pairs of
    // adjacent characters which are equal
    static void reduceString(string s)
    {
          
        // Stores the resultant String
        string result = "";
      
        // Keeps track of previously
        // iterated string
        string pre = s;
      
        while (true)
        {
              
            // Update the result after
            // deleting adjacent pair of
            // characters which are similar
            result = removeAdjacent(pre);
      
            // Termination Conditions
            if (result == pre)
                break;
      
            // Update pre variable with
            // the value of result
            pre = result;
        }
      
        if (result.Length != 0)
            Console.WriteLine(result);
      
        // Case for "Empty String"
        else
            Console.WriteLine("Empty String");
    }
 
  static void Main() {
    string S = "aaabccddd";
      
    reduceString(S);
  }
}


Javascript




<script>
    // Javascript program for the above approach
     
    // Function to delete pair of adjacent
    // characters which are equal
    function removeAdjacent(s)
    {
           
        // Base Case
        if (s.length == 1)
            return s;
       
        // Stores the update string
        let sb = "";
       
        // Traverse the string s
        for(let i = 0; i < s.length - 1; i++)
        {
            let c = s[i];
            let d = s[i + 1];
       
            // If two unequal pair of
            // adjacent characters are found
            if (c != d)
            {
                sb = sb + c;
       
                if (i == s.length - 2)
                {
                    sb = sb + d;
                }
            }
       
            // If two equal pair of adjacent
            // characters are found
            else
            {
                for(let j = i + 2; j < s.length; j++)
       
                    // Append the remaining string
                    // after removing the pair
                    sb = sb + s[j];
       
                return sb;
            }
        }
       
        // Return the final String
        return sb;
    }
       
    // Function to find the shortest string
    // after repeatedly removing pairs of
    // adjacent characters which are equal
    function reduceString(s)
    {
           
        // Stores the resultant String
        let result = "";
       
        // Keeps track of previously
        // iterated string
        let pre = s;
       
        while (true)
        {
               
            // Update the result after
            // deleting adjacent pair of
            // characters which are similar
            result = removeAdjacent(pre);
       
            // Termination Conditions
            if (result == pre)
                break;
       
            // Update pre variable with
            // the value of result
            pre = result;
        }
       
        if (result.length != 0)
            document.write(result);
       
        // Case for "Empty String"
        else
            document.write("Empty String");
    }
     
    let S = "aaabccddd";
       
    reduceString(S);
   
  // This code is contributed by suresh07
</script>


Output: 

abd

 

Time Complexity: O(N2)
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!

RELATED ARTICLES

Most Popular

Recent Comments