Tutorialspoint
Problem
Solution
Submissions

Remove Duplicates from an Array

Certification: Basic Level Accuracy: 50% Submissions: 6 Points: 10

Write a C++ function to remove duplicates from an array of integers and return the new array.

Example 1
  • Input: arr = [1, 2, 2, 3, 4, 4]
  • Output: [1, 2, 3, 4]
  • Explanation:
    • Step 1: Create an empty result array and a hash set to track seen elements.
    • Step 2: Iterate through the input array: [1, 2, 2, 3, 4, 4].
    • Step 3: For each element, check if it's already in the hash set.
    • Step 4: If not in the set, add it to both the set and the result array.
    • Step 5: Return the result array containing unique elements: [1, 2, 3, 4].
Example 2
  • Input: arr = [5, 5, 5, 5]
  • Output: [5]
  • Explanation:
    • Step 1: Create an empty result array and a hash set to track seen elements.
    • Step 2: Iterate through the input array: [5, 5, 5, 5].
    • Step 3: For each element, check if it's already in the hash set.
    • Step 4: If not in the set, add it to both the set and the result array.
    • Step 5: Return the result array containing unique elements: [5].
Constraints
  • 1 ≤ array length ≤ 10^4
  • -10^5 ≤ array elements ≤ 10^5
  • Time Complexity: O(n)
  • Space Complexity: O(n)
ArraysSetIBMSnowflake
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 hash set to store unique elements.
  • Traverse the array and add elements to the set if they are not already present.
  • Convert the set back to an array and return it.

Steps to solve by this approach:

 Step 1: Create a data structure (unordered_set) to track seen elements.

 Step 2: Create a vector to store the result (array without duplicates).
 Step 3: Iterate through each element of the input array.
 Step 4: For each element, check if it exists in our set of seen elements.
 Step 5: If not seen before, add it to both the result vector and the set of seen elements.

Submitted Code :