Given a collection of items with their corresponding prices, design a data structure that efficiently supports the following operations:
- add(price, item): Adds a new item along with its price.
- find(price): Fetches the item associated with the given price.
- printSorted(): Prints all items in increasing order of price.
- printGreaterSorted(price): Prints all items in increasing order of price, but only those with a price greater than the given price.
- printSmallerSorted(price): Prints all items in increasing order of price, but only those with a price smaller than the given price.
Note: We assume that all prices are distinct.
Naive Solution
In this approach, items are stored in a sorted array based on price, ensuring that all elements remain ordered at all times.
- Maintain an array of (price, item) pairs sorted by price.
- Insert a new item at the correct position to keep the array sorted.
- Use binary search to find an item by its price.
- Traverse the array directly to print all items in sorted order.
- Use binary search to locate the boundary index for printing greater or smaller prices.
OutputEraser 30
Notebook 75
WaterBottle 120
Backpack 180
Notebook
WaterBottle 120
Backpack 180
Eraser 30
Notebook 75
Time Complexity
- add: O(N) - elements may need to be shifted to maintain order.
- find: O(log N) - binary search on sorted array.
Space Complexity: O(N) - array storage for items.
Efficient Solution
To overcome the limitations of array-based approaches, a more efficient approach uses TreeMap, which stores items automatically sorted by price and supports fast searching and range-based queries.
- Store item prices as keys and item names as values in a TreeMap.
- Insert items directly using the put() method.
- Retrieve an item using direct key lookup.
- Traverse the map to print all items in sorted order.
- Use headMap() and tailMap() for range-based printing.