LeetCode 2675: Array of Objects to Matrix Solution

Master LeetCode problem 2675 (Array of Objects to Matrix), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2675. Array of Objects to Matrix

Hard

Problem Explanation

Explanation:

Given an array of objects, we need to convert it into a matrix where each row represents an object and each column represents a property of the object.

To achieve this, we can follow these steps:

  1. Get the list of properties from the first object to determine the number of columns in the matrix.
  2. Initialize a 2D matrix where the number of rows is the size of the input array and the number of columns is the number of properties.
  3. Iterate through the input array and populate the matrix by mapping each object to a row and each property to a column in the matrix.

The time complexity of this solution is O(n * m), where n is the number of objects in the input array, and m is the number of properties in each object. The space complexity is O(n * m) to store the resulting matrix.

:

Solution Code

import java.util.List;

public int[][] arrayToMatrix(List<Object> objects) {
    if (objects == null || objects.isEmpty()) return new int[0][0];
    
    int n = objects.size();
    int m = objects.get(0).getClass().getDeclaredFields().length;
    
    int[][] matrix = new int[n][m];
    
    for (int i = 0; i < n; i++) {
        Object obj = objects.get(i);
        int j = 0;
        for (java.lang.reflect.Field field : obj.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            try {
                matrix[i][j++] = field.getInt(obj);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
    
    return matrix;
}

Try It Yourself

Loading code editor...

Frequently Asked Questions

How to solve LeetCode 2675 (Array of Objects to Matrix)?

This page provides optimized solutions for LeetCode problem 2675 (Array of Objects to Matrix) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2675 (Array of Objects to Matrix)?

The time complexity for LeetCode 2675 (Array of Objects to Matrix) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2675 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2675 in Java, C++, or Python.

Back to LeetCode Solutions