Problem · Array

Count Distinct Users by Activity

Learn this problem
EasyGoogle logoGoogleFULLTIMEPHONE SCREEN
See Google hiring insights

Problem statement

Given a collection of user-activity records, count how many distinct users performed each activity.

Each source record is represented as exactly three strings in this order:

  1. decimal user_id
  2. timestamp
  3. activity

Return the mapping as a two-column String[][]. Each row must be [activity, distinctUserCount], where the count is a decimal string. Order the rows by the first appearance of each activity in records.

Repeated records or repeated occurrences of the same activity by one user count that user only once for that activity. The timestamp is part of the input record but does not change the distinct-user count. If records is empty, return an empty matrix.

Function

countDistinctUsersByActivity(records: String[][]) → String[][]

Examples

Example 1

records = [["1","2024-07-26 10:00:00","login"],["2","2024-07-26 10:05:00","login"],["1","2024-07-26 10:10:00","view"],["1","2024-07-26 10:15:00","purchase"],["2","2024-07-26 10:20:00","view"],["3","2024-07-26 10:25:00","login"],["1","2024-07-26 10:30:00","logout"]]return = [["login","3"],["view","2"],["purchase","1"],["logout","1"]]

The distinct users are {1, 2, 3} for login, {1, 2} for view, and {1} for both purchase and logout. The activities first appear in the order login, view, purchase, logout.

Example 2

records = [["10","2024-08-01 09:00:00","search"],["10","2024-08-01 09:01:00","search"],["20","2024-08-01 09:02:00","search"],["10","2024-08-01 09:03:00","checkout"],["20","2024-08-01 09:04:00","checkout"]]return = [["search","2"],["checkout","2"]]

User 10 performs search twice but contributes once to that activity's distinct-user count. Both users perform search and checkout.

More Google problems

drafts saved locally
public String[][] countDistinctUsersByActivity(String[][] records) {
  // write your code here
}
records[["1","2024-07-26 10:00:00","login"],["2","2024-07-26 10:05:00","login"],["1","2024-07-26 10:10:00","view"],["1","2024-07-26 10:15:00","purchase"],["2","2024-07-26 10:20:00","view"],["3","2024-07-26 10:25:00","login"],["1","2024-07-26 10:30:00","logout"]]
expected[["login", "3", "view", "2", "purchase", "1", "logout", "1"]]
checking account