Arrays

Arrays are one of the most important building blocks in your solutions. In this section, let's practice problems with arrays and study some related techniques.

1D arrays. Prefix sums

Prefix sums are one of the most important techniques with the arrays. Here is how you build prefix sums arrays:

int[] a = {5, 7, 8, 9, -1, 3};

int[] prefixSum = new int[a.length];
for (int i = 0; i < a.length; i++) {
    prefixSum[i] = a[i];
    if (i > 0) 
        prefixSum[i] += prefixSum[i - 1];
}

Note how prefixSum[i] here keeps sum of the initial array elements from indexes 0 to i.

Not sure yet how this may be useful? Try solving this problem:

Hint
Solution

Here are some more good 1D arrays problems. You may use prefix sum related ideas in some of them:

2D arrays.

Idea similar to the prefix sums also applies to 2D arrays. Can you solve the following problem?

Hint
Solution

Here are some more good 2D arrays problems to practice on: