KatInterview

Count Shoppers With Visits on Two or More Days

Arrays & HashingAuto-graded · 16 test cases
EasyAuto-gradedArrays & Hashinghash-sethash-mapgrouping

Last updated

Group log entries by person and ignore repeats on the same day, then count how many people appear on at least two different calendar days.

A shop records every time a shopper passes through its entrance gate. Each record is a pair holding the shopper's ID and the calendar date of that entry.

A shopper may come through the gate several times in one day. All entries on the same date count as a single day of presence.

Write a function that returns how many different shoppers were present on at least two different dates.

Input

  • entries: a list of records, where each record is [shopper_id, entry_date].
    • shopper_id is a string identifying the shopper. IDs are case-sensitive, so "Bob" and "bob" are different shoppers.
    • entry_date is a string in "YYYY-MM-DD" format. Two records fall on the same date exactly when their date strings are equal.

Records may appear in any order.

Output

Return an integer: the number of distinct shoppers whose records contain two or more distinct dates.

Rules and edge cases

  • If entries is empty, return 0.
  • Many records for the same shopper on the same date must be treated as one date.
  • If every record has the same date, return 0.

Constraints

  • 0 <= len(entries) <= 2 * 10^5
  • 1 <= len(shopper_id) <= 32, alphanumeric characters only
  • entry_date is always a valid date in "YYYY-MM-DD" format

Examples

Example 1

Input: count_repeat_day_shoppers([['cust_1', '2023-11-01'], ['cust_2', '2023-11-01'], ['cust_1', '2023-11-01'], ['cust_1', '2023-11-02'], ['cust_3', '2023-11-03']])

Output: 1

Example 2

Input: count_repeat_day_shoppers([['alice', '2023-10-05'], ['bob', '2023-10-05'], ['alice', '2023-10-06'], ['bob', '2023-10-07'], ['alice', '2023-10-05']])

Output: 2

Hints

Hint 1

Counting how many records a shopper has is not enough, because several records may share one date. Think about what you need to track per shopper instead.

Hint 2

Use a dictionary keyed by shopper ID whose values are sets of date strings. The set automatically discards repeated dates.

Hint 3

You never need more than two dates per shopper. Once a shopper has two different dates, you can stop tracking them and just count them once.