Binary Search - Leetcode 704 - Python

  Рет қаралды 142,887

NeetCode

NeetCode

Күн бұрын

🚀 neetcode.io/ - A better way to prepare for Coding Interviews
🥷 Discord: / discord
🐦 Twitter: / neetcode1
🐮 Support the channel: / neetcode
⭐ BLIND-75 PLAYLIST: • Two Sum - Leetcode 1 -...
💡 DYNAMIC PROGRAMMING PLAYLIST: • House Robber - Leetco...
Problem Link: neetcode.io/problems/binary-s...
0:00 - Read the problem
0:58 - Drawing Explanation
5:10 - Coding Explanation
leetcode 704
This question was identified as an interview question from here: github.com/xizhengszhang/Leet...
#sorted #array #python
Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.

Пікірлер: 76
@tanmay______
@tanmay______ 2 жыл бұрын
Thanks for mentioning the integer overflow problem!
@CST1992
@CST1992 4 ай бұрын
This kind of attention to detail is what separates great from just good.
@jameelshehadeh9011
@jameelshehadeh9011 Жыл бұрын
It's fascinating how beginner friendly this explanation was despite how professional you are, thank you
@numberonep5404
@numberonep5404 2 жыл бұрын
Always good to practice the basics! I am just happy to recieve a notification from neetcode :d
@dragonoid296
@dragonoid296 2 жыл бұрын
gotta do the classics sometimes
@h.t.4846
@h.t.4846 2 жыл бұрын
can't thank you enough for ur tutorials! it's for sure in depth and easy to digest!
@bartekbinda6978
@bartekbinda6978 6 ай бұрын
I’ve actually always coded the binary search using the distance approach and never thought about your original approach to determine the mid point, thanks
@re4388
@re4388 2 жыл бұрын
The best explain to beginner including the integer overflow I ever seen
@staffeng
@staffeng 2 жыл бұрын
There's also a version of binary search where we would need to return where the element's index would be had it been there in the collection. And this is exactly how Collections.binarySearch() and Arrays.binarySearch() is implemented in Java. For example, you have a collection [1,2,3,4,5] and if you search for 0, then Collections.binarySearch() will return -1 but that's because 0 would have been at the first place at index 0 so it's that index 0 in negative form minus 1 which is equal to -1. To take another example, let's say you are searching the same collection for element 6, then Collections.binarySearch() will return -6 (-5 - 1).
@JamieDawsonCodes
@JamieDawsonCodes Жыл бұрын
Great video! It helped me with this! For those coding in JavaScript, be sure to make the middle variable: let middle = Math.round((left + right) / 2); Otherwise the value will be 2.5 instead of 3.
@TheQuinnB
@TheQuinnB 3 ай бұрын
Thank You!
@SENSEIFILES
@SENSEIFILES Жыл бұрын
that log n breakdown just helped me for sure !
@Ashley-mc5bi
@Ashley-mc5bi 2 ай бұрын
My data structures professor secretly gets his entire lectures from your videos! Except you explain things much better lol. Thanks for all your help!
@jasonnguyen128
@jasonnguyen128 Жыл бұрын
Thank you, your explanation is amazing
@hamedbavar566
@hamedbavar566 Жыл бұрын
the recursive approach. if len(nums) == 0: return -1 mid = (len(nums)) // 2 if nums[mid] == target: return mid elif nums[mid] > target: return self.search(nums[:mid], target) else: result = self.search(nums[mid+1:], target) startIdx = mid + 1 if result != -1: return startIdx + result else: return -1
@dkijc
@dkijc Жыл бұрын
Thank you for the video! Is there a way to do this with recursion??? Thanks!
@abhimanyuambastha2595
@abhimanyuambastha2595 5 ай бұрын
I've always implemented the binary search using the distance method. I guess thats how they teach in all good algorithms course. But never knew the reason why
@a.rohimsama7222
@a.rohimsama7222 4 ай бұрын
Thank you. love it!
@AndersonSilvaMMA
@AndersonSilvaMMA Ай бұрын
OMG thank you very much for your channel!
@HibiTeamQueso
@HibiTeamQueso 7 ай бұрын
Lol it's so hilarious that the last way you showed it's the one I did. Cause I was like surely it has to be simpler but I guess not 😂 Took me a few tries to come up with it
@hyungminkim6664
@hyungminkim6664 2 жыл бұрын
Hi, Is there a pattern or a rule when choosing whether l
@orangethemeow
@orangethemeow 2 жыл бұрын
I used l < r, but you have to check in the end when l == r, whether nums[l] or nums[r] == target l, r = 0, len(nums) - 1 while l < r: m = (l + r) // 2 if nums[m] == target: return m elif nums[m] < target: l = m + 1 else: r = m - 1 return l if nums[l] == target else -1
@kwakubiney5175
@kwakubiney5175 2 жыл бұрын
I am guessing it depends on if you need to do something with the l=r condition, also for binary search, if the element has just one element, condition l
@thiagot7706
@thiagot7706 2 жыл бұрын
Thanks, neetcode.
@doodle_mo_ka4336
@doodle_mo_ka4336 Жыл бұрын
but you also have to add something for that solution of overflow problem, Because when the array have only one element, right would be negative in te while loop, they've been tricky these days
@tanoybhowmick8715
@tanoybhowmick8715 2 жыл бұрын
Thank you!
@nur_6ek
@nur_6ek 4 ай бұрын
you are legend bro😄
@chai01724
@chai01724 Жыл бұрын
Thanks for the video! I think it helps to mention the // syntax is a floor division, I have been implementing unnecessary checks on whether the array length is odd or even🥲
@ericdwkim
@ericdwkim 9 ай бұрын
this comment cleared that up for me, thanks!
@chessingh
@chessingh 2 жыл бұрын
Ah, neetcode doing the daily leetcode challenge 🥺🏆
@zeki7540
@zeki7540 2 ай бұрын
that was great!
@dewangpatil4990
@dewangpatil4990 2 жыл бұрын
Hello Sir i am a big fan......I have a very important request....... Could you please make solution playlist of Striver's SDE Sheet. Its will be very beneficial for us students
@free-palestine000
@free-palestine000 2 жыл бұрын
Do you have any advice on how to remember the fundamentals on a topic while you're working on other topics? I'm struggling to retain details from trees while im working on strings problems for example
@cc-to2jn
@cc-to2jn 2 жыл бұрын
i would recc u do them in pattern order rather than randomly. This will help u truly understand the pattern and retain it.
@bbbo85
@bbbo85 2 жыл бұрын
Grokking the coding interview is the answer you are looking for
@mindsetnuggets
@mindsetnuggets 2 жыл бұрын
Review old solutions or topics you've done every other day.
@scvkurt03
@scvkurt03 2 жыл бұрын
Use Anki to make flash cards. It’ll drill you every day using Spaced Repetition.
@shleebeez
@shleebeez 2 жыл бұрын
@@scvkurt03 how would the problems/solutions translate to cards?
@liabasqulizad7962
@liabasqulizad7962 5 ай бұрын
Thank you sir
@XxRazcxX
@XxRazcxX 4 күн бұрын
For the overflow couldnt you also do (L // 2) + (R//2)
@jesuyedavid9497
@jesuyedavid9497 2 жыл бұрын
can we make the variable names more explanatory?
@raghavkcc3234
@raghavkcc3234 Жыл бұрын
How can the list be added in the program????
@pradeepjigalur
@pradeepjigalur 2 жыл бұрын
Can you explain, why it should be l=mid+1 or r=mid-1 not l=mid or r=mid
@VedantaNayak
@VedantaNayak 2 жыл бұрын
Since we know mid is not the target, it will be redundant to include it in the next window.
@TheRailJunction
@TheRailJunction 6 ай бұрын
TIL how we get log n complexity..
@indhumathi5846
@indhumathi5846 Жыл бұрын
understood
@masternobody1896
@masternobody1896 2 жыл бұрын
nice
@darKnight_-_
@darKnight_-_ 10 ай бұрын
running it with m=l+r//2 doesnt work anymore you have to use m=l+l-r//2 only, otherwise it gives a time limit exceeded error
@eteran23
@eteran23 9 ай бұрын
(l+r)//2 works just fine. Mind the brackets. In your m=l+l-r//2 you're really doing m=2*l - r//2, which works here, but is probably not what you intended to do.
@darKnight_-_
@darKnight_-_ 9 ай бұрын
m=l+(r-l)//2 sorry@@eteran23
@thameemansari4767
@thameemansari4767 3 күн бұрын
In leetcode,I tried it and got wrong answer for nums = [4,5,6,7,0,1,2] , target = 0.output is -1 but expected is 4.Can u please help me?
@shurale85
@shurale85 8 ай бұрын
Why we can't just make left or right equal to middle without increasing or decreasing mid value? I know that's more efficient but don't understand why search doesn't work without modifying mid value
@juandager5220
@juandager5220 Ай бұрын
Left and right limit the section of nums where the possible solution is. And middle is the current index that you are comparing to the target. If middle is not the target, you need to adjust the new size by updating left OR right. Basically, discarding the upper or lower half. And then check again the new middle. The easiest real life example is how you search a dictionary. Grab a physical thesaurus and search for a word... That's binary search! Does that answer your question?
@pauljones9150
@pauljones9150 2 жыл бұрын
What confuses me is what happens in an array with a single value and the target is LESS than the value contained in the array. ie. Array = [1], Target = 0. Code Variable Theoretical Printout. L = 0, R=0, M=0 Target is less than value at M, so R=m-1 and M=-1 L=0 R=-1 M=-1 Target is STILL less than value at M, so R=M-1, so R=-2 and M=-1?? Value at M can never be reached, as M will never get smaller than -1???? Neetcode, bless me with your knowledge of edgecases
@CoolerJ0k3r
@CoolerJ0k3r 2 жыл бұрын
The while condition is L
@ikthedarchowdhury8947
@ikthedarchowdhury8947 2 жыл бұрын
@@CoolerJ0k3r What if the Target is inside the left or right pointer itself? [-1,0,3,5,9,12] target 5. I changed the target to 5 in the given test case, the solution works fine, but how? Which line is handling that?
@juandager5220
@juandager5220 Ай бұрын
You are confusing values with index. Target is the actual number you are looking for. Middle is the current index of what you are searching for. So when M=0, you are checking for the value of the number at the index 0 of nums. Same with left and right: they are the minimum and maximum index. Makes sense?
@juandager5220
@juandager5220 Ай бұрын
​@@ikthedarchowdhury8947If the target is at an extreme, either on the left or right, the while loop will keep running until left == Right== middle. How do you search for words in a physical thesaurus or dictionary? What happens if you are searching for the first or last word in the entire dictionary? Zzzzzzzuly? Hope this helps!
@pauljones9150
@pauljones9150 Ай бұрын
@@juandager5220 oh thx 🙏 that helped
@mehikrt8112
@mehikrt8112 Жыл бұрын
"l, r=0, len(nums)-1 " can you explain this one ? i guess l=0 , r=0 but len(nums) -1 == ? its not like this r= len(nums) -1 , am i right ? Thank you
@ashish7936
@ashish7936 Жыл бұрын
nope it means l=0 and r=len(nums)-1 -> which means length of nums array - 1 so that we get last index of nums array and -1 because the index of array start from 0. hope it helps
@juandager5220
@juandager5220 Ай бұрын
In Python, you can declare variables like this: Variable1, Variable2 = Value1, Value2 So: L, R = 0, lens(nums) -1 Is the same as: L=0 R=lens(nums) - 1 Does that answer your question?
@TOUNSI28CSS28GHASSEN
@TOUNSI28CSS28GHASSEN 2 жыл бұрын
for the (r+l)//2 problem you can easily do r//2 + l//2 because maths
@onwa
@onwa 2 жыл бұрын
Not so. Remember, // is floor-division not float-division. Sometimes they're equal, but not always. E.g. (3+5)//2 = 4 while 3//2 + 5//2 = 1 + 2 = 3
@ZyneBeatbox
@ZyneBeatbox 2 жыл бұрын
First :o
@calebsparks5344
@calebsparks5344 Ай бұрын
Anyone else think the l was a 1 and get really confused for a second?
@juandager5220
@juandager5220 Ай бұрын
In which line of code? What timestamp? Some solutions: 1. Write full words for variables: left, right 2. Notice how the IDE has different colors for variables and numbers. L is white, 1 is purple. 3. Practice more. And you'll gain intuition.
@ninjaturtle205
@ninjaturtle205 Жыл бұрын
this solution gives the wrong answer for me Target = 0 [-5, 0, .....] last iteration, L=0, R=1, Midpoint: (0+1)//2 = 0 since target >nums[midpoint], L = Midpoint +1 = 0 + 1 = 1 now L has become greater than R, and the program returns false.
@heatchecknyc2142
@heatchecknyc2142 Жыл бұрын
Make it while L
@opreastefan5371
@opreastefan5371 Жыл бұрын
Beautiful!
@Exploshi
@Exploshi 6 ай бұрын
👑you dropped this
@sanooosai
@sanooosai Жыл бұрын
thank you sir
Koko Eating Bananas - Binary Search - Leetcode 875 - Python
15:12
How I would learn Leetcode if I could start over
18:03
NeetCodeIO
Рет қаралды 403 М.
哈莉奎因以为小丑不爱她了#joker #cosplay #Harriet Quinn
00:22
佐助与鸣人
Рет қаралды 8 МЛН
Идеально повторил? Хотите вторую часть?
00:13
⚡️КАН АНДРЕЙ⚡️
Рет қаралды 9 МЛН
Gym belt !! 😂😂  @kauermotta
00:10
Tibo InShape
Рет қаралды 18 МЛН
Survive 100 Days In Nuclear Bunker, Win $500,000
32:21
MrBeast
Рет қаралды 107 МЛН
How Binary Search Makes Computers Much, Much Faster
6:51
Tom Scott
Рет қаралды 1,4 МЛН
Winning Google Kickstart Round A 2020 + Facecam
17:10
William Lin
Рет қаралды 9 МЛН
I quit Amazon after two months
10:09
NeetCode
Рет қаралды 592 М.
Search Insert Position - Binary Search - Leetcode 35 - Python
13:42
I Solved 1583 Leetcode Questions  Here's What I Learned
20:37
ThePrimeTime
Рет қаралды 598 М.
The LeetCode Fallacy
6:08
NeetCode
Рет қаралды 462 М.
Coding Interviews Be Like
5:31
Nicholas T.
Рет қаралды 6 МЛН
Why is everyone LYING?
7:56
NeetCodeIO
Рет қаралды 197 М.
SHA: Secure Hashing Algorithm - Computerphile
10:21
Computerphile
Рет қаралды 1,2 МЛН
5 Useful F-String Tricks In Python
10:02
Indently
Рет қаралды 288 М.
low battery 🪫
0:10
dednahype
Рет қаралды 1,8 МЛН
Samsung laughing on iPhone #techbyakram
0:12
Tech by Akram
Рет қаралды 7 МЛН
Vision Pro наконец-то доработали! Но не Apple!
0:40
ÉЖИ АКСЁНОВ
Рет қаралды 485 М.
#samsung #retrophone #nostalgia #x100
0:14
mobijunk
Рет қаралды 14 МЛН