We are given an integer array nums
. We need to construct a difference array diff
such that for each i
(0 <= i < n):
diff[i]
is equal to the difference between the number of distinct elements in the subarray nums[0:i+1]
and the number of distinct elements in the subarray nums[i+1:n]
.We need to return the diff
array.
nums
?nums
contain (positive, negative, zero)?Assume for our purposes:
n
can be up to (10^5).nums
can be positive, negative, and zero.Given this, let’s proceed with the solution.
nums[0:i+1]
.nums[i+1:n]
.prefix_distinct
such that prefix_distinct[i]
stores the count of distinct elements from the start to index i
.Suffix Array: Construct an array suffix_distinct
such that suffix_distinct[i]
stores the count of distinct elements from index i
to the end.
Difference Calculation: Compute the diff
array by subtracting the suffix_distinct
values from prefix_distinct
values.
def find_distinct_difference_array(nums):
n = len(nums)
if n == 0:
return []
# Initialize the prefix and suffix distinct count arrays
prefix_distinct = [0] * n
suffix_distinct = [0] * n
seen_prefix = set()
seen_suffix = set()
# Constructing prefix_distinct array
for i in range(n):
seen_prefix.add(nums[i])
prefix_distinct[i] = len(seen_prefix)
# Constructing suffix_distinct array
for i in range(n-1, -1, -1):
seen_suffix.add(nums[i])
suffix_distinct[i] = len(seen_suffix)
# Calculating the difference array
diff = [0] * n
for i in range(n):
if i + 1 < n:
diff[i] = prefix_distinct[i] - suffix_distinct[i+1]
else:
diff[i] = prefix_distinct[i]
return diff
# Example usage
nums = [1, 2, 3, 4, 5]
print(find_distinct_difference_array(nums)) # Output should be [1, 1, 1, 1, 1]
prefix_distinct
array involves iterating over the array and maintaining a set. This is (O(n)).suffix_distinct
array also involves a single pass with a set, making it (O(n)).diff
array comprises a simple iteration which is (O(n)).Therefore, the overall time complexity of the solution is (O(n)).
n
.n
.Thus, the space complexity is (O(n)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?