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 details
  • remove_item(item_id) - Remove an item completely from the cart
  • update_quantity(item_id, new_quantity) - Update the quantity of an existing item
  • calculate_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
INPUTOperations Arrayadd_item:A001,Apple,2.50,2add_item:B002,Bread,3.00,1update_quantity:A001,3add_item:C003,Milk,4.00,14 operations to processALGORITHMHash Map Processing1Initialize Hash Mapcart = {}2Process Each OperationO(1) lookup by item ID3Update Cart StateAdd/Remove/Update items4Calculate TotalSum price × quantityFinal Cart State:A001: Apple×3B002: Bread×1C003: Milk×1RESULTFinal TotalCalculation:Apple: $2.50 × 3 = $7.50Bread: $3.00 × 1 = $3.00Milk: $4.00 × 1 = $4.00Total: $14.50Rounded to 2 decimal places✓ Cart Updated✓ Total CalculatedKey Insight:Hash maps provide O(1) item lookup by ID, making cart operations efficient even with many items. Much faster than linear array searches!TutorialsPoint - Shopping Cart Implementation | Hash Map Approach
Asked in
Amazon 85 Shopify 72 eBay 58 Walmart 45
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen