LeetCode 1532: The Most Recent Three Orders Solution
Master LeetCode problem 1532 (The Most Recent Three Orders), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1532. The Most Recent Three Orders
Problem Explanation
Explanation:
To solve this problem, we can maintain a data structure to store the most recent three orders for each customer. We can use a HashMap where the key is the customer id and the value is a Queue of the most recent three orders. Whenever a new order comes in for a customer, we update the Queue with the latest order and remove the oldest one if necessary.
Algorithmic Idea:
- Initialize a HashMap to store the most recent three orders for each customer.
- For each new order:
- Check if the customer already exists in the HashMap.
- If the customer exists:
- Update the existing Queue with the new order and remove the oldest order if the Queue size exceeds three.
- If the customer does not exist:
- Create a new Queue with the new order and add it to the HashMap.
Time Complexity:
- Inserting a new order: O(1)
- Removing the oldest order if the Queue size exceeds three: O(1)
Space Complexity:
- O(n) where n is the number of unique customers.
:
Solution Code
class RecentOrders {
Map<Integer, Queue<Integer>> recentOrders;
public RecentOrders() {
recentOrders = new HashMap<>();
}
public void addOrder(int customer_id, int order_id) {
if (recentOrders.containsKey(customer_id)) {
Queue<Integer> queue = recentOrders.get(customer_id);
queue.offer(order_id);
if (queue.size() > 3) {
queue.poll();
}
} else {
Queue<Integer> queue = new LinkedList<>();
queue.offer(order_id);
recentOrders.put(customer_id, queue);
}
}
public List<Integer> getRecentOrders(int customer_id) {
if (recentOrders.containsKey(customer_id)) {
return new ArrayList<>(recentOrders.get(customer_id));
} else {
return new ArrayList<>();
}
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1532 (The Most Recent Three Orders)?
This page provides optimized solutions for LeetCode problem 1532 (The Most Recent Three Orders) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1532 (The Most Recent Three Orders)?
The time complexity for LeetCode 1532 (The Most Recent Three Orders) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1532 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1532 in Java, C++, or Python.