Problem · Array

Count Distinct Categories

Learn this problem
HardAmazonNEW GRADOA
See Amazon hiring insights

Problem statement

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].

Function

countDistinctCategories(categories: int[]) → long

Complete the function countDistinctCategories in the editor.

countDistinctCategories has the following parameter:

  1. int categories[n]: the products viewed by the customer

Returns

long integer: the sum of the number of distinct categories over all subarrays

Examples

Example 1

categories = [1, 2, 1]return = 9
Example 1 illustration
The answer is 1 + 1 + 1 + 2 + 2 + 2 = 9.

More Amazon problems

drafts saved locally
public long countDistinctCategories(int[] categories) {
  // write your code here
}
categories[1, 2, 1]
expected9
checking account