703483. Average Count Array
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:
- Initialize an empty list
resultto store the subarrays. - Iterate through the input array
arr. - For each element
xin the array, check if it is different from the previous element (if this is the first element or ifxis not equal to the last element of the current subarray). - If
xis different from the previous element, increment the consecutive count and update the current element. - Store the consecutive integers in a new subarray and add it to the
resultlist.
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
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;
}
}