Given a string s , we have to remove all the consecutive duplicate characters of the string and return the resultant string.
Examples:
Input: str = "aaaaabbbbbb"
Output: ab
Explanation: Remove consecutive duplicate characters from a stringssuch as 5 a's are at consecutive so only write a and same like that in b's condition.Input: str = "geeksforgeeks"
Output: geksforgeks
Explanation: Remove consecutive duplicate characters from"geeksforgeeks", so"ee"becomes"e", resulting in"geksforgeks"
[Approach 1] Using recursion - O(n) time and O(n) space
Idea is comparing the current character with the previous character
Steps to solve the problem:
- Compare the current character with the previous one.
- If they are different, append the current character to the result string.
- Move to the next index with the updated result.
#include <iostream>
#include <string>
using namespace std;
// Recursive helper function to build the result string
void removeDuplicatesHelper(char prev, int index, string &str, string &result) {
// Base case: reached end of string
if (index == str.size()) {
return;
}
// If current char is different from previous, add it
if (str[index] != prev) {
result.push_back(str[index]);
}
// Recurse for the next character
removeDuplicatesHelper(str[index], index + 1, str, result);
}
// Wrapper function
string removeDuplicates(string &str) {
string result = "";
removeDuplicatesHelper('\0', 0, str, result);
return result;
}
int main() {
string str = "geeksforgeeks";
cout << removeDuplicates(str) << endl; // Output: "geksforgeks"
return 0;
}
public class GFG {
// Recursive helper function to build the result string
static void removeDuplicatesHelper(char prev, int index, String str, StringBuilder result) {
// Base case: reached end of string
if (index == str.length()) {
return;
}
// If current char is different from previous, add it
if (str.charAt(index) != prev) {
result.append(str.charAt(index));
}
// Recurse for the next character
removeDuplicatesHelper(str.charAt(index), index + 1, str, result);
}
// Wrapper function
static String removeDuplicates(String str) {
StringBuilder result = new StringBuilder();
removeDuplicatesHelper('\0', 0, str, result);
return result.toString();
}
public static void main(String[] args) {
String str = "geeksforgeeks";
System.out.println(removeDuplicates(str)); // Output: "geksforgeks"
}
}
# Recursive helper function to build the result string
def removeDuplicatesHelper(prev, index, str, result):
# Base case: reached end of string
if index == len(str):
return
# If current char is different from previous, add it
if str[index] != prev:
result.append(str[index])
# Recurse for the next character
removeDuplicatesHelper(str[index], index + 1, str, result)
# Wrapper function
def removeDuplicates(str):
result = []
removeDuplicatesHelper('\0', 0, str, result)
return ''.join(result)
# Example usage
str = "geeksforgeeks"
print(removeDuplicates(str)) # Output: "geksforgeeks"
using System;
using System.Text;
class RemoveDuplicatesProgram
{
// Recursive helper function to build the result string
static void removeDuplicatesHelper(char prev, int index, string str, StringBuilder result)
{
// Base case: reached end of string
if (index == str.Length)
return;
// If current char is different from previous, add it
if (str[index] != prev)
result.Append(str[index]);
// Recurse for the next character
removeDuplicatesHelper(str[index], index + 1, str, result);
}
// Wrapper function
static string removeDuplicates(string str)
{
StringBuilder result = new StringBuilder();
removeDuplicatesHelper('\0', 0, str, result);
return result.ToString();
}
static void Main()
{
string str = "geeksforgeeks";
Console.WriteLine(removeDuplicates(str)); // Output: "geksforgeks"
}
}
// Recursive helper function to build the result string
function removeDuplicatesHelper(prev, index, str, result) {
// Base case: reached end of string
if (index === str.length) {
return;
}
// If current char is different from previous, add it
if (str[index] !== prev) {
result.push(str[index]);
}
// Recurse for the next character
removeDuplicatesHelper(str[index], index + 1, str, result);
}
// Wrapper function
function removeDuplicates(str) {
let result = [];
removeDuplicatesHelper('\0', 0, str, result);
return result.join('');
}
// Driver Code
// Example usage
let str = "geeksforgeeks";
console.log(removeDuplicates(str)); // Output: "geksforgeeks"
Output
geksforgeks
[Expected Approach] Using Stack - O(n) time and O(n) space
Idea is Iteratively traverses the string, appending characters to a new string only if they are different from the next character, thus removing consecutive duplicates.
Step by step approach:
- Create a string to store the result
- iterate the string from 0 to length-2
- if current char is not equal to next char then add it to answer string
- else continue
- return string
#include <iostream>
#include <string>
#include <stack>
using namespace std;
// Function to remove adjacent duplicates using a stack
string removeDuplicates(string str) {
stack<char> st;
int n = str.length();
// Traverse through the string
for (int i = 0; i < n; i++) {
// If stack is empty or current char is not equal to top of stack, push it
if (st.empty() || st.top() != str[i]) {
st.push(str[i]);
}
// If current char is same as top of stack, skip adding it
}
// Build result from stack
string result = "";
while (!st.empty()) {
result = st.top() + result; // Insert at front to maintain order
st.pop();
}
return result;
}
int main() {
string str = "geeksforgeeks";
cout << removeDuplicates(str) << endl; // Output: "geksforgeks"
return 0;
}
import java.util.Stack;
public class RemoveDuplicatesStack {
// Function to remove adjacent duplicates using a stack
static String removeDuplicates(String str) {
Stack<Character> st = new Stack<>();
int n = str.length();
// Traverse through the string
for (int i = 0; i < n; i++) {
// If stack is empty or current char is not equal to top of stack, push it
if (st.isEmpty() || st.peek() != str.charAt(i)) {
st.push(str.charAt(i));
}
// If current char is same as top of stack, skip adding it
}
// Build result from stack
StringBuilder result = new StringBuilder();
while (!st.isEmpty()) {
result.insert(0, st.pop()); // Insert at front to maintain order
}
return result.toString();
}
public static void main(String[] args) {
String str = "geeksforgeeks";
System.out.println(removeDuplicates(str)); // Output: "geksforgeks"
}
}
# Function to remove adjacent duplicates using a stack
def removeDuplicates(str):
st = []
n = len(str)
# Traverse through the string
for i in range(n):
# If stack is empty or current char is not equal to top of stack, push it
if not st or st[-1] != str[i]:
st.append(str[i])
# If current char is same as top of stack, skip adding it
# Build result from stack
result = "".join(st) # Stack already maintains order
return result
if __name__ == "__main__":
str = "geeksforgeeks"
print(removeDuplicates(str)) # Output: "geksforgeks"
using System;
using System.Collections.Generic;
using System.Text;
class GFG
{
// Function to remove adjacent duplicates using a stack
static string removeDuplicates(string str)
{
Stack<char> st = new Stack<char>();
int n = str.Length;
// Traverse through the string
for (int i = 0; i < n; i++)
{
// If stack is empty or current char is not equal to top of stack, push it
if (st.Count == 0 || st.Peek() != str[i])
{
st.Push(str[i]);
}
// If current char is same as top of stack, skip adding it
}
// Build result from stack
StringBuilder result = new StringBuilder();
while (st.Count > 0)
{
result.Insert(0, st.Pop()); // Insert at front to maintain order
}
return result.ToString();
}
static void Main()
{
string str = "geeksforgeeks";
Console.WriteLine(removeDuplicates(str)); // Output: "geksforgeks"
}
}
// Function to remove adjacent duplicates using a stack
function removeDuplicates(str) {
let st = [];
let n = str.length;
// Traverse through the string
for (let i = 0; i < n; i++) {
// If stack is empty or current char is not equal to top of stack, push it
if (st.length === 0 || st[st.length - 1] !== str[i]) {
st.push(str[i]);
}
// If current char is same as top of stack, skip adding it
}
// Build result from stack
return st.join(''); // Stack already maintains order
}
// Driver Code
// Example usage
let str = "geeksforgeeks";
console.log(removeDuplicates(str)); // Output: "geksforgeks"
Output
geksforgeks
[Expected Approach] Using Sliding window - O(n) time and O(n) space
Idea is Initialize pointers
i,jandnowtraverse withj, skip ifs[i] == s[j], else append tonew, then return the result
Step by step approach:
- Initialize two pointer i, j and new string .
- Traverse the string using j pointer .
- Compare S[i] and S[j].
- if both element are same then skip.
- if both element are not same then append into new string set and slide over the window
- return the result.
#include <iostream>
#include <string>
using namespace std;
// Function to remove adjacent duplicates using sliding window
string removeDuplicates(string str) {
int n = str.length();
if (n == 0) return str;
string result = "";
int i = 0;
// Traverse through the string using a sliding window
while (i < n) {
// Add current character
result.push_back(str[i]);
// Skip all consecutive duplicates
while (i + 1 < n && str[i] == str[i + 1]) {
i++;
}
i++;
}
return result;
}
int main() {
string str = "geeksforgeeks";
cout << removeDuplicates(str) << endl; // Output: "geksforgeks"
return 0;
}
public class RemoveDuplicatesSlidingWindow {
// Function to remove adjacent duplicates using sliding window
static String removeDuplicates(String str) {
int n = str.length();
if (n == 0) return str;
StringBuilder result = new StringBuilder();
int i = 0;
// Traverse through the string using a sliding window
while (i < n) {
// Add current character
result.append(str.charAt(i));
// Skip all consecutive duplicates
while (i + 1 < n && str.charAt(i) == str.charAt(i + 1)) {
i++;
}
i++;
}
return result.toString();
}
public static void main(String[] args) {
String str = "geeksforgeeks";
System.out.println(removeDuplicates(str)); // Output: "geksforgeks"
}
}
# Function to remove adjacent duplicates using sliding window
def removeDuplicates(str):
n = len(str)
if n == 0:
return str
result = []
i = 0
# Traverse through the string using a sliding window
while i < n:
# Add current character
result.append(str[i])
# Skip all consecutive duplicates
while i + 1 < n and str[i] == str[i + 1]:
i += 1
i += 1
return ''.join(result)
if __name__ == "__main__":
str = "geeksforgeeks"
print(removeDuplicates(str)) # Output: "geksforgeks"
using System;
using System.Text;
class GFG
{
// Function to remove adjacent duplicates using sliding window
static string removeDuplicates(string str)
{
int n = str.Length;
if (n == 0) return str;
StringBuilder result = new StringBuilder();
int i = 0;
// Traverse through the string using a sliding window
while (i < n)
{
// Add current character
result.Append(str[i]);
// Skip all consecutive duplicates
while (i + 1 < n && str[i] == str[i + 1])
{
i++;
}
i++;
}
return result.ToString();
}
static void Main()
{
string str = "geeksforgeeks";
Console.WriteLine(removeDuplicates(str)); // Output: "geksforgeks"
}
}
// Function to remove adjacent duplicates using sliding window
function removeDuplicates(str) {
let n = str.length;
if (n === 0) return str;
let result = [];
let i = 0;
// Traverse through the string using a sliding window
while (i < n) {
// Add current character
result.push(str[i]);
// Skip all consecutive duplicates
while (i + 1 < n && str[i] === str[i + 1]) {
i++;
}
i++;
}
return result.join('');
}
// Driver Code
// Example usage
let str = "geeksforgeeks";
console.log(removeDuplicates(str)); // Output: "geksforgeks"
Output
geksforgeks
[Alternate Approach] Using Regex Approach - O(n) time and O(1) space
This idea is that regular expression to match any character followed by one or more of the same character in a string. It then replaces these sequences of consecutive duplicates with just a single occurrence of that character.
Step by step approach:
- It uses a regular expression
"(.)\\1+"to match any character followed by one or more of the same character. - The
regex_replacefunction then replaces these matches with a single occurrence of that character, resulting in a string without consecutive duplicates
#include <iostream>
#include <regex>
using namespace std;
string removeDuplicates(string str) {
// Create a regex pattern to match consecutive duplicate characters
regex r("(.)\\1+");
// Use regex_replace to replace consecutive duplicates with a single character
str = regex_replace(str, r, "$1");
return str;
}
int main() {
string str = "geeksforgeeks";
cout << removeDuplicates(str) << endl;
return 0;
}
import java.util.regex.*;
public class GFG {
public static String removeDuplicates(String str) {
// Create a regex pattern to match consecutive duplicate characters
Pattern p = Pattern.compile("(.)\1+");
// Use matcher to replace consecutive duplicates with a single character
Matcher m = p.matcher(str);
str = m.replaceAll("$1");
return str;
}
public static void main(String[] args) {
String str = "geeksforgeeks";
System.out.println(removeDuplicates(str));
}
}
import re
def remove_duplicates(str):
# Create a regex pattern to match consecutive duplicate characters
return re.sub(r'(.)\1+', r'\1', str)
if __name__ == "__main__":
str = "geeksforgeeks"
print(remove_duplicates(str))
using System;
using System.Text.RegularExpressions;
class GfG {
// Method to remove consecutive duplicates using regex
static string RemoveDuplicates(string str) {
// Create a regex pattern to match consecutive duplicate characters
return Regex.Replace(str, "(.)\\1+", "$1");
}
// Main method to test the solution
static void Main() {
string str = "geeksforgeeks";
Console.WriteLine(RemoveDuplicates(str));
}
}
function removeDuplicates(str) {
// Create a regex pattern to match consecutive duplicate characters
return str.replace(/(.)\1+/g, '$1');
}
// Driver Code
let str = "geeksforgeeks";
console.log(removeDuplicates(str));
Output
geksforgeks