LeetCode 2885: Rename Columns

Problem Description

Explanation:

To rename the columns in a DataFrame, we can simply create a mapping of the old column names to the new column names and then update the column names accordingly. This can be done by iterating through the existing column names and replacing them with the corresponding new names based on the mapping.

  • Time complexity: O(n), where n is the number of columns in the DataFrame.
  • Space complexity: O(1) since we are only using a constant amount of extra space for the mapping.

:

Solutions

public void renameColumns(List<String> columnNames) {
    Map<String, String> mapping = new HashMap<>();
    mapping.put("id", "student_id");
    mapping.put("first", "first_name");
    mapping.put("last", "last_name");
    mapping.put("age", "age_in_years");
    
    for (int i = 0; i < columnNames.size(); i++) {
        if (mapping.containsKey(columnNames.get(i))) {
            columnNames.set(i, mapping.get(columnNames.get(i)));
        }
    }
}

Loading editor...