Interview Question
Software DevelopersCountry: United States
struct Point{
int x;
int y;
}Point;
Point* m_x_n_Grid(int * input, int length, int width, int test, Point pos)
{
int x = pos.x;
int y = pos.y;
if (*(input+(x*width) + y) == test){
return new Point(x, y);
}
else{
Point * p1, p2;
if (y + 1 >= length)
return null;
else if(*(input+(x*width) + y+1) > test)
p1 = m_x_n_Grid(input, length, width, test, new Point(x, y+1))
if (x + 1 >= width)
return null;
if (*(input+((x+1)*width) + y) > test)
p2 = m_x_n_Grid(input, length, width, test, new Point(x+1, y))
return (p1 == null)?p2:p1;
}
}
void main()
{
// some initialization for input, length and width of the grid
// plus the input integer
Point *p = m_x_n_Grid(input, length, width, test, new Point(0,0));
}
This took some doing to get right. I wouldn't have gotten this on an interview... The basic idea is to start from the lower right corner, and search the grid with this repeating pattern: left, up, right, up... until the value is found. Binary search is used to improve O(n). As to what O(n) is... maybe something like O(d*log(d)), where d is the average of width and height. Anyone?
output:
- tjcbs2 March 08, 2015