Implement the removeDuplicateCharacters method that returns the text after keeping only the first occurrence of each character.

The input contains a string text. Your task is to remove duplicate characters while keeping the first occurrence of each character.

The original order of the remaining characters must be preserved. For example, banana becomes ban because b, a, and n are kept only the first time they appear.

Example 1

Input
text (string) = banana
Returns (string) ban

Example 2

Input
text (string) = programming
Returns (string) progamin

Example 3

Input
text (string) = aaaa
Returns (string) a

Use a set to remember which characters are already added to the result.

Scan the string from left to right. If a character has not been seen before, append it to the result and mark it as seen. If it is already seen, skip it.

Pseudocode:

function removeDuplicateCharacters(text):
    seen = empty set
    result = empty string
    for each character in text:
        if character not in seen:
            add character to result
            add character to seen
    return result
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.