703483. Average Count Array

Basic

Average Count Array

Slug: average-count-array2215

Difficulty: Basic

Id: 703483

Topic Tags: Arrays, Mathematical, logical-thinking, Data Structures, Algorithms

Company Tags: None

Summary

Given an array of integers, the task is to calculate the average count of consecutive integers. For example, if the input array is [1, 2, 3, 4, 5, 6], the output should be [[1], [2, 3], [4, 5, 6]] as the first subarray contains only one element (1), the second subarray contains two elements (2 and 3), and the third subarray contains three elements (4, 5, and 6).

Detailed Explanation

To solve this problem, we can iterate through the input array and maintain a variable to keep track of the current consecutive count. When the current element is different from the previous one, we increment the count and update the current element. We also store the consecutive integers in a subarray.

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

  1. Initialize an empty list result to store the subarrays.
  2. Iterate through the input array arr.
  3. For each element x in the array, check if it is different from the previous element (if this is the first element or if x is not equal to the last element of the current subarray).
  4. If x is different from the previous element, increment the consecutive count and update the current element.
  5. Store the consecutive integers in a new subarray and add it to the result list.

Here's an example:

Input: [1, 2, 3, 4, 5, 6]
Consecutive count = 1
Current element = 1
Result: [[1]]

Input: [1, 2, 3, 4, 5, 6]
Consecutive count = 2
Current element = 2
Result: [[1], [2, 3]]

Input: [1, 2, 3, 4, 5, 6]
Consecutive count = 3
Current element = 4
Result: [[1], [2, 3], [4, 5, 6]]

Time complexity: O(n), where n is the length of the input array. Space complexity: O(n), as we need to store the subarrays in the result list.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.ArrayList;
import java.util.List;

public class AverageCountArray {
    public static List<List<Integer>> averageCountArray(int[] arr) {
        List<List<Integer>> result = new ArrayList<>();
        int consecutiveCount = 1;
        List<Integer> currentSubarray = new ArrayList<>();

        for (int i = 0; i < arr.length - 1; i++) {
            if (arr[i] + 1 != arr[i + 1]) {
                result.add(currentSubarray);
                consecutiveCount = 1;
                currentSubarray = new ArrayList<>();
            } else {
                consecutiveCount++;
            }
            currentSubarray.add(arr[i]);
        }

        // Add the last subarray
        result.add(currentSubarray);

        return result;
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.