Last Updated: 27 Jul, 2020

Remove Duplicates From String

Moderate
Asked in companies
SquadstackAmazonGoldman Sachs

Problem statement

You are given a string (STR) of length N, consisting of only the lower case English alphabet.

Your task is to remove all the duplicate occurrences of characters in the string.

For Example:
If the given string is:
abcadeecfb

Then after deleting all duplicate occurrences, the string looks like this:
abcdef
Input Format:
The only input line contains a string (STR).
Output Format:
Print the string after removing all the duplicate occurrences.
Constraints:
1 <= N <= 4*10^5

Time Limit: 1sec

Approaches

01 Approach

Iterate for each character of the string. For each index, we run another loop starting from the beginning of the string upto that index, and check whether that character has occurred before. If so, we do not include this character in the final string.

02 Approach

We maintain a self-balancing BST/TreeSet to keep track of all previously encountered characters. 

 

Now, as we traverse the string, for each index, we check whether that character is present in the BST/TreeSet. 

 

If so, we do not include it in the final string.

03 Approach

We can maintain a 26 sized array to keep track of whether a character has previously occurred in the string or not since it is mentioned that we will encounter only lower case characters. 


Alternately, we can use either a hashmap, hashset or dictionary as well. keep track whether a character has previously occurred in the string or not. 

 

This makes our updates and lookups much faster.