2

The problem is to find the prefix sum of array of length N by repeating the process M times. e.g.

Example N=3
M=4
array = 1 2 3
output = 1 6 21
Explanation:
Step 1 prefix Sum = 1 3 6
Step 2 prefix sum = 1 4 10
Step 3 prefix sum = 1 5 15
Step 4(M) prefix sum = 1 6 21

Example 2:
N=5
M=3
array = 1 2 3 4 5
output = 1 5 15 35 70

I was not able to solve the problem and kept getting lime limit exceeded. I used dynamic programming to solve it in O(NM) time. I looked around and found the following general mathematical solution but I still not able to solve it because my math isn't that great to understand it. Can someone solve it in a better time complexity?

https://math.stackexchange.com/questions/234304/sum-of-the-sum-of-the-sum-of-the-first-n-natural-numbers

rsham
  • 23
  • 2
  • If I understand the problem, then you need to sum whatever numbers are in the array -- it's not always going to be 1, 2, 3, 4, 5... So a general formula for the sums of the first N naturals won't solve the problem. Are there any constraints given on N and M? – Matt Timmermans Jun 09 '22 at 12:40
  • No, they are always going to be N natural numbers like 1, 2, 3, 4,....Don't remember the exact constraints but it was in the range of N is 1000 and M is 10^9 because I also need to modulo 10^9 when doing the sum. – rsham Jun 09 '22 at 13:23

1 Answers1

1

Hint: 3, 4, 5 and 6, 10, 15 are sections of diagonals on Pascal's Triangle.

JavaScript code:

function f(n, m) {
  const result = [1];
  
  for (let i = 1; i < n; i++)
    result.push(result[i-1] * (m + i + 1) / i);
  
  return result;
}

console.log(JSON.stringify(f(3, 4)));
console.log(JSON.stringify(f(5, 3)));
גלעד ברקן
  • 23,602
  • 3
  • 25
  • 61
  • But the pascal's triangle is O(N^2) and works by adding the previous rows so I don't see how this approach differs from what I did with O(MN) complexity. Which apparently didn't pass the time limit for some cases. – rsham Jun 09 '22 at 16:43
  • @rsham could you please share a link to the online judge? – גלעד ברקן Jun 09 '22 at 17:54
  • That was part of an online assessment and it's no longer available. Haven't received the results yet but most probably I failed it. Now asking for a solution for future and my own understanding. – rsham Jun 09 '22 at 18:12
  • @rsham I added code and a link to an explanation. – גלעד ברקן Jun 09 '22 at 20:10
  • thanks a lot. Seems like I still have a lot to learn. – rsham Jun 10 '22 at 08:17