Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Find Minimum in Rotated Sorted Array #56

Open
kokocan12 opened this issue Jul 4, 2022 · 0 comments
Open

Find Minimum in Rotated Sorted Array #56

kokocan12 opened this issue Jul 4, 2022 · 0 comments

Comments

@kokocan12
Copy link
Owner

kokocan12 commented Jul 4, 2022

Problem

When an array is given, that is sorted in ascending order.
But it is rotated 1~n times.

When array is [0,1,2,4,5,6,7]
[4,5,6,7,0,1,2] if it was rotated 4 times.
[0,1,2,4,5,6,7] if it was rotated 7 times.

Approach

First, find out it is rotated or not.
If it rotated n times that is its length, it is same as default.

Then, find out which part the initial value exist by comparing mid value of array with start value of array.
It can be in left part or right part.

The code is below.

/**
 *  [0,1,2,3,4,5,6,7] not rotated
 *  [7,0,1,2,3,4,5,6] rotated && nums[mid] < nums[0] Then MIN is in the LEFT-SIDE
 *  [6,7,0,1,2,3,4,5] rotated && nums[mid] < nums[0] Then MIN is in the LEFT-SIDE
 *  [5,6,7,0,1,2,3,4] rotated && nums[mid] < nums[0] Then MIN is in the LEFT-SIDE
 *  [4,5,6,7,0,1,2,3] rotated && nums[mid] >= nums[0] Then MIN is in the RIGHT-SIDE
 *  [3,4,5,6,7,0,1,2] rotated && nums[mid] >= nums[0] Then MIN is in the RIGHT-SIDE
 *  [2,3,4,5,6,7,0,1] rotated && nums[mid] >= nums[0] Then MIN is in the RIGHT-SIDE
 *  [1,2,3,4,5,6,7,0] rotated && nums[mid] >= nums[0] Then MIN is in the RIGHT-SIDE
 *  [0,1,2,3,4,5,6,7] not rotated
 *
 *  [3,4,5,6,7,0,1,2] rotated,  nums[mid] >= nums[0] MIN is in the RIGHT-SIDE
 *  [7,0,1,2] rotated, nums[mid] < nums[0] MIN is in the LEFT-SIDE
 *  [7,0] rotated, nums[mid] >= nums[0] MIN is in the RIGHT-SIDE
 *  [0] MIN detected.
 *
 *  [4,5,6,7,0,1,2,3] rotated  nums[mid] >= nums[0] MIN is in the RIGHT-SIDE
 *  [0,1,2,3] is not rotated, return nums[0];
 *
 *  [2,3,4,5,6,7,0,1] rotated  nums[mid] >= nums[0] MIN is in the RIGHT-SIDE
 *  [6,7,0,1] rotated, nums[mid] >= nums[0] MIN is in the RIGHT-SIDE
 *  [0,1] not rotated, return nums[0];
 */

function findMinValue(nums, s, e) {
    // If not rotated
    if(nums[s] < nums[e] || s===e) return nums[s];
    
    // If rotated.
    const mid = (s + e) >> 1;
    
    // Min value is in the left-side.
    if(nums[mid] < nums[s]) {
        return findMinValue(nums, s, mid);
    } 
    // Min value is in the right-side.
    else {
        return findMinValue(nums, mid+1, e);
    }
}
# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

No branches or pull requests

1 participant