![]() |
VOOZH | about |
Given an array of integers arr[], the task is to return the no of distinct elements in every prefix.
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 outputInput: 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.
Table of Content
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.
data[] that is going to store distinct elements.x in input array. x is positive, search data[] for x. If not found, append x to data[]x is negative, search data[] for -x. If found, remove it from data[]data[] into ans[]1 2 1 2 2
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.
st and empty array ansx in input array. If x is positive, insert x into stx is negative, remove -x from stst into ans1 2 1 2 2