Remove Duplicate Characters

Remove Duplicate Characters

Hard C++ Strings 40 views
Explanation Complexity

Problem Statement

Remove all duplicate characters, keep only first occurrence.
Real Life: Unique character extraction.

Input Format

A string S.

Output Format

String after removing duplicate characters
(only first occurrence kept).

Example

programming
progamin

Constraints

• String length ≥ 1

• Case-sensitive (a and A are different)

• Maintain original order

Concept Explanation

Duplicate characters are removed,
but the first occurrence of each character is kept.
This is useful when extracting unique characters.

Step-by-Step Explanation

1.Take input string S.

2.Create a boolean array of size 256 (for all ASCII characters).

3.Initialize all values as false.

4.Traverse the string from left to right.

5.For each character ch:

• If visited[ch] is false:

• Print ch.

• Mark visited[ch] = true.

• Else:

• Skip the character.

6.Continue till end of string.

Concept Explanation

Duplicate characters are removed,
but the first occurrence of each character is kept.
This is useful when extracting unique characters.

Step-by-Step Explanation

1.Take input string S.

2.Create a boolean array of size 256 (for all ASCII characters).

3.Initialize all values as false.

4.Traverse the string from left to right.

5.For each character ch:

• If visited[ch] is false:

• Print ch.

• Mark visited[ch] = true.

• Else:

• Skip the character.

6.Continue till end of string.

Input / Output Format

Input Format
A string S.
Output Format
String after removing duplicate characters
(only first occurrence kept).
Constraints
• String length ≥ 1

• Case-sensitive (a and A are different)

• Maintain original order

Examples

Input:
programming
Output:
progamin

Example Solution (Public)

C++
void string_q12_remove_duplicates() {
    string text = "programming";
    string result = "";
    bool seen[256] = {false};
    
    cout << "Original: " << text << endl;
    
    for(int i = 0; i < text.length(); i++) {
        if(!seen[text[i]]) {
            result += text[i];
            seen[text[i]] = true;
        }
    }
    
    cout << "After removing duplicates: " << result << endl;
}

Official Solution Code

void string_q12_remove_duplicates() {
    string text = "programming";
    string result = "";
    bool seen[256] = {false};
    
    cout << "Original: " << text << endl;
    
    for(int i = 0; i < text.length(); i++) {
        if(!seen[text[i]]) {
            result += text[i];
            seen[text[i]] = true;
        }
    }
    
    cout << "After removing duplicates: " << result << endl;
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.