Given an array of integers, generate successive levels where each level contains the sum of consecutive elements from the previous level. The number of elements in each level decreases by one, starting from the original array as the first level. Print the levels in reverse order, i.e., starting from the last level upwards to the first.
⏰ Time complexity: O(n^2). Summing consecutive elements for each level takes O(n) for the first level, O(n-1) for the second level, and so on. The total is approximately O(n^2).
🧺 Space complexity: O(n^2). Storing intermediate levels requires O(n^2) space as levels reduce in size.
In the recursive approach, instead of iteratively generating each level, you define a recursive function that computes the next level and calls itself until reaching the smallest level (a single element). The recursion builds up the hierarchy, which can then be printed in reverse.
Here is the approach:
Base Case: The recursion terminates when the current level has only a single element (i.e., size 1).
Recursion: The function repeatedly calculates the next level and calls itself, gradually reducing the size of the levels.
Appending: After the recursive stack returns, each level is appended to the result list to preserve the reverse order.
classSolution:
def reverseLevelSumHierarchy(self, arr):
def generateLevels(level):
# Base case: if the current level has only one element
iflen(level) == 1:
return[level]# Recursive case: compute next level and append current level to the result
next_level =[level[i]+ level[i + 1]for i in range(len(level) - 1)] levels = generateLevels(next_level)
levels.append(level)
return levels
# Generate all levels recursively and reverse to print
levels = generateLevels(arr)
for level in levels:
print(level)
# Example usage
sol = Solution()
print("Example 1:")
sol.reverseLevelSumHierarchy([1, 2, 3, 4])
print("\nExample 2:")
sol.reverseLevelSumHierarchy([5, 6, 7])
public classSolution {
public void reverseLevelSumHierarchy(int[] arr) {
List<List<Integer>> levels = generateLevels(arr, arr.length);
// Print levels directly
for (List<Integer> level : levels) {
System.out.println(level);
}
}
private List<List<Integer>> generateLevels(int[] level, int n) {
// Base case: if the current level has only one element
List<List<Integer>> levels = new ArrayList<>();
if (n ==1) {
levels.add(toList(level));
return levels;
}
// Compute next level: sums of consecutive pairs
int[] nextLevel = new int[n -1];
for (int i =0; i < n -1; i++) {
nextLevel[i] = level[i] + level[i +1];
}
// Recursive call to compute smaller levels
levels = generateLevels(nextLevel, nextLevel.length);
// Add current level in reverse order (at the end)
levels.add(toList(level));
return levels;
}
// Helper method to convert an array to list
private List<Integer> toList(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int num : arr) {
list.add(num);
}
return list;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println("Example 1:");
sol.reverseLevelSumHierarchy(new int[]{1, 2, 3, 4});
System.out.println("\nExample 2:");
sol.reverseLevelSumHierarchy(new int[]{5, 6, 7});
}
}
⏰ Time complexity: O(n^2). Each level generation takes linear time (O(n) for the first level, O(n-1) for the second, etc.), summing to approximately O(n^2).
🧺 Space complexity: O(n^2). The recursive calls stack up in memory, with levels stored in reverse order as part of the recursion stack.