KatInterview

Count Distinct Users by Department and Time Window

SQL & DataAuto-graded · 18 test cases
MediumAuto-gradedSQL & Datadata-manipulationset-operationsfiltering

Last updated

Tests set-based deduplication and join logic to find unique users who interacted with products in a specific department during a time range.

You are given two datasets representing product catalog information and user interaction logs.

Products dataset: Each entry contains [product_id, department, category, subcategory] where the department is the top-level classification.

Clicks dataset: Each entry contains [user_id, product_id, timestamp] representing a user clicking on a product at a specific time.

Write a function that calculates how many distinct users clicked on at least one product belonging to a specified department within a given time window.

Requirements:

  • The time window is defined by start_ts (inclusive) and end_ts (exclusive): count clicks where start_ts <= timestamp < end_ts
  • A user who clicks multiple products within the same department should be counted exactly once
  • Clicks on products not present in the products dataset should be ignored
  • The department match must be exact (case-sensitive)

Constraints:

  • 0 ≤ len(products) ≤ 10⁵
  • 0 ≤ len(clicks) ≤ 10⁶
  • All product_ids, user_ids, and timestamps are non-negative integers
  • Department, category, and subcategory are non-empty strings
  • start_ts ≤ end_ts

Examples

Example 1

Input: count_unique_users_by_department([[101, 'Electronics', 'Phones', 'Smartphones'], [102, 'Electronics', 'Computers', 'Laptops'], [201, 'Home', 'Kitchen', 'Appliances']], [[1, 101, 10], [1, 102, 20], [2, 101, 30], [3, 201, 40], [2, 101, 50]], 'Electronics', 0, 40)

Output: 2

Example 2

Input: count_unique_users_by_department([[1, 'A', 'C1', 'S1'], [2, 'A', 'C2', 'S2'], [3, 'B', 'C3', 'S3']], [[10, 1, 100], [10, 2, 101], [11, 3, 101], [12, 1, 200]], 'A', 100, 200)

Output: 1

Hints

Hint 1

Build a lookup structure mapping product IDs to their departments before processing clicks

Hint 2

Use a set data structure to automatically handle user deduplication

Hint 3

Remember that the time window is half-open: include the start boundary but exclude the end boundary