Pregunta de entrevista de American Express

given an API that looks like this: interface EventReporter { enum Interval = {SECOND, MINUTE, HOUR}; public void recordEvent(String eventName, LocalDateTime t); public Map<String, Int> getEventCounts(String eventName, LocalDateTime start, LocalDateTime end, Interval i) } and data that looks like this: "x", 20:00:01 "x", 20:00:01 "x", 20:00:15 "x", 20:10:00 "x", 20:58:00 Describe a data structure and how you might implement the API's that come up with counts (via the "getEventCounts") for these three different "interval" types: Ask for event counts for "x", from 20: to 21:, with interval Second, you'd get: {"20:00:01": 2, "20:00:15": 1, "20:10:00": 1, "20:58:00": 1} Or with interval Minute: "20:00" -> 3, "20:10" -> 1, "20:58" -> 1 Or with interval hour: "20" -> 5

Respuesta de la entrevista

Anónimo

21 de feb de 2016

I'd write down the actual code but Glassdoor doesn't allow strict code formatting, so I'll describe the concept of the solution instead. I created an event record object with an event name property and a DateTime property. I then started writing the "getEventCount" method, doing a "for" loop across a (mutable) array of event record objects. I first made sure the event's name property matched the "eventName" of the API, then I made sure the event falls within the range of the start & end time. Finally, I increment a dictionary (where the key is the second -- e.g. 20:00:01, or minute, 20:00 or hour, 20) and the value was the number of times that key was encountered in the array of records matching the event name. The interviewer reminded me to add a "recordEvent: withTime:" API, which in my case was simply initialzing a new event record object, setting the time and name properties and then adding that to the mutable array of events. The interviewer prodded me a bit for optimization (so this might have been a place where they raised a veto flag on my candidacy), but the optimization he was looking for was to do pre-sorting of the events in the "recordEvent: withTime" API (i.e. a dictionary first sorted by event names as the keys, where the values are mutable dictionaries. These dictionaries would have HOUR, MINUTE, SECOND string keys and then an array of events and counts hanging off this dictionary -- e.g. a single "recordEvent" would modify 1 + 3 + 3*1 dictionaries & counts. In the interview I guessed this would have been a constant time but in retrospect, I'm not sure what the lookup time is for dictionaries on a mobile platform so the more records generating three dictionaries each, the longer the lookup times might take.