Return Top K Open Businesses
Company: Microsoft
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's ability to perform filtering and multi-criteria ranking, requiring correct handling of an open-status filter and tie-breaking by score and distance.
Constraints
- 0 <= len(businesses) <= 100000
- 0 <= k <= 100000
- Each business contains at least the keys 'score', 'distance', and 'isOpen'
- 'score' and 'distance' are numeric values
- If k exceeds the number of open businesses, return all open businesses
Examples
Input: ([{'id': 'A', 'score': 4.8, 'distance': 3.2, 'isOpen': True}, {'id': 'B', 'score': 4.9, 'distance': 5.0, 'isOpen': False}, {'id': 'C', 'score': 4.8, 'distance': 1.1, 'isOpen': True}, {'id': 'D', 'score': 5.0, 'distance': 4.0, 'isOpen': True}], 2)
Expected Output: [{'id': 'D', 'score': 5.0, 'distance': 4.0, 'isOpen': True}, {'id': 'C', 'score': 4.8, 'distance': 1.1, 'isOpen': True}]
Explanation: Only open businesses are A, C, and D. D has the highest score. A and C have the same score, so the closer one, C, comes first.
Input: ([{'id': 'X', 'score': 4.2, 'distance': 2.0, 'isOpen': True}, {'id': 'Y', 'score': 4.2, 'distance': 2.0, 'isOpen': True}, {'id': 'Z', 'score': 3.9, 'distance': 1.0, 'isOpen': False}, {'id': 'W', 'score': 4.2, 'distance': 1.5, 'isOpen': True}], 10)
Expected Output: [{'id': 'W', 'score': 4.2, 'distance': 1.5, 'isOpen': True}, {'id': 'X', 'score': 4.2, 'distance': 2.0, 'isOpen': True}, {'id': 'Y', 'score': 4.2, 'distance': 2.0, 'isOpen': True}]
Explanation: There are only three open businesses, so all are returned. W comes first because it is closer among businesses with the same score. X and Y remain in original order because both score and distance are equal.
Input: ([], 3)
Expected Output: []
Explanation: An empty input list has no open businesses to return.
Input: ([{'id': 'P', 'score': 5, 'distance': 10, 'isOpen': True}, {'id': 'Q', 'score': 2, 'distance': 1, 'isOpen': True}], 0)
Expected Output: []
Explanation: When k is 0, the result must be an empty list regardless of the businesses available.
Hints
- It may be easier to ignore all closed businesses first, then rank only the remaining ones.
- A single sort key can handle both rules: descending by score and ascending by distance.