LeetCode 2253: Dynamic Unpivoting of a Table Solution

Master LeetCode problem 2253 (Dynamic Unpivoting of a Table), 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.

2253. Dynamic Unpivoting of a Table

Problem Explanation

Explanation:

To dynamically unpivot a table means to convert columns into rows. Given a table with a certain number of columns, the goal is to unpivot the table such that each row corresponds to a unique combination of values from the original columns.

Algorithmic Idea:

  1. Iterate through each row of the table.
  2. For each row, create a new row for each distinct column value, duplicating the remaining columns.
  3. Append these new rows to the output table.

Time Complexity:

  • The time complexity of this algorithm is O(n * m) where n is the number of rows and m is the number of columns in the original table.

Space Complexity:

  • The space complexity is also O(n * m) as we need to store the unpivoted table.

: :

Solution Code

import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<List<String>> dynamicUnpivot(List<List<String>> table) {
        List<List<String>> result = new ArrayList<>();
        
        for (List<String> row : table) {
            for (int i = 1; i < row.size(); i++) {
                List<String> newRow = new ArrayList<>();
                newRow.add(row.get(0));
                newRow.add(row.get(i));
                for (int j = 1; j < row.size(); j++) {
                    if (j != i) {
                        newRow.add(row.get(j));
                    }
                }
                result.add(newRow);
            }
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2253 (Dynamic Unpivoting of a Table)?

This page provides optimized solutions for LeetCode problem 2253 (Dynamic Unpivoting of a Table) 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 2253 (Dynamic Unpivoting of a Table)?

The time complexity for LeetCode 2253 (Dynamic Unpivoting of a Table) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2253 on DevExCode?

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

Back to LeetCode Solutions