700639. Linked List Matrix

Easy

Here is a detailed Markdown blog post for the "Linked List Matrix" problem:

Linked List Matrix

Summary

Given a linked list and an integer k, write a function to flatten the linked list into a matrix with dimensions k x n, where n is the number of nodes in the linked list. The function should return the flattened matrix.

This problem involves manipulating a linked list, which is a fundamental data structure in computer science.

Detailed Explanation

To solve this problem, we can use a simple iterative approach. We will create an array to store the flattened matrix and iterate through the linked list. For each node, we will add its value to the ith row of the matrix, where i is the current index in the linked list.

Here's the step-by-step breakdown of the solution:

  1. Initialize an integer k representing the number of rows in the matrix.
  2. Initialize an array matrix with dimensions k x n, where n is the number of nodes in the linked list.
  3. Initialize an integer i to 0, which will be used as the current index in the linked list.
  4. Iterate through the linked list until we reach the end:
    • For each node, get its value and add it to the ith row of the matrix.
    • Increment i by 1 for the next iteration.
  5. Return the flattened matrix.

Time complexity: O(n), where n is the number of nodes in the linked list. We only need to iterate through the linked list once, so the time complexity is linear.

Space complexity: O(k x n), where k is the number of rows and n is the number of columns in the matrix. We are creating a new array to store the flattened matrix, so the space complexity is proportional to the size of the matrix.

Optimized Solutions

Java

View on GeeksforGeeks
public int[][] flattenLinkedList(LinkedListNode node, int k) {
    int n = 0;
    LinkedListNode current = node;
    while (current != null) {
        n++;
        current = current.next;
    }
    int[][] matrix = new int[k][n];
    int i = 0;
    current = node;
    while (current != null) {
        for (int j = 0; j < k; j++) {
            matrix[j][i] = current.val;
        }
        current = current.next;
        i++;
    }
    return matrix;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.