Open In App

Remove all duplicate adjacent characters from a string using Stack

Last Updated : 01 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// 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


Java




// 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


Python3




# 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))


C#




// 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


Javascript




<script>
 
// JavaScript program to implement
// the above approach
 
// Function to remove adjacent
// duplicate elements
function ShortenString(str1)
{
     
    // Store the string without
    // duplicate elements
    var st = [];
     
    // Store the index of str
    var 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.length==0 || str1[i] != st[st.length-1])
        {
            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.length==0)
    {
        return ("Empty String");
    }
         
    // If stack is not Empty
    else
    {
        var short_string = "";
        while(st.length!=0)
        {
            short_string = st[st.length-1] +
                           short_string;
            st.pop();
        }
        return (short_string);
    }
}
 
// Driver Code
var str1 ="azzxzy";
document.write( ShortenString(str1));
 
 
 
</script>


Output: 

axzy

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads