#1174
Immediate Food Delivery II
MediumDatabaseHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
In the optimal solution, we use a single pass to gather the first orders and check for immediacy in one go. This reduces the number of iterations and improves efficiency.
⚙️
Algorithm
4 steps- 1Step 1: Use a HashMap to store the first order date for each customer.
- 2Step 2: Iterate through the Delivery table and populate the HashMap with the earliest order date for each customer.
- 3Step 3: Count the immediate orders by checking if the preferred delivery date matches the first order date.
- 4Step 4: Calculate the percentage of immediate orders and round to 2 decimal places.
solution.py6 lines
1# Full working Python code
2SELECT ROUND(SUM(CASE WHEN order_date = customer_pref_delivery_date THEN 1 ELSE 0 END) * 100.0 / COUNT(*), 2) AS immediate_percentage
3FROM (SELECT customer_id, MIN(order_date) AS first_order_date
4 FROM Delivery
5 GROUP BY customer_id) AS first_orders
6JOIN Delivery ON first_orders.customer_id = Delivery.customer_id AND first_orders.first_order_date = Delivery.order_date;ℹ
Complexity note: This complexity is linear because we only pass through the data a couple of times, making it efficient.
- 1Understanding the difference between immediate and scheduled orders is crucial.
- 2Using a HashMap can significantly reduce time complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.