Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

LeetCode 2677: Chunk Array

LeetCode 2677 Solution Explanation

Explanation:

To chunk an array into subarrays of a specified size, we can iterate through the input array and create subarrays of the desired size. We keep track of the current chunk and add elements to it until it reaches the specified size or we exhaust all elements in the array. Each chunk formed is then added to the result list.

  • Algorithm:

    1. Initialize an empty list to store the chunked arrays.
    2. Iterate through the input array:
      • Create a new chunk list.
      • Add elements to the chunk list until it reaches the specified size or we run out of elements.
      • Add the chunk list to the result list.
    3. Return the list of chunked arrays.
  • Time Complexity: O(n)

  • Space Complexity: O(n)

:

LeetCode 2677 Solutions in Java, C++, Python

class Solution {
    public List<List<Integer>> chunkArray(int[] arr, int size) {
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> chunk = new ArrayList<>();
        
        for (int num : arr) {
            if (chunk.size() == size) {
                result.add(new ArrayList<>(chunk));
                chunk.clear();
            }
            chunk.add(num);
        }
        
        if (!chunk.isEmpty()) {
            result.add(chunk);
        }
        
        return result;
    }
}

Interactive Code Editor for LeetCode 2677

Improve Your LeetCode 2677 Solution

Use the editor below to refine the provided solution for LeetCode 2677. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems