Skip to main content

Display the First Three Rows - Solution & Explanation

Easy5 min readAsked at: Amazon, Microsoft, Meta +1
Practice this problem

Problem Statement

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.

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.

Code

Python

JavaScript

Complexity

Time Complexity: O(1), since it directly accesses the specified rows.
Space Complexity: O(1), no additional space usage beyond the output.

Try this approach in the editor →

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.

This C++ solution manually iterates through the rows of a DataFrame using a for loop. We ensure to only access rows as long as they exist, preventing out-of-bound errors.

Code

C++

Java

Complexity

Time Complexity: O(1), since we only loop through a fixed number of rows.
Space Complexity: O(1), as we only store a constant number of rows.

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Using Built-in Methods for DataFrames

Time Complexity: O(1), since it directly accesses the specified rows.
Space Complexity: O(1), no additional space usage beyond the output.

Manual Iteration

Time Complexity: O(1), since we only loop through a fixed number of rows.
Space Complexity: O(1), as we only store a constant number of rows.

Default Approach—

Detailed Complexity Analysis

ApproachTimeSpaceWhen 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 IterationO(k) where k=3O(k)When DataFrame helpers are unavailable and data is stored in arrays or lists

Video Solution

2879. Display the First Three Rows | LeetCode | Python | Pandas • You Data And AI • 774 views views

Watch 5 more video solutions →

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.

Ready to solve this problem?

Practice Display the First Three Rows with our built-in code editor and test cases.

Practice on FleetCode