Talentd
FleetCode
Make and follow sheets.Sign in

Immediate Food Delivery II solution and explanation

MediumDatabase8 min read57.3% acceptanceUpdated 9 Apr 2026
Immediate Food Delivery II | Leetcode 1174 | Crack SQL Interviews in 50 Qs #mysql #leetcodeLearn With Chirag · 10:22 · 18K viewsWatch on YouTube
9 more videos on this problem
  1. Immediate Food Delivery II | Leetcode 1174 | Crack SQL Interviews in 50 Qs #mysql #leetcodeLearn With Chirag · 10:22 · 18K views
  2. 21. Immediate Food Delivery II | SQL Interview Questions and AnswersStart Practicing · 10:19 · 11K views
  3. LeetCode Medium 1174 Interview SQL Question with Detailed ExplanationEveryday Data Science · 10:51 · 7K views
  4. LeetCode 1174: Immediate Food Delivery IIFrederik Müller · 14:51 · 3K views
  5. SQL Interview | "Immediate Food Delivery II" | SQL 50 | Leetcode Problem 1174 | row_number functionManvi Jha · 6:24 · 183 views
  6. #LeetCode 1174 | Immediate Food Delivery II #SQLSleepy Cracker · 4:47 · 109 views
  7. Immediate Food Delivery II | Leetcode 1174Code with Siddhant · 5:42 · 66 views
  8. LeetCode 1174 | Immediate Food Delivery II | Step-by-Step Explanation | Interview Friendly ApproachVivek The Analyst · 8:38 · 55 views
  9. 21. Leetcode 1174. Immediate Food Delivery II : MYSQLWeb Fusion with Bharadwaj · 18:25 · 43 views
  10. LeetCode SQL50 | Day 21 | 1174. Immediate Food Delivery IIA for Analysis · 4:53 · 42 views

The problem

Table: Delivery

+-----------------------------+---------+
| Column Name                 | Type    |
+-----------------------------+---------+
| delivery_id                 | int     |
| customer_id                 | int     |
| order_date                  | date    |
| customer_pref_delivery_date | date    |
+-----------------------------+---------+
delivery_id is the column of unique values of this table.
The table holds information about food delivery to customers that make orders at some date and specify a preferred delivery date (on the same order date or after it).

If the customer's preferred delivery date is the same as the order date, then the order is called immediate; otherwise, it is called scheduled.

The first order of a customer is the order with the earliest order date that the customer made. It is guaranteed that a customer has precisely one first order.

Write a solution to find the percentage of immediate orders in the first orders of all customers, rounded to 2 decimal places.

The result format is in the following example.

Example 1:

Input: 
Delivery table:
+-------------+-------------+------------+-----------------------------+
| delivery_id | customer_id | order_date | customer_pref_delivery_date |
+-------------+-------------+------------+-----------------------------+
| 1           | 1           | 2019-08-01 | 2019-08-02                  |
| 2           | 2           | 2019-08-02 | 2019-08-02                  |
| 3           | 1           | 2019-08-11 | 2019-08-12                  |
| 4           | 3           | 2019-08-24 | 2019-08-24                  |
| 5           | 3           | 2019-08-21 | 2019-08-22                  |
| 6           | 2           | 2019-08-11 | 2019-08-13                  |
| 7           | 4           | 2019-08-09 | 2019-08-09                  |
+-------------+-------------+------------+-----------------------------+
Output: 
+----------------------+
| immediate_percentage |
+----------------------+
| 50.00                |
+----------------------+
Explanation: 
The customer id 1 has a first order with delivery id 1 and it is scheduled.
The customer id 2 has a first order with delivery id 2 and it is immediate.
The customer id 3 has a first order with delivery id 5 and it is scheduled.
The customer id 4 has a first order with delivery id 7 and it is immediate.
Hence, half the customers have immediate first orders.

Approach overview

Problem Overview: The Delivery table stores food delivery orders with the order date and the customer’s preferred delivery date. A delivery is considered immediate when order_date = customer_pref_delivery_date. The task is to compute the percentage of customers whose first order was delivered immediately.

Approach 1: SQL Approach with Subquery (Time: O(n), Space: O(n))

The key step is identifying each customer's first order. Use a subquery that groups rows by customer_id and extracts MIN(order_date). Join this result back to the Delivery table to retrieve the actual first order rows. After that, compute how many of those rows satisfy order_date = customer_pref_delivery_date. Divide the count of immediate deliveries by the total number of first orders and multiply by 100. This approach works well in most SQL engines and clearly separates the steps: find first orders, then compute the ratio. Useful when practicing fundamental SQL grouping and filtering patterns.

Approach 2: SQL Query with Window Functions (Time: O(n), Space: O(n))

Window functions provide a cleaner way to identify the first order per customer. Use ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date) to assign a rank to each order within a customer group. Filter rows where row_number = 1 to keep only the first order. From those rows, calculate the percentage where order_date = customer_pref_delivery_date. This avoids an explicit join and keeps the logic inside one query. Preferred when working with modern SQL systems that support window functions.

Approach 3: Python Pandas Approach (Time: O(n), Space: O(n))

Load the table into a Pandas DataFrame and sort by customer_id and order_date. Use groupby('customer_id').first() to extract each customer's earliest order. Then compare order_date and customer_pref_delivery_date to determine which rows are immediate. Compute the percentage by dividing the number of immediate rows by the total number of first orders. This approach mirrors the SQL logic but uses DataFrame operations from Pandas.

Approach 4: Iterative Approach with Data Structures (Time: O(n), Space: O(n))

In a general programming language, store the earliest order for each customer using a hash map keyed by customer_id. Iterate through all rows and update the stored record if a smaller order_date appears. After collecting the earliest order per customer, iterate over the stored records and count how many are immediate deliveries. Compute the percentage from these counts. This mirrors the SQL grouping behavior using basic data structures.

Recommended for interviews: The SQL window function approach is usually the cleanest and easiest to reason about. It shows that you understand partitioning and ranking within groups. The subquery solution demonstrates strong fundamentals and works even when window functions are unavailable, but the window-based query is typically the expected optimal solution.

Approach 1: SQL Approach with Subquery

This approach uses SQL to isolate the first order for each customer and then calculate the percentage of immediate orders.

<pre><code>SELECT ROUND(100.0 * SUM(CASE WHEN order_date = customer_pref_delivery_date THEN 1 ELSE 0 END) / COUNT(*), 2) AS immediate_percentage FROM ( SELECT customer_id, MIN(order_date) AS first_order_date FROM Delivery GROUP BY customer_id ) AS FirstOrders JOIN Delivery ON FirstOrders.customer_id = Delivery.customer_id AND FirstOrders.first_order_date = Delivery.order_date;</code></pre>

The query consists of two main parts:

  • An inner query which finds the first order date for each customer via a GROUP BY with the MIN() function.
  • An outer query that calculates the percentage of immediate orders from these first orders using a conditional SUM() within a CASE WHEN statement.
Complexity

Time Complexity: O(N), as we need to scan all deliveries to determine the first order per customer, where N is the number of records.
Space Complexity: O(K), where K is the number of unique customers since the auxiliary data structure to store these results depends on the number of unique customers.

Try this approach in the editor

Approach 2: Python Pandas Approach

This implementation relies on the Pandas library in Python to filter, group and compute the solution.

<pre><code>import pandas as pd
from io import StringIO

# Simulate database table as DataFrame
data = StringIO(""" delivery_id,customer_id,order_date,customer_pref_delivery_date
1,1,2019-08-01,2019-08-02
2,2,2019-08-02,2019-08-02
3,1,2019-08-11,2019-08-12
4,3,2019-08-24,2019-08-24
5,3,2019-08-21,2019-08-22
6,2,2019-08-11,2019-08-13
7,4,2019-08-09,2019-08-09
""")

df = pd.read_csv(data, parse_dates=['order_date', 'customer_pref_delivery_date'])

# Find first order for each customer
first_orders = df.loc[df.groupby('customer_id')['order_date'].idxmin()]

# Count immediate first orders
total_first_orders = len(first_orders)
immediate_orders = first_orders[first_orders['order_date'] == first_orders['customer_pref_delivery_date']].shape[0]

# Calculate and print the percentage of immediate first orders
immediate_percentage = round((immediate_orders / total_first_orders) * 100, 2)

# Print the result in the required format
print(pd.DataFrame({'immediate_percentage': [immediate_percentage]}))</code></pre>

In this solution, we use Pandas to:

  • Simulate the SQL GROUP BY functionality to find the first order for each customer using groupby and idxmin().
  • Calculate the percentage of immediate first orders by comparing the subset of first orders where order_date equals customer_pref_delivery_date.
Complexity

Time Complexity: O(N), as we need to process each order to determine which are the first for their customers.
Space Complexity: O(K), with K being the number of unique customers, since the additional memory used scales with the number of unique customer IDs.

Try this approach in the editor

Approach 3: SQL Query with Window Functions

This approach uses SQL window functions to determine the first order for each customer by order date. We utilize the ROW_NUMBER() function to rank each customer's orders and filter out the first one. Afterwards, we count which of these are immediate by comparing the order date with the customer's preferred delivery date.

SELECT ROUND(100.0 * SUM(CASE WHEN order_date = customer_pref_delivery_date THEN 1 ELSE 0 END) / COUNT(*), 2) AS immediate_percentage FROM (SELECT delivery_id, customer_id, order_date, customer_pref_delivery_date, ROW_NUMBER() OVER(PARTITION BY customer_id ORDER BY order_date) as rn FROM Delivery) tmp WHERE rn = 1;

Firstly, we use the ROW_NUMBER() function partitioned by customer_id and ordered by order_date to assign a sequence number to each order within a customer group. The innermost query captures this for each customer's orders. We then filter these to only include those with rn = 1, effectively giving us the first order for each customer. Finally, we calculate the percentage of immediate orders by taking the ratio of immediate first orders to total first orders.

Complexity

Time Complexity: O(N), where N is the number of rows in the Delivery table.
Space Complexity: O(N) due to the storage of intermediate results in the temporary table.

Try this approach in the editor

Approach 4: Iterative Approach with Data Structures

This approach involves using a programming language to iterate through the data stored in a collection, like a list or an array. We first sort the deliveries by customer ID and order date, then track the first order for each customer using a dictionary or hash map. Finally, we check each first order for immediacy and calculate the percentage of immediate deliveries.

def immediate_percentage(deliveries):
    from collections import defaultdict
    first_orders = defaultdict(lambda: (None, None))
    for delivery_id, customer_id, order_date, pref_date in sorted(deliveries, key=lambda x: (x[1], x[2])):
        if first_orders[customer_id][0] is None:
            first_orders[customer_id] = (order_date, pref_date)
    immediate_count = sum(1 for order_date, pref_date in first_orders.values() if order_date == pref_date)
    total_count = len(first_orders)
    return round(100.0 * immediate_count / total_count, 2)

deliveries = [
    (1, 1, '2019-08-01', '2019-08-02'),
    (2, 2, '2019-08-02', '2019-08-02'),
    (3, 1, '2019-08-11', '2019-08-12'),
    (4, 3, '2019-08-24', '2019-08-24'),
    (5, 3, '2019-08-21', '2019-08-22'),
    (6, 2, '2019-08-11', '2019-08-13'),
    (7, 4, '2019-08-09', '2019-08-09')
]
print(immediate_percentage(deliveries))
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <iomanip>
using namespace std;

double immediatePercentage(const vector<tuple<int, int, string, string>>& deliveries) {
    map<int, pair<string, string>> firstOrders;
    vector<tuple<int, int, string, string>> sortedDeliveries = deliveries;
    sort(sortedDeliveries.begin(), sortedDeliveries.end(), [](const auto& a, const auto& b) {
        return get<1>(a) < get<1>(b) || (get<1>(a) == get<1>(b) && get<2>(a) < get<2>(b));
    });

    for (const auto& delivery : sortedDeliveries) {
        int customer_id = get<1>(delivery);
        auto [order_date, pref_date] = make_pair(get<2>(delivery), get<3>(delivery));
        if (firstOrders.find(customer_id) == firstOrders.end()) {
            firstOrders[customer_id] = {order_date, pref_date};
        }
    }
    int immediateCount = count_if(firstOrders.begin(), firstOrders.end(), [](const auto& entry) {
        return entry.second.first == entry.second.second;
    });
    return round(100.0 * immediateCount / firstOrders.size() * 100) / 100;
}

int main() {
    vector<tuple<int, int, string, string>> deliveries = {
        {1, 1, "2019-08-01", "2019-08-02"},
        {2, 2, "2019-08-02", "2019-08-02"},
        {3, 1, "2019-08-11", "2019-08-12"},
        {4, 3, "2019-08-24", "2019-08-24"},
        {5, 3, "2019-08-21", "2019-08-22"},
        {6, 2, "2019-08-11", "2019-08-13"},
        {7, 4, "2019-08-09", "2019-08-09"}
    };
    cout << fixed << setprecision(2) << immediatePercentage(deliveries) << endl;
    return 0;
}

We first use a dictionary to store the first order date and preferred delivery date of each customer. By iterating over the sorted list of deliveries, we ensure only the earliest order for each customer is stored. We then use this data to count how many of these first orders are immediate and calculate their percentage.

Complexity

Time Complexity: O(N log N) due to sorting of deliveries.
Space Complexity: O(K), where K is the number of unique customers.

Try this approach in the editor

Complexity comparison

ApproachComplexity
SQL Approach with Subquery

Time Complexity: O(N), as we need to scan all deliveries to determine the first order per customer, where N is the number of records.
Space Complexity: O(K), where K is the number of unique customers since the auxiliary data structure to store these results depends on the number of unique customers.

Python Pandas Approach

Time Complexity: O(N), as we need to process each order to determine which are the first for their customers.
Space Complexity: O(K), with K being the number of unique customers, since the additional memory used scales with the number of unique customer IDs.

SQL Query with Window Functions

Time Complexity: O(N), where N is the number of rows in the Delivery table.
Space Complexity: O(N) due to the storage of intermediate results in the temporary table.

Iterative Approach with Data Structures

Time Complexity: O(N log N) due to sorting of deliveries.
Space Complexity: O(K), where K is the number of unique customers.

Complexity analysis

ApproachTimeSpaceWhen to Use
SQL with SubqueryO(n)O(n)When practicing classic SQL aggregation and joins
SQL with Window FunctionsO(n)O(n)Best approach in modern SQL engines supporting window functions
Python PandasO(n)O(n)Data analysis workflows or Python-based data processing
Iterative Hash MapO(n)O(n)Implementing database-style grouping in general programming languages

Frequently asked questions

Immediate Food Delivery II Python solution

In Python, the problem can be solved using Pandas by sorting the DataFrame by customer_id and order_date, then using groupby('customer_id').first() to get the earliest order. Compare order_date with customer_pref_delivery_date and compute the percentage of immediate deliveries.

Is Immediate Food Delivery II easy or hard?

Immediate Food Delivery II is generally considered a medium difficulty SQL problem. The challenge comes from identifying the first order per customer and then calculating a percentage from that filtered dataset. Familiarity with GROUP BY or window functions makes the problem straightforward.

How to solve Immediate Food Delivery II in O(n)?

First identify the earliest order for each customer using either MIN(order_date) with GROUP BY or a window function like ROW_NUMBER(). Filter to keep only those first orders. Count how many have order_date equal to customer_pref_delivery_date and divide by the total number of first orders to compute the percentage.

What is the best approach for Immediate Food Delivery II?

The SQL window function approach using ROW_NUMBER() is typically the best solution. Partition rows by customer_id and order by order_date to identify the first order per customer. Then calculate the percentage of those rows where order_date equals customer_pref_delivery_date. The query runs in O(n) time and is concise in modern SQL engines.

Is Immediate Food Delivery II asked at Google/Amazon/Meta?

Database aggregation and window-function problems like Immediate Food Delivery II appear frequently in SQL interview rounds at companies such as Amazon, Meta, and data-focused roles at Google. These questions test your ability to group records, find first events, and compute ratios from filtered data.

What data structure is used in Immediate Food Delivery II?

In SQL, the solution relies on grouping operations or window functions rather than explicit data structures. In a programming-language implementation, a hash map keyed by customer_id can store the earliest order for each customer, enabling an O(n) solution.

What is the time complexity of Immediate Food Delivery II?

Most optimal solutions run in O(n) time where n is the number of rows in the Delivery table. SQL engines scan the table once and perform grouping or window partitioning by customer_id. Space complexity is generally O(n) for intermediate grouping or ranking results.

Comments

Now write it yourselfClose this page and solve Immediate Food Delivery II in the editor, without looking.
Practise Immediate Food Delivery II