Change Data Type solution and explanation
4 more videos on this problem
2886. Change Data Type | LeetCode | Python | PandasYou Data And AI · 1:53 · 398 views
Change Data Type | Data Cleaning | Introduction to Pandas | #pandas #python #leetcodeLearn With Chirag · 4:55 · 263 views
Change Data Type LeetCode 2886CuteLeetCrafter · 0:57 · 164 views
Leetcode 2886 - Change column type [Pandas]Ptolémé · 1:33 · 9 views
LeetCode, intro to pandas, 2886. Change Data TypePooyaDev · 1:27 · 5 views
The problem
DataFrame students
+-------------+--------+
| Column Name | Type |
+-------------+--------+
| student_id | int |
| name | object |
| age | int |
| grade | float |
+-------------+--------+
Write a solution to correct the errors:
The grade column is stored as floats, convert it to integers.
The result format is in the following example.
Example 1: Input: DataFrame students: +------------+------+-----+-------+ | student_id | name | age | grade | +------------+------+-----+-------+ | 1 | Ava | 6 | 73.0 | | 2 | Kate | 15 | 87.0 | +------------+------+-----+-------+ Output: +------------+------+-----+-------+ | student_id | name | age | grade | +------------+------+-----+-------+ | 1 | Ava | 6 | 73 | | 2 | Kate | 15 | 87 | +------------+------+-----+-------+ Explanation: The data types of the column grade is converted to int.
Approach overview
Problem Overview: You are given a dataset where one or more fields are stored using the wrong data type (for example, numbers stored as strings). The task is to convert the column into the correct data type so it can be used for numeric operations, sorting, or analysis.
Approach 1: Using DataFrame Libraries (O(n) time, O(1) extra space)
Most modern languages provide high-level data processing libraries that handle type conversion efficiently. In Python, libraries like pandas allow direct casting using astype(). Similar functionality exists in JavaScript data libraries, Java data processing frameworks, and C# data table APIs. The key idea is simple: select the column and apply a built-in conversion function that transforms every value to the target type internally. These libraries are optimized in native code and perform the conversion in linear time relative to the number of rows.
This approach is concise and reliable because the library automatically handles iteration, parsing, and potential edge cases such as null values. When working with structured datasets, analytics pipelines, or tabular processing, this is the most practical solution.
Approach 2: Manual Iteration and Conversion (O(n) time, O(1) extra space)
If a DataFrame-style library is not available, you can convert values manually. Iterate through each record in the dataset, read the value as a string (or existing type), and apply a type conversion function such as int(), parseInt(), or language-specific casting operators. Replace the original value with the converted one while iterating through the collection.
This approach explicitly performs the conversion step for every element. The algorithm scans the dataset once, making the time complexity O(n). Memory usage stays constant because the conversion happens in place without allocating additional structures.
Manual iteration is useful when you are working with raw arrays, custom objects, or low-level systems where DataFrame utilities are unavailable. It also helps reinforce basic iteration and type conversion concepts that appear frequently in data processing tasks.
Recommended for interviews: The DataFrame approach is the cleanest solution in real-world data engineering environments because it uses optimized library operations. However, interviewers often expect you to explain the underlying logic. Showing the manual iteration approach demonstrates that you understand how each value is parsed and converted, while still recognizing that the optimal complexity remains O(n).
Approach 1: Approach 1: Using DataFrame Libraries
In this approach, we use the standard data handling libraries or frameworks provided by each language to manipulate the DataFrame. This generally involves directly converting the column data type from float to int.
import pandas as pd
# Example data
students = pd.DataFrame({
'student_id': [1, 2],
'name': ['Ava', 'Kate'],
'age': [6, 15],
'grade': [73.0, 87.0]
})
# Converting grade column to int
def convert_grade_to_int(students_df):
students_df['grade'] = students_df['grade'].astype(int)
return students_df
# Output
converted_students = convert_grade_to_int(students)
print(converted_students)import java.util.*;
class Student {
int student_id;
String name;
int age;
double grade;
Student(int student_id, String name, int age, double grade) {
this.student_id = student_id;
this.name = name;
this.age = age;
this.grade = grade;
}
}
public class Main {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student(1, "Ava", 6, 73.0));
students.add(new Student(2, "Kate", 15, 87.0));
for (Student student : students) {
student.grade = (int) student.grade;
}
for (Student student : students) {
System.out.printf("%d, %s, %d, %d\n", student.student_id, student.name, student.age, (int) student.grade);
}
}
}let students = [
{ student_id: 1, name: "Ava", age: 6, grade: 73.0 },
{ student_id: 2, name: "Kate", age: 15, grade: 87.0 }
];
students.forEach(student => {
student.grade = Math.floor(student.grade);
});
console.log(students);#include <stdio.h>
typedef struct {
int student_id;
char name[50];
int age;
double grade;
} Student;
void convertGradeToInt(Student *students, int size) {
for (int i = 0; i < size; i++) {
students[i].grade = (int)students[i].grade;
}
}
int main() {
Student students[] = {
{1, "Ava", 6, 73.0},
{2, "Kate", 15, 87.0}
};
int size = sizeof(students) / sizeof(students[0]);
convertGradeToInt(students, size);
for (int i = 0; i < size; i++) {
printf("%d, %s, %d, %d\n", students[i].student_id, students[i].name, students[i].age, (int)students[i].grade);
}
return 0;
}using System;
using System.Data;
class Program
{
static void Main()
{
DataTable students = new DataTable();
students.Columns.Add("student_id", typeof(int));
students.Columns.Add("name", typeof(string));
students.Columns.Add("age", typeof(int));
students.Columns.Add("grade", typeof(double));
students.Rows.Add(1, "Ava", 6, 73.0);
students.Rows.Add(2, "Kate", 15, 87.0);
foreach (DataRow row in students.Rows)
{
row["grade"] = Convert.ToInt32(row["grade"]);
}
foreach (DataRow row in students.Rows)
{
Console.WriteLine($"{row["student_id"]}, {row["name"]}, {row["age"]}, {row["grade"]}");
}
}
}This Python code uses pandas, a popular library for data manipulation. The 'astype' method is used to convert the 'grade' column to integer type, thereby eliminating the decimal part.
Time Complexity: O(n), where n is the number of elements in the DataFrame.
Space Complexity: O(1), as it modifies the DataFrame in place.
Approach 2: Approach 2: Manual Iteration and Conversion
This approach involves manually iterating over the data structure (for example, an array or list) and converting each 'grade' entry from a float or double to an integer representation. It's a more generalized approach and less dependent on specific data manipulation libraries.
def convert_grades_to_int_manually(students):
for student in students:
student['grade'] = int(student['grade'])
return students
# Example
students = [
{'student_id': 1, 'name': 'Ava', 'age': 6, 'grade': 73.0},
{'student_id': 2, 'name': 'Kate', 'age': 15, 'grade': 87.0}
]
converted_students = convert_grades_to_int_manually(students)
print(converted_students)const students = [
{ student_id: 1, name: "Ava", age: 6, grade: 73.0 },
{ student_id: 2, name: "Kate", age: 15, grade: 87.0 }
];
for (let i = 0; i < students.length; i++) {
students[i].grade = parseInt(students[i].grade, 10);
}
console.log(students);#include <stdio.h>
typedef struct {
int student_id;
char name[50];
int age;
float grade;
} Student;
int main() {
Student students[] = {
{1, "Ava", 6, 73.0},
{2, "Kate", 15, 87.0}
};
int num_students = sizeof(students) / sizeof(students[0]);
for (int i = 0; i < num_students; i++) {
students[i].grade = (int)students[i].grade; // Manual conversion
}
for (int i = 0; i < num_students; i++) {
printf("%d, %s, %d, %d\n", students[i].student_id, students[i].name, students[i].age, (int)students[i].grade);
}
return 0;
}This code demonstrates how to manually iterate over a list of dictionaries in Python, converting the 'grade' field of each dictionary to an integer.
Time Complexity: O(n), where n is the number of dictionaries.
Space Complexity: O(1), due to in-place updates.
Complexity comparison
| Approach | Complexity |
|---|---|
| Approach 1: Using DataFrame Libraries | Time Complexity: O(n), where n is the number of elements in the DataFrame. |
| Approach 2: Manual Iteration and Conversion | Time Complexity: O(n), where n is the number of dictionaries. |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Using DataFrame Libraries | O(n) | O(1) | Best for structured datasets and analytics workflows using libraries like pandas or similar table APIs |
| Manual Iteration and Conversion | O(n) | O(1) | Useful when working with raw arrays, objects, or environments without DataFrame utilities |
Frequently asked questions
Is Change Data Type easy or hard?
Change Data Type is considered an easy problem because the algorithm only requires a single pass through the dataset. The main concept is understanding how to apply type casting correctly across all elements.
Change Data Type Python/Java solution
In Python, pandas provides df['column'] = df['column'].astype(int) to convert the column type. In Java or C#, similar transformations can be done by iterating through rows and parsing values using Integer.parseInt or equivalent casting utilities.
How to solve Change Data Type in O(n)?
Iterate through the dataset once and convert each value to the desired type using a casting function such as int(), parseInt(), or a library equivalent. Replace the original value with the converted value during iteration. DataFrame libraries internally follow the same linear scan approach.
What is the best approach for Change Data Type?
The most practical approach is using built-in DataFrame or table libraries that support column casting. Functions like pandas astype() convert an entire column in O(n) time while keeping code concise and readable. These libraries also handle edge cases such as missing values and invalid formats.
Is Change Data Type asked at Google/Amazon/Meta?
Data type conversion problems commonly appear in data engineering and analytics interviews at companies like Google, Amazon, and Meta. They often appear as part of larger data manipulation tasks involving datasets, parsing, or preprocessing pipelines.
What data structure is used in Change Data Type?
The problem typically operates on tabular datasets such as DataFrames, tables, or arrays of records. The conversion is applied column-wise while iterating through rows. No advanced data structures are required beyond basic collections.
What is the time complexity of Change Data Type?
The time complexity is O(n) because each value in the column must be converted once. Whether using a DataFrame library or manual iteration, the algorithm processes every row exactly one time. Space complexity is typically O(1) if the conversion happens in place.
