Count Apples and Oranges — LeetCode 1715 Python Solution
MediumLeetCode PremiumDatabase
- Problem
- #1715
- Reading time
- 3 min
- Source
- leetcode.com
Table schema
SQL
Table: Boxes +--------------+------+ | Column Name | Type | +--------------+------+ | box_id | int | | chest_id | int | | apple_count | int | | orange_count | int | +--------------+------+ box_id is the column with unique values for this table. chest_id is a foreign key (reference column) of the chests table.Example
SQL
+--------------+------+
| Column Name | Type |
+--------------+------+
| box_id | int |
| chest_id | int |
| apple_count | int |
| orange_count | int |
+--------------+------+
box_id is the column with unique values for this table.
chest_id is a foreign key (reference column) of the chests table.
This table contains information about the boxes and the number of oranges and apples they have. Each box may include a chest, which also can contain oranges and apples.Python solution
Python
import pandas as pd
def count_apples_and_oranges(boxes: pd.DataFrame, chests: pd.DataFrame) -> pd.DataFrame:
merged_df = boxes.merge(
chests, on="chest_id", how="left", suffixes=("_box", "_chest")
)
apple_count = (
merged_df["apple_count_box"].fillna(0)
+ merged_df["apple_count_chest"].fillna(0)
).sum()
orange_count = (
merged_df["orange_count_box"].fillna(0)
+ merged_df["orange_count_chest"].fillna(0)
).sum()
return pd.DataFrame({"apple_count": [apple_count], "orange_count": [orange_count]})Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 1715. Count Apples and Oranges?
- LeetCode 1715. Count Apples and Oranges is rated Medium on LeetCode.
- What topics does LeetCode 1715. Count Apples and Oranges cover?
- LeetCode 1715. Count Apples and Oranges is tagged Database on LeetCode.
- Is LeetCode 1715. Count Apples and Oranges a premium problem?
- Yes. LeetCode 1715. Count Apples and Oranges is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.