Tutorialspoint
Problem
Solution
Submissions

Remove Duplicates from a Vector

Certification: Intermediate Level Accuracy: 66.67% Submissions: 3 Points: 10

Write a C++ program that removes duplicates from a vector using the STL 'set'.

Example 1
  • Input: {1, 2, 2, 3, 3, 3}
  • Output: {1, 2, 3}
  • Explanation:
    • Step 1: Create a vector with the input elements.
    • Step 2: Create a set from the vector elements (duplicates are automatically removed).
    • Step 3: Convert the set back to a vector or use it directly.
    • Step 4: Return or display the result with duplicates removed.
Example 2
  • Input: {5, 5, 5, 5, 5}
  • Output: {5}
  • Explanation:
    • Step 1: Create a vector with the input elements.
    • Step 2: Create a set from the vector elements (duplicates are automatically removed).
    • Step 3: Convert the set back to a vector or use it directly.
    • Step 4: Return or display the result with duplicates removed.
Constraints
  • 1 ≤ size of vector ≤ 10^6
  • Elements of the vector are integers within the range [-10^9, 10^9]
  • Time Complexity: O(n log n), where n is the size of the vector
  • Space Complexity: O(n)
SetFunctions / MethodsSTL GoogleWipro
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a `set` to store unique elements from the vector.
  • Insert all elements of the vector into the set.
  • Convert the set back to a vector.

Steps to solve by this approach:

 Step 1: Create a set from the input vector to automatically remove duplicates.

 Step 2: The set keeps only unique elements and sorts them.
 Step 3: Create a new vector from the set's elements.
 Step 4: Return the new vector with unique elements.
 Step 5: Print the unique elements in the main function.

Submitted Code :