Be the first user to complete this post

  • 0
Add to List
Medium

248. Remove Duplicates from a string | 4 Approaches

Objective:  Given a string, write an algorithm to remove the duplicate characters in that string.

Example:

Input: tutorialhorizon
Output: tuorialhzn

Approaches:

There are multiple approaches to solve this problem-

  1. Use Sorting – (Will change the order of the characters)
  2. Use Hash Set - (Will change the order of the characters).
  3. Use Linked HashMap - (Will retain the order of the characters).
  4. Use Buffer Array - (Will retain the order of the characters).

Let’s discuss all the approaches

Sorting:

  1. Convert the string to character array. S
  2. Sort the array, this will bring all the identical characters together.
  3. Iterate through character array and remove the duplicate characters.
  4. This approach will change the order of characters.
Output: ahilnortuz

Hash Set:

  1. Convert the string to character array.
  2. Store all the characters in the Set.
  3. Set will store only one instance of each character
  4. Iterate through Set and print the characters.
  5. This approach will change the order of characters.
Output: artuhizlno

Linked Hash Set:

  1. Convert the string to character array.
  2. Store all the characters in the Linked Hash Set.
  3. Set will store only one instance of each character
  4. Iterate through Set and print the characters.
  5. This approach will retain the order of characters.
Output: tuorialhzn

Buffer Array:

  1. Convert the string to character array.
  2. Create the boolean array of 256,( for all 0 – 255 ASCII characters)
  3. Iterate through character array from step one and set the Boolean array index ( index = ascii value of the character). Ignore if that index is already true.
  4. Create a separate array based on the index set as true in Boolean array.
  5. This approach will retain the order of characters.
Output: tuorialhzn