Skip to content

Commit

Permalink
Solution as discussed in video at neetcode channel
Browse files Browse the repository at this point in the history
  • Loading branch information
sidhant-khamankar authored Sep 9, 2022
1 parent fb55f39 commit 5301655
Showing 1 changed file with 33 additions and 28 deletions.
61 changes: 33 additions & 28 deletions cpp/153-Find-Minimum-In-Rotated-Sorted-Array.cpp
Original file line number Diff line number Diff line change
@@ -1,36 +1,41 @@
/*
Given sorted array after some rotation, find min value
Ex. nums = [3,4,5,1,2] -> 1, nums = [4,5,6,7,0,1,2] -> 0
* @lc app=leetcode id=153 lang=cpp
*
* [153] Find Minimum in Rotated Sorted Array
*/

Binary search + ensuring we never disqualify possible min value
// @lc code=start
class Solution
{
public:
int findMin(vector<int> &nums)
{
// Neetcode solution Ologn time O1 space binary search
int res = nums[0];
int l = 0;
int r = nums.size() - 1;

Time: O(log n)
Space: O(1)
*/
while (l <= r)
{
if (nums[l] < nums[r])
{
res = min(res, nums[l]);
break;
}
int mid = l + (r - l) / 2;
res = min(res, nums[mid]);

class Solution {
public:
int findMin(vector<int>& nums) {
int low = 0;
int high = nums.size() - 1;

// not low <= high since not searching for target
while (low < high) {
int mid = low + (high - low) / 2;
// ex. [3,4,5,6,7,8,9,1,2], mid = 4, high = 8
// nums[mid] > nums[high], min must be right
if (nums[mid] > nums[high]) {
// never consider mid bc know for sure not min
low = mid + 1;
// ex. [8,9,1,2,3,4,5,6,7], mid = 4, high = 8
// nums[mid] <= nums[right], min must be left
} else {
// consider mid still bc could be min
high = mid;
if (nums[mid] >= nums[l]) // mid present in left sorted array
{
l = mid + 1; // try to move closer to right sorted array
}
else
{
r = mid - 1;
}
}

// low lands on correct value, never disqualified mins
return nums[low];

return res;
}
};
// @lc code=end

0 comments on commit 5301655

Please sign in to comment.