Search⌘ K

Remove all Adjacent Duplicates from a String

Explore how to use recursion to remove all adjacent duplicate characters in a string while preserving case sensitivity. Understand the base and recursive cases that allow the function to process the string by comparing characters and reducing string length with each call. This lesson equips you with the skills to handle string manipulation challenges in coding interviews effectively.

What does “Removing Adjacent Duplicates from a String” Mean?

This means that we’ll remove all extra instances of a character when multiple instances are found together. In other words, only one instance should remain after this process.

Lower and upper case letters are considered different characters. Example: string Hhelo doesn’t contain any duplicates.

Repeated occurrences of the same letter within a string are allowed as long as they are not next to each other. Example: string hele has no adjacent duplicates.

widget

Implementation

Javascript (babel-node)
function removeDuplicates(string) {
// Base case
if (string.length <= 1) {
return string;
}
// Recursive case1
else if (string[0] == string[1]) {
return removeDuplicates(string.substr(1));
}
// Recursive case2
return string[0] + removeDuplicates(string.substr(1));
}
// Driver Code
console.log(removeDuplicates('Hellloo'));

Explanation

To remove duplicates, we reduce the length of the string with each recursive call. If the current ...