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 a prefix sums array:
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 the sum of the initial array elements from indexes 0
to i
.
Not sure yet how this may be useful? Try solving the following problem:
Hint
Solution
Here are some more good one-dimensional array problems. You can use prefix sums related ideas in some of them:
2D arrays.
The 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: