Back to blog
May 21, 2024
3 min read

Modify Columns

Modify the data type of a specific column in a 2D array from string to integer.

Difficulty: Easy | Acceptance: 92.30% | Paid: No Topics: Array, Matrix

You are given a 2D array employees where each row represents an employee with columns employee_id, name, and salary. The salary column (index 2) contains string values. You need to modify the salary column by converting all string values to integers.

Examples

Example 1

Input:

DataFrame employees
+---------+--------+
| name    | salary |
+---------+--------+
| Jack    | 19666  |
| Piper   | 74754  |
| Mia     | 62509  |
| Ulysses | 54866  |
+---------+--------+

Output:

+---------+--------+
| name    | salary |
+---------+--------+
| Jack    | 39332  |
| Piper   | 149508 |
| Mia     | 125018 |
| Ulysses | 109732 |
+---------+--------+

Explanation: Every salary has been doubled.

Constraints

- The array will have at least 1 row.
- Each row will have exactly 3 elements.
- The salary column contains valid integer values as strings.
- employee_id and name columns remain unchanged.

Approach 1: Direct Iteration

Intuition Iterate through each row and convert the salary column value from string to integer.

Steps

  • Loop through each row in the 2D array.
  • For each row, access the salary column (index 2).
  • Convert the string value to integer using parseInt or equivalent.
  • Update the row with the converted value.
python
from typing import List

def modifySalaryColumn(employees: List[List[str]]) -> List[List[object]]:
    for row in employees:
        row[2] = int(row[2])
    return employees

Complexity

  • Time: O(n) where n is the number of rows in the array
  • Space: O(1) additional space (in-place modification)
  • Notes: Simple and direct approach for type conversion.

Approach 2: Using Map

Intuition Use the map function to transform each row, converting the salary column value.

Steps

  • Use map to iterate over each row.
  • For each row, create a new row with the salary value converted to integer.
  • Return the mapped array.
python
from typing import List

def modifySalaryColumn(employees: List[List[str]]) -> List[List[object]]:
    return [[row[0], row[1], int(row[2])] for row in employees]

Complexity

  • Time: O(n) where n is the number of rows in the array
  • Space: O(n) for creating a new array
  • Notes: Functional approach that creates a new array instead of modifying in-place.