Google Interview Question
Software Engineer / DevelopersUsing Jquery:
alert(numCol("table") + " is the max number of cols");
function numCol(table) {
var maxColNum = 0;
var i=0;
var trs = $(table).find("tr");
// var thead = $(table).find("tr").find("th");
for ( i=0; i<trs.length; i++ ) {
var span = $(trs[i]).attr("colspan");
var thead= $(trs[i]).find("th");
if (thead)
{
if(span){
maxColNum += parseInt(span);
}
maxColNum++;
}
else {
maxColNum++;
}
}
return maxColNum;
}
Basically, keep track of the number of columns for each row in some list structure, then sort the list and grab the highest value.
For each row (<TR>) count the header and detail elements (<TH> and <TR>); for each one, increment the corresponding entry in your list structure. The trick is to look for ROWSPAN attributes within the TH and TD elements; if you find such a rowspan attribute, increment the appropriate number of subsequent entries in your list structure, as well.
Semi-Pseudo code:
When finding the TR, TH, TD and ROWSPAN strings, be sure to ignore commented or quoted instances
- Anonymous August 22, 2011