Remove all duplicate adjacent characters from a string using Stack
Last Updated :
01 Sep, 2021
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:
- Create a stack, st to remove the adjacent duplicate characters in str.
- 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.
- Otherwise, pop the element from the top of the stack.
- 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>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Remove all occurrences of a character from a string using STL Given a string S and a character C, the task is to remove all the occurrences of the character C from the given string. Examples: Input:vS = "GFG IS FUN", C = 'F' Output:GG IS UN Explanation: Removing all occurrences of the character 'F' modifies S to "GG IS UN". Therefore, the required output is GG
2 min read
Character replacement after removing duplicates from a string Given a string. The task is to replace each character of the minimized string with a character present at the index 'IND' of the original string. The minimized string is the string obtained by removing all duplicates from the original string keeping the order of elements the same. IND for any index
7 min read
Remove All Adjacent Duplicates in String II Given a string s and an integer k, the task is to repeatedly delete k adjacent duplicates till no deletions are possible and then return the final string. On deletion of k adjacent duplicates, the left and right sides of the deleted substring is concatenated together. Examples: Input: s = "abcd", k
3 min read
Print all the duplicate characters in a string Given a string s, the task is to identify all characters that appear more than once and print each as a list containing the character and its count. Examples:Input: s = "geeksforgeeks"Output: ['e', 4], ['g', 2], ['k', 2], ['s', 2]Explanation: Characters e, g, k, and s appear more than once. Their co
8 min read
Remove all consecutive duplicates from the string Given a string s , The task is to remove all the consecutive duplicate characters of the string and return the resultant string. Examples: Input: s = "aaaaabbbbbb"Output: abExplanation: Remove consecutive duplicate characters from a string s such as 5 a's are at consecative so only write a and same
10 min read
Replace '?' in a string such that no two adjacent characters are same Given a string S of length N consisting of "?" and lowercase letters, the task is to replace "?" with lowercase letters such that no adjacent characters are the same. If more than one possible combination exists, print any one of them. Examples: Input: S = "?a?a"Output: babaExplanation:Replacing all
9 min read
Find the duplicate characters in a string in O(1) space Given a string str, the task is to find all the duplicate characters present in a given string in lexicographical order without using any additional data structure. Examples: Input: str = "geeksforgeeks" Output: e g k s Explanation: Frequency of character 'g' = 2 Frequency of character 'e' = 4 Frequ
10 min read
Rearrange characters in a String such that no two adjacent characters are same Given a string s with lowercase repeated characters, the task is to rearrange characters in a string so that no two adjacent characters are the same. If it is not possible to do so, then print empty string ("").Note: Multiple valid rearranged strings can be possible for same input string. Examples:
14 min read
Minimum replacements in a string to make adjacent characters unequal Given a lowercase character string str of size N. In one operation any character can be changed into some other character. The task is to find the minimum number of operations such that no two adjacent characters are equal.Examples: Input: Str = "caaab" Output: 1 Explanation: Change the second a to
6 min read
Reduce string to shortest length by deleting a pair of same adjacent characters Given a string str of lowercase characters. The task is to count the number of deletions required to reduce the string to its shortest length. In each delete operation, you can select a pair of adjacent lowercase letters that match, and then delete them. The task is to print the count of deletions d
5 min read