Shopping Cart - Problem
You are tasked with implementing a Shopping Cart system that supports the following operations:
add_item(item_id, name, price, quantity)- Add an item to the cart with given detailsremove_item(item_id)- Remove an item completely from the cartupdate_quantity(item_id, new_quantity)- Update the quantity of an existing itemcalculate_total()- Calculate and return the total price of all items in the cart
Your task is to implement the ShoppingCart class and process a series of operations, then return the final total.
Input: An array of operation strings in the format ["operation_type:param1,param2,..."]
Output: The final total price after all operations (rounded to 2 decimal places)
Input & Output
Example 1 — Basic Shopping Cart Operations
$
Input:
operations = ["add_item:A001,Apple,2.50,2", "add_item:B002,Bread,3.00,1", "update_quantity:A001,3", "add_item:C003,Milk,4.00,1"]
›
Output:
14.50
💡 Note:
Add 2 apples ($2.50 each), add 1 bread ($3.00), update apples to 3 total, add 1 milk ($4.00). Total: $2.50×3 + $3.00×1 + $4.00×1 = $14.50
Example 2 — Adding Same Item Multiple Times
$
Input:
operations = ["add_item:A001,Apple,2.50,1", "add_item:A001,Apple,2.50,2"]
›
Output:
7.50
💡 Note:
Add 1 apple, then add 2 more apples with same ID. Total quantity becomes 3. Total: $2.50×3 = $7.50
Example 3 — Remove Item Operation
$
Input:
operations = ["add_item:A001,Apple,2.50,2", "add_item:B002,Bread,3.00,1", "remove_item:A001"]
›
Output:
3.00
💡 Note:
Add apples and bread, then remove all apples. Only bread remains: $3.00×1 = $3.00
Constraints
- 1 ≤ operations.length ≤ 1000
- Item IDs are unique strings
- 0.01 ≤ price ≤ 1000.00
- 1 ≤ quantity ≤ 100
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code