Dev HUMILIATED after writing Brute Force Search on a Sorted List

  Рет қаралды 243,984

NeetCodeIO

NeetCodeIO

Күн бұрын

Пікірлер: 375
@NeetCodeIO
@NeetCodeIO 9 ай бұрын
Kinda surprised how many people think it's a Linked List.. does this look familiar: List list = new ArrayList();
@rinat2160
@rinat2160 9 ай бұрын
If you are writing a library which functions work reasonably well __only__ when Lists they accepting are ArrayLists, you are writing a bad library. If a function requires constant-time random iterators, it should only accept containers which have constant-time random iterators. That way compiler will prevent library users from using your library incorrectly.
@IronicHavoc
@IronicHavoc 3 ай бұрын
​@rinat2160 its a leetcode question though, not a library
@IronicHavoc
@IronicHavoc 3 ай бұрын
​@rinat2160 Also what do you mean by "random" iterator? Do you mean, like, arbitrary/generic?
@KeepOnBlazing
@KeepOnBlazing 2 ай бұрын
@@IronicHavocrandom means random access also knows as constant access, like arrays. In linked lists, on the other hand, to get the n-th element you have to pass through all the ones before it (because of how a linked list is implemented, look it up on wikipedia) and thus the access time cannot be constant i.e. random
@LeeO0704
@LeeO0704 2 ай бұрын
why is he calling variable "pointers"?
@taaaaaaay
@taaaaaaay 9 ай бұрын
Bro was able to identify the Leetcode number from the top of his head💀
@chillsjiujitsu
@chillsjiujitsu 9 ай бұрын
That’s why he’s the GOAT
@aflous
@aflous 9 ай бұрын
His name is Neetcode, what did you expect?
@VampiricBard
@VampiricBard 9 ай бұрын
@@aflous 🤣
@xcuu
@xcuu 9 ай бұрын
Tell me you’re a sex haver without telling me you’re a sex haver
@kingpen5866
@kingpen5866 9 ай бұрын
Bro
@LandoKalrissian
@LandoKalrissian 9 ай бұрын
For small arrays, linear search actually beats binary search because it's so branch-prediction friendly.
@NeetCodeIO
@NeetCodeIO 9 ай бұрын
Also why didnt he just do .indexOf(element)
@LandoKalrissian
@LandoKalrissian 9 ай бұрын
​@@NeetCodeIO I usually code in languages that don't have that method built-in, so if I were tasked with writing linear search in Java, it wouldn't occur to me to see if a built-in function with such functionality exists.
@CrabGuyy
@CrabGuyy 9 ай бұрын
@@LandoKalrissianhe was being sarcastic, you stated the obvious missing the point of the video, so he prompted you with a equally useless comment. No hate, just explaining
@ecchioni
@ecchioni 9 ай бұрын
Same reason why C# uses quicksort and insertion sort combo as its default sort.
@TacoMaster07
@TacoMaster07 9 ай бұрын
@@CrabGuyy cache locality and branch predictability effects on different DS and algorithm ordinance is obvious? Dumbass.
@halfjainam
@halfjainam 9 ай бұрын
did he just fucking quote a LEETCODE question with NUMBER by looking 4 lines of code!!! 😭😭
@someoneontheweb4515
@someoneontheweb4515 8 ай бұрын
its not that big of a deal lmao
@rockdude1122
@rockdude1122 8 ай бұрын
@@someoneontheweb4515 most people watching this video or just programmers in general have not done enough leetcode problems to remember the exact leetcode problem by just looking at 4 lines of code so its pretty impressive.
@Random-ev6xq
@Random-ev6xq 3 ай бұрын
bro im sayin i thought i was tweakin 😂😂😂
@monkemode8128
@monkemode8128 Ай бұрын
@@rockdude1122 Yeah I have 300 problems solved on leetcode over my time in uni but I don't remember any by number (except the first few).
@fplancke3336
@fplancke3336 Ай бұрын
Well the 4 lignes of code are definitively NOT the answer to that LeetCode question: the identifier and types do not match.
@GnomeEU
@GnomeEU 9 ай бұрын
When do you ever use binary search in a real project? It's either dictionary lookup or flat list. 99% of our performance issues are crappy sql queries, a bad coded UI framework, or just plain logic errors. If binary search is your problem then it looks like your project is in an AMAZING state!
@JosephGleespen
@JosephGleespen 9 ай бұрын
It's a leetcode problem bro, that's what they are like
@mycommentmyopinion
@mycommentmyopinion 9 ай бұрын
@@JosephGleespen Literally not the point.
@NeetCodeIO
@NeetCodeIO 9 ай бұрын
i agree, even if you needed binary search you would use the built in one. Even i made a mistake in mine (l + r can lead to overflow). Best to rely on std libraries, even in the video why didnt he just use the built in linear scan of ArrayLists.
@QuanNguyen-og6pq
@QuanNguyen-og6pq 9 ай бұрын
yup. Bad sql, bad joins has caused more slowness than any search problems I've seen.
@talareese580
@talareese580 9 ай бұрын
I had to use binary search for a procedural level generation component in my game. I had to randomly choose an asset to spawn on a grid. But each asset had an associated percentage chance of spawning. So yeah.
@shobhandash8720
@shobhandash8720 9 ай бұрын
the bully: good, now do this in O(1)
@sharpfang
@sharpfang 9 ай бұрын
ret=-1; for (i=0; i
@Zattilio
@Zattilio 2 ай бұрын
Ok i will use a hashmap
@thepriestofvaranasi
@thepriestofvaranasi 2 ай бұрын
Proceeds to create a hashmap 🗿🗿
@LukeDrumm
@LukeDrumm 9 ай бұрын
Discussion of performance without mentioning CPU caching is ... interesting.
@elijahbuscho7715
@elijahbuscho7715 9 ай бұрын
This is why I use PHP and throw performance out the window
@niggacockball7995
@niggacockball7995 9 ай бұрын
@@elijahbuscho7715 unironically based, only old hags with shitpads from 2001 complain about performance like bruv just get a new pc its not that hard
@TehIdiotOne
@TehIdiotOne 8 ай бұрын
@@elijahbuscho7715 I do Python
@naughtiousmaximus7853
@naughtiousmaximus7853 3 ай бұрын
​@@elijahbuscho7715 No need to solve a problem if there isnt one,
@JNelson_
@JNelson_ Ай бұрын
I actually work on a project which requires hundreds of lookup tables and for lookup tables with fewer than 100 elements brute force (because of caching) is as fast as naive binary search and faster at lower numbers. That said spending a lot of time optimising it, you can write a branchless variant and you can get the compile to unroll your look if you know the size at compile time to give you log2(N) iterations. This beats out naive binary search and brute force by only about 2 times. It's all about measurement and use case and seeing if it's actually worth the time saved.
@fplancke3336
@fplancke3336 Ай бұрын
But the worst mistake in the code is not that it’s obscure or needlessly slow. The worst mistake is it fails on an empty array.
@kebien6020
@kebien6020 Ай бұрын
Always remember though: Binary search produces maximally unpredictable branches (bad for speculative execution), and jumping around in memory (bad for cache locality). So it's actually slower than linear search for small lists. The exact element count where binary search becomes faster than linear depends on multiple factors, such as the list implementation, the element size, the size of the processor's caches, etc. So you have to benchmark in order to actually know for a particular situation. It's often suprising how big the list has to be for binary search to be faster.
@JNelson_
@JNelson_ Ай бұрын
You can actually write a branchless binary search. I work on a project which requires hundreds of lookup tables and for lookup tables with fewer than 100 elements brute force (because of cpu cache) is as fast as naive binary search and faster at lower numbers. That said spending a lot of time optimising it, you can write a branchless variant and you can get the compile to unroll your look if you know the size at compile time to give you log2(N) iterations. This beats out naive binary search and brute force by only about 2 times. It's all about measurement and use case and seeing if it's actually worth the time saved. Saying to always use binary search like this guy is saying is brainless.
@444limm
@444limm 9 ай бұрын
there are actually quite a few languages that better to use method to get an element with index. Because with [ ] most programming languages will just panic / throw exception when index out of bound, but with method like .get() we can make the return type not the bare element but a wrapper like Option in rust so Some(value) if the value is present and None if the index is out of bound
@nikhilchouhan1802
@nikhilchouhan1802 3 ай бұрын
or just use std::optional
@nikhilchouhan1802
@nikhilchouhan1802 3 ай бұрын
in c++ ofc
@Kokurorokuko
@Kokurorokuko Ай бұрын
how about you just overload square brackets operator to act like get? Problem solved
@ryu_lidu
@ryu_lidu 14 күн бұрын
Usually those get methods have an overhead to check for oob every single access which is unnecessary When writing high performance stuff where you're accessing something a bunch of times it's better to just use []
@444limm
@444limm 14 күн бұрын
@@ryu_lidu good point for most software, get is much better since it gives us more control and it's a lot easier to handle and maintain but for performance critical software like games, square bracket is much more preferable because we likely will make sure the index will never get out of bound
@justADeni
@justADeni 8 ай бұрын
2:30 No, in Java the syntax to get a value from an Array (as you said) is array[index]. However to get value from a List, you'd use .get(index) as you can see in the vid.
@LeeO0704
@LeeO0704 2 ай бұрын
why is he calling variable "pointers"?
@monkemode8128
@monkemode8128 Ай бұрын
@@LeeO0704 It's not a pointer in the sense that it points to a memory address, but the "point" of the variable `i` in the bad code is to "point" at index in the array.
@varunsodhani6812
@varunsodhani6812 Күн бұрын
@@LeeO0704 the variable points to an index in the array (so colloquially known as a pointer), not in memory which is where the word pointer should be used
@unixpro1970
@unixpro1970 9 ай бұрын
Silicon Valley was a popular TV show, but this is ridiculous and uncalled for. He should have stood up for himself and left, if they continued to act like this. Constructive criticism is one thing, but abuse should never be tolerated. They acted like a bunch of clowns 🤡
@flaried9345
@flaried9345 23 күн бұрын
you just said it was a show, why does it upset you when its a script? like the actor should of left then and there?
@lucascamelo3079
@lucascamelo3079 20 күн бұрын
​​@@flaried9345Because the show helps normalizing this kinda of conduct
@LudicrousAvian
@LudicrousAvian 18 күн бұрын
yea in the real world only a couple jokes would come out of it then we would discuss the better solution and learn together
@GrandHighGamer
@GrandHighGamer 3 күн бұрын
@@lucascamelo3079 The show is a comedy and frequently shows cartoonishly shitty people. This normalises this kind of content way less than say House MD normalizes doctors breaking into patient's houses to discover they actually have a rare fungal infection transmitted by an windcharm they bought in a bootsale.
@asandax6
@asandax6 9 ай бұрын
Not gonna lie when I write code I always write whatever pops in my head. I optmise it latter if I need to. The reason I do this is because I sometimes get side tracked into optimizing a single piece of code and by the time I realize I have wasted a lot of time on it. So better make it work then improve once it works.
@amzker
@amzker 2 ай бұрын
Yes, exactly
@ramanchaudhary2518
@ramanchaudhary2518 Ай бұрын
Similar thing with leetcode problems if you try for the optimal solution first you will go in circles ,if you brute force it then you find out how to actually implement a optimisation and why it is needed
@taragnor
@taragnor Ай бұрын
Yeah, I generally use this practice too. Unless I know the list is going to be massive, or I'm specifically coding something that needs top end performance, I generally don't even bother with any optimization and do the quick and dirty method. This is the kind of code you can always refactor later if need be. Sometimes you may even screw yourself being too clever. Like if the sortedList was actually a linked list and not an array, doing a binary search would often get worse performance than a linear one.
@n_x1891
@n_x1891 9 ай бұрын
If I was getting grilled like that I would have just said that in spite of the list saying it was sorted there was no guarantee so I had to check manually. Might work 😂
@likesonggame
@likesonggame 2 ай бұрын
Yes, this is true. I got scream for this in my first year of work. Even thought the guy who build and manage the database should have sorted it but they argue that people never do their job correctly so i have to check it again. Sadly coders never checked or test their programs because of laziness so yeah it's a good measure.
@monkemode8128
@monkemode8128 Ай бұрын
I'm front end so I know my code will never run over thousands or millions of elements, a lot of times I just sort stuff like responses to API calls which say they should come sorted because I've had cases where they aren't or they aren't sorted in the way advertised. The cost is low for so few elements and it adds some resilience against bad updates to the API implementation or weird responses.
@jibreelkeddo7030
@jibreelkeddo7030 Ай бұрын
@@monkemode8128 The downside of doing that is that you end up covering up what should be a bug report to the backend guy.
@chandrap8391
@chandrap8391 9 ай бұрын
The current generation CPU / GPUs process what ever junk we write inside a loop in a matter of no time. For 90% of Application Software the current Processors just chew any loop throwed at them before we notice it unless we have millions of rows in memory, which is not the case in 90% of the work.
@NeetCodeIO
@NeetCodeIO 9 ай бұрын
I think the more embarrassing thing is the person using a Windows laptop at 1:18
@NeetCodeIO
@NeetCodeIO 9 ай бұрын
I'm tempted to delete your comment and edit mine...
@abdalla4425
@abdalla4425 9 ай бұрын
LMAOO @@NeetCodeIO
@pengie_
@pengie_ 9 ай бұрын
I run that same laptop but it's got linux running on it, had to put a sticker of my distro on it so people didnt think i run windows
@jonathanng7141
@jonathanng7141 9 ай бұрын
What is wrong with Microsoft surface laptop?
@GreatTaiwan
@GreatTaiwan 2 ай бұрын
@@pengie_expensive, poor performance per watt and per dollar Why would u buy surface (beside maybe Lilith the package itself that hardware removing the touch screen and so on)
@ofbaran
@ofbaran 9 ай бұрын
I see myself using linear search under pressure, it just seems like the most natural way of searching in non computed primitive way of searching items in real life, of course in a real situation the best method would be using a built in search mechanism of the language such as the .indexOf() or its equivalent if present in the language and let the compiler or the interpreter get clever with it if not implement a more sophisticated searching algorithm more fitting for the expected data size. For me the problem in the video is not the error itself but rather the reaction to the errors. We all make mistakes, especially in the beginning but instead of putting each other down over it we should be correcting each other while lifting each other up. Unfortunately I have seen this kind of snobbery in real life. Pressuring devs into making untested solutions that even they couldn't revise themselves to get solutions and then talk them down for mistakes.
@ofbaran
@ofbaran 9 ай бұрын
Note: apparently I was wrong, Java implementation of .indexOf() is also linear search! In large samples a binary on a sorted array would be faster
@ofbaran
@ofbaran 9 ай бұрын
The linear search is still useful if the array is unsorted, I'm sorry.
@Dan-codes
@Dan-codes Ай бұрын
If interviewers laugh at a person for their solution, instead of helping the candidate learn, they are unfit for their role. They could be your boss someday or a connection at a company you want to work for. Candidates are nervous and show up for free. Meanwhile, you're getting paid to watch them. They deserve professionalism, at the very least. I do lots of interviews(real and mock) and *always* root for the interviewee.
@fromjavatohaskell909
@fromjavatohaskell909 9 ай бұрын
3:44 (l + r)/2 would cause overflow for big arrays
@tylerd5924
@tylerd5924 3 ай бұрын
🤓☝🏻
@jamjam3448
@jamjam3448 2 ай бұрын
Yeah l+(r-l) /2 is better
@ursalight
@ursalight Ай бұрын
@@calculovo4219 oh right
@yashmalviya0149
@yashmalviya0149 Ай бұрын
(l + ((r - l) >> 1)) 😎
@monkemode8128
@monkemode8128 Ай бұрын
What about....... l/2 + r/2 Seems intuitive to me.
@romanivanov6183
@romanivanov6183 9 ай бұрын
Hey! l +r ?? You will get integer overflow!
@NeetCodeIO
@NeetCodeIO 9 ай бұрын
🤦i've dishonored my entire family
@oussamabennasr4936
@oussamabennasr4936 9 ай бұрын
m = l + (r-l)/2
@blasttrash
@blasttrash 9 ай бұрын
Correct me if I am wrong, but this issue doesnt exist in python right? Only in C, Java, C++ I guess coz of how ints are handled? If thats the case, it might explain why a python dev would not think of this. Also in Java, we have to be careful while writing comparators with integers(especially with heap based questions like top k etc). If we do a - b instead of Integer.compare(a, b) we will have similar issues.
@se4geniuses
@se4geniuses 9 ай бұрын
@romanivanov True, but if you're iterating over more than 2^((sizeof(int) * 8) - 1) / 2 elements, you have bigger concerns to deal with.
@TehIdiotOne
@TehIdiotOne 8 ай бұрын
@@se4geniuses You do, but it's not entirely unheard of
@mycommentmyopinion
@mycommentmyopinion 9 ай бұрын
Fuccc I think I need a refresh on algorithms, I use them so rarely I keep forgetting how they work lol
@EvanPilb
@EvanPilb Ай бұрын
2:00 bro it's your twin
@michaellk2254
@michaellk2254 Ай бұрын
2:20 just a nitpick, java doesn't need a method to get a value from an array, it needs a method to get a value from a list.
@SuperMaDBrothers
@SuperMaDBrothers 9 ай бұрын
it's not a mistake, it's being frugal with your time when the complexity doesnt affect the runtime for fuck. if he's searching a list of size 3 then the complexity doesnt matter. this tv show fucking sucks, no one acts like a software dev. painful to watch
@234lk
@234lk 9 ай бұрын
Do you really think anyone would watch the show if they acted like software engineers?
@SuperMaDBrothers
@SuperMaDBrothers 9 ай бұрын
@@234lk you really wanna watch a bunch of people act like brainless zombies? I guess that's what modern tv has become, let me just watch my character act in the way i want them to act. That is SO what jim and pam would do! LOVE ittttt!
@mycommentmyopinion
@mycommentmyopinion 9 ай бұрын
I doubt it's made to be realistic lol, nobody would want to watch a realistic version
@anon_y_mousse
@anon_y_mousse 9 ай бұрын
@@SuperMaDBrothers No, it's definitely a mistake, because there is a function to perform the search for you on a sorted array in every major programming language, even Java.
@meatbleed
@meatbleed 2 ай бұрын
hey buddy software dev is boring as fuck. clearly they're gonna make up more interesting scenarios than just sitting there coding SQL or some lame shit
@mukeshrawat1304
@mukeshrawat1304 9 ай бұрын
Guess what?! I landed on Neetcode's YT channel while doing a brute force linear search on KZbin. Definitely worth it ❤😊
@vinayemani4105
@vinayemani4105 9 ай бұрын
Well, to be pedantic, without knowing the type of sortedList (assumed in the show to be an array, hence the joke) which could've been a LinkedList, we cannot really comment on the efficiency of this code. Binary search on a linked list is worse than linear search.
@phoneix24886
@phoneix24886 2 ай бұрын
But it was really cool that a TV show brought up the basics of CS and actually showed a code that makes sense. Silicon valley is still the goat along with Mr. Robot among all tech based movies/series.
@thimowellner7686
@thimowellner7686 Ай бұрын
I'm not too familiar with the implementation of a LinkedList, but I assume that the given solution would still be terrible for it, as it uses .get(index). For a LinkedList this method would have linear runtime and it's used in a loop over all indexes, making the algorithm's runtime quadratic. If it's a linked list, the search should follow the pointers directly, not use a retrieval method that has to follow the pointers again and again.
@cwagnello
@cwagnello Ай бұрын
@@thimowellner7686 yeah it's a linear scan for .get(index), assuming that it's a LinkedList. But saying that anyone using Java is going to use an ArrayList 99.99999% of the time so that wouldn't be an issue.
@CottidaeSEA
@CottidaeSEA Ай бұрын
If you're ever going to do a linear search, please just use a good old for-loop. Don't try to do anything fancy.
@dracsharp
@dracsharp 9 ай бұрын
From a business perspective and assuming you are building an MVP or a possible feature, the fastest to add solution is the right solution.
@xavier7769
@xavier7769 9 ай бұрын
well bin search is fast to add he did it in like 2 mins
@mycommentmyopinion
@mycommentmyopinion 9 ай бұрын
@@xavier7769 With a bug that could cost money and time to debug :D
@def__init
@def__init 9 ай бұрын
Skill issue
@nemikuuro
@nemikuuro 9 ай бұрын
There also seems to be a bug in the solution from the clip - it always tries to get the first element from the sortedList? What if the list is empty?
@tjhooperofficial
@tjhooperofficial 23 күн бұрын
I'd like to point out that, unless you know for a fact you are searching through a large sorted array, it is probably just as good, if not better to just do a linear search. It's less overhead, easier to read, no possible cache misses, and in some cases, just plain faster if the target element is near the beginning of the array.
@jonathanng7141
@jonathanng7141 9 ай бұрын
I just learnt sorting this week and this video was perfect in helping me understand how the code is implemented!
@ishanbajpai6940
@ishanbajpai6940 9 ай бұрын
Silicon Valley, baby!!!
@connormc711
@connormc711 9 ай бұрын
Wow. I have never seen someone with that close of an approximation to real skills
@ehfoss
@ehfoss Ай бұрын
The scene is a bit deeper. Richard is a low level coder who is used to squeezing out loads of perf. In C and C++ it's known that a linear walk of an array will be faster in many cases where the array is rather small (say,
@TacoMaster07
@TacoMaster07 9 ай бұрын
Java allows direct array access(I don't think any language doesn't since the purpose of an array is data storage in memory sequence), Java's arrays are implemented as objects, nums[5] = 69 is a valid assignment.
@technophile_
@technophile_ 9 ай бұрын
I think you forgot about the fact that (l+r)/2 might cause the integer to overflow. I know that solving the problem is not the point of the video. But I’m just putting it in here.
@mgancarzjr
@mgancarzjr 2 ай бұрын
In case anyone needs to see this: int mid = left + (right - left) / 2;
@monkemode8128
@monkemode8128 Ай бұрын
For anyone wondering, to prevent this, you could use the distributive property of division and convert: (l+r)/2 to (l/2)+(r/2) edit not really
@steffenrumpel2784
@steffenrumpel2784 Ай бұрын
@@monkemode8128 Assume L=3 and R=5. What you get in the second case is 1+2=3 (because of integer based calculations) which is still within the bounds, but certainly not the "middle". mgancarzjr's "left+(right-left)/2" is better.
@monkemode8128
@monkemode8128 Ай бұрын
​@@steffenrumpel2784 Yup, you're correct :) Someone else pointed out my error, I forgot about integer division going down to floor. Good example it makes it very clear.
9 ай бұрын
NitPick : In java you need a method to get a value from a list, not an array.
@carolinaraeper
@carolinaraeper Ай бұрын
If the expected data sets to be iterated over are always small, then I'd argue it doesn't really matter. It's only when you encounter large data sets does the time complexity difference become relevant. I'd merge it.
@rinat2160
@rinat2160 9 ай бұрын
Code in the show mentioned a list, not an array. You can't really do a binary search in a list unless you preprocess it first. But then its not just a list anymore. The joke was that the code in the snippet tries to get nth element from a list N times, so the overall complexity is O(N^2).
@69k_gold
@69k_gold 9 ай бұрын
Wouldn't this be a massive code duplication issue? He's reinventing the wheel
@lmao4982
@lmao4982 9 ай бұрын
you don't need a method to access array members in java, it has c-style syntax for that. these are lists. edit: ah you just did it
@kantamei7707
@kantamei7707 Ай бұрын
Pretty sure there's a bug at 3:08. Because java doesnt use bignum, l+r can overflow if the array size is near int max.
@ivanjermakov
@ivanjermakov Күн бұрын
If this is a hot spot, data structure should reflect the ordering (for Java probably SortedSet) and you should use built-in methods for such basic operations (e.g. indexOf() or includes()). If this is not a hot spot, who cares how you find an index? The list is probably small (under 1k elements) for this to have performance hit.
@EudaderurScheiss
@EudaderurScheiss 9 ай бұрын
i actually like the first solution more. it is standard pattern and you see what it does in a second. the l+r stuff is nice to have for high performance areas. but i dont understand leetcode. if i want to program or have it hard, i start game dev and waste time there
@joshmosley
@joshmosley Ай бұрын
The first solution is extremely slow, and the 'hard' one is extremely fast. It doesn't really matter for small things because computers are very fast anyway - but when you're dealing with a large array it makes a big difference. Leetcode and Data Structures/Algorithms in general is about learning the "right" way to do things as a programmer and even beyond that, learning WHY the 2nd answer is correct. The concepts are very useful if you can get them down. Common sense guide to DSA was a very helpful book for me to begin learning DSA concepts.
@monkemode8128
@monkemode8128 Ай бұрын
@@joshmosley Yeah, this depends on the usage. If you know your code will only deal with a few elements, it's fine code. Say it's an API call and there's a cap of 100 elements. However, you should be able to understand binary search. Besides, it's pretty intuitive and simple, especially if you look at non-code practical examples. For example the way people look for a page in a long book is akin to binary search but it's not binary it's more... random.
@CottidaeSEA
@CottidaeSEA Ай бұрын
@@joshmosley The first one is only slow under the assumption that the list is sorted. It was in this case, but you're not always working with a sorted list, or at least not sorted in the way you want to search.
@AzidHouse
@AzidHouse 9 ай бұрын
Why are you assuming that sortedList is just an array of integers? In Java, simple arrays don't have methods. You have to use [index] as usual to retrieve an item. On the other hand you cannot use < > operators for comparison between two arbitrary objects. And clearly sortedList is an ordered objects container. The proof is that here is used the equals method. So, what is the solution in that case? I'm truly interested, I saw many answers that address the problem without taking into consideration those aspects.
@ramanchaudhary2518
@ramanchaudhary2518 Ай бұрын
The .size() method returns an integer value if that’s what you meant ?
@AzidHouse
@AzidHouse Ай бұрын
No, I just want to see a general purpouse Object comparison with the use of the .equals() method and not assuming that the object is simply an integer comparable with angular brackets. Example: you must find an object that is inside the sortedList but ordered by more than one field. To be clear, assume that you have a Box object that you need to retrieve and his position in space is given by WarehouseNo, Lane, Rack, Shelf. The comparison logic, obviously, resides into the equals() method. You cannot use other means to compare 2 instances of the same object.
@TheOnlyTahooey
@TheOnlyTahooey 23 күн бұрын
always write sub-optimal code first. makes it way easier to find performance improvements later
@Terrados1337
@Terrados1337 8 ай бұрын
Back when I learned about search algorithms in school I was amazed. So much performance! Now that I have to handle actual data I rarely get to us any. Since data is complete diarrhea 99% of the time might as well map it. Too much memory usage? Download more RAM, duh!
@imerence6290
@imerence6290 3 ай бұрын
I'm actually impressed how short the code is.
@DynamicalisBlue
@DynamicalisBlue 8 күн бұрын
Binary search kinda reminds of linked lists. They were both theoretically supposed to be faster but in most real use cases, they perform worse.
@JaredT
@JaredT 9 ай бұрын
This channel has potential to hit a million subs 🚀
@NeetCodeIO
@NeetCodeIO 9 ай бұрын
Now that i think of it, i should really start uploading on the main channel again. I need to hit one milli before the end of the year 😤😤😤
@upsidedownChad
@upsidedownChad 9 ай бұрын
​@@NeetCodeIO I'll watch every video you post on my phone, computer and tv at the same time
@fahad_hassan_92
@fahad_hassan_92 25 күн бұрын
Hurray! I've learned binary search through this video
@tungpho2132
@tungpho2132 9 ай бұрын
Wow, actually rarely to see someone beat 100% of runtime 😮
@sunnyyasser5625
@sunnyyasser5625 9 ай бұрын
How do you even perform binary search on a linked list? Random access iterators are not available
@julioflores1849
@julioflores1849 9 ай бұрын
I’m pretty sure it is to be sorted and the linked list needs to have a total node count
@Schnorzel1337
@Schnorzel1337 9 ай бұрын
You basicly run past nodes not looking at their value. So you can not effectively do binary search on a linked list.
@matthewgraham790
@matthewgraham790 9 ай бұрын
you still need to look at their 'next' pointer so by omitting looking at the value and comparing, you are still only diving the time by roughly 3, which although good, is still O(n) not O(ln n)@@Schnorzel1337
@TehIdiotOne
@TehIdiotOne 8 ай бұрын
It's not a linked list, where'd you get that idea? FYI dynamic arrays are called ArrayLists in Java.
@lundril
@lundril 3 ай бұрын
Because it's called "List" and not "Vector" or "Array" ???
@notro657
@notro657 2 ай бұрын
I hate the fact that even if he wrote a very bad code they laugh at him, not cool.
@liquidsnake6879
@liquidsnake6879 Ай бұрын
Interview questions consisting of bs nobody actually does in the real world
@rfolks92
@rfolks92 19 күн бұрын
Why is everyone assuming the list is (1) sorted, and (2) large enough to be better than linear search?
@Mankind5490
@Mankind5490 8 ай бұрын
Bro really knew the LeetCode Number lmfao
@yashgangrade5460
@yashgangrade5460 9 ай бұрын
Even though I've seen this before, watching it again with Neetcode makes it even funnier.
@shardator
@shardator Ай бұрын
Linear search can be a lot faster than binary search if the elements are stored consecutively in memory, and the list is relatively small.
@caoinismyname
@caoinismyname Ай бұрын
That's more on the implementation details. Coding interviews focus more on the logic. Logically, binary search is always faster for sorted data.
@shardator
@shardator Ай бұрын
@@caoinismyname Not really. Most coding interviews I took went for stupid leetcode-style questions with micro-optimizations.
@caoinismyname
@caoinismyname Ай бұрын
@@shardator Well, that's your experience.
@shardator
@shardator Ай бұрын
@@caoinismyname My job in low latency C++ for 18 years now. So ye.
@steves9250
@steves9250 Ай бұрын
I’ve seen lists before that were called “sortedList” that aren’t in fact sorted😮
@sprytnychomik
@sprytnychomik 9 ай бұрын
Not sure that binary search would be so much better on a sorted (assuming linked) *list*, though.
@ValerieLoveTV
@ValerieLoveTV 9 ай бұрын
Linked lists aren't accessible by index.
@TragicGFuel
@TragicGFuel 9 ай бұрын
What kinda indexed linked lists are you playing around with?
@sprytnychomik
@sprytnychomik 9 ай бұрын
@@ValerieLoveTVThis one apparently is.
@isodoubIet
@isodoubIet 9 ай бұрын
@@ValerieLoveTV They can be if you write the api to do it. In Haskell for example they are.
@ramanchaudhary2518
@ramanchaudhary2518 Ай бұрын
⁠​⁠​⁠​⁠​⁠​⁠​⁠​⁠​⁠​⁠@@TragicGFuel these are most likely Java array lists
@pencilcheck
@pencilcheck 9 ай бұрын
Just nit picking the naming of this title. Brute Force usually implied trying all possible solutions in a solution space. Those terms usually applied in optimization problems. Search in a 1d array isn't an optimization problem.
@James-l5s7k
@James-l5s7k 9 ай бұрын
"int index = 0;" -> how the hell is this a pointer?
@lesterdelacruz5088
@lesterdelacruz5088 2 ай бұрын
The code in the show will never have a -1 output. It will find the last index in the case where the item isn’t there.
@nehadyounis
@nehadyounis 9 ай бұрын
bro said "this is leetcode 704" and it was actually leetcode 704
@sergrojGrayFace
@sergrojGrayFace 9 ай бұрын
Also, never write binary search for a simple list, because you'll probably find a standard implementation for it in any language.
@TheSirNiklas
@TheSirNiklas 22 күн бұрын
How do you know that is a "pointer" Without any pointer defining it? Looks like a regular old int type variable to me.
@conscofd3534
@conscofd3534 24 күн бұрын
So glad I left this kind of toxic/egocentric environment as a dev and went to important QA role so I can now make fun of their stuff when it fails LOL
@Dom-zy1qy
@Dom-zy1qy 9 ай бұрын
This dude writes binary search like I breathe.
@edwardmitchell6581
@edwardmitchell6581 9 ай бұрын
It's basically his full time job.
@ceciljoel9577
@ceciljoel9577 9 ай бұрын
For seniors those algorithms for really that easy
@yt-sh
@yt-sh 3 ай бұрын
binary search is a pretty good algorithm, only problem is arrays have to be sorted first...
@hassaniq0777
@hassaniq0777 3 ай бұрын
yea bro i hate this bruh I was gonna write Binary Search in C or C++ but then realized the list has to be sorted 😤 now I'm gonna implement both the sorting algorithm and the binary search
@DankMemes-xq2xm
@DankMemes-xq2xm Ай бұрын
@@hassaniq0777 the sorting algorithm is the hard part. Unless you're being asked to do it from scratch for homework or on an exam / interview, just use the built in sorting function of a language.
@Cammymoop
@Cammymoop 9 ай бұрын
I've never written a binary search algorithm in my life, I always know what the index is anyway
@RadenVijaya
@RadenVijaya 2 ай бұрын
If the element count is small, e.g.
@sonicfind
@sonicfind 9 ай бұрын
They get the value at an index... *before* checking if the index is valid? Imma just use that with an empty list. That should be fun.
@ChrisBakare
@ChrisBakare 9 ай бұрын
High school never ends
@marcotroster8247
@marcotroster8247 3 ай бұрын
The criticism isn't justified at all unless you come up with a proper benchmark. He should have used the standard indexOf() function though. It reads a lot better.
@monkemode8128
@monkemode8128 Ай бұрын
Honestly not bad, IDC. Depends on the use.
@Devloup
@Devloup 2 ай бұрын
im getting confused with you calling pointers to variables (or index used?) mmm am i missing something? i ask cause none noticed it so i think im wrong
@kebien6020
@kebien6020 Ай бұрын
I think it's just because they're so similar. A pointer is just an index into the virtual memory space of a process, and an index is just a pointer into a sub-region of memory
@lukaszwinnicki6880
@lukaszwinnicki6880 Ай бұрын
He should own it and say that it was a joke to see if it will pass on the review.
@CallousCoder
@CallousCoder 9 ай бұрын
Memory used 45MB?!?! I used to run a whole fucking file server with 32MB with a 100 clients attached. Also this isn't that trivia depending on the size of the list. As getting the length and dividing it and then doing the branch logic may well be slower on a list with a certain amount of entries (depending what also fits into the cpu cache).
@phoneix24886
@phoneix24886 2 ай бұрын
You will ve surprised how many java 6/7 code that exists till date has several such code. The devs might have outgrown themselves but the code remains. Its not embarrassing. Its lazy work.
@akialter
@akialter 9 ай бұрын
You’ll be surprised how many average dev cant write a bug free binary search
@mycommentmyopinion
@mycommentmyopinion 9 ай бұрын
Tbf I haven't had a case where I had to implement binary search myself and I think that goes for most devs
@anon_y_mousse
@anon_y_mousse 9 ай бұрын
@@mycommentmyopinion As an exercise, write your own libc. Go back and do it every 5 to 10 years.
@JosephGleespen
@JosephGleespen 9 ай бұрын
​@@mycommentmyopinionlmfao it's not about how much it comes up at work, it's a test, are you all being purposely dense about this? It is an EASY way for companies to TEST if they want to hire you. Jfc.
@mycommentmyopinion
@mycommentmyopinion 9 ай бұрын
@@anon_y_mousse Good idea, gonna try that
@blasttrash
@blasttrash 9 ай бұрын
Well even oracle jdk apparently had a bug in binary search for many years. And JVM is said to be one of the most optimized software written. So even the geniuses at Oracle made binary search mistakes :P
@dineshvikramvenkatesh4911
@dineshvikramvenkatesh4911 2 ай бұрын
Isn't the code actually wrong? Wouldn't it throw an index out of bounds exception when sorted list is empty?
@kamurashev
@kamurashev Ай бұрын
In java you can access array element by square brackets but not the array list element. Other languages also have accessors for collection elements, even python. Nothing wrong with it. Moreover the main issue is the code is garbage.
@NonsensGaming
@NonsensGaming 13 күн бұрын
last time i checked a pointer is not a index
@chemaalonso7931
@chemaalonso7931 9 ай бұрын
Who need brackets? Is an ArrayList and is SO MUCH DIFFERENT from an Array, in JAVA you DONT need a fucking method to get an element.
@joonotfins
@joonotfins Ай бұрын
What season was this? I don’t remember seeing this
@James-l5s7k
@James-l5s7k 9 ай бұрын
it's absolutely readable code; if you know C XD
@Finkelfunk
@Finkelfunk 20 күн бұрын
Why do you call an integer a pointer? As a C++ dev, this makes me cringe. It's an index, not a pointer.
@groot3271
@groot3271 9 ай бұрын
Which video is that. Can someone share the link??
@SashaCianuro
@SashaCianuro 9 ай бұрын
TV series Silicon valley
@__samuel-cavalcanti__
@__samuel-cavalcanti__ 29 күн бұрын
am I the only one who thinks that recursive way is more beautiful ?
@soupcup4069
@soupcup4069 21 күн бұрын
Yeah I think if this happens to you in an interview, its a toxic environment to work...
@LeeO0704
@LeeO0704 2 ай бұрын
why is he calling variable "pointers"?
@ballakobe24
@ballakobe24 9 ай бұрын
I also watched Silicon Valley for the code snippets.
@sabart5
@sabart5 9 сағат бұрын
"Java is the only language that needs a method call to get a value from an array". No, man, that was not an array, but a collection. Java arrays also use brackets. You have no idea what you are talking about.
@NeetCodeIO
@NeetCodeIO 6 сағат бұрын
Yeah dog, I know the difference lol. Most languages let you use brackets for indexing objects lol, did you never use a non java language
@notanonymous3976
@notanonymous3976 2 күн бұрын
there's no way this happens
@tmerb
@tmerb 9 ай бұрын
"to turn up the difficulty lets do it in java" 🤣
@davidr.603
@davidr.603 9 ай бұрын
So you just split the list in the half, and then search the right half. Why dont you split it multiple times, for a small list like in the example it might not be viable but for an even bigger list it for sure would be. Or am i thinking wrong here
@arjundureja
@arjundureja 9 ай бұрын
It's a loop. The list is constantly being split until the target is found or the left pointer is greater than the right pointer
@davidr.603
@davidr.603 9 ай бұрын
@@arjundureja gotcha, thank you for explaining
@janisir4529
@janisir4529 3 ай бұрын
It's fine for small arrays, and when you are in a hurry. ¯\_(ツ)_/¯
@asagiai4965
@asagiai4965 9 ай бұрын
To be fair he might not have known it or forgot about it.
@parryhotter9333
@parryhotter9333 9 ай бұрын
why do you call an index a pointer? they are two very different things
@groff8657
@groff8657 9 ай бұрын
He meant value pointers in DSA not memory pointers in C++.
@parryhotter9333
@parryhotter9333 9 ай бұрын
@@groff8657 Since the programming language in question is Java, he most certainly should have said "index" because the .get method on a list takes an integer to index into the list and not a pointer. A pointer is not even a defined datatype in Java so using this keyword in this context is not even appropriate. If you really want to be fringe, then you might argue that a variable reference to an object is a "pointer", however this is incorrect as Java never actually provides direct references to objects with an address (which is the definition of a pointer to an object), but rather to a proxy that keeps track of the object. An apt name for a strategy that encapsulates this behavior is therefore "pass-by-proxy". In any case, a "value pointer" is not even a recognized term in DSA, so why even bring this up? edit: this is not to discredit NeetCode in any way, but as a channel that teaches and talks about programming, he should be precise in his wording and explanation. With that said, it is a nice video and not all that serious.
@def__init
@def__init 9 ай бұрын
who tf writes while statements with no body 💀
@janisir4529
@janisir4529 3 ай бұрын
It's perfectly valid to do so.
My Techlead Roasted Me
10:24
NeetCodeIO
Рет қаралды 143 М.
Why is everyone LYING?
7:56
NeetCodeIO
Рет қаралды 341 М.
小丑揭穿坏人的阴谋 #小丑 #天使 #shorts
00:35
好人小丑
Рет қаралды 53 МЛН
How To Choose Mac N Cheese Date Night.. 🧀
00:58
Jojo Sim
Рет қаралды 59 МЛН
The Ultimate Sausage Prank! Watch Their Reactions 😂🌭 #Unexpected
00:17
La La Life Shorts
Рет қаралды 6 МЛН
The 3 Laws of Writing Readable Code
5:28
Kantan Coding
Рет қаралды 709 М.
Projects Every Programmer Should Try
16:58
ThePrimeTime
Рет қаралды 509 М.
Abstraction is not the enemy... lack of documentation is.
17:41
The Problem with Object-Oriented Programming
8:21
NeetCodeIO
Рет қаралды 190 М.
I Solved 1583 Leetcode Questions  Here's What I Learned
20:37
ThePrimeTime
Рет қаралды 726 М.
how NASA writes space-proof code
6:03
Low Level
Рет қаралды 2,3 МЛН
Dynamic Programming isn't too hard. You just don't know what it is.
22:31
DecodingIntuition
Рет қаралды 194 М.
"My Minecraft World is Deleting Itself..."
27:57
Wifies
Рет қаралды 61 М.
Programmers in 2024 have no Deep Knowledge
8:38
NeetCodeIO
Рет қаралды 199 М.
Why I focus on patterns instead of technologies
7:55
NeetCodeIO
Рет қаралды 235 М.