FastPrepCount a User's Actions in an Event Log

Count a User's Actions in an Event Log

Microsoft logoMicrosoft● EasyINTERNONSITE INTERVIEW

Problem statement

A service writes one line to a log every time a user does something. Each line looks like "eventId userId action", for example "e3 u2 click" means event e3: user u2 did click.

The same event can be written more than once, for example when it is sent again after a network retry. Every copy has the same event ID and the same text. Count each event ID only once.

You are given the log events and a list of questions queries, where queries[j] = [userId, action]. For each question, return how many different events show that user doing that action. A user or action that never appears in the log has a count of 0.

Return the answers in the same order as queries.

Follow-up: in a real service, many callers would ask questions while new events keep arriving. How would you store the counts so each question is fast, and how would you keep them safe when several threads update them at once?

Function

countActions(events: String[], queries: String[][]) → int[]

Examples

Example 1

events = ["e1 u1 click","e2 u2 close","e3 u2 click","e4 u3 open"]queries = [["u2","click"],["u1","click"],["u3","close"],["u9","open"]]return = [1,1,0,0]

User u2 clicked once (e3), and u1 clicked once (e1). u3 only opened something, so close gives 0. u9 never appears, so its count is 0.

Example 2

events = ["a1 alice login","a2 alice view","a1 alice login","a3 bob view","a4 alice view","a2 alice view"]queries = [["alice","view"],["alice","login"],["bob","view"]]return = [2,1,1]

Events a1 and a2 each appear twice, but each event ID counts only once. So alice viewed twice (a2 and a4), logged in once (a1), and bob viewed once (a3).

Constraints

  • 1 <= events.length <= 5000
  • 1 <= queries.length <= 1000
  • Each events[i] is three names separated by single spaces: "eventId userId action". Lines with the same eventId are identical.
  • Each queries[j] has exactly two names: [userId, action].
  • Every name is 1 to 10 characters, using only lowercase English letters and digits.

More Microsoft problems

See Microsoft hiring insights
Saved
public int[] countActions(String[] events, String[][] queries) {
    // Write your code here.
}
Checking account…