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.
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.
The function find_student() iterates through an array of Student structs, checking each student_id. When it finds a match (101), it prints out the 'name' and 'age' fields in a formatted manner.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the number of students. We may have to check each student in the worst case.
Space Complexity: O(1), as no additional space beyond input storage is used.
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.
Using a HashMap, students are stored with their ID as keys. By accessing studentMap.get(101), we retrieve the record instantly, allowing the program to directly print out the 'name' and 'age'.
Python
C#
JavaScript
Time Complexity: O(1), as hash table operations (get) average constant time.
Space Complexity: O(n), space usage increases with input size.
| Approach | Complexity |
|---|---|
| Approach 1: Iterate and Filter | Time Complexity: O(n), where n is the number of students. We may have to check each student in the worst case. Space Complexity: O(1), as no additional space beyond input storage is used. |
| Approach 2: HashMap/Dictionary Lookup | Time Complexity: O(1), as hash table operations (get) average constant time. Space Complexity: O(n), space usage increases with input size. |
How to Start Leetcode (as a beginner) • Ashish Pratap Singh • 1,177,673 views views
Watch 9 more video solutions →Practice Select Data with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor