Thursday, August 16, 2007

Google's Interview Question

This question my uncle asked me to solve, was a Google's interview question and it was very good. I enjoyed solving it, but the irony is I am not sure if it is correct. So i am publishing the question and my algorithm.

Question: You are asked to write an algorithm to find the serial number of the column name in Excel (Note:In Excel, the column name is in Uppercase like A,..Z,AA...AAZ..)

Sample input:
AAZ
Sample output:
728


Recursive algorithm:

long int Excel(char col[],int len)
{
int c = col[n-1] - 64; /* ASCII value of letter just before A, for A being 1*/
if(len==1)
return c;
else
return(Excel(col,len-1)*26 + c);
}

Solution:
This problem is similar to converting any String to an Integer. For an Integer like 372, we do (3*100)+(7*10) + (2*1). We multiply each digit with its places value which is of base 10. Similarly, here each digit has 26 possible values.
For input AAZ, we do (A*26*26)+(A*26)+(Z*1) where as A = 1, B= 2,.., Z = 26.

Special cases:
1. Ip: "a" - convert input to UpperCase.
2. Ip: "A" - Classic calculation of char - 'A' would return zero. But we need 1, hence we move the base to one char below 'A'.

public void findSerialNumberInExcel(String columnName){

char[] inputArray = columnName.toUpperCase().toCharArray();

int base = 'A' - 1;

int num = inputArray[0] - base;

for(int i=1; i< inputArray.length; i++){

num = (num * 26) + (inputArray[i] - base);

}

System.out.println(num);

}

1 comment:

Krishna said...

You should probably avoid recursion for these kind of questions.