#2887

Fill Missing Data

Easy
Hash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Using built-in functions in pandas allows us to efficiently fill missing values in a single operation, which is much faster than manually iterating through each row. This takes advantage of optimized internal implementations.

⚙️

Algorithm

2 steps
  1. 1Step 1: Use the pandas function fillna() to replace None values in the 'quantity' column with 0.
  2. 2Step 2: Return the modified DataFrame.
solution.py15 lines
1# Full working Python code
2import pandas as pd
3
4def fill_missing_quantity(df):
5    df['quantity'] = df['quantity'].fillna(0)
6    return df
7
8# Example usage
9input_df = pd.DataFrame({
10    'name': ['Wristwatch', 'WirelessEarbuds', 'GolfClubs', 'Printer'],
11    'quantity': [None, None, 779, 849],
12    'price': [135, 821, 9319, 3051]
13})
14output_df = fill_missing_quantity(input_df)
15print(output_df)

Complexity note: The time complexity is O(n) because we are processing each row in the DataFrame once. The space complexity is O(1) since we are modifying the DataFrame in place without using additional data structures.

  • 1Using built-in functions can improve efficiency significantly.
  • 2Understanding data structures like DataFrames is crucial.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.