Given a grid find how many points a robot can navigate given if it can explore a point where sum of digits of both X,Y(co-ordinates) is smaller than K.
One obvious solution is O(n^2).(Looping through the 2D matrix and accepting/ignoring a point based on the condition)
Other is take 0 to K-1 elements in an array , then find 2 elements such that there sum is less then K. involves O(k) space and O(k) time.
Can anyone suggest some better approach, improving upon anything in terms of space time . I am looking for a better answer.
The equation
x+y = Kdefines a diagonal in your grid, from a point in the northwest to a point in the southeast.If the points in your grid are all integral values of
xandy, andKis an integer too, then the number of points south of the diagonal (x+y < K) will beK(K-1)/2.The number of points in the grid including the diagonal (
x+y <= K) will beK(K+1)/2.Obviously, this is computed in constant time
O(1).