Filter Users by Max Price and Return Unique Names
You are given an array of user objects, where each user has three properties:
id(an integer)name(a string)price(an integer)
Write a function filterUsers(users, maxPrice) that:
- Keeps only the users whose
priceis less than or equal tomaxPrice. - From the filtered users, extracts the
nameproperty. - Returns an array containing only the unique names, preserving the order in which the names first appear in the filtered list.
If no user satisfies the price condition, the function should return an empty array.
Example
const users = [
{id: 1, name: "Alice", price: 150},
{id: 2, name: "Bob", price: 80},
{id: 3, name: "Alice", price: 70},
{id: 4, name: "Charlie", price: 200}
];
filterUsers(users, 100); // returns ["Bob", "Alice"]
Explanation: Only Bob (price 80) and the second Alice (price 70) are ≤ 100. The first Alice is excluded because her price is 150. The resulting names are "Bob" then "Alice", and both are unique.
Your solution should run in O(n) time where n is the number of users.
[ "[{\"id\":1,\"name\":\"Alice\",\"price\":150},{\"id\":2,\"name\":\"Bob\",\"price\":80},{\"id\":3,\"name\":\"Alice\",\"price\":70},{\"id\":4,\"name\":\"Charlie\",\"price\":200}]", "100" ]
Explanation. Only Bob (80) and the second Alice (70) are ≤ 100. Their names are unique and appear in that order.
[ "[{\"id\":10,\"name\":\"Dave\",\"price\":50},{\"id\":11,\"name\":\"Eve\",\"price\":50},{\"id\":12,\"name\":\"Dave\",\"price\":30}]", "50" ]
Explanation. All three users satisfy the price condition. The first occurrence of "Dave" is kept, then "Eve". The second "Dave" is a duplicate name and is ignored.
[ "[]", "1000" ]
Explanation. Empty input array yields an empty result.
[ "[{\"id\":5,\"name\":\"Zoe\",\"price\":200},{\"id\":6,\"name\":\"Yann\",\"price\":300}]", "150" ]
Explanation. No user has a price ≤ 150, so the result is empty.
[ "[{\"id\":1,\"name\":\"Anna\",\"price\":0},{\"id\":2,\"name\":\"anna\",\"price\":0}]", "0" ]
Explanation. Names are case‑sensitive, so "Anna" and "anna" are considered different and both are kept.
[ "[{\"id\":1,\"name\":\"Bob\",\"price\":10},{\"id\":2,\"name\":\"Bob\",\"price\":20},{\"id\":3,\"name\":\"Bob\",\"price\":5}]", "15" ]
Explanation. Three users named Bob, all ≤ 15 except the second (price 20). The first qualifying Bob is kept, duplicates are removed.
Follow-up: Modify the function so that it returns the unique names **sorted alphabetically** instead of preserving the original order. The overall time complexity should remain O(n log n) or better.
- 1 ≤ number of users ≤ 10⁵ - Each `id` is unique and fits in a 32‑bit signed integer. - `name` consists of only alphabetic characters (A‑Z, a‑z) and has length between 1 and 20. - 0 ≤ `price` ≤ 10⁹ - 0 ≤ `maxPrice` ≤ 10⁹ - The function must run in linear time O(n) and use O(n) additional space at most.
- Accepted
- 1/1
- Acceptance Rate
- 100.0%
- Views
- 2