Readable && clean JAVA solution

  • 1
    public int search(int[] a, int s, int e, int target){
            //base case
            if(s >= e) return a[s] == target?s:-1;
            int m = (s+e)/2;
            if(a[m] == target) return m;
            //(right side is correctly sorted && target is within right side) || (left is correct && target is not in left)
            boolean searchRight = (a[m]<a[e]&&target <= a[e]&&target>a[m])||(a[m]>a[e]&&!(target>=a[s]&&target<a[m]));
            return search(a, searchRight ? m+1:s, searchRight ? e:m-1, target);

  • 0

    Nice code .
    But is this O(logn)?

  • 0

    Yes, it is still log(n) since I get rid of half of the search space at each search.

  • 0

    I wouldn't say this is very readable in an interview.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.