Given two arrays arr1[] and arr2[] of dimension N and M (M < N) add all parts of arr2[] in all doable subarrays of arr1[] of dimension M precisely as soon as. The duty is to return the ultimate array arr1[] after performing the above operations.
Examples:
Enter: arr1[] = {1, 1, 1, 1, 1}, arr2[] = {1, 1, 1}
Output: 2 3 4 3 2
Rationalization: There are precisely 3 subarrays of dimension M in arr1[]
including corresponding parts of arr2[] in first subarray from factor 1 to 3. arr1[] turns into {2, 2, 2, 1, 1}
including corresponding parts of arr2[] in second subarray from factor 2 to 4. arr1[] turns into {2, 3, 3, 2, 1}
including corresponding parts of arr2[] within the third subarray from parts 3 to 5. arr1[] turns into {2, 3, 4, 3, 2}Enter: arr1[] = {1, 2, 3, 4, 5}, arr2[] = {10}
Output: 11 12 13 14 15
Naive Method: The issue could be solved utilizing linear iteration primarily based on the next concept:
Maintain including all parts of arr2[] in all doable subarrays of dimension M of arr1[]. There shall be precisely N – M + 1 subarrays.
Comply with the steps talked about beneath to implement the thought:
 Iterate from i = 0 to NM+1:
 Iterate from j = 0 to M:
 Add arr2[j] with arr[i+j.
 Iterate from j = 0 to M:
 Return the final state of arr1[] because the required reply.
Under is the implementation of the above method.
C++

2 3 4 3 2 20 21 22 23 24 12 11 10 9
Time Complexity: O(N * M)
Auxiliary Area: O(1)
Environment friendly Method: The above method could be optimized primarily based on the next concept:
This may be noticed each factor i of arr1[] can have some vary of parts from arr2[] that will get added.
For instance.
in case of arr1[] = {0, 0, 0, 0, 0}, arr2[] = {1, 2, 3}
factor 1 can have 1 in its sum. Vary of parts that obtained added from arr2[] is [0, 0].
factor 2 can have 1 and a couple of in its sum. Vary of parts that obtained added from arr2[] is [0, 1].
factor 3 can have 1, 2, and three in its sum. Vary of parts that obtained added from arr2[] is [0, 2].
factor 4 can have 2 and three in its sum. Vary of parts that obtained added of arr2[] is [1, 2].
factor 5 can have 3 in its sum. Vary of parts that obtained added of arr2[] is [2, 2].Commentary: each factor ‘i’ can have sum of parts of arr2[] from max(0, M – N + i) to min(i, M1).
Sum from max(1, M – N + i) to min(i, M1) could be calculated utilizing prefix sum in fixed time.
Comply with the steps beneath to unravel the issue:
 Initializing prefix[] array which shall be used to retailer the sum of all ranges of arr2[].
 Initializing L = max(1, M – N + i) and R = min(i, M).
 Traverse from 1 to N, Including prefix[R] – prefix[L – 1] in arr[i – 1] .
 print the ultimate array
Under is the implementation of the above method.
C++

Time Complexity: O(N)
Auxiliary Area: O(M)
Associated Articles: