Remove Duplicates in a String Efficient Code

In this class, We discuss Remove Duplicates in a String Efficient Code.

The reader can complete a competitive coding course to crack product development companies. Click Here.

The reader should have some basic coding skills to work with competitive coding.

Take our placement training course for basic coding skills. Click Here.

Question:

Given a string S without spaces.

Our task is to remove duplicates from the given string.

Example:

Input: hello

Output: helo

Example 2:

Input: abcbeb

Output: abce

b has duplicates, we remove them and maintain the order.

The first b should be kept in the same place, and the remaining b’s should be removed.

Time complexity: O(|S|)

Space complexity: O(1)

Logic:

First way:

Use nested loops to remove duplicates.

The approach to removing duplicates was discussed in our placement training course.

Second way:

Use an array of size 256 to maintain the count of occurrence of the character to avoid duplicates.

The ASCII value approach was used in our previous ANAGRAM example.

S = “abcbeb”

Str=””

Take empty string str.

Take each character from the string S; if the first time the character is identified, increment count in the array and attach to str.

If the character is repeated repeatedly, don’t concatenate with str.

The step-by-step explanation is provided in the video.

Code:

class Solution:

    def removeDups(self, S):

        st = “”

        length = len(s)

        count1 = [0] * 256

        for i in S:

            if count1[ord(i)]==0:

                st += i

            count1[ord(i)]+=1

        return st

s=input()

ob = Solution()

print(ob.removeDups(s))