Display the First Three Rows solution and explanation
5 more videos on this problem
2879. Display the First Three Rows | LeetCode | Python | PandasYou Data And AI · 1:00 · 774 views
Display The First Three Rows. LeetCode 2879CuteLeetCrafter · 0:44 · 148 views
Leetcode 2879 - Display the first three rows [Pandas]Ptolémé · 1:35 · 73 views
2879. Display the First Three RowsTech Guides · 1:05 · 50 views
2879 Display the First Three Rows | LeetCodeBrain Bloom · 0:32 · 18 views
2879. Display the First Three Rows | LeetCode Using Python (Panda Library)Muhammad Marenah · 1:42 · 18 views
The problem
DataFrame: employees
+-------------+--------+
| Column Name | Type |
+-------------+--------+
| employee_id | int |
| name | object |
| department | object |
| salary | int |
+-------------+--------+
Write a solution to display the first 3 rows of this DataFrame.
Example 1:
Input: DataFrame employees +-------------+-----------+-----------------------+--------+ | employee_id | name | department | salary | +-------------+-----------+-----------------------+--------+ | 3 | Bob | Operations | 48675 | | 90 | Alice | Sales | 11096 | | 9 | Tatiana | Engineering | 33805 | | 60 | Annabelle | InformationTechnology | 37678 | | 49 | Jonathan | HumanResources | 23793 | | 43 | Khaled | Administration | 40454 | +-------------+-----------+-----------------------+--------+ Output: +-------------+---------+-------------+--------+ | employee_id | name | department | salary | +-------------+---------+-------------+--------+ | 3 | Bob | Operations | 48675 | | 90 | Alice | Sales | 11096 | | 9 | Tatiana | Engineering | 33805 | +-------------+---------+-------------+--------+ Explanation: Only the first 3 rows are displayed.
Approach overview
Problem Overview: You are given a DataFrame and need to return only the first three rows. The task focuses on selecting a small subset of rows from a tabular structure while preserving the original column layout.
Approach 1: Using Built-in DataFrame Methods (O(1) time, O(1) space)
Most DataFrame libraries provide direct utilities to retrieve the first k rows. In Python's pandas, df.head(3) returns the first three records without modifying the original DataFrame. JavaScript DataFrame libraries typically expose a similar slice or head-style function. Since the number of rows requested is constant (3), the operation runs in O(1) time and uses O(1) additional space for references to the rows. This approach relies on optimized library internals and is the cleanest way to solve the problem when working with structured tabular data.
Under the hood, the method simply selects the first three row indices and constructs a new view or shallow copy. No full traversal of the dataset is required. If you frequently work with tabular datasets, mastering built-in operations like head(), tail(), and slicing will significantly improve productivity.
Approach 2: Manual Iteration (O(k) time, O(k) space)
When built-in DataFrame utilities are unavailable, you can manually iterate through the dataset and collect the first three rows. Use a loop that stops after reading three records and store them in a result container such as a vector or list. Here k = 3, so the algorithm performs only three iterations, resulting in O(k) time and O(k) space for the output structure.
This approach is common in languages like C++ or Java where datasets are often represented as arrays, lists, or custom row objects. You iterate from index 0 up to min(3, n) and copy each row into the result. While simple, it demonstrates control over iteration and boundary handling.
The manual method is essentially a constrained traversal problem related to basic arrays and iteration. It also mirrors how row slicing works internally in many dataframe implementations.
Recommended for interviews: The built-in DataFrame method is the expected solution when the environment provides a DataFrame API. It is concise, readable, and leverages optimized library operations. Manual iteration still matters because it proves you understand how row selection works internally. Interviewers often expect you to recognize the library shortcut first, then explain the underlying iteration logic.
Approach 1: Using Built-in Methods for DataFrames
Most data manipulation libraries provide a direct method to access the top few rows of a DataFrame. This approach utilizes the built-in method to fetch the first three rows efficiently.
import pandas as pd
def get_first_three_rows(employees):
return employees.head(3)function getFirstThreeRows(employees) {
return employees.slice(0, 3);
}Using Pandas in Python, the head function allows us to grab the first few rows of the DataFrame. By default, it retrieves 5 rows, but you can specify the number, in this case, 3.
Time Complexity: O(1), since it directly accesses the specified rows.
Space Complexity: O(1), no additional space usage beyond the output.
Approach 2: Manual Iteration
This approach involves manually iterating over the DataFrame and extracting the first three rows. It's useful in languages or environments where built-in functionality might not exist.
import java.util.List;
import java.util.ArrayList;
public List<List<String>> getFirstThreeRows(List<List<String>> employees) {
return employees.subList(0, Math.min(3, employees.size()));
}#include <iostream>
#include <vector>
#include <string>
using namespace std;
typedef vector<vector<string>> DataFrame;
DataFrame getFirstThreeRows(const DataFrame &employees) {
DataFrame result;
for (int i = 0; i < 3 && i < employees.size(); ++i) {
result.push_back(employees[i]);
}
return result;
}In Java, this approach uses the subList method to extract the first three rows. We take care to not exceed the bounds of the list with Math.min.
Time Complexity: O(1), assuming subList is a constant time operation.
Space Complexity: O(1), the sublist does not require additional space.
Complexity comparison
| Approach | Complexity |
|---|---|
| Using Built-in Methods for DataFrames | Time Complexity: O(1), since it directly accesses the specified rows. |
| Manual Iteration | Time Complexity: O(1), assuming subList is a constant time operation. |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Built-in DataFrame Methods (head/slice) | O(1) | O(1) | When working with pandas or DataFrame libraries that provide row-selection utilities |
| Manual Iteration | O(k) where k=3 | O(k) | When DataFrame helpers are unavailable and data is stored in arrays or lists |
Frequently asked questions
Is Display the First Three Rows easy or hard?
Display the First Three Rows is categorized as an Easy problem. It primarily tests familiarity with DataFrame APIs or basic iteration logic rather than complex algorithms or data structures.
Display the First Three Rows Python/Java solution
In Python with pandas, the solution is simply employees.head(3). In Java or C++, if the data is stored in arrays or lists, iterate from index 0 to min(3, n) and copy those rows into the result structure. Both implementations rely on selecting the first three entries of the dataset.
How to solve Display the First Three Rows in O(1)?
Use a built-in DataFrame operation that directly returns the first k rows. In pandas, calling df.head(3) selects the first three records without scanning the entire dataset. Because the number of accessed rows is constant, the runtime stays O(1).
What is the best approach for Display the First Three Rows?
The best approach is using built-in DataFrame utilities such as df.head(3) in pandas or an equivalent slice/head method in JavaScript DataFrame libraries. These functions directly return the first three rows without manual iteration. The operation runs in O(1) time and O(1) extra space because only a constant number of rows are accessed.
Is Display the First Three Rows asked at Google/Amazon/Meta?
This problem reflects common data manipulation tasks used in data engineering and analytics interviews rather than traditional algorithm-heavy interviews. Companies that evaluate data processing skills often expect familiarity with DataFrame operations such as selecting rows, filtering, and slicing.
What data structure is used in Display the First Three Rows?
The problem operates on a DataFrame, which is a tabular data structure similar to a table with labeled columns and indexed rows. Internally, many implementations store columns as arrays or series, making row slicing a lightweight index-based operation.
What is the time complexity of Display the First Three Rows?
The optimal solution runs in O(1) time since only three rows are retrieved regardless of dataset size. Manual iteration would technically be O(k) where k = 3, which still behaves like constant time. Space complexity is O(1) for built-in methods or O(k) if copying rows into a new container.
