- Expand the sequence by adding it’s elements in reverse order (in this case 1, 0).
- Prepend zeros to the first half and Ones to the second Half
- “11” as the previous item contains one instance of 1.
- “21” as the previous entry contains two 1’s.
- “1211” as the previous entry contains one 2 and one 1.
For example int_sqrt(4) = 2, int_sqrt(10) = 3. (We have to take floor of the actual square root)
A simple method is to iterate i from 1 to N/2 and keep checking until i2 < N, and whenever i2 >= N return i.
for( int i = 1; i <= N/2 ; i++ )
if( i*i >= N )
But this algorithm takes O(n) time. For large numbers this takes a lot of time. Any way to improve this further?
Binary search comes to our rescue. we start with the initial range [0, N]. In each iteration we check if mid2 <= N and (mid+1)2 >N. If this is satisfied, we return mid.
If mid2 > N, we confine our search to the left half; otherwise we search in the right half.
This implementation takes only O(log N) time.
Here is the C++ implementation.
This problem looks simple at the first glance, but if we do not write the program carefully it results in the wrong output, typically marks all the elements in the matrix to zeros.
So a wrong solution can be iterate through all the elements of a matrix, and whenever we found a zero, set the corresponding rows and columns as zero.
This will have undesired effect. Since we are modifying the same matrix, it is possible that an unexplored element may be set to zero because of a zero in the same row or column. So it is not possible to solve this problem in just one iteration.
An inefficient, but correct solution could be to create a temporary matrix which is a copy of the original matrix, and mark the elements in temp instead of the original. This will take O(m*n) extra space.
Can we solve this more efficiently?
One possibility is to first go through all the elements in the matrix and store the zero containing row and column indices into two sets.
Then set all the elements in the corresponding rows and columns to zeros in the next step. This approach will only take O(m+n) space, an improvement over the previous. Any solution should take O(m*n) time because we have to iterate through all the elements of the matrix at least once.
Here is the C++ function which takes the matrix as input and modify it.