VOOZH about

URL: https://www.geeksforgeeks.org/dsa/distinct-elements-in-a-stream/

⇱ Distinct Elements in a Stream - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Distinct Elements in a Stream

Last Updated : 14 Jun, 2026

Given an array of integers arr[], the task is to return the no of distinct elements in every prefix.

  • The array will have positive and negative values. positive value means you have to append it into your data and negative value means you have to remove it from your data.
  • If the element is not present in the data and you get the -ve of that element then no changes should occur.

Example:

Input: arr[] = [5, 5, 7, -5, -7, 1, 2, -2]
Output: [1, 1, 2, 2, 1, 2, 3, 2]
Explanation: Proper adding and removal of intgers will give this output

Input: arr[] = [9, 9, 3, -9, -3, -9]
Output: [1, 1, 2, 2, 1, 0]
Explanation: Proper adding and removal of intgers will give this output.

[Naive Approach] Simulation with Linear Search - O(n²) Time and O(n) Space

Maintain an array of current elements. For positive numbers, add only if not already present. For negative numbers, remove the corresponding positive element. Track distinct count after each operation.

  • Initialize empty data[] that is going to store distinct elements.
  • For each element x in input array.
  • If x is positive, search data[] for x. If not found, append x to data[]
  • If x is negative, search data[] for -x. If found, remove it from data[]
  • Store current size of data[] into ans[]

Output
1 2 1 2 2 

[Optimal Approach] Hashing for O(1) Operations - O(n) Time and O(n) Space

Use a hash set to track current elements. For positive numbers, add to set. For negative numbers, remove the corresponding positive number. Set size after each step gives number of distinct elements.

  • Initialize empty set st and empty array ans
  • For each element x in input array. If x is positive, insert x into st
  • If x is negative, remove -x from st
  • Store current size of st into ans

Output
1 2 1 2 2 


Comment
Article Tags:
Article Tags: