Remove all duplicate adjacent characters from a string using Stack

Given a string, str, the task is to remove all the duplicate adjacent characters from the given string.

Examples:

Input: str= “azxxzy”
Output: ay 
Removal of “xx” modifies the string to “azzy”. 
Now, the removal of “zz” modifies the string to “ay”. 
Since the string “ay” doesn’t contain duplicates, the output is ay.

Input: “aaccdd”
Output: Empty String

Recursive Approach: Refer to the article Recursively remove all adjacent duplicates to solve this problem recursively. 
Time Complexity: O(N)
Auxiliary Space: O(N)

String Functions-based Approach: Refer to this article Remove first adjacent pairs of similar characters until possible to solve this problem using inbuilt functions pop_back() and back() methods of string.  

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



Stack-based Approach: The problem can be solved using Stack to use the property of LIFO. The idea is to traverse the string from left to right and check if the stack is empty or the top element of the stack is not equal to the current character of str, then push the current character into the stack. Otherwise, pop the element from the top of the stack. Follow the steps below to solve the problem: 

  1. Create a stack, st to remove the adjacent duplicate characters in str.
  2. Traverse the string str and check if the stack is empty or the top element of the stack not equal to the current character. If found to be true, push the current character into st.
  3. Otherwise, pop the element from the top of the stack.
  4. Finally, print all the remaining elements of the stack.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement 
// the above approach 
#include <bits/stdc++.h>
using namespace std;
  
// Function to remove adjacent 
// duplicate elements 
string ShortenString(string str1)
{
      
    // Store the string without 
    // duplicate elements 
    stack<char> st; 
      
    // Store the index of str 
    int i = 0;
      
    // Traverse the string str
    while (i < str1.length())
    {
          
        // Checks if stack is empty or top of the 
        // stack is not equal to current character 
        if (st.empty() || str1[i] != st.top())
        {
            st.push(str1[i]);
            i++;
        }
              
        // If top element of the stack is 
        // equal to the current character 
        else
        {
            st.pop(); 
            i++;
        
    }
      
    // If stack is empty 
    if (st.empty())
    {
        return ("Empty String");
    }
          
    // If stack is not Empty 
    else
    {
        string short_string = ""
        while (!st.empty())
        {
            short_string = st.top() + 
                           short_string;
            st.pop();
        }
        return (short_string);
    }
}
  
// Driver Code
int main()
{
    string str1 ="azzxzy";
      
    cout << ShortenString(str1); 
  
    return 0;
}
  
// This code is contributed by divyeshrabadiya07

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement 
// the above approach 
import java.util.*;
class GFG{
  
// Function to remove adjacent 
// duplicate elements 
static String ShortenString(String str1)
{
  // Store the String without 
  // duplicate elements 
  Stack<Character> st = 
        new Stack<Character>(); 
  
  // Store the index of str 
  int i = 0;
  
  // Traverse the String str
  while (i < str1.length())
  {
    // Checks if stack is empty 
    // or top of the stack is not
    // equal to current character 
    if (st.isEmpty() || 
        str1.charAt(i) != st.peek())
    {
      st.add(str1.charAt(i));
      i++;
    }
  
    // If top element of the stack is 
    // equal to the current character 
    else
    {
      st.pop(); 
      i++;
    
  }
  
  // If stack is empty 
  if (st.isEmpty())
  {
    return ("Empty String");
  }
  
  // If stack is not Empty 
  else
  {
    String short_String = ""
    while (!st.isEmpty())
    {
      short_String = st.peek() + 
                     short_String;
      st.pop();
    }
    return (short_String);
  }
}
  
// Driver Code
public static void main(String[] args)
{
  String str1 ="azzxzy";
  System.out.print(ShortenString(str1)); 
  
}
}
  
// This code is contributed by Rajput-Ji

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
  
# Function to remove adjacent
# duplicate elements
def ShortenString(str1):
      
    # Store the string without 
    # duplicate elements
    st = []
      
    # Store the index of str
    i = 0
      
    # Traverse the string str
    while i < len(str1):
          
        # Checks if stack is empty or top of the
        # stack is not equal to current character
        if len(st)== 0 or str1[i] != st[-1]:
            st.append(str1[i])
            i += 1
              
        # If top element of the stack is 
        # equal to the current character
        else:
            st.pop()
            i += 1
              
    # If stack is empty
    if len(st)== 0:
        return("Empty String")
          
    # If stack is not Empty
    else:
        short_string = ""
        for i in st:
            short_string += str(i)
        return(short_string)
        
# Driver Code
if __name__ == "__main__"
    str1 ="azzxzy"
    print(ShortenString(str1))

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement 
// the above approach 
using System;
using System.Collections.Generic;
  
class GFG{
  
// Function to remove adjacent 
// duplicate elements 
static String ShortenString(String str1)
{
      
    // Store the String without 
    // duplicate elements 
    Stack<char> st = new Stack<char>(); 
      
    // Store the index of str 
    int i = 0;
      
    // Traverse the String str
    while (i < str1.Length)
    {
          
        // Checks if stack is empty 
        // or top of the stack is not
        // equal to current character 
        if (st.Count == 0 || (st.Count != 0 &&
             str1[i] != st.Peek()))
        {
            st.Push(str1[i]);
            i++;
        }
      
        // If top element of the stack is 
        // equal to the current character 
        else
        {
            if (st.Count != 0)
                st.Pop(); 
                  
            i++;
        
    }
      
    // If stack is empty 
    if (st.Count == 0)
    {
        return ("Empty String");
    }
      
    // If stack is not Empty 
    else
    {
        String short_String = ""
          
        while (st.Count != 0)
        {
            short_String = st.Peek() + 
                           short_String;
            st.Pop();
        }
        return (short_String);
    }
}
  
// Driver Code
public static void Main(String[] args)
{
    String str1 ="azzxzy";
      
    Console.Write(ShortenString(str1)); 
}
}
  
// This code is contributed by Amit Katiyar

chevron_right


Output: 

axzy

Time Complexity: O(N)
Auxilairy 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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.