Microsoft Interview Question
Software Engineer in TestsGiven k rows and an array of size n; we want to add every (n/k)th element of the array
for every element 'i' in array
array[i%k] += array[i]
// not the first k elements of the array is the required output
-> Time: O(n), Space: O(1)
my solution..has bugs..but the core logic works..
int[] retArray SumColumns(int[] array, int numRows)
{
if(numRows<=0||numRows==1||numRows>=8||array.length<=0)
return array;
int arrLength=array.length();
bool isMatrix=false;
if(arrLength>numRows)// check if this can be assumed a valid matrix
{
if(arrLenght%numRows==0)
isMatrix=true;
else
isMatrix=false;
}
if(isMatrix)
{
int col=floor(arrrLen/numRows);
int[] resultArray=new int[col];
int temp1=0;
int temp2=0;
//currentIndex = numcols * currentrow + current column
//resultArray[currentCol] = array[numcols * currentrow + current column]
for(int currentRow=0;i<numRows;i++)
for(int currentCol=0;j<col;j++)
{
{
resultArray[currentCol]=array[numcols * currentrow + current column]
}
}
}
}
int* ArrayColSum (int*pAray, int numRow, int size)
{
int numOfCol = size/numRow;
int* pColSum = (int*)malloc (numOfCol * sizeof (int));
int i = 0;
int j = 0;
int count = 0;
memset (pColSum, 0x00, numOfCol);
while (j < numOfCol)
{
while (i < size)
{
pColSum [j] += pAray [i];
i = i + numOfCol;
}
j++;
i = j;
}
return pColSum;
}
complexity = (size/numOfCol)*numOfCol = size
O(size)
public static int[] retArray(int[] arr, int numR)
{
int [] ret = new int[arr.Length/numR];
int addon = arr.Length / numR;
int k =0;
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(k % addon);
ret[k % addon] = ret[k % addon] + arr[i];
k++;
}
return ret;
}
my bad....an extra print statement which i omitted:
public static int[] retArray(int[] arr, int numR)
{
int [] ret = new int[arr.Length/numR];
int addon = arr.Length / numR;
int k =0;
for (int i = 0; i < arr.Length; i++)
{
ret[k % addon] = ret[k % addon] + arr[i];
k++;
}
return ret;
}
Time Complexity: O(columns * numRows) = O(n);
- S February 07, 2011Space Complexity: O(columns) - the result array