The Wayback Machine - https://web.archive.org/web/20210227015101/https://www.geeksforgeeks.org/shortest-string-possible-after-removal-of-all-pairs-of-similar-adjacent-characters/
Skip to content
Related Articles

Related Articles

Shortest string possible after removal of all pairs of similar adjacent characters
  • Difficulty Level : Medium
  • Last Updated : 26 Feb, 2021

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:

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);
    }
}


Output:

abd

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

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 :