Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Written by Prashant Basnet
Prashant Basnet, a software engineer at Unisala.com, focuses on software development and enjoys building platforms to share knowledge. Interested in system design, data structures, and is currently learning NLP
#7 Find Minimum in Rotated Sorted Array
Blind 75. Array
Suppose an array of length
n
sorted in ascending order is rotated between1
andn
times. For example, the arraynums = [0,1,2,4,5,6,7]
might become:[4,5,6,7,0,1,2]
if it was rotated4
times.[0,1,2,4,5,6,7]
if it was rotated7
times.Notice that rotating an array
[a[0], a[1], a[2], ..., a[n-1]]
1 time results in the array[a[n-1], a[0], a[1], a[2], ..., a[n-2]]
.Given the sorted rotated array
nums
of unique elements, return the minimum element of this array.You must write an algorithm that runs in
O(log n) time.
Before we solve this problem let's understand what is rotated array?
1. first question, why is rotated array even needed. let's answer this question first:
Real world application of min rotated sorted array: How is it applied to our day to day life product?
Imaging you're in-charge of the lunch menu in school cafeteria.
You have board with seven slots, one for each day of the week:
Instead of erasing and rewriting menu each day, you have a clever system. The board is circular and can rotate. Each day, you rotate it one slot, so the current day's special is always on the top.
1. Wednesday, your board might look like this:
[Burgers, Thursday, Friday, Saturday, Sunday, Monday, Tuesday]
2. By Sunday:
[Vegetarian, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]
The system has several benefits:
In computer terms, this rotated array structure allows for:
The key idea is the information stays in order, but the starting point moves, creating a ROTATED effect.
This concept is useful in CS for managing cyclical data or when you need quick access to both recent past and near future information.
now that i understand what is importance of rated array, now let's focus on this problem min rotated sorted array.
Let's focus on our leetcode problem now:
0 1 2 3 4
[3, 4, 5, 1, 2]
Let's see how binary search works to find a value
now let's see how we can use this to solve our find min in rotated sorted array.
At anytime if the array is roated, it is sorted in two ways:
[4, 5, 6, 7, 0, 1, 2]
---left--- --right--
So how can we know if we are @ left sorted position?
every value in the right sorted position is smaller than left sorted position.
if value[left] <= value[mid]
we know the mid value is also the part of left sorted array.
in this case to find smaller num we want to search right
so
l = mid + 1
else
r = mid - 1
This is how we can solve this.
#datastructure #blind75 #computerScience #FANNG