No video

LeetCode 33. Search in Rotated Sorted Array

  Рет қаралды 97,707

Nick White

Nick White

4 жыл бұрын

The Best Place To Learn Anything Coding Related - bit.ly/3MFZLIZ
Join my free exclusive community built to empower programmers! - www.skool.com/software-develo...
Preparing For Your Coding Interviews? Use These Resources
--------------------
(My Course) Data Structures & Algorithms for Coding Interviews - thedailybyte.dev/courses/nick
AlgoCademy - algocademy.com/?referral=nick...
Daily Coding Interview Questions - bit.ly/3xw1Sqz
10% Off Of The Best Web Hosting! - hostinger.com/nickwhite
Follow Me on X/Twitter - x.com/nickwhitereal
Follow My Instagram - / nickwwhite
Other Social Media
----------------------------------------------
Discord - / discord
Twitch - / nickwhitettv
TikTok - / nickwhitetiktok
LinkedIn - / nicholas-w-white
Show Support
------------------------------------------------------------------------------
Patreon - / nick_white
PayPal - paypal.me/nickwwhite?locale.x...
Become A Member - / @nickwhite
#coding #programming #softwareengineering

Пікірлер: 134
@alexcuenca
@alexcuenca 3 жыл бұрын
Guys don't freak out, questions like this you have to look up the solution, would someone be able to guess this approach without ever seen a problem similar to this one? Probably not, it doesn't mean you're not smart or that you suck at this. Most people saw the solution if the problem was somewhat hard at least.
@jagr6741
@jagr6741 2 жыл бұрын
I came to this video thinking that I am dumb for not knowing the solution even though I know how to search in a regular sorted list... Thanks for boosting my spirits!!!
@neohubris
@neohubris 2 жыл бұрын
exactly, it just boils down to lots of practice
@aryankumar87771
@aryankumar87771 Жыл бұрын
whatever helps you sleep at night
@alexcuenca
@alexcuenca Жыл бұрын
@@aryankumar87771 is this a joke? Lol
@aryankumar87771
@aryankumar87771 Жыл бұрын
@@alexcuenca yes m8 it is lmao don't take my comment seriously, to all the beginners leetcode is tough for the first few months for everyone, even the pros have to go through the grind
@soledapper
@soledapper 4 жыл бұрын
Right on for explaining it, I knew I had to use the technique from LC 153, but I kept messing up on determining the search space before performing regular binary search.
@azn0180
@azn0180 4 жыл бұрын
You are such a legend at young age. Your explanation is much more clearer than leetcode. I hope to see your name on some big thing in the future.
@hacker-7214
@hacker-7214 4 жыл бұрын
this question was so fucking hard almost made me quit coding.
@benjamimo1
@benjamimo1 3 жыл бұрын
Thanks bro, It became better to understand as you divided the problem in two parts.
@bobmarley3342
@bobmarley3342 4 жыл бұрын
That was "freakin" amazing explanation...Thank you very much!
@codegranate7409
@codegranate7409 4 жыл бұрын
Simple and clear explanation! Thank you!
@Xyvier
@Xyvier 4 жыл бұрын
8:54 the "YEA BOIIIIIIIIEEEE" moment ;)
@HktDarren
@HktDarren 4 жыл бұрын
HI! Thanks for sharing your knowledge every time, it's really help me, can you also teach us how to look at the time complexity when we finished the program ?
@wheresthebeach0138
@wheresthebeach0138 4 жыл бұрын
You've got some of the best content out there bro; thank you for all the work you put into these!!
@Avagabond
@Avagabond Ай бұрын
he is just not good at explaining... may be because he sneaked the answerss from somewhere.. over confidence is not good when you're teaching man
@emersonschefferst
@emersonschefferst 4 жыл бұрын
Great tutorial Nick, but... there's an edge corner case here where if the smallest number in the array is == target and at the same time is the value at the midpoint index, the search will return -1 even thou the target value exists in the array. To solve that little problem you should check in the first while loop after finding the midpoint if the array[midpoint] == target and return midpoint from there. Hope that helps , let me know
@joshuayolles6962
@joshuayolles6962 4 жыл бұрын
Thank you! Good explanation!
@codingbosemalayalam1059
@codingbosemalayalam1059 2 жыл бұрын
We can also use the fact that either (Left -> MID) or (MID -> Right) will always be sorted. If the target is not present in the sorted half, limit your search to the other half. static int shiftedArrSearch(int[] A, int num) { int l = 0, r = A.length -1; while(l
@boli7171
@boli7171 2 жыл бұрын
Thank you! This is really helpful
@varanasiaditya
@varanasiaditya 3 жыл бұрын
Honestly, you changed the way I think about problem-solving.
@michaelchan6144
@michaelchan6144 3 жыл бұрын
You are a legend! Never stop making vids!!
@anamikakumari3777
@anamikakumari3777 4 жыл бұрын
finding pivot technique .. awesome
@mmowaffak
@mmowaffak 4 жыл бұрын
Can anyone tell me why this condition cannot suffice? if(nums[midpoint] < nums[start]){ end = midpoint -1; } else{ start = midpoint; }
@emanuel0723
@emanuel0723 4 жыл бұрын
Correct me please. In line 21, the condition is target >= nums[start]... which will always be TRUE since our nums[start] is the minimum number in the array, right? so the if statement could be only the second part: target
@piscopowerdarkside
@piscopowerdarkside 4 жыл бұрын
Oracle asked me this question in an interview and i failed badly lol. With this explanation i look back and can't believe how stupid i was..
@cloud5887
@cloud5887 4 жыл бұрын
You are not stupid. This question is not THAT easy to solve, if you are not really into Leetcoding.
@thugsmf
@thugsmf 3 жыл бұрын
Hi Gilberto. were you not able to solve the question at all? or just not optimally, using binary search?. I had the same question today. I was able to solve it O(n). But interviewer asked if I could do better, and I mentioned binary search but didnt know how to implement it. thank you
@EE12345
@EE12345 3 жыл бұрын
@@thugsmf Did you pass the interview? I could implement it in O(N), and design an O(logN) solution with 2 modified binary searches, but it's hard to implement it the first time without errors.
@thugsmf
@thugsmf 3 жыл бұрын
@@EE12345 nah. I didnt pass the interview. I just implemented it in O(n). Didnt bother designing the O(logn) solution. just basically told interviewer I didnt want to risk not getting the solution so just did it linear time. guess it was way too easy and too naive! but it was my first interview. so learned a lot. always give most optimal solution. hows job search for you? still struggling here
@EE12345
@EE12345 3 жыл бұрын
@@thugsmf I'm trying to get good at leetcode before I mass apply, but its taking so long... maybe I should just apply now?
@vamsiKrishna96
@vamsiKrishna96 3 жыл бұрын
Bro, you're next level cool guy. Any leetcode question I'm stuck on I hope there'll be a youtube video from your end. Sometimes, hard luck :(
@dj_b1627
@dj_b1627 2 жыл бұрын
Try being less dumb, maybe this helps
@thepardhu100
@thepardhu100 2 жыл бұрын
@@dj_b1627 Bob the Builder
@Vinny254
@Vinny254 3 жыл бұрын
Will this work with these inputs array --> [4, 5, 6, 1, 2, 3], search for element 3
@abhi220
@abhi220 4 жыл бұрын
Why not set right to start -1 instead of start? It seems weird says you array is [3, 4, 0, 1, 2] and target is 4. For the binary search left = 0 index and right = 2, but ideally right should be 1 I think. Does this make sense? :)
@SangharshSeth
@SangharshSeth 4 жыл бұрын
i thought the same thing right should be start-1 and it actually runs faster in leetcode compared to right=start.
@pratyush2604
@pratyush2604 4 жыл бұрын
@@SangharshSeth yes, and when it is right = start, shouldnt it give an error since we are doing binary search on an unsorted array
@ianpan0102
@ianpan0102 4 жыл бұрын
You're right, I noticed that too.
@milnueve89
@milnueve89 3 жыл бұрын
I was about to comment this.
@shrimatkapoor2200
@shrimatkapoor2200 3 жыл бұрын
Still a bit confused by setting the indexes after the check, like the +1 and -1 for left and right
@titoluzuriaga8217
@titoluzuriaga8217 Жыл бұрын
I loved the forced clap in the beginning 😆
@iamnoob7593
@iamnoob7593 4 жыл бұрын
ur explanation is really good,All ur videos are amazing,Please keep doing more leetcode questions.
@MichaelSalo
@MichaelSalo 3 жыл бұрын
How did you decide the first loop condition is (left < right), and the second loop condition is (left
@duniecool
@duniecool 3 жыл бұрын
because you will always find the smallest element in the list, you may not always find the point they are looking for
@nick2629
@nick2629 2 жыл бұрын
@@duniecool Thank you so much for this explanation. So simple but I was wondering this too.
@alex_smallet
@alex_smallet 2 жыл бұрын
I wonder if it's necessary to find the midpoint? I was trying to solve this without the first step. It seems doable, but every time I try my solution, it finds some edge cases where it does not work.
@poorpanda9033
@poorpanda9033 11 ай бұрын
What a explanation thanks a lot !!
@mrbeastfannatic
@mrbeastfannatic 4 жыл бұрын
Hey nick I keep trying to find your leetcode solutions on GITHUB but I don't really know where the are . Could you let me know which repo do they belong to ?
@sadafalam2903
@sadafalam2903 Жыл бұрын
Hi Nick! I loved your solution but it is failing for a particular test case [1,3] target =3 Answer = -1 Expected Output = 1 Can you please explain?
@jl1835
@jl1835 3 жыл бұрын
thanks man! that's great!
@arpitvaish89
@arpitvaish89 2 жыл бұрын
made my life easier, thank you.. best explanation
@Batman001
@Batman001 4 жыл бұрын
Is the Pivot Element always going to be the smallest value element? I don't see that in the question, why can we assume the smallest number is always on the side that has the pivot?
@shreevatsalamborghin
@shreevatsalamborghin 4 жыл бұрын
Yes in a sorted then rotated array, Pivot element has a unique property in which elements towards its left and right will always be greater. The index of this pivot ele(Smallest element) gives the number of times the array which was sorted has been rotated. Hope I cleared you're doubt!
@bensas42
@bensas42 3 жыл бұрын
Thank you so much!
@Arthurgarzajr
@Arthurgarzajr 2 жыл бұрын
When it came up in your interview, did you do well on this problem? Or did you not know how to do it then?
@amansayer4943
@amansayer4943 Жыл бұрын
this guy even make jokes he was like creating history 😂😂
@amitkumartiwari477
@amitkumartiwari477 3 жыл бұрын
You explain every question in a splandid manner which is easily understandable. So thank you so much for the videos.
@100bands
@100bands 4 жыл бұрын
This condition "target >= nums[start]" is not needed since nums[start] is already the smallest value in your array
@onion_____
@onion_____ 4 жыл бұрын
good catch
@onion_____
@onion_____ 4 жыл бұрын
@Duy Ngo thank you 🙏
@shahbazalam4565
@shahbazalam4565 4 жыл бұрын
What if the array is rotated n (length of array) times such that the rotated array is same as initial array then the smallest element would be the first element?I think this approach would fail....It would be better to check for rotation such that first element is always greater than the last element in the rotated array.... Am i making sense?
@shaurya4242
@shaurya4242 2 жыл бұрын
Lol got this in a CoderPad interview. Like bruh...how am I supposed to figure this out without looking it up?
@priavtechannel2458
@priavtechannel2458 4 жыл бұрын
why do you do midpoint = left + (right-left) /2, doesn't the left cancel out, so you can just do right/2?
@NickWhite
@NickWhite 4 жыл бұрын
priavtechannel2 the way I did it is the right way because in some languages and situations there is integer overflow error
@NickWhite
@NickWhite 4 жыл бұрын
Look up “binary search midpoint integer overflow”
@TrevoZnaniy
@TrevoZnaniy 4 жыл бұрын
Well another point is that when left is, for example, 5 and right is 10 where is the middle point? Sure on 7. And what happens if you do "right/2"? Your midpoint would become equals to left
@kl191
@kl191 2 жыл бұрын
Shouldn't line 24 be right = start - 1; rather than right = start; ?
@ahmedouyahya
@ahmedouyahya 4 жыл бұрын
thank you sooooo much
@hkharryfunk
@hkharryfunk 3 жыл бұрын
Well explained. Leetcode's own solutions are so hard to understand.
@SangharshSeth
@SangharshSeth 4 жыл бұрын
Nice approach.
@NickWhite
@NickWhite 4 жыл бұрын
thanks dude
@hritik6507
@hritik6507 3 жыл бұрын
@Nick White this code doesnt work for all the test cases
@rohanpandey3704
@rohanpandey3704 2 жыл бұрын
How can we get the written code ?
@surendrapeatihar2650
@surendrapeatihar2650 4 жыл бұрын
thanks man !!!!!!!
@vishalsingh-nk8nt
@vishalsingh-nk8nt 3 жыл бұрын
how come runtime is 0ms?
@fridtariverdiyev3927
@fridtariverdiyev3927 2 жыл бұрын
thank you !
@AbhishekSura
@AbhishekSura 4 жыл бұрын
How can we handle if there are duplicates, for search in rotated sorted array ii LC #81
@kanhappyable
@kanhappyable 3 жыл бұрын
Did u get any answer?
@aman4434
@aman4434 3 жыл бұрын
I don't know if I am stupid or.... lol nice one. Wish I could have come up with this on my own rather than trying some weird lengthy bunch of if statements
@prosenbagula
@prosenbagula 3 жыл бұрын
Good explanation
@unknownman1
@unknownman1 3 жыл бұрын
5:45 can anyone tell me how this loop will ever break? left is always smaller than right?
@nirmalbisht8297
@nirmalbisht8297 3 жыл бұрын
first loop is for finding smallest element in that array ,as soon as left will be equal to right our loop will break
@AkashGupta-pc2cb
@AkashGupta-pc2cb Жыл бұрын
I have still not been able to understand what is happening in the first while loops else condition
@alex.perfecto
@alex.perfecto 3 жыл бұрын
I suppose your code doesn't work for nums=[3,1], target=1 - incorrect pivot found
@beyondlimits384
@beyondlimits384 2 жыл бұрын
If u don't write Right = n.length -1; on line no 19 again then code will crash for {1,3} target 3
@annkitplays8925
@annkitplays8925 3 жыл бұрын
Thanks
@tomok284
@tomok284 2 жыл бұрын
Will you make a blind 75 series?
@siobhanahbois
@siobhanahbois 4 жыл бұрын
Your solution is great also because you used int midpoint=left + (right - left)/2; instead of int midpoint=(left+right)/2; to avoid overflow.
@davemustainejigsaw
@davemustainejigsaw 4 жыл бұрын
Why did you do while(left
@bling6
@bling6 4 жыл бұрын
I think its because if u have a 1 element array, the second loop will not run since left==right.
@abarag8
@abarag8 2 жыл бұрын
1st while loop will just find smallest element. So in 1st while loop, when left == right (i.e., loop breaks) left will be same as right which will be same as smallest (or pivot) element. 2nd one is a good old simple binary search hence left
@AolaDIY
@AolaDIY 4 жыл бұрын
Please do leetcode number of island 2
@The.Dark.Panther
@The.Dark.Panther 3 жыл бұрын
@Nick White: Proposed modification: =============================== You can already check if you found the looked up value, skip binary tree redundant processing =============================== if (target == array[start]) { return start; } else if (target == array[right]) { return right; } =============================== else if (target > array[start] && target < array[right]) { left = start; } else { right = start; }
@theyellowflash100
@theyellowflash100 Жыл бұрын
I'm a beginner programmer, but in python couldnt you do "nums.sort()" which would sort the array, then run a binary search on it? I understand that you're doing java and that I may be completely wrong
@richardliu5297
@richardliu5297 Жыл бұрын
If you look at the question on leetcode the problem requires you to solve it in log(n) run time, sorting is nlog(n) so you can't use it
@theyellowflash100
@theyellowflash100 Жыл бұрын
@@richardliu5297 Thanks Richard, I don't know how time complexities work at all atm. I'm trying to do the problems without taking time complexities in mind (as stupid as that sounds). I'm also practicing on hackerrank and edabit, to make it easier 😅
@richardliu5297
@richardliu5297 Жыл бұрын
@@theyellowflash100 Np, you have to learn how time complexities work. It's a fundamental part of leetcode and Computer Science.
@babumon5351
@babumon5351 4 жыл бұрын
You are amazing sir.
@eugenevedensky6071
@eugenevedensky6071 3 жыл бұрын
Hey Nick, great video. On line 35, you set right = mid - 1; Given that right may in fact be the target, shouldn't it be right = mid? You even say yourself , "Target is less than nums of midpoint or equal to..." , actually as I typed this I answered my own question. This could not be the case since you proactively check if nums[midpoint] == target. In the previous binary search, this would not work since we do not know the target.
@edwardteach2
@edwardteach2 3 жыл бұрын
U a God
@tanveersayyed561
@tanveersayyed561 2 жыл бұрын
good sir
@yygysgtyfugunvt
@yygysgtyfugunvt 3 жыл бұрын
I got time limit exceeded with this code
@ankurgupta4696
@ankurgupta4696 4 жыл бұрын
why we cant do this by two pointers??
@kevinrobinson6685
@kevinrobinson6685 4 жыл бұрын
While your solution is obviously ok. In the real world, I would say this function is too big. I would split it into smaller functions. Is this taken into consideration during these types of coding tests (during an interview) ?
@darod6098
@darod6098 4 жыл бұрын
Yes, it is absolutely taken into consideration.
@alokbisht3158
@alokbisht3158 3 жыл бұрын
I was asked this question in Snapdeal interview. But your solution have too many loops. I think we can just modify the basic binary search to eliminate a part of the array without caring for where min element is or then further dividing by that min element.
@alokbisht3158
@alokbisht3158 3 жыл бұрын
public int search(int[] nums, int target) { int left = 0; int right = nums.length - 1; while(left
@huihuang2294
@huihuang2294 4 жыл бұрын
cool de bro
@trinitygaming3863
@trinitygaming3863 3 жыл бұрын
Showing time limit exceed , i wrote the same code twice and checked
@trinitygaming3863
@trinitygaming3863 3 жыл бұрын
For the test case : [ 4,5,6,7,0,1,2] 3
@Richard-ok5un
@Richard-ok5un 3 жыл бұрын
Thank us for what???? I guess we'll never know.....
@santhoshrao9302
@santhoshrao9302 4 жыл бұрын
[4,5,6,7,0,1,2] 3 This code does an infinite loop for the above input. Just adding the following two lines will resolve the issue: if(nums[0]==target) return 0; if(nums[n-1]==target) return n-1;
@JamesHalpert8555
@JamesHalpert8555 4 жыл бұрын
Why not do a simple linear search to find the target since it's a 1D array?
@bling6
@bling6 4 жыл бұрын
need to do it in O( log n)
@sameerkadam4830
@sameerkadam4830 3 жыл бұрын
class Solution { public int search(int[] nums, int target) { for(int i=0;i
@VivekSolankiAqua
@VivekSolankiAqua 3 жыл бұрын
Solution should have O(log n) instead of O(n) time complexity!
@jinny5025
@jinny5025 3 жыл бұрын
How could he don't make any mistakes? Do people who've got offers from FAANG companies all be like him? Maybe I should give up.. 😔
@VivekSolankiAqua
@VivekSolankiAqua 3 жыл бұрын
Because he has practiced this solution like 3-4 times before doing this video(check his submissions) No one is perfect! Don’t give up, and keep practicing! :)
@codewithkolhar3131
@codewithkolhar3131 4 жыл бұрын
Is this a even a Medium difficulty question ??? I mean you just need to find the value and return it's index. Still not understanding why leetcode has set the difficulty to Medium. class Solution: def search(self, nums: List[int], target: int) -> int: for e in range(len(nums)): if nums[e] == target: return e else: return -1 My solution...
@Ownage10297
@Ownage10297 4 жыл бұрын
the solution needs to be in O(log n) time. Yours is O(n)
@codewithkolhar3131
@codewithkolhar3131 4 жыл бұрын
@@Ownage10297Then leetcode should not accept my solution
@unknownman1
@unknownman1 3 жыл бұрын
dude you must be kidding? If you come up with this solution in an interview, then the interviewer will not even ask you the next question. And leetcode accepted your solution because all the test cases will run successfully but in the question, it is clearly mentioned that the solution must be in O(log n).
@Avagabond
@Avagabond Ай бұрын
he is just not good at explaining... may be because he sneaked the answerss from somewhere.. over confidence is not good when you're teaching man
@davemustainejigsaw
@davemustainejigsaw 4 жыл бұрын
A test case, that would fail: Array: [2,3,4,8,7] Target: 8 This will return -1 based on your code.
@alexandrostf2784
@alexandrostf2784 4 жыл бұрын
This test case does not meet the requirement of being a sorted array which has been rotated around a pivot. Binary search only works for sorted arrays, so we must have an array that is sorted. In this problem we have an array which has been unsorted about a pivot. Sorted, your array would be [2,3,4,7,8], if we rotate that about a pivot, we might get [7,8,2,3,4] as an example. but we could not just switch the 7 and the 8. I hope this helps
Self Taught Programmers... Listen Up.
11:21
Nick White
Рет қаралды 1 МЛН
Inside Out Babies (Inside Out Animation)
00:21
FASH
Рет қаралды 23 МЛН
Son ❤️ #shorts by Leisi Show
00:41
Leisi Show
Рет қаралды 8 МЛН
Это реально работает?!
00:33
БРУНО
Рет қаралды 3,3 МЛН
Schoolboy - Часть 2
00:12
⚡️КАН АНДРЕЙ⚡️
Рет қаралды 6 МЛН
I gave 127 interviews. Top 5 Algorithms they asked me.
8:36
Sahil & Sarra
Рет қаралды 633 М.
Search in Rotated Sorted Array | Решение на Python | LeetCode 33
19:20
Сурен Хоренян
Рет қаралды 573
Search in rotated sorted array | Leetcode #33
13:52
Techdose
Рет қаралды 83 М.
LeetCode 238. Product of Array Except Self (Solution Explained)
14:49
LeetCode 442. Find All Duplicates in an Array (Solution Explained)
12:37
JPEG is Dying - And that's a bad thing
8:09
2kliksphilip
Рет қаралды 103 М.
Inside Out Babies (Inside Out Animation)
00:21
FASH
Рет қаралды 23 МЛН