VOOZH about

URL: https://www.geeksforgeeks.org/java/design-a-ds-for-prices-duplicates-allowed/

⇱ Design a DS for prices - duplicates allowed - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Design a DS for prices - duplicates allowed

Last Updated : 28 Jan, 2026

Design a data structure that stores items with associated prices (duplicates allowed) while supporting fast insertion, lookup by price, and sorted as well as range-based retrieval of items.

Naive Approach (ArrayList)

Follow these steps to implement using a simple list:

  • Create an Item class with fields name and price.
  • Maintain an ArrayList of all items.
  • add(price, item) : Append the item to the list.
  • find(price): Traverse the list and collect items with the given price.
  • printSorted(): Sort the list by price and print all items.
  • printGreaterSorted(price): Filter items with price ≥ given price, sort, and print.
  • printSmallerSorted(price): Filter items with price < given price, sort, and print.

Implementation


Output
Sorted Data:
Book 50
Notebook 50
Pen 100
Pencil 100
Phone 150
Laptop 200

Items at price 100:
[Pen, Pencil]

Items with price >= 100:
Pen 100
Pencil 100
Phone 150
Laptop 200

Efficient Approach (TreeMap)

Follow these steps to implement the efficient solution:

  • Use a TreeMap where the key is the price and the value is a list of items.
  • Add items to the list corresponding to their price.
  • Retrieve items for a given price directly from the map.
  • Iterate over the TreeMap to print items in sorted order.
  • Use tailMap() for prices greater than or equal to a value.
  • Use headMap() for prices smaller than a value.

Implementation


Output
Sorted Data:
Book 50
Notebook 50
Pen 100
Pencil 100
Phone 150
Laptop 200

Items at price 100:
[Pen, Pencil]

Items with price >= 100:
Pen 100
Pencil 100
Phone 150
Laptop 200
Comment
Article Tags:
Article Tags: