Problem

DataFrame students

1
2
3
4
5
6
7
+-------------+--------+
| Column Name | Type   |
+-------------+--------+
| student_id  | int    |
| name        | object |
| age         | int    |
+-------------+--------+

Write a solution to select the name and age of the student with student_id = 101.

The result format is in the following example.

Examples

**Example 1:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
Input:
+------------+---------+-----+
| student_id | name    | age |
+------------+---------+-----+
| 101        | Ulysses | 13  |
| 53         | William | 10  |
| 128        | Henry   | 6   |
| 3          | Henry   | 11  |
+------------+---------+-----+

Output:
+---------+-----+
| name    | age | 
+---------+-----+
| Ulysses | 13  |
+---------+-----+

Explanation:
Student Ulysses has student_id = 101, we select the name and age.

Solution

Method 1 - Simple Filtering

Intuition

We need to select the name and age of the student with a specific student_id. This is a simple filter operation.

Approach

  1. Filter the DataFrame (or table) for rows where student_id = 101.
  2. Select only the name and age columns.

Code

1
2
3
SELECT name, age
FROM students
WHERE student_id = 101;
1
2
3
SELECT name, age
FROM students
WHERE student_id = 101;
1
2
# students is a pandas DataFrame
result = students.loc[students['student_id'] == 101, ['name', 'age']]

Complexity

  • ⏰ Time complexity: O(N) where N = number of students
  • 🧺 Space complexity: O(1) (output is a single row)