Set - Store Unique Elements

Set - Store Unique Elements

Medium C++ STL 61 views
Explanation Complexity

Problem Statement

Set automatically keeps only unique elements, sorted.
Real Life: Collection of unique items, no duplicates.

Input Format

An integer n (number of elements)
Then n integers (may contain duplicates).

Output Format

All unique elements printed in sorted order.

Example

6
5 2 3 5 2 4
2 3 4 5

Constraints

• n ≥ 1

• Elements can repeat

• Order is automatically sorted

Concept Explanation

A set stores only unique values.
If a duplicate value is inserted, it is ignored automatically.
All elements are kept in sorted order.

This is useful for maintaining a collection of unique items,
like unique IDs, roll numbers, or product codes.

Step-by-Step Explanation

1.Create a set.

2.Read elements one by one.

3.Insert each element into the set using insert().

4.If an element already exists:

• Set ignores it.

5.Set automatically sorts all stored elements.

6.Traverse the set using iterator or loop.

7.Print all elements.

Concept Explanation

A set stores only unique values.
If a duplicate value is inserted, it is ignored automatically.
All elements are kept in sorted order.

This is useful for maintaining a collection of unique items,
like unique IDs, roll numbers, or product codes.

Step-by-Step Explanation

1.Create a set.

2.Read elements one by one.

3.Insert each element into the set using insert().

4.If an element already exists:

• Set ignores it.

5.Set automatically sorts all stored elements.

6.Traverse the set using iterator or loop.

7.Print all elements.

Input / Output Format

Input Format
An integer n (number of elements)
Then n integers (may contain duplicates).
Output Format
All unique elements printed in sorted order.
Constraints
• n ≥ 1

• Elements can repeat

• Order is automatically sorted

Examples

Input:
6 5 2 3 5 2 4
Output:
2 3 4 5

Example Solution (Public)

C++
void stl_q7_set() {
    set<int> uniqueNumbers;
    
    uniqueNumbers.insert(30);
    uniqueNumbers.insert(10);
    uniqueNumbers.insert(20);
    uniqueNumbers.insert(10);  // Duplicate, will be ignored
    
    cout << "Unique numbers (sorted): ";
    for(int num : uniqueNumbers) {
        cout << num << " ";
    }
    cout << endl;
    
    cout << "Size: " << uniqueNumbers.size() << endl;
}

Official Solution Code

void stl_q7_set() {
    set<int> uniqueNumbers;
    
    uniqueNumbers.insert(30);
    uniqueNumbers.insert(10);
    uniqueNumbers.insert(20);
    uniqueNumbers.insert(10);  // Duplicate, will be ignored
    
    cout << "Unique numbers (sorted): ";
    for(int num : uniqueNumbers) {
        cout << num << " ";
    }
    cout << endl;
    
    cout << "Size: " << uniqueNumbers.size() << endl;
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.