Talentd
FleetCode
Make and follow sheets.Sign in

Rename Columns solution and explanation

Easy5 min read85.4% acceptanceUpdated 9 Apr 2026
2885. Rename Columns | LeetCode | Python | PandasYou Data And AI · 3:46 · 610 viewsWatch on YouTube
8 more videos on this problem
  1. 2885. Rename Columns | LeetCode | Python | PandasYou Data And AI · 3:46 · 610 views
  2. Rename Columns | Data Cleaning | Introduction to Pandas | #pandas #python #leetcodeLearn With Chirag · 5:12 · 276 views
  3. Rename Columns LeetCode 2885CuteLeetCrafter · 1:51 · 121 views
  4. LeetCode 2885 Rename Columns in Python | Pandas Tutorial for BeginnersJR: Educational Channel · 1:10 · 97 views
  5. Leetcode 2885 - Rename Columns [Pandas]Ptolémé · 2:02 · 10 views
  6. Rename Columns | Pandas - Python | CoderCodesCoderCodes · 1:52 · 10 views
  7. LeetCode, intro to pandas, 2885. Rename ColumnsPooyaDev · 2:07 · 9 views
  8. Rename Columns || Leetcode Pandas PracticeTechify Tutorials · 3:26 · 5 views
  9. LeetCode. Pandas, [2885 -2891]. Rename Columns, уровень EASYДиванная аналитика · 39:14

The problem

DataFrame students
+-------------+--------+
| Column Name | Type   |
+-------------+--------+
| id          | int    |
| first       | object |
| last        | object |
| age         | int    |
+-------------+--------+

Write a solution to rename the columns as follows:

  • id to student_id
  • first to first_name
  • last to last_name
  • age to age_in_years

The result format is in the following example.

Example 1:
Input:
+----+---------+----------+-----+
| id | first   | last     | age |
+----+---------+----------+-----+
| 1  | Mason   | King     | 6   |
| 2  | Ava     | Wright   | 7   |
| 3  | Taylor  | Hall     | 16  |
| 4  | Georgia | Thompson | 18  |
| 5  | Thomas  | Moore    | 10  |
+----+---------+----------+-----+
Output:
+------------+------------+-----------+--------------+
| student_id | first_name | last_name | age_in_years |
+------------+------------+-----------+--------------+
| 1          | Mason      | King      | 6            |
| 2          | Ava        | Wright    | 7            |
| 3          | Taylor     | Hall      | 16           |
| 4          | Georgia    | Thompson  | 18           |
| 5          | Thomas     | Moore     | 10           |
+------------+------------+-----------+--------------+
Explanation: 
The column names are changed accordingly.

Approach overview

Problem Overview: You receive a table-like data structure (typically a DataFrame) and a list of new column names. The task is to rename the existing columns so they match the provided list while preserving the underlying data.

Approach 1: Direct Column Assignment (O(n) time, O(1) extra space)

The most straightforward approach updates the column metadata directly. Iterate through the column list or assign the new column list to the table's column property. In environments like Python DataFrames or similar structures, setting df.columns = new_names immediately replaces the existing column labels. The operation touches each column once, so the time complexity is O(n) where n is the number of columns, while space remains O(1) because only metadata changes. This method is ideal when the number of new names exactly matches the current column count and no conditional logic is required.

Approach 2: Library Rename Utility (O(n) time, O(n) space)

Many data-processing libraries provide a built-in rename utility that accepts a mapping between old and new column names. You construct a dictionary or map where keys represent existing column labels and values represent their replacements, then call the library helper (for example rename()). Internally the library iterates over the column list and applies the mapping. The traversal takes O(n) time and the mapping structure requires O(n) extra space. This approach is preferred when only some columns change or when you want safer transformations with explicit mappings.

Both approaches rely on basic dataframe metadata manipulation rather than complex algorithms. The key operation is iterating across column identifiers and updating their labels. In some implementations, column names are stored in an array-like structure or managed through a hash map for quick lookup during rename operations.

Recommended for interviews: Direct column reassignment is typically the cleanest and most efficient solution when the problem guarantees the new name list matches the column count. It demonstrates you understand how column metadata works internally. The mapping-based rename utility is useful when partial renaming is required and shows familiarity with built-in library features. Interviewers usually expect the O(n) traversal approach because every column must be processed at least once.

Approach 1: Data Structure Manipulation

This approach focuses on manipulating the data structures that hold the DataFrame or its equivalent to rename the columns. The idea is to access the data structure directly and modify the column headers.

import pandas as pd

def rename_columns(df):
    return df.rename(columns={
        'id': 'student_id',
        'first': 'first_name',
        'last': 'last_name',
        'age': 'age_in_years'
    })

# Example Usage
students = pd.DataFrame({
    'id': [1, 2, 3, 4, 5],
    'first': ['Mason', 'Ava', 'Taylor', 'Georgia', 'Thomas'],
    'last': ['King', 'Wright', 'Hall', 'Thompson', 'Moore'],
    'age': [6, 7, 16, 18, 10]
})

renamed_students = rename_columns(students)
print(renamed_students)
function renameColumns(objArray) {
    return objArray.map(({ id, first, last, age, ...rest }) => ({
        student_id: id,
        first_name: first,
        last_name: last,
        age_in_years: age,
        ...rest
    }));
}

// Example Usage
const students = [
    { id: 1, first: 'Mason', last: 'King', age: 6 },
    { id: 2, first: 'Ava', last: 'Wright', age: 7 },
    { id: 3, first: 'Taylor', last: 'Hall', age: 16 },
    { id: 4, first: 'Georgia', last: 'Thompson', age: 18 },
    { id: 5, first: 'Thomas', last: 'Moore', age: 10 }
];

console.log(renameColumns(students));

In Python, the Pandas library provides a rename function which can easily rename columns. The rename method takes a dictionary where keys are existing column names and values are the new names.

Complexity

Time Complexity: O(1) as renaming columns in a DataFrame does not depend on the number of rows.
Space Complexity: O(1), no additional space required beyond the rename operation.

Try this approach in the editor

Approach 2: Library Specific Utility

This approach relies on using specific libraries available for each programming language that are geared towards data manipulation. These libraries often offer built-in functionalities for renaming columns effortlessly.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Student {
    int student_id;
    String first_name;
    String last_name;
    int age_in_years;

    Student(int id, String first, String last, int age) {
        this.student_id = id;
        this.first_name = first;
        this.last_name = last;
        this.age_in_years = age;
    }

    @Override
    public String toString() {
        return student_id + ", " + first_name + ", " + last_name + ", " + age_in_years;
    }
}

public class Main {
    public static void main(String[] args) {
        List<Map<String, Object>> students = new ArrayList<>();
        addStudent(students, 1, "Mason", "King", 6);
        addStudent(students, 2, "Ava", "Wright", 7);
        addStudent(students, 3, "Taylor", "Hall", 16);
        addStudent(students, 4, "Georgia", "Thompson", 18);
        addStudent(students, 5, "Thomas", "Moore", 10);

        List<Student> renamedStudents = renameColumns(students);
        for (Student student : renamedStudents) {
            System.out.println(student);
        }
    }

    static void addStudent(List<Map<String, Object>> list, int id, String first, String last, int age) {
        Map<String, Object> student = new HashMap<>();
        student.put("id", id);
        student.put("first", first);
        student.put("last", last);
        student.put("age", age);
        list.add(student);
    }

    static List<Student> renameColumns(List<Map<String, Object>> original) {
        List<Student> renamed = new ArrayList<>();
        for (Map<String, Object> entry : original) {
            renamed.add(new Student(
                (int) entry.get("id"),
                (String) entry.get("first"),
                (String) entry.get("last"),
                (int) entry.get("age")
            ));
        }
        return renamed;
    }
}
using System;
using System.Collections.Generic;
using System.Data;

class Program {
    static void Main() {
        DataTable students = new DataTable();
        students.Columns.Add("id", typeof(int));
        students.Columns.Add("first", typeof(string));
        students.Columns.Add("last", typeof(string));
        students.Columns.Add("age", typeof(int));

        students.Rows.Add(1, "Mason", "King", 6);
        students.Rows.Add(2, "Ava", "Wright", 7);
        students.Rows.Add(3, "Taylor", "Hall", 16);
        students.Rows.Add(4, "Georgia", "Thompson", 18);
        students.Rows.Add(5, "Thomas", "Moore", 10);

        RenameColumns(students);

        foreach (DataRow row in students.Rows) {
            Console.WriteLine(string.Join(", ", row.ItemArray));
        }
    }

    static void RenameColumns(DataTable table) {
        table.Columns["id"].ColumnName = "student_id";
        table.Columns["first"].ColumnName = "first_name";
        table.Columns["last"].ColumnName = "last_name";
        table.Columns["age"].ColumnName = "age_in_years";
    }
}

In Java, without a direct DataFrame equivalent, we use a List of Maps to simulate the data structure. We rename columns by reconstructing the map into a custom class instance expressing the new naming.

Complexity

Time Complexity: O(n) where n is the number of rows in the data.
Space Complexity: O(n) as it creates a new list of student objects with renamed properties.

Try this approach in the editor

Complexity comparison

ApproachComplexity
Data Structure Manipulation

Time Complexity: O(1) as renaming columns in a DataFrame does not depend on the number of rows.
Space Complexity: O(1), no additional space required beyond the rename operation.

Library Specific Utility

Time Complexity: O(n) where n is the number of rows in the data.
Space Complexity: O(n) as it creates a new list of student objects with renamed properties.

Complexity analysis

ApproachTimeSpaceWhen to Use
Direct Column AssignmentO(n)O(1)When replacing all column names with a new ordered list
Library Rename Utility (Mapping)O(n)O(n)When renaming only specific columns or using explicit old-to-new mappings

Frequently asked questions

Is Rename Columns easy or hard?

Rename Columns is considered an Easy problem. The task focuses on understanding how table schemas store column labels and applying a simple iteration or built-in rename operation without complex algorithms.

Rename Columns Python/Java solution

Python solutions typically modify the DataFrame directly using column reassignment or the rename() utility. In Java or C#, similar behavior is implemented through table metadata APIs or mapping-based rename functions. All approaches iterate through the column list once, resulting in O(n) time complexity.

How to solve Rename Columns in O(n)?

Traverse the column list and update the labels with the new names. In DataFrame-style structures, you can directly assign the new column list to the column metadata property. Because each column is processed exactly once, the operation runs in O(n) time.

What is the best approach for Rename Columns?

The most efficient approach is direct column reassignment. Replace the column list with the new names in one operation, which processes each column once for O(n) time and O(1) extra space. This works best when the number of new names exactly matches the existing column count.

Is Rename Columns asked at Google/Amazon/Meta?

Rename Columns represents a basic data manipulation pattern often used in data engineering and analytics interviews. While the exact problem may not appear frequently in big-tech algorithm rounds, similar tasks involving DataFrame transformations and metadata updates are common in data-focused roles.

What data structure is used in Rename Columns?

Most implementations store column names in an array-like structure attached to the DataFrame schema. Some rename utilities also use a hash map or dictionary to map old column names to new ones before applying the transformation.

What is the time complexity of Rename Columns?

Renaming columns requires processing each column label at least once. The time complexity is O(n), where n is the number of columns in the table. Direct reassignment uses O(1) extra space, while mapping-based rename utilities typically require O(n) space for the mapping structure.

Comments

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