Dev HUMILIATED after writing Brute Force Search on a Sorted List
Вставка
- Опубліковано 12 лют 2024
- 🚀 neetcode.io/ - A better way to prepare for Coding Interviews
🧑💼 LinkedIn: / navdeep-singh-3aaa14161
🐦 Twitter: / neetcode1
⭐ BLIND-75 PLAYLIST: • Two Sum - Leetcode 1 -...
#neetcode #leetcode #python
Kinda surprised how many people think it's a Linked List.. does this look familiar:
List list = new ArrayList();
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.
Bro was able to identify the Leetcode number from the top of his head💀
That’s why he’s the GOAT
His name is Neetcode, what did you expect?
@@aflous 🤣
Tell me you’re a sex haver without telling me you’re a sex haver
Bro
For small arrays, linear search actually beats binary search because it's so branch-prediction friendly.
Also why didnt he just do .indexOf(element)
@@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.
@@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
Same reason why C# uses quicksort and insertion sort combo as its default sort.
@@CrabGuyy cache locality and branch predictability effects on different DS and algorithm ordinance is obvious? Dumbass.
did he just fucking quote a LEETCODE question with NUMBER by looking 4 lines of code!!! 😭😭
its not that big of a deal lmao
@@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.
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!
It's a leetcode problem bro, that's what they are like
@@JosephGleespen Literally not the point.
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.
yup. Bad sql, bad joins has caused more slowness than any search problems I've seen.
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.
Discussion of performance without mentioning CPU caching is ... interesting.
This is why I use PHP and throw performance out the window
@@elijahbuscho7715 unironically based, only old hags with shitpads from 2001 complain about performance like bruv just get a new pc its not that hard
@@elijahbuscho7715 I do Python
the bully: good, now do this in O(1)
ret=-1;
for (i=0; i
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
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 😂
I think the more embarrassing thing is the person using a Windows laptop at 1:18
Do you mean the Microsoft surface laptop?
I'm tempted to delete your comment and edit mine...
LMAOO
@@NeetCodeIO
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
What is wrong with Microsoft surface laptop?
I just learnt sorting this week and this video was perfect in helping me understand how the code is implemented!
Guess what?! I landed on Neetcode's YT channel while doing a brute force linear search on UA-cam. Definitely worth it ❤😊
Fuccc I think I need a refresh on algorithms, I use them so rarely I keep forgetting how they work lol
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.
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?
Wow. I have never seen someone with that close of an approximation to real skills
Silicon Valley, baby!!!
How do you even perform binary search on a linked list? Random access iterators are not available
I’m pretty sure it is to be sorted and the linked list needs to have a total node count
You basicly run past nodes not looking at their value. So you can not effectively do binary search on a linked list.
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
It's not a linked list, where'd you get that idea?
FYI dynamic arrays are called ArrayLists in Java.
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.
Hey! l +r ?? You will get integer overflow!
🤦i've dishonored my entire family
m = l + (r-l)/2
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.
@romanivanov True, but if you're iterating over more than 2^((sizeof(int) * 8) - 1) / 2 elements, you have bigger concerns to deal with.
@@se4geniuses You do, but it's not entirely unheard of
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.
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.
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
The linear search is still useful if the array is unsorted, I'm sorry.
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.
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.
Even though I've seen this before, watching it again with Neetcode makes it even funnier.
Wouldn't this be a massive code duplication issue? He's reinventing the wheel
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
Do you really think anyone would watch the show if they acted like software engineers?
@@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!
I doubt it's made to be realistic lol, nobody would want to watch a realistic version
@@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.
NitPick : In java you need a method to get a value from a list, not an array.
Bro pulled the question number out of his ass and got it right lmao!
Wow, actually rarely to see someone beat 100% of runtime 😮
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
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.
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 teacked into optimizing a single piece of code and by thw the time I realize I have wasted a lot of time on it. So better make it work then improve once it works.
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
Which show is that?
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.
From a business perspective and assuming you are building an MVP or a possible feature, the fastest to add solution is the right solution.
well bin search is fast to add he did it in like 2 mins
@@xavier7769 With a bug that could cost money and time to debug :D
Skill issue
Not sure that binary search would be so much better on a sorted (assuming linked) *list*, though.
Linked lists aren't accessible by index.
What kinda indexed linked lists are you playing around with?
@@ValerieLoveTVThis one apparently is.
@@ValerieLoveTV They can be if you write the api to do it. In Haskell for example they are.
3:44 (l + r)/2 would cause overflow for big arrays
I also watched Silicon Valley for the code snippets.
What site did you used to do that?
This dude writes binary search like I breathe.
It's basically his full time job.
For seniors those algorithms for really that easy
High school never ends
Which video is that. Can someone share the link??
TV series Silicon valley
Bro really knew the LeetCode Number lmfao
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).
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!
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).
This channel has potential to hit a million subs 🚀
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 😤😤😤
@@NeetCodeIO I'll watch every video you post on my phone, computer and tv at the same time
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.
bro said "this is leetcode 704" and it was actually leetcode 704
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
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
@@arjundureja gotcha, thank you for explaining
post more videos like this
I've never written a binary search algorithm in my life, I always know what the index is anyway
To be fair he might not have known it or forgot about it.
Well at least he didn't do a bogosort.
it's absolutely readable code; if you know C XD
"to turn up the difficulty lets do it in java" 🤣
"int index = 0;" -> how the hell is this a pointer?
Who do I get to be as good as you at leetcode bro?
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 🤡
from bisect import bisect_left (*ducks)
Also, never write binary search for a simple list, because you'll probably find a standard implementation for it in any language.
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.
who tf writes while statements with no body 💀
why do you call an index a pointer? they are two very different things
He meant value pointers in DSA not memory pointers in C++.
@@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.
The funniest part is that binary search is not that big of improvement on a (linked) list
The guy have my same name. But I will never write that monstrosity
If I am not mistaken that while loop does nothing. Notice the semi-colon at the end of line 114. That closed the while loop.
Notice the ++index in the condition header? Yeah, that's the loop.
Technically it does something. It is increasing the index. The index which the item is on will exit the loop thus giving the answer
It's a funny way to write a loop (at least I haven't seen it before) but it looks valid. I guess they were trying to be terse.
@@asagiai4965 "Technically"
@@anon_y_mousse no that's what cause the loop to end. The loop itself still does nothing... other than increasing the index.
If N is small you can get away with being lazy and do a linear vs logN search. Say searching through a list of countries or states.😂
This video sounds like you could’ve wrote this code…
You’ll be surprised how many average dev cant write a bug free binary search
Tbf I haven't had a case where I had to implement binary search myself and I think that goes for most devs
@@mycommentmyopinion As an exercise, write your own libc. Go back and do it every 5 to 10 years.
@@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.
@@anon_y_mousse Good idea, gonna try that
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
It's O(n), it's not the slowest subroutine in history (That would be my response xD)
✍👍
Most people that make to big tech are nerds. Most of the time a nerd becomes a nerd because of social pressure and abuse from parents (endless comparisons, pushing kid to study more). Btw this is also a result of parents growing up poor and realizing the need to study more and more to make more money. If not parents, grandparents. Then these nerds also get subjected to peer abuse (working hard stereotype).
I was a smart kid in HS. But quickly realized if I get best grades, this would lead to peer bullying (nerd jokes). So I avoided studying harder.
In the end these people have mental voids inside to fill. This comes out as abusing other people.
nerds are mostly people that are very interested in that stuff and enjoy solving problems. no nerd i know is a nerd because of peer pressure or pressure from their parents, its the absolute opposite. they love it because its fun.
but they are made fun of, because they often have an higher iq and therefore have it harder to interact with normal people. if your brain runs at 3x speed of others to intake and process information you have a hard time to interact with mostly affect driven people. its like being belonging to a different species
Like if you tried to increase volume through UA-cam's volume icon on video 🤣
definitely one of the worst way to write linear search.
What are you actually doing, if you used to write binary search? Who would write it at most twice in a lifetime?..
Yeah, I was wondering the same thing. Don’t most standard libraries have this implemented? Just like the actual sorting of the list/array?
i dont understand what the hell all of this means but okay
In the real-world interview, you make a stupid mistake, and they will make you dumber than usual.
This only matters if the code segment is performance critical, otherwise probably unnecessary to do a binary search. It's better to optimize the critical parts and leave the other parts as simple as possible. Anyway, nothing to laugh at, really.
I would also agree. The firmware code base I worked on for has various non performance command handlers for calling functions based on opcode used linear search. They are straightforward to read and historically functioned reliably. Changes are often made to the opcode / function pointer table so the table isn't guaranteed to be sorted anyways if someone accidentally adds a table entry out of order based on the opcode. Sometimes, better readability and maintainability is more important.
I'm a senior developer and I do a lot of code reviews. I can definitely tell you if I saw code like this in a pull request I'd wonder about the dev's competency.
I would accept code like this from a junior dev (but I wouldn't let them merge it - they'd have to change the code) but if anyone with more than 2 years experience submitted this .... either they go or I go
Kumail!
test
By calling "int index=0" a pointer you are already done with a interview.
Who needs brackets? - bye, next candidate.
Pointer is a very generic term in programming lol, google it if you don't believe me