1. Code Question 1 Your team at Amazon wants to develop a service that takes in an array…
- User
- Code Question 1
Your team at Amazon wants to develop a service that takes in an array of integers where the ith element represents the category of the ith product viewed by the customer and returns the sum of the number of distinct categories on all contiguous segments of the array.
Given an array of n integers, categories, find the sum of the numbers of distinct integers over all of its subarrays.
Note: A subarray is a contiguous part of an array. For example, the subarrays of [1, 2, 3] are [1], [2], [3], [1, 2], [2, 3], [1, 2, 3].
Example:
Given an array of n = 3 integers, categories = [1, 2, 1]:
Subarray
Distinct Category Count
[1]
1
[2]
1
[1]
1
[1, 2]
2
[2, 1]
2
[1, 2, 1]
2 The answer is 1+1+1+2+2+2=9.
Function Description
Complete the function countDistinctCategories in the editor below.
countDistinctCategories has the following
parameter:
int categories[n]: the products viewed by the customer
Constraints
• 1 ≤ n ≤ 105
• 1 ≤ categories[i] ≤ 109
► Input Format For Custom Testing
▼ Sample Case 0
Sample Input For Custom Testing
STDIN
FUNCTION
3
categories [] size n = 3
2
categories = [2, 1, 3]
1
3
←
→
Sample Output
10
Explanation
The subarrays are [2], [1], [3], [2, 1], [1, 3], [2, 1,
3]. The sum of distinct element counts per
subarray is 1+1+1+2+2+3=10 ▼Sample Case 1
Sample Input For Custom Testing
STDIN
FUNCTION
4
categories [] size n = 4
1
I
←
←
categories = [1, 5, 1,
3]
5
1
3
Sample Output
18
Explanation
Given n = 4, categories = [1, 5, 1, 3]. The sum of distinct element counts over all subarrays is 1+1+1+1+2+2+2+2+3+3 = 18.
For example, for subarray [1, 5, 1] there are two distinct integers in it i.e {1, 5}.
write the python code with time complexity O(n) or less
- Assistant