Given n>=0, create an array with the pattern {1,1, 2,1, 2, 3, ... 1, 2, 3 .. n}.
As an example if you given n=3, your method should return array as {1,1,2,1,2,3}.
My solution is here….
public int[] upSeries(int n) {
int var1 = n + 1;
int var2 = n;
int var3 = (var1*var2) / 2;
int arr_length = var3;
int value = 1;
int index = 0;
int[] arr = new int[arr_length];
for (int j = 0; j < arr.length; j++) {
for (int p = 0; p < j + 1; p++) {
arr[index] = value;
value++;
if (index == arr.length - 1) {
arr[index] = n;
break;
} else {
index++;
}
}
value = 1;
}
return arr;
}
What will be the best solution?
I cleaned it up a bit. But its the same general idea. You had a few redundancies that you could have removed.
This solution is better by a constant multiple. If you are looking for Big-Oh they are both O(i^2) and it is not possible to do better.
If you need a proof to why it is not possible to do better. First prove that the size of the returned array is ((i) * (i+1)) /2). Then make the argument that you have to fill every position in the array. If you do better than O(i^2) you have not filled every position in the array.