Talentd
FleetCode
Make and follow sheets.Sign in

Select Data solution and explanation

Easy4 min read79.2% acceptanceUpdated 9 Apr 2026
2880. Select Data | LeetCode | Python | PandasYou Data And AI · 1:42 · 880 viewsWatch on YouTube
4 more videos on this problem
  1. 2880. Select Data | LeetCode | Python | PandasYou Data And AI · 1:42 · 880 views
  2. LeetCode 2880 | Select Data | PythonSleepy Cracker · 0:48 · 195 views
  3. Select data LeetCode 2880CuteLeetCrafter · 2:05 · 139 views
  4. LeetCode 2880 Select Data in Python | Pandas Filtering Tutorial for BeginnersJR: Educational Channel · 1:05 · 87 views
  5. 2880 Select Data LeetCodeBrain Bloom · 0:32

The problem

DataFrame students
+-------------+--------+
| 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.

Example 1:
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.

Approach overview

Problem Overview: You are given a collection of data records and a condition that determines which records should be returned. The task is to scan the dataset and select only the entries that satisfy the required criteria. The challenge is straightforward: efficiently filter the relevant data while keeping the implementation simple.

Approach 1: Iterate and Filter (Time: O(n), Space: O(1) or O(k))

The most direct strategy is a linear scan of the dataset. Iterate through every record and check whether it satisfies the required condition. If the record matches, append it to the result list. This approach relies only on basic array iteration and conditional checks, making it easy to implement in any language.

The key idea is that you don't need extra preprocessing. Each element is evaluated exactly once using a simple if condition. The time complexity is O(n) because every element must be checked, while the space complexity is O(1) excluding the output (or O(k) if you count the selected results). This approach works well when the dataset is small or when you only perform the filtering operation once.

Approach 2: HashMap / Dictionary Lookup (Time: O(n), Space: O(n))

If the selection condition depends on matching specific identifiers or keys, a hash map (dictionary) can speed up repeated lookups. First build a map where the key represents the searchable attribute (for example, an ID) and the value stores the corresponding record. Building the map takes O(n) time.

Once the map exists, selecting records becomes a constant-time lookup using the key. Each lookup runs in O(1) average time due to hashing. This approach is useful when multiple queries are performed on the same dataset or when you frequently retrieve records by a unique field. The tradeoff is additional O(n) memory for storing the hash structure.

Hash-based lookups are a common pattern in problems involving dictionary-style access. Instead of repeatedly scanning the entire dataset, you convert the data into a structure optimized for fast retrieval.

Recommended for interviews: Start with the iterative filtering approach since it directly reflects the problem statement and demonstrates clear reasoning. Then mention the HashMap optimization if the problem involves repeated lookups or key-based access. Interviewers expect candidates to recognize when linear scanning is sufficient and when a hash-based structure reduces repeated work.

Approach 1: Approach 1: Iterate and Filter

Explanation: Iterator Filtering

This approach involves iterating through each record (or row) in the DataFrame and checking the 'student_id' against the specified value (101). Once a match is found, we can extract the 'name' and 'age' and return it as the result.

students = [
    {'student_id': 101, 'name': 'Ulysses', 'age': 13},
    {'student_id': 53, 'name': 'William', 'age': 10},
    {'student_id': 128, 'name': 'Henry', 'age': 6},
    {'student_id': 3, 'name': 'Henry', 'age': 11}
]

for student in students:
    if student['student_id'] == 101:
        print('+---------+-----+')
        print('| {name} | {age} |'.format(name=student['name'], age=student['age']))
        print('+---------+-----+')
        break
import java.util.ArrayList;

class Student {
    int student_id;
    String name;
    int age;

    public Student(int student_id, String name, int age) {
        this.student_id = student_id;
        this.name = name;
        this.age = age;
    }
}

public class SelectData {
    public static void main(String[] args) {
        ArrayList<Student> students = new ArrayList<>();
        students.add(new Student(101, "Ulysses", 13));
        students.add(new Student(53, "William", 10));
        students.add(new Student(128, "Henry", 6));
        students.add(new Student(3, "Henry", 11));

        for (Student student : students) {
            if (student.student_id == 101) {
                System.out.println("+---------+-----+");
                System.out.printf("| %7s | %3d |\n", student.name, student.age);
                System.out.println("+---------+-----+");
                break;
            }
        }
    }
}
#include <iostream>
#include <vector>
#include <string>

struct Student {
    int student_id;
    std::string name;
    int age;
};

void findStudent(const std::vector<Student>& students) {
    for (const auto& student : students) {
        if (student.student_id == 101) {
            std::cout << "+---------+-----+\n";
            std::cout << "| " << student.name << " | " << student.age << " |\n";
            std::cout << "+---------+-----+\n";
            break;
        }
    }
}

int main() {
    std::vector<Student> students = {
        {101, "Ulysses", 13},
        {53, "William", 10},
        {128, "Henry", 6},
        {3, "Henry", 11}
    };
    findStudent(students);
    return 0;
}
const students = [
    { student_id: 101, name: 'Ulysses', age: 13 },
    { student_id: 53, name: 'William', age: 10 },
    { student_id: 128, name: 'Henry', age: 6 },
    { student_id: 3, name: 'Henry', age: 11 }
];

for (let student of students) {
    if (student.student_id === 101) {
        console.log('+---------+-----+');
        console.log(`| ${student.name} | ${student.age} |`);
        console.log('+---------+-----+');
        break;
    }
}
#include <stdio.h>
#include <string.h>

typedef struct {
    int student_id;
    char name[50];
    int age;
} Student;

void find_student(Student students[], int length) {
    for(int i = 0; i < length; i++) {
        if(students[i].student_id == 101) {
            printf("+---------+-----+\n");
            printf("| %-7s | %-3d |\n", students[i].name, students[i].age);
            printf("+---------+-----+\n");
            break;
        }
    }
}

int main() {
    Student students[] = {
        {101, "Ulysses", 13},
        {53, "William", 10},
        {128, "Henry", 6},
        {3, "Henry", 11}
    };
    int length = sizeof(students)/sizeof(students[0]);
    find_student(students, length);

    return 0;
}
using System;
using System.Collections.Generic;

public class Student {
    public int student_id;
    public string name;
    public int age;

    public Student(int student_id, string name, int age) {
        this.student_id = student_id;
        this.name = name;
        this.age = age;
    }
}

public class SelectData {
    public static void Main() {
        List<Student> students = new List<Student> {
            new Student(101, "Ulysses", 13),
            new Student(53, "William", 10),
            new Student(128, "Henry", 6),
            new Student(3, "Henry", 11)
        };

        foreach (var student in students) {
            if (student.student_id == 101) {
                Console.WriteLine("+---------+-----+");
                Console.WriteLine("| {0,7} | {1,3} |", student.name, student.age);
                Console.WriteLine("+---------+-----+");
                break;
            }
        }
    }
}

The solution uses a list of dictionaries to represent the student data. By iterating over the list with a for loop and using Python's string formatting, we can output the desired 'name' and 'age' when the student ID is found.

Complexity

Time Complexity: O(n), since all students need to be considered until the correct ID is found.

Space Complexity: O(1), with no extra space allocated, merely a loop iterator.

Try this approach in the editor

Approach 2: Approach 2: HashMap/Dictionary Lookup

Explanation: Lookup with Map/Dictionary

This approach involves using a hash table, such as a Dictionary in Python or HashMap in Java, to store each student record with their student_id as the key. This enables direct access to a record based on student_id with average O(1) complexity, extracting 'name' and 'age' immediately.

students = {
    101: {'name': 'Ulysses', 'age': 13},
    53: {'name': 'William', 'age': 10},
    128: {'name': 'Henry', 'age': 6},
    3: {'name': 'Henry', 'age': 11}
}

student = students.get(101)
if student:
    print('+---------+-----+')
    print('| {name} | {age} |'.format(name=student['name'], age=student['age']))
    print('+---------+-----+')
import java.util.HashMap;

class Student {
    String name;
    int age;

    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class SelectData {
    public static void main(String[] args) {
        HashMap<Integer, Student> studentMap = new HashMap<>();
        studentMap.put(101, new Student("Ulysses", 13));
        studentMap.put(53, new Student("William", 10));
        studentMap.put(128, new Student("Henry", 6));
        studentMap.put(3, new Student("Henry", 11));

        Student student = studentMap.get(101);
        if (student != null) {
            System.out.println("+---------+-----+");
            System.out.println("| " + student.name + " | " + student.age + " |");
            System.out.println("+---------+-----+");
        }
    }
}
const studentMap = {
    101: { name: 'Ulysses', age: 13 },
    53: { name: 'William', age: 10 },
    128: { name: 'Henry', age: 6 },
    3: { name: 'Henry', age: 11 }
};

const student = studentMap[101];
if (student) {
    console.log('+---------+-----+');
    console.log(`| ${student.name} | ${student.age} |`);
    console.log('+---------+-----+');
}
using System;
using System.Collections.Generic;

public class Student {
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Program {
    public static void Main() {
        Dictionary<int, Student> studentsMap = new Dictionary<int, Student> {
            {101, new Student {Name = "Ulysses", Age = 13}},
            {53, new Student {Name = "William", Age = 10}},
            {128, new Student {Name = "Henry", Age = 6}},
            {3, new Student {Name = "Henry", Age = 11}}
        };

        if (studentsMap.TryGetValue(101, out Student student)) {
            Console.WriteLine("+---------+-----+");
            Console.WriteLine($"| {student.Name} | {student.Age} |");
            Console.WriteLine("+---------+-----+");
        }
    }
}

The solution leverages Python's dict structure, which maps student IDs to their details. Retrieval using students.get(101) fetches the necessary record in constant time.

Complexity

Time Complexity: O(1), due to direct dictionary key access.

Space Complexity: O(n), proportional to how many elements are stored.

Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach 1: Iterate and Filter

Time Complexity: O(n), since all students need to be considered until the correct ID is found.

Space Complexity: O(1), with no extra space allocated, merely a loop iterator.

Approach 2: HashMap/Dictionary Lookup

Time Complexity: O(1), due to direct dictionary key access.

Space Complexity: O(n), proportional to how many elements are stored.

Complexity analysis

ApproachTimeSpaceWhen to Use
Iterate and FilterO(n)O(1) or O(k)Best for a single pass through the dataset or when filtering is done once.
HashMap / Dictionary LookupO(n) build + O(1) lookupO(n)Useful when selecting data by key repeatedly or handling multiple queries efficiently.

Frequently asked questions

Is Select Data easy or hard?

Select Data is generally classified as an easy problem. The core idea is straightforward filtering using iteration. The HashMap variation introduces a common optimization pattern but remains beginner-friendly and focuses on fundamental data structure usage.

Select Data Python/Java solution

In Python, you typically iterate through the list and append matching elements to a result list or use dictionary lookups for faster retrieval. In Java, a loop over the collection with conditional checks works for filtering, while a HashMap<Integer, Record> can store key-to-record mappings for constant-time access.

How to solve Select Data in O(n)?

Traverse the dataset once and apply a conditional check to each record. If the record satisfies the selection rule, add it to the result. Since each element is processed exactly once, the algorithm runs in O(n) time with constant auxiliary space.

What is the best approach for Select Data?

The most practical solution is a single pass iteration that filters records matching the required condition. This runs in O(n) time and requires minimal extra memory. If the problem involves repeated lookups by a key or identifier, building a HashMap first allows O(1) average-time access for each query.

Is Select Data asked at Google/Amazon/Meta?

Problems involving filtering datasets and using hash-based lookups appear frequently in interviews at large tech companies. While the exact problem title may vary, the underlying pattern of linear scanning or HashMap-based retrieval is commonly tested in coding interviews.

What data structure is used in Select Data?

The simplest implementation uses arrays or lists for sequential traversal. For optimized retrieval, a HashMap (dictionary) is used to map keys to records, enabling constant-time lookups and avoiding repeated scans of the dataset.

What is the time complexity of Select Data?

The standard filtering solution runs in O(n) time because every record must be checked once. Space complexity is O(1) if only scanning the dataset, or O(k) if storing the filtered results. A HashMap-based approach still requires O(n) preprocessing but enables O(1) average lookup afterward.

Comments

Now write it yourselfClose this page and solve Select Data in the editor, without looking.
Practise Select Data