Hash map · Easy
A cart summary must total only selected products before rendering. Selection events may repeat a product ID.
Return the selected total in integer cents without charging for an ID more than once.
Input
Call
- Implement
solve(input)and return its result. Do not print fromsolve.
Input object
{ items: {id: string, cents: integer}[], selected: string[] }
Input rules
- Item IDs are unique; unknown selected IDs are ignored.
What each field means
items— available products. Each has a uniqueidand a price in integercents.selected— product IDs chosen by the user; the same ID may occur more than once.
Output
Return value and rules
- Return the total price as one integer number of cents.
- Count each selected product once. Ignore selected IDs that are not in
items. - Return
0when no known product is selected.
Constraints
- 0 <= items.length, selected.length <= 100000
- IDs contain 1–40 ASCII characters; 0 <= cents <= 1000000
- Do not mutate either input array. All totals fit a safe JavaScript integer.
Examples
Example 1
{
"items": [
{
"id": "a",
"cents": 120
},
{
"id": "b",
"cents": 250
}
],
"selected": [
"b",
"b",
"missing"
]
}Returns
250Duplicate selections count once.
Example 2
{
"items": [],
"selected": []
}Returns
0Empty cart.
Required complexity
O(n + m) time and O(n + m) auxiliary space