category-wise-problems

contains category wise problems(data structures, competitive) of popular platforms.

View the Project on GitHub mayankdutta/category-wise-problems

33. Search in Rotated Sorted Array

method 1

public int search(int[] nums, int target) {
    int n = nums.length;

    int low = 0;
    int high = n - 1;

    while (low < high) {
        int mid = (low + high) / 2;
        if (nums[mid] > nums[high]) {
            low = mid + 1;
        }
        else {
            high = mid;
        }
    }

    int rotated = low;
    low = -1;
    high = n;

    while (low + 1 < high) {
        int mid = (low + high) / 2;
        int modifiedMid = (mid + rotated) % n;

        if (nums[modifiedMid] == target) {
            return modifiedMid;
        }
        else if (nums[modifiedMid] > target) {
            high = mid;
        }
        else {
            low = mid;
        }
    }

    return -1;
}

Lets discuss the upper binary search loop.


sorted | sorted

WHY low = mid + 1 ???


## method 2

- treat as two separate sorted array, merged together.

```java
public class Solution {
    public int search(int[] A, int target) {
        int lo = 0;
        int hi = A.length - 1;
        while (lo <= hi) {
            int mid = (lo + hi) / 2;
            if (A[mid] == target) return mid;

            if (A[lo] <= A[mid]) {
                if (A[lo] <= target && target < A[mid]) {
                    hi = mid - 1;
                } else {
                    lo = mid + 1;
                }
            } else {
                if (A[mid] < target && target <= A[hi]) {
                    lo = mid + 1;
                } else {
                    hi = mid - 1;
                }
            }
        }
        if (lo < 0 || lo >= A.length) return -1;
        return A[lo] == target ? lo : -1;
    }
}