143. You are given a 1D array of integers ......
Microsoft Interview Questions and Answers
(Continued from previous question...)
143. You are given a 1D array of integers ......
Question:
You are given a 1D array of integers, such as:
int[] array = [3,4,7,2,2,6,0,9];
Suppose you need to treat this array as a 2D table with a given number of rows.
You want to sum the columns of the table.
another value for numRows is 4..in that case the resultant array would look like
what if numRows==4?
3 4
7 2
2 6
0 9
----
12 21
write up a function as follows:
int[] retArray SumColumns(int[] array, int numRows)
{
}
try to come up with a linear solution- no constraints on space..
maybe an answer:
int[] retArray SumColumns(int[] array, int numRows){
int n = array.Length;
if (n % numRows != 0)
throw new Exception("Invalid parameters");
int columns = n / numRows;
int[] result = new int[columns];
for (int i = 0 ; i < columns; ++i)
for (int j = 0; j < numRows; ++j)
result[i] += array[i + columns * j];
return result;
}
Time Complexity: O(columns * numRows) = O(n);
Space Complexity: O(columns) - the result array
(Continued on next question...)
Other Interview Questions
|