First and last position of a user

binary search

First and last position of a user

Meta Python Interview Question

Meta's login logs are sorted by user id, so all logins for one user sit next to each other.

Write a function find_range(user_ids, user_id) that returns a list with the first and last positions of the user in the sorted list, or [-1, -1] if the user has no logins. The list can be very long, so avoid checking every entry.

Asked of

  • Data Analyst
  • Data Engineer
  • Data Scientist
  • ML Engineer
  • AI Engineer

Example 1

Input

user_ids = [5, 7, 7, 8, 8, 10], user_id = 8

Output

[3, 4]

Example 2

Input

user_ids = [5, 7, 7, 8, 8, 10], user_id = 6

Output

[-1, -1]

Explanation

In the first example, user 8 appears at positions 3 and 4, so the answer is [3, 4]. In the second example, user 6 never logged in, so the answer is [-1, -1].

Submit also runs 4 hidden test cases that check edge cases.