One approach can be to iterate in reverse order over the string, and keep track of all the characters seen in the string. If a character is repeated, we don't add it to the new_list.
def remove_rep(x: str):
new_list = []
seen = set()
for char in reversed(x):
if char not in seen:
new_list.append(char)
seen.add(char)
return ''.join(reversed(new_list))
print(remove_rep('abcdea'))
Result: 'bcdea'
Note that the above solution doesn't exactly work as desired, as it'll remove all occurrences of a character except the last one; for example, if you have 2+ occurrences of a chracter and you only want to remove the first one. To resolve that, you can instead do something like below:
def remove_rep(x: str):
new_list = []
first_seen = set()
for char in x:
freq = x.count(char)
if char in first_seen or freq == 1:
new_list.append(char)
elif freq > 1:
first_seen.add(char)
return ''.join(new_list)
Now for the given input:
print(remove_rep('abcdeaca'))
We get the desired result - only the first a and c is removed:
bdeaca
Test for a more complicated input:
print(remove_rep('abcdeaabcdea'))
We do get the correct result:
aabcdea
Do you see what happened in that last one? The first abcde sequence got removed, as all characters are repeated in this string. So our result is actually correct, even though it doesn't look so at an initial glance.