Two Dimensional Array Binary Search

Problem

Given a square two dimensional integer array of size (n). Both rows and columns are sorted in ascending order. Write an efficient code to search for a particular element in the array. Assume the array has no duplicates.

Solution

A brute force solution is to loop through the entire array until we find the desired element. The time complexity for this solution is O(n^2). Another solution is to search for the element working on one row at a time using binary search. Binary searching a given sorted row of size (n) takes O(Log(n)) so it would take O(nlog(n)) to search the entire array in worst case. If we are lucky and find the element in the very first row then it would take us only O(log(n)). There could be a O(Log(n)) solution if we can treat the whole array as a single sorted array but the tricky part is how to determine the middle element. I will publish another post for that once I finalize it.

Code

Here is the code in C#

Add a Comment

Your email address will not be published. Required fields are marked *