Skip to main content

Command Palette

Search for a command to run...

How to Remove Duplicates from a String

Updated
2 min read
How to Remove Duplicates from a String

You are given this coding instruction:

Create a function to remove duplicates and empty spaces in a given string.

Step one is always to consider all possible conditions and ask questions to clarify. For example:

  1. Should the check be case sensitive?

  2. Does the new string keep the same casing and order?

Next, consider what data structures should be used with the conditions to meet the requirements.

In general, coding exercises involving strings are easier to handle by converting them into an array because it has a lot of handy methods. But it all comes down to the time and space complexity. For simple changes, even converting into a different data structure itself is an overhead cost. Another consideration is whether you can use an object for its advantage of O(1).

const removeDuplicates = (str:string): string =>{

  type letterMapType = {[key:string]: number};
  let letterMap:letterMapType ={};
  let uniqueString = "";

  for(const letter of str){
    const letterLowerCase = letter.toLowerCase();
    if(letter === " "){
        continue;
    }
    else if(!letterMap[letterLowerCase]){
        uniqueString += letter;
        letterMap[letterLowerCase] = 1;
    }
  }
  return uniqueString;
}

removeDuplicates('This is a test. TEST1 Test2 Done!'); // "Thisae.12Don!"

Also, for the questions involving uniqueness, consider using Set. One thing to remember is that Sets are case-sensitive, so an array needs to be converted to lowercase first, then a Set for a case-insensitive check. The output will then be all in lowercase as well, unless we loop through the original string again.

So let’s say the requirement for the function is simply to remove any duplicate letters in a case-sensitive way. Below is a quick solution using Set.

const removeDuplicates = (str:string): string =>{

  const letterSet = new Set(str.split(''));
  return [...letterSet].join('');

}

removeDuplicates('This is a test. TEST1 Test2 Done!'); //"This ate.ES12Don!"

More from this blog

UI Dev

18 posts