1

I have already designed the following algorithm that determines the binomial coefficient using a two dimensional array. For example, to calculate the binomial coefficient of n choose k, we can create a two dimensional array like so:

int[][] arr = new int[n][k];

We can populate the array in the following way:

for(int i = 0; i <= n; i++){
   for(int j = 0; j <= minimum(i, k); j++){
      if(j == 0 || i == j){
         arr[i, j] = 1;
      } else{
         arr[i, j] = arr[i - 1, j - 1] + arr[i - 1, j];
      }
   }
}

However, I need to redesign this algorithm to use a one dimensional array from indexes 0-k. I am having a lot of trouble pinpointing how to do this. I have started in small steps, and realized some common occurrences:

  • If k = 0, arr[0] will be 1, and that will be returned regardless of n.
  • If k = 1, arr[0] will be 1, arr[1] should be n, if I'm designing it in a loop.

When I say k = 2, this is where it gets tricky, because the value of arr[2] will really depend on the previous values. I believe that as I loop (say from i = 0 to i = n), the values of arr[] will change but I can't quite grasp how. I've started with something along these lines:

for(int i = 0; i <= n; i++){
   for(int j = 0; j <= minimum(i, k); j++){
      if(j == 0 || i == j){
         arr[j] = 1;
      } else if(j == 1){
         arr[j] = i;
      } else{
         arr[j] = ??; // I can't access previous values, because I didn't record them?
      }
   }
}

How should I handle this?

AdamMc331
  • 16,492
  • 10
  • 71
  • 133
  • This is nCr, which can be calculated using factorials (which you can implement using loops or recursion, but they are not constant-time) – Dave Mar 01 '15 at 21:19
  • @Dave The problem states to modify the first algorithm so that it only uses a single dimensional array, I don't think factorials are what they're looking for? Is there another approach to solving it? – AdamMc331 Mar 01 '15 at 21:23

1 Answers1

5

Here is a code which uses only one one dimensional array:

int[] coefficients = new int[k + 1];
coefficients[0] = 1;
for (int i = 1; i <= n; i++) {
    for (int j = k; j >= 1; j--) {
        coefficients[j] += coefficients[j - 1];
    }
}

Why is it correct? To compute coefficients[j] for a fixed i, we need to know the value of coefficients[j - 1] and coefficients[j] for i - 1. If we iterate from k down to 0, we can safely record a new value for the current position because we will never need its old value.

kraskevich
  • 18,368
  • 4
  • 33
  • 45
  • Thank you! I did not even think to iterate downward from k, but that makes perfect sense because we have access to the previous values before replacing them. – AdamMc331 Mar 01 '15 at 21:36