Want to give it a shot?? Sign up with us to make sure your upcoming interviews are the best they can be by practicing with our experienced engineers. interviewing.io/signup?.com&
Congrats! You passed the interview and got the job offer! Now spend the rest of your career writing rest apis that have nothing to do with this sort of problem!
Until he needs to refactor a method in one of these rest apis that is running slow because it was implemented by that employee who was interviewed by someone with your line of thought.
@@LukeAmaral I think it's a bit naive to think that interviews are a good determination from good software engineers and bad ones. For instance, this guy could be a stud at solving algorithm problems, but he also is the type of person who "rolls his own" everything. And the problem with rolling your own is 1. It's typically not time well spent. and 2. It doesn't get all the exposure that a commonly used library would. That's just a very contrived example, but dealing with poorly written code is part of the job. Mostly because poorly written code is somewhat subjective. Perhaps in your example, the implementation was fine until the scope of the software grew and it wasn't worth spending the time up front to come up with a solution that scales better. Or perhaps the person is just a dingus and is wasting clock cycles doing meaningless calculations. All scenarios are possible. Besides, there are a plethora of scenarios where improving the algorithm isn't the solution and you need to look to restructuring the system.
@@theterribleanimator1793 C++ is not easier than JS. Maybe it depends on the person but C++ was really not clicking with me, I tried JS and was having a jolly ol time.
It’s because the interviewer is a complete idiot. “Uuummmm yeaahhhhh hmmmm umm and then you....uuuuuhhhhmmmm....” Seriously, whoever hired that guy to conduct interviews needs to be fired, along with the interviewer.
@@jscorpio1987 Thats natural speech, when interviewing its much better to not have a script and to make a few mistakes yourself because it makes the interviewee more relaxed so that they can focus on the task and stop them from being nervous
me: does an interview about segment trees and topological sorting >spends the rest of my careers solving bug tickets assigned to me by someone in the US
We can use Manhattan distance to calculate the closest point. Just go through the list of coins and calculate the distance and take the closest as answer
@Sho Yu Weeni actually this sort of things are pretty simple in c++, now if he wanted some sort of allocator or thread pool where you had to deal with raw memory that is another game.
59:00 The simple solution is ... To repeat the algorithm in reverse 1. Get the position of the closest coin with respect to your coordinates 2. Call the Algorithm with that closest coin and calculate distance of users from that coin (Just reverse the scenario of step 1) 3. Any coin where you are the closest, becomes your target. ... basically an iterative function where the stopping rule is either all the searches are exhausted ... or you are closest
usually when doing a search loop like that, you set currentval using the first list item, then iterate the remaining items, and test for empty list beforehand.
Given a vector of coin positions it will always be searching the min => O(n), regardless of grid size etc. Early exit condition would be if you found a coin which is directly next to you. P.S.: std::vector by value... bad idea!
@@X3o2AndyPEW Could you point me to the point in the C++ standard you are referring to? As to my knowledge, this is incorrect. C++ doesn't "manage" anything for you (maybe except for RAII), the compiler will not attempt to guess whether to copy the elements of the vector or not.
@@X3o2AndyPEW So what if I want pass by value ? I would be a bit offended if a compiler was undoing pass-by-value and replacing it with pass-by-reference. That sounds closer to Java behaviour.
6:30 How do you do a breadth first search of an un-ordered list? I don't think that really has any meaning. I guess the guy is just nervous, and problem overly simple?
Well you don't have to do that because you know the location of the coins, but I've seen simple pathfinding in a matrix referred to as breadth first search. Essentially traversing from your current position, keeping track of seen nodes and path, then returning when you reach the goal.
Yes exactly, first of all when he is giving a vector array to the guy he can do nothing but form an Adjancy List in O(n) by traversing the whole points vector. So the earliest algorithm is the fastest. However, if he gave him the graph beforehand then bfs could have been better.
Am I missing something? You've got an input of vector, you have to iterate over the full set b/c the last one may be (n-/+1,m-/+1) or sort by x and y, which is worse. OMFG : O(N) = N, where N is the number of coins... giving up on the video.
Honestly, I'd love to just do the interview and work through the problems because I find it mildly entertaining. This is why I'm a CS major, even though the actual work I'll be doing is boring as hell.
They made the whole solution incredibly laborious by talking constantly over details which don‘t add „value“ to the algorithm itself. They kind of entangled themselves in insignificant details in my oppinion.
It ain't like he's gonna be writing this type of program when he gets a job, he's testing his reasoning as you can't ask interwievee to recreate youtube or smth
Wait until you discover a multiinheritance from a functors by deducing their types with a fold expression and CTAD. Remember - "dot, dot, dot is where the fun begins" in C++ :>
Put it in simple words for the algorithm selection: Algorithm 1: number of coins IS the cost Algorithm 2: #coins/#cells (says 1/4, meaning you would BFS 4 times to expect to find the closet coin) So #Coins VS. #Cells/#Coins
I think the most flexible solution would be to sort coinPositions by distance, and return the entire array. in my case we are sorting some coordinates by distance relevant to a point, and animating them one by one on the canvas. while watching this video(so i could learn about C++, a language i've barely ever used), i discovered i had already written the same algorithm before in javascript. here it is modified to suit this example below: const coinPositions = [ [3,3], [5,5] ]; const yourPosition = [1,1]; const sortByDistance = (yourPosition,coinPositions) => coinPositions.sort( (a, b) => { const aDistance = Math.abs(yourPosition[0] - a[0]) + Math.abs(yourPosition[1] - a[1]); const bDistance = Math.abs(yourPosition[0] - b[0]) + Math.abs(yourPosition[1] - b[1]); aDistance > bDistance ? bDistance: aDistance; }); const closestCoin = (...args) => sortByDistance(...args)[0]; const result = closestCoin(yourPosition,coinPositions); console.log('the closest coin is at x:%s,y:%s',...result);
I stopped at around 26-27 minutes in, because I got confused as to why would you want to complicate further the initial solution? O(N) where N is the amount of coins is pretty much the best you can get, unless of course you stop at a coin which distance equals to 1, since there's no coin that could be closer than that (in which case it's still O(N), but best case might be O(1). All the other solutions (cutting out a portion of the map), if you know the x and y of the coin, you would still have to touch each coin at least once to know if it's in the map or not. Maybe I misunderstood something completely as it seems to me the whole further discussion seems to make no sense based on what I understand. Edit: Okay, I understand they decided silently to change the input from Vector of coins to HashMap of coins so you can look up by X and Y? Because converting Vector to HashMap would already be at least O(N), no?
You don't need to touch each coin once necessarily. Consider a grid of 1,000,000 squares on which there are 500,000 coins. Under naive algo you need to consider distance for each of teh coins. Under BFS you consider adjacent squares, then squares adjacent to those squares, like concentric circles from your position - as soon as you hit a coin you can stop without ever looking at the other coins because every other coin would have to be farther away.
I don't understand how BFS could be implemented here. As far as I can tell, there is no way to check in constant time whether particular point has a coin or not, which seems to be necessary in order to implement BFS. Can someone explain?
Yeah... BFS could be implemented but it would be inefficient since, as you mentioned, the position of the coins are given as a vector of positions. If, instead, we had constant access to whether a certain "cell" has a coin or not (e.g. by having a matrix of cells and a specific value to it denoting it has a coin), then BFS would be a more valid approach.
For the coins race, you could simply calculate the closest point to you, calculate the closest player to that coin, if that player isn't you then eliminate both the coin and the player, repeat until it's you who's closest. This would be easily implemented using the same method of finding closest coin, but instead passing the coins position as the players position and the vector of opponents as the vector of coins
With multiple players; distance alone isn't enough, you also have to consider the direction in relation to the position too! There might be a coin that is closer to another player than you for example you could be located at (2,2) in the grid, the coin could be located at say (3, 5) which is 4 cells from you down one and right 3. This coin might be say 3 cells from an opponent who is located at (4,7). Now according to the interviewee he would have this coin removed from the list as it would not be possible for you to consume, however, that opponent may not be interested in that coin because there could be another coin located at(5,8) which is only 2 cells away. So his algorithm would be potentially removing possible valid solutions. Then the algorithm would have to run longer to find a potential solution. When there is just a single player, you only need to be concerned with the overall distances, but when you introduce other players or competitors now the direction's are important as well. My thoughts would be to go through each player and find the nearest coin searching all directions then determine which coin or coins are potential targets and put them into a queue where the direction of the vector is the element since all of these coins have the same distance if more than one exists. Then the algorithm would need to check to see where all the other players and their potential target coins are located with respect to both the current players position and targeted facing direction. If there happens to be a coin that has an equal distance between two players then we can mark that coin as having contention. Let's say we have two players A & B where player A is located at (3,3) a coin is located at (4,4) and player B is located at (5,5). Both players are 2 cells from that coin. The direction vector for player A is SE and the direction vector for player B is NW. So now that we have a coin in contention the next step would be to check to see if there is another coin in your queue that doesn't have contention. If there is another coin then that coin moves up in the priority queue. If there are no others, then their could be a wait signal to see if the current contention coin becomes uncontested since another player did find a valid coin, then they can mark that coin as their target coin. Otherwise if that coin still remains contended then you have several choices after that, either A you could then look for the next closest coin and repeat that process again, or while doing the search you could always move one step closer to the nearest uncontested coin and update the parameters to make sure it then doesn't become contested. This is one approach, there are others. A* Path finding with Ray Tracing - collision detection, BSP Trees, Sparse Matrix solvers etc.
First thing that came to my mind is that i would store this map in one chunk of memory then find closest coin based on pointer position in that memory. Traverse back and forth from player pointer and take in account that coin closer on Y axis can be little farther in memory space... Easy to write, no math involved and i think realy fast. Edit: Another thing is that when adding coins to grid you can save closest in player struct. And compare every new added coin against last closest coin that player knows of. Coins race did catch my attention, interesting problem. I problably would calculate optimal path for everyone and start to exclude nodes that other players will get faster based on distance they need to travel between their path nodes. That would also solve problem of going after closest even if oponent can get to his closest and next one that was my target (in situation that my travel distance is for example 4 to first but oponent only has to travel 3 fields to get 2 coins, including mine)
Even up to like tens or hundreds of thousands of coins, I bet a well written "naive" solution would be vastly faster. If you're using a good compiler with good vectorization diagnostics, you could write the loop to run faster than any kind of fancy algorithm... I've done this with rendering code, where the vectorised versions are insanely fast, because it's all very simple math, linear memory access, and few branches. After all, this is *a lot* like how video encoders work, and they can do this stuff hundreds of thousands of times per second.
Should consider using unsigned integers for the positions as they can't have a negative coordinate. Also the class doesn't need an explicit constructor for initialization of public values. A better thing would be to use std::pair though, which would make the class unecessary
I disagree with the runtime analysis for the breadth-first search method. Assuming you have random access to grid cells (which is required for searching the grid to even make sense) the runtime they gave for that algorithm is N/C, being the number of grid cells divided by the number of coins. Before I break down my argument, I will specify that by "breadth-first search" I mean that we begin at the given player's cell and search every cell in order of increasing distance, i.e. we check all cells that are a distance of 1 away, all cells that are a distance of 2 away, et cetera. To make this example fairly easy let's say we're working with a 10x10 grid (100 cells) and 10 coins. Based on the N/C analysis we should expect the algorithm to take on the order of 10 grid cell examinations (N/C = 100/10 = 10) on average before finding a coin. To me this seems patently incorrect, for instance imagine an adversarial example in which all 10 coins are maximally far away from the starting cell in such a way that breadth first search will search _every_ empty cell before finding a single coin. There are 90 free cells, meaning this takes 90 read operations from the grid. At best I would say the average case performance for this specific case (100 cells, 10 coins, and assuming random distribution) would be 45 grid cell examinations, assuming that on average you might stop after searching the nearest 45 grid cells. It seems plain to me that simply using your list of coins and doing exactly 10 operations here would be the superior option. Based on that, my complexity analysis for this a algorithm in the average case would be (N-C)/2, that is, the number of empty cells divided by two, with the worst case simply being N-C. I don't see anyone else discussing this, but I'd really like to know if there's a flaw in my reasoning here. Thanks for reading if you did :)
I don't think either of these guys use C++ very often.. lol Also, if the players weren't satiated by a single coin you, rather than iterating repeatedly... you could do it occasionally on coin pickup and on conditions of having no closer coin. Say you calculate a coin 1 unit closer to you than any other player, rather than the closest coin to you (if it exists). Then take into account the distance/steps you would take to get to that coin and the next closest coin from firstCoin (x, y) to nextCoin while also taking into account the steps another player closest to nextCoin is. If you're not closer to any coin then you attempt to step in the direction that puts you closest to all coins so that you can reroute while updating player distances to their closest and possibleNextCoin. And then you would need to calculate the route time to each players closest coin. If you are closer to none you then you calculate the distance to a new coin taking into account the route time between other players route time between their closest coin (and the coin that's 1 closer to them than to you or another player) and any given possibleNextCoin. You could keep adding complexity (for different play styles) on top of that but it seems like a good base level for a simple game.
I am a senior engineer at Google. would you be interested in a position at our company? Your answer fascinates me. I would like to invite you to a special meeting at Google. We have free ice cream and coffee. Please advise.
@@AP-bo1if If that's a real offer. I appreciate the gesture but there are a lot of people more qualified than I am and are more deserving of the opportunity. So I would have to respectfully decline.
@@blahchop dude, you don't know what you're missing. I'm talking about hookers and cocaine dude. We have big orgies here at Google HQ. We don't just code all day, that's fucking boring. I want you to meet our AI Hooker, she's fantastic, uses the MAKE ME HORNY ALGORITHM. ever heard of it? Zuckerberg comes by a lot as well, he brings his lizard people along with him.
@@peterschneider127 Ah, yes. For some reason I was thinking of the first parameter "yourPosition", not the second parameter. You're absolutely correct that passing that vector by value is disastrous when it contains more than a few elements.
For which position was this interview for ??? Was the interview for position in field of embedded systems or systems software or operating systems at google ???
There is a bug in the solution: initial value of shortestPath should not be -1, it should be std::numeric_limits::max() instead, otherwise this code will return the position of the first coin all the time. I see no tests at all:(
no its not a bug . distance cannot be negative . and shortestPath gets updated if the shortestPath is -1 or current coin's distance is less than the current value of shortestPath ,
I guess he realized that if the density is 1/x that there would be (on average) one coin every x cells, so he would need to check about x cells to find a coin, x being the inverse of the density.
Interesting, it took a lot of time to fix the syntaxes errors. I am wondering what is important in this case, the algorithm, or the skills to write in C++?
So the main expectation of interviewee was you to utilize more Collection types like Maps and Sets that would let you break down the math and decrease runtime and efficiency of JVM or C++VM Thats just my opinion, but overall you did great! Thanks for sharing!!
Well, Dijkstra's Algorithm for optimal paths is the efficient technique, though mapping that Edge List thinking efficiently and clearly to a 2D array of bools or a bitfield is a bit tough to do on the spot. Should make for a fair discussion point with the interviewer. 1) If you more need to validate my knowledge of algorithms and problem solving, then let's use the easy abstractions, and I can tell you what would make v2.0 memory or time efficient 2) If it's my HPC skills you need to validate, then I can spend a LOOOONG time on this.
so i'm new to coding (a few weeks) and i decided to see if i could make something like this myself... it seems to work, however i'm unsure if this also follows the rule about distances (over and up) versus simply checking the actual distance... here is what i came up with.. #include class Point { public: int x, y; int diff(int x2,int y2){ return sqrt((pow((x2 - x),2)) + (pow((y2 - y),2))); } }; int main() { Point player{ 1,1 }, point1{ 3,3 }, point2{ 5,5 }; Point closest = player.diff(point1.x, point1.y) < player.diff(point2.x, point2.y) ? point1 : point2; std::cout
I am watching this video and its crazy how someone can pick up on code like that. How does someone pick up how to code this fast. Right now I am going over tutorials but I don't feel this good.
Practice man, an expert is someone who did a lot of "errors". Experience is made of those "errors". Don't give up and keep practicing, knowing your brain will be able to achieve that proficiency.
I wonder if you had pushed Euclidean distance as soon as the flexibility changed would he have allowed that as a heuristic instead of still holding the manhattan distance condition. Because the other conditions are changing with each iteration of the interview. And this is a great opportunity to engineer solutions when being interviewed. Because he is interested if you are seeking to see if you have any new advantages available which you can exploit. Which demonstrates that you are taking control of solving this problem, or at least exploring. I'm learning so much from this. The two men speaking are obviously intelligent and thank you guys for sharing this.
There's a way to keep it more simple: The points are already given, so write a method that calculates like in simple math the distance (square root) between two points. Call that method in your main code, compare the results to choose the shortest one.
The Distance Theorem (based on Pythagorean Theorem) gives you the *direct* distance between two points. In the grid, you can only move vertically or horizontally not diagonally. This is known as the Manhattan distance because you can imagine being in a city driving along a grid of streets. You can't cut through buildings in the way, you have to drive along the streets. This is why he is finding distance = abs(x1-x0) + abs(y1-y0) rather than distance = sqrt((x1-x0)^2 + (y1-y0)^2).
I think that there are cases that we have many closest points. This is my solution: #include #include #include class Point { public: int x_, y_; public: Point(int x, int y) : x_(x), y_(y) { } friend std::ostream& operator
True; I don't care if you're a 20 year profession; C++ will allow you to make all kinds of mistakes even ones that will compile, build and run for 10 years before the bug finally pops its ugly head. All this time you should of been calculating `x += y` but you were calculating `x = y` or `x = y + 2` instead of `x = y - 2` etc. Yet there are things that C++ will allow you to do that you shouldn't, but still can.
@@skilz8098 I agree that C++ can be more complicated to debug, but the examples you gave will compile in any language. I think the most complicated thing in C++ would be memory management and the fact that you can reference uninitialized variables.
I don't like the Interviewee's voice. He seems too self-righteous, but didn't catch his error on using references vs pointers. Not the type of person I'd enjoy working with.
I do not believe this is an actual interview with Google. Perhaps Google has very different hiring bars for different people, because this level of difficulty has no match compared to my friends' Google Interview experience.
Read the description. This is a recorded mock interview for training purposes. To help the interviewee show how they can improve in a real interview. Both parties kinda have to take this seriously for this exercise to be helpful
It's because the guy being interviewed seems to be a really good programmer, I've never seen someone write c++ in such a readable and concise way. Even the interviewer was impressed.
These follow up questions are so weird? You have a vector... O(N) is the only answer why are we talking about how sparse the board is when you already have all the coins??
Agnes Akne ur trying to act like he is only saying ummm so much because his brain is massive like elon musk, but i am studying computer science right now and ive seen plenty of people being capable of talking about this stuff without sounding like their having a seizure every time they open their mouth
Can you not mutate the class in any way? I would've thought making a distance method or even a helper function would've helped a ton with just code cleanliness. Ah well.
Want to give it a shot?? Sign up with us to make sure your upcoming interviews are the best they can be by practicing with our experienced engineers. interviewing.io/signup?.com&
only in programming
Interviewee: "I have no idea why its not working"
Interviewer: "I have no idea why its not working"
lmaooooo true dat!
My family and friends think I'm a genius programmer. Little do they know, I'm just a master at google search queries. xD
@@selimosman5451start learning
@@nopanik7371 It was a joke lol. I already program for a living.
@@selimosman5451 are you working in turkey? if you are, how much do you get a month?else, ignore this
This is what my parents think i do when i restart the wifi
😂😂😂😂😂😂
big fan of sacasm
😂😂😂😂😂😂😂😂
Congrats! You passed the interview and got the job offer! Now spend the rest of your career writing rest apis that have nothing to do with this sort of problem!
😃😃
I was thinking the same thing
😂😂😂😂
Until he needs to refactor a method in one of these rest apis that is running slow because it was implemented by that employee who was interviewed by someone with your line of thought.
@@LukeAmaral I think it's a bit naive to think that interviews are a good determination from good software engineers and bad ones. For instance, this guy could be a stud at solving algorithm problems, but he also is the type of person who "rolls his own" everything. And the problem with rolling your own is 1. It's typically not time well spent. and 2. It doesn't get all the exposure that a commonly used library would.
That's just a very contrived example, but dealing with poorly written code is part of the job. Mostly because poorly written code is somewhat subjective. Perhaps in your example, the implementation was fine until the scope of the software grew and it wasn't worth spending the time up front to come up with a solution that scales better. Or perhaps the person is just a dingus and is wasting clock cycles doing meaningless calculations. All scenarios are possible.
Besides, there are a plethora of scenarios where improving the algorithm isn't the solution and you need to look to restructuring the system.
0:30 I see you already picked c++, bold move I like it.
That's another way of saying they dread writing C++.
@@dumbass3618 why tho? C++ seems easy, atleast compared to java and javascript.
@@theterribleanimator1793 C++ is not easier than JS. Maybe it depends on the person but C++ was really not clicking with me, I tried JS and was having a jolly ol time.
@@theblackhundreds7124 Damn, Js is like brail to me.
What do you not understand about C++ tho?
@@theterribleanimator1793 It's magic for me, i can only write javascript and php.
Sounds like two drug dealers communicating with their secret words
Inb4 Trump bans programming because he cant understand it.
@@ss-to7ii hahaa
I love it when non-CS people comment on these videos
4:18 they electrocuted the old Google Engineer
Lmao
This made me laugh so hard!
xD
hahahahahaha
LMAO
xD holy shit laughed so hard
**When you actually paying attention watching video and you have still no idea what's going on**
That's because he's talking about calculus calculating an algorithm to achieve a certain parameter.
It’s because the interviewer is a complete idiot.
“Uuummmm yeaahhhhh hmmmm umm and then you....uuuuuhhhhmmmm....”
Seriously, whoever hired that guy to conduct interviews needs to be fired, along with the interviewer.
@@jscorpio1987 Thats natural speech, when interviewing its much better to not have a script and to make a few mistakes yourself because it makes the interviewee more relaxed so that they can focus on the task and stop them from being nervous
This is giving me anxiety. I feel like I'm the one getting interviewed lmao
_>does an interview about coins_
_> spends the rest of his career assigning bug tickets to guys in India_
me:
does an interview about segment trees and topological sorting
>spends the rest of my careers solving bug tickets assigned to me by someone in the US
I genuinely understood everything that happened in this video, I guess college is working.
For 40K $ per year, it better be
@@R3AktoRMacedonia College in France is free
I taught myself C++, so what conclusion does that lead you to?
dumb ass that doesn’t lead me to any conclusion, what conclusion were you trying to lead me to?
@@dumbass3618 leads me to the conclusion you're feeble-minded
When he first misspelled "positions" I felt like having a heart attack from just WAITING for him to change it
Posistion
We can use Manhattan distance to calculate the closest point. Just go through the list of coins and calculate the distance and take the closest as answer
@Sho Yu Weeni actually this sort of things are pretty simple in c++, now if he wanted some sort of allocator or thread pool where you had to deal with raw memory that is another game.
@Sho Yu Weeni What makes you think it's entry level? It's not even a real interview, just practice.
This dude is an absolute Chad, he was trying to be nice, that's why he chose c, if he had the option he would have done assembly.
C++ Is the chad of programing languages, Python and JavaScript are for noobs
Grumm Pyro he did but you think the interviewer would have been able to make a few test cases? He already knew that answer, Chad’s know ahead of time
59:00
The simple solution is ...
To repeat the algorithm in reverse
1. Get the position of the closest coin with respect to your coordinates
2. Call the Algorithm with that closest coin and calculate distance of users from that coin (Just reverse the scenario of step 1)
3. Any coin where you are the closest, becomes your target.
... basically an iterative function where the stopping rule is either all the searches are exhausted ... or you are closest
usually when doing a search loop like that, you set currentval using the first list item, then iterate the remaining items, and test for empty list beforehand.
I usually try to avoid O(N2)
It 17 minutes to fix that ; it’s not a big issue but It was literally killing me lol
Of all interviewers in these videos I feel like Intergalactic Avenger is the best.
Given a vector of coin positions it will always be searching the min => O(n), regardless of grid size etc. Early exit condition would be if you found a coin which is directly next to you.
P.S.: std::vector by value... bad idea!
he suggested breadth first search but the interviewer didnt seem to care about the time complexity
std::vector by value is a better idea in c++17 since its managed by the compiler
@@X3o2AndyPEW Could you point me to the point in the C++ standard you are referring to? As to my knowledge, this is incorrect. C++ doesn't "manage" anything for you (maybe except for RAII), the compiler will not attempt to guess whether to copy the elements of the vector or not.
@@X3o2AndyPEW So what if I want pass by value ? I would be a bit offended if a compiler was undoing pass-by-value and replacing it with pass-by-reference. That sounds closer to Java behaviour.
6:30 How do you do a breadth first search of an un-ordered list? I don't think that really has any meaning. I guess the guy is just nervous, and problem overly simple?
Well you don't have to do that because you know the location of the coins, but I've seen simple pathfinding in a matrix referred to as breadth first search. Essentially traversing from your current position, keeping track of seen nodes and path, then returning when you reach the goal.
bfs on the grid, adding adjacent tiles to the queue
Yes exactly, first of all when he is giving a vector array to the guy he can do nothing but form an Adjancy List in O(n) by traversing the whole points vector. So the earliest algorithm is the fastest. However, if he gave him the graph beforehand then bfs could have been better.
THANK YOU. Was searching the comments for somebody to point this out. There is no solution runtime < N if we receive input as a vector of point.
This. Sad neither interviewer nor interviewee brought up this point.
Am I missing something? You've got an input of vector, you have to iterate over the full set b/c the last one may be (n-/+1,m-/+1) or sort by x and y, which is worse. OMFG : O(N) = N, where N is the number of coins... giving up on the video.
Honestly, I'd love to just do the interview and work through the problems because I find it mildly entertaining.
This is why I'm a CS major, even though the actual work I'll be doing is boring as hell.
same
Finally a channel about tech job interviews with no bullshit. Thank you.
it seems like it's bill gates taking the coding exam
From his voice, I had the same thought. LOL
@@jeremywilliamson4363 Lol
Gives you the sense of the level you need to be at to work at Google, doesn't it?
@@dumbass3618 hahahaha
DUDE MY THOUGHT EXACT!
Looks easy, maybe I should try too.
They made the whole solution incredibly laborious by talking constantly over details which don‘t add „value“ to the algorithm itself. They kind of entangled themselves in insignificant details in my oppinion.
It ain't like he's gonna be writing this type of program when he gets a job, he's testing his reasoning as you can't ask interwievee to recreate youtube or smth
in romania when we had regional programming competition in 9th grade we had these to solve (back in 1998). This is thinking test.
:)
in albania we had it in 5th grade
In Germany we have to do this directly after we come out of our mother's.
I'm a Romanian and I can confirm
In America our dad’s, before releasing the sperm, have to take this test
Watching this video has made me fall in love with C++. Being an expert in C++ is my goal by the end of 2019 now.
very optimistic plan, gl anyway
Bold move. I like it.
Wait until you discover a multiinheritance from a functors by deducing their types with a fold expression and CTAD. Remember - "dot, dot, dot is where the fun begins" in C++ :>
No chance. Even Bjorne is still learning.
@@dumbass3618 Bjarne, but yeah true that
Put it in simple words for the algorithm selection:
Algorithm 1: number of coins IS the cost
Algorithm 2: #coins/#cells (says 1/4, meaning you would BFS 4 times to expect to find the closet coin)
So #Coins VS. #Cells/#Coins
why does a senior developer from google struggle with getting "stupid c++ code" to work, especially such simple code?
He's definitely not doing C++ as part of his day job.
I think the most flexible solution would be to sort coinPositions by distance, and return the entire array. in my case we are sorting some coordinates by distance relevant to a point, and animating them one by one on the canvas. while watching this video(so i could learn about C++, a language i've barely ever used), i discovered i had already written the same algorithm before in javascript. here it is modified to suit this example below:
const coinPositions = [
[3,3],
[5,5]
];
const yourPosition = [1,1];
const sortByDistance = (yourPosition,coinPositions) => coinPositions.sort( (a, b) => {
const aDistance = Math.abs(yourPosition[0] - a[0]) + Math.abs(yourPosition[1] - a[1]);
const bDistance = Math.abs(yourPosition[0] - b[0]) + Math.abs(yourPosition[1] - b[1]);
aDistance > bDistance ? bDistance: aDistance;
});
const closestCoin = (...args) => sortByDistance(...args)[0];
const result = closestCoin(yourPosition,coinPositions);
console.log('the closest coin is at x:%s,y:%s',...result);
Depending on the time complexity of the Javascript sort() function, this might actually be slower.
I stopped at around 26-27 minutes in, because I got confused as to why would you want to complicate further the initial solution? O(N) where N is the amount of coins is pretty much the best you can get, unless of course you stop at a coin which distance equals to 1, since there's no coin that could be closer than that (in which case it's still O(N), but best case might be O(1). All the other solutions (cutting out a portion of the map), if you know the x and y of the coin, you would still have to touch each coin at least once to know if it's in the map or not. Maybe I misunderstood something completely as it seems to me the whole further discussion seems to make no sense based on what I understand.
Edit: Okay, I understand they decided silently to change the input from Vector of coins to HashMap of coins so you can look up by X and Y? Because converting Vector to HashMap would already be at least O(N), no?
It is a theoretical exercise. Its real goal is not to find the optimal algorithm, but an optimal candidate. But otherwise, you are right.
It is similar to Campus bikes problem on Leetcode!
They're trying to generalize. Trying to create an algorithm that solves the problem in any situation.
Where do they change the hashMap? I agree, this doesn’t make any sense. How would a breadth first search be any faster using a vector.
You don't need to touch each coin once necessarily. Consider a grid of 1,000,000 squares on which there are 500,000 coins. Under naive algo you need to consider distance for each of teh coins. Under BFS you consider adjacent squares, then squares adjacent to those squares, like concentric circles from your position - as soon as you hit a coin you can stop without ever looking at the other coins because every other coin would have to be farther away.
You could solve this problem by applying any of the search algorithms. The shortest path and best cost would be A* or greedy search.
The interviewee writes C++ so old that my eyes bleed a bit. But at least his core ideas for solving the problem are good.
*_Sargeant Koala 1_*
*_Intergalactic Avenger 0_*
I don't understand how BFS could be implemented here. As far as I can tell, there is no way to check in constant time whether particular point has a coin or not, which seems to be necessary in order to implement BFS. Can someone explain?
Yeah... BFS could be implemented but it would be inefficient since, as you mentioned, the position of the coins are given as a vector of positions. If, instead, we had constant access to whether a certain "cell" has a coin or not (e.g. by having a matrix of cells and a specific value to it denoting it has a coin), then BFS would be a more valid approach.
For the coins race, you could simply calculate the closest point to you, calculate the closest player to that coin, if that player isn't you then eliminate both the coin and the player, repeat until it's you who's closest.
This would be easily implemented using the same method of finding closest coin, but instead passing the coins position as the players position and the vector of opponents as the vector of coins
With multiple players; distance alone isn't enough, you also have to consider the direction in relation to the position too! There might be a coin that is closer to another player than you for example you could be located at (2,2) in the grid, the coin could be located at say (3, 5) which is 4 cells from you down one and right 3. This coin might be say 3 cells from an opponent who is located at (4,7). Now according to the interviewee he would have this coin removed from the list as it would not be possible for you to consume, however, that opponent may not be interested in that coin because there could be another coin located at(5,8) which is only 2 cells away. So his algorithm would be potentially removing possible valid solutions. Then the algorithm would have to run longer to find a potential solution. When there is just a single player, you only need to be concerned with the overall distances, but when you introduce other players or competitors now the direction's are important as well.
My thoughts would be to go through each player and find the nearest coin searching all directions then determine which coin or coins are potential targets and put them into a queue where the direction of the vector is the element since all of these coins have the same distance if more than one exists. Then the algorithm would need to check to see where all the other players and their potential target coins are located with respect to both the current players position and targeted facing direction. If there happens to be a coin that has an equal distance between two players then we can mark that coin as having contention. Let's say we have two players A & B where player A is located at (3,3) a coin is located at (4,4) and player B is located at (5,5). Both players are 2 cells from that coin. The direction vector for player A is SE and the direction vector for player B is NW. So now that we have a coin in contention the next step would be to check to see if there is another coin in your queue that doesn't have contention. If there is another coin then that coin moves up in the priority queue. If there are no others, then their could be a wait signal to see if the current contention coin becomes uncontested since another player did find a valid coin, then they can mark that coin as their target coin. Otherwise if that coin still remains contended then you have several choices after that, either A you could then look for the next closest coin and repeat that process again, or while doing the search you could always move one step closer to the nearest uncontested coin and update the parameters to make sure it then doesn't become contested.
This is one approach, there are others. A* Path finding with Ray Tracing - collision detection, BSP Trees, Sparse Matrix solvers etc.
I hope you make some interview recording for dart / flutter engineer
I actually was picking the guys code apart as he typed it ... You really can teach yourself these things if you try hard enough
First thing that came to my mind is that i would store this map in one chunk of memory then find closest coin based on pointer position in that memory. Traverse back and forth from player pointer and take in account that coin closer on Y axis can be little farther in memory space... Easy to write, no math involved and i think realy fast.
Edit: Another thing is that when adding coins to grid you can save closest in player struct. And compare every new added coin against last closest coin that player knows of.
Coins race did catch my attention, interesting problem. I problably would calculate optimal path for everyone and start to exclude nodes that other players will get faster based on distance they need to travel between their path nodes. That would also solve problem of going after closest even if oponent can get to his closest and next one that was my target (in situation that my travel distance is for example 4 to first but oponent only has to travel 3 fields to get 2 coins, including mine)
Even up to like tens or hundreds of thousands of coins, I bet a well written "naive" solution would be vastly faster. If you're using a good compiler with good vectorization diagnostics, you could write the loop to run faster than any kind of fancy algorithm... I've done this with rendering code, where the vectorised versions are insanely fast, because it's all very simple math, linear memory access, and few branches. After all, this is *a lot* like how video encoders work, and they can do this stuff hundreds of thousands of times per second.
Use std::sort if you are going to do more than 4 or 5 times, you payoff a little of performance, but the access to the elements later will be faster
I don't know if you're talking about hashing or what
Should consider using unsigned integers for the positions as they can't have a negative coordinate. Also the class doesn't need an explicit constructor for initialization of public values. A better thing would be to use std::pair though, which would make the class unecessary
I think the same. Actually a method would be nice instead a a class
I disagree with the runtime analysis for the breadth-first search method. Assuming you have random access to grid cells (which is required for searching the grid to even make sense) the runtime they gave for that algorithm is N/C, being the number of grid cells divided by the number of coins.
Before I break down my argument, I will specify that by "breadth-first search" I mean that we begin at the given player's cell and search every cell in order of increasing distance, i.e. we check all cells that are a distance of 1 away, all cells that are a distance of 2 away, et cetera. To make this example fairly easy let's say we're working with a 10x10 grid (100 cells) and 10 coins. Based on the N/C analysis we should expect the algorithm to take on the order of 10 grid cell examinations (N/C = 100/10 = 10) on average before finding a coin. To me this seems patently incorrect, for instance imagine an adversarial example in which all 10 coins are maximally far away from the starting cell in such a way that breadth first search will search _every_ empty cell before finding a single coin. There are 90 free cells, meaning this takes 90 read operations from the grid. At best I would say the average case performance for this specific case (100 cells, 10 coins, and assuming random distribution) would be 45 grid cell examinations, assuming that on average you might stop after searching the nearest 45 grid cells. It seems plain to me that simply using your list of coins and doing exactly 10 operations here would be the superior option.
Based on that, my complexity analysis for this a algorithm in the average case would be (N-C)/2, that is, the number of empty cells divided by two, with the worst case simply being N-C. I don't see anyone else discussing this, but I'd really like to know if there's a flaw in my reasoning here. Thanks for reading if you did :)
I don't think either of these guys use C++ very often.. lol Also, if the players weren't satiated by a single coin you, rather than iterating repeatedly... you could do it occasionally on coin pickup and on conditions of having no closer coin. Say you calculate a coin 1 unit closer to you than any other player, rather than the closest coin to you (if it exists). Then take into account the distance/steps you would take to get to that coin and the next closest coin from firstCoin (x, y) to nextCoin while also taking into account the steps another player closest to nextCoin is. If you're not closer to any coin then you attempt to step in the direction that puts you closest to all coins so that you can reroute while updating player distances to their closest and possibleNextCoin. And then you would need to calculate the route time to each players closest coin. If you are closer to none you then you calculate the distance to a new coin taking into account the route time between other players route time between their closest coin (and the coin that's 1 closer to them than to you or another player) and any given possibleNextCoin. You could keep adding complexity (for different play styles) on top of that but it seems like a good base level for a simple game.
Passing things like vector as a copy to a function instead of a reference makes me wince a little..
I am a senior engineer at Google. would you be interested in a position at our company? Your answer fascinates me. I would like to invite you to a special meeting at Google. We have free ice cream and coffee. Please advise.
@@AP-bo1if If that's a real offer. I appreciate the gesture but there are a lot of people more qualified than I am and are more deserving of the opportunity. So I would have to respectfully decline.
@@blahchop
dude, you don't know what you're missing. I'm talking about hookers and cocaine dude. We have big orgies here at Google HQ. We don't just code all day, that's fucking boring. I want you to meet our AI Hooker, she's fantastic, uses the MAKE ME HORNY ALGORITHM. ever heard of it? Zuckerberg comes by a lot as well, he brings his lizard people along with him.
@@AP-bo1if Sounds great! I'm in.
And no one complains that vector is passed by value?
It's a tiny class, so probably not that big of a deal. Literally like passing two ints by value.
@@mykalimba it's a vector of a Tiny class. In the example maybe half a dozen items, potentially millions in real usage.
@@peterschneider127 Ah, yes. For some reason I was thinking of the first parameter "yourPosition", not the second parameter. You're absolutely correct that passing that vector by value is disastrous when it contains more than a few elements.
hahahahahaha true (y)
Isn't google interview in Google docs?
It's not official
Does someone let it rip around 21:35 ?
ThunderCat hahahahahahaha...sure sounds like it
hahahaha
Isn’t the answer Bellmanns ford algorithm? With starting point x0 and weights of the edges as the length between xi and x0 and yi and y0...?
For which position was this interview for ??? Was the interview for position in field of embedded systems or systems software or operating systems at google ???
There is a bug in the solution: initial value of shortestPath should not be -1, it should be std::numeric_limits::max() instead, otherwise this code will return the position of the first coin all the time. I see no tests at all:(
no its not a bug . distance cannot be negative . and shortestPath gets updated if the shortestPath is -1 or current coin's distance is less than the current value of shortestPath ,
How he came to conclusion that BFS = 1/density at 40:45 ?
I guess he realized that if the density is 1/x that there would be (on average) one coin every x cells, so he would need to check about x cells to find a coin, x being the inverse of the density.
Watched it for 14 minutes and my eyes are bleeding ...
I made it to 35 min
This is why FP is the best!
const minimumBy = (keyFn) => (x1, x2) =>
keyFn(x1) < keyFn(x2) ? x1 : x2
const manhattanDistance = ([x1, y1]) => ([x2, y2]) =>
Math.abs(x1 - x2) + Math.abs(y1 - y2)
const closest = (origin, points) =>
points.reduce(minimumBy(manhattanDistance(origin)), [Infinity, Infinity])
closest([1, 1], [[3, 3], [5, 5], [10, 10]]) // [3, 3]
Ummmm I can't remember how to turn on my PS4!
Interesting, it took a lot of time to fix the syntaxes errors. I am wondering what is important in this case, the algorithm, or the skills to write in C++?
I mean, this app doesn't have syntax checking or auto completion, so I don't think syntax matters.
For anyone who calls himself a professional with a supposed C++ background, to try to initially compile that program is just shocking...
The fact that they can't catch so many errors before compiling the program is stupid!
@@ldohlj1 I would be laughing if they had to link in about 4 different libraries some being static while others being dynamic hahah!
ikr, i don't even code c++ professionally (i use it for programming puzzles only) and i found em all so soon
Why was a bitwise or operator used instead of logical or at ln 33?
oh it was pointed out nevermind.
So the main expectation of interviewee was you to utilize more Collection types like Maps and Sets that would let you break down the math and decrease runtime and efficiency of JVM or C++VM
Thats just my opinion, but overall you did great! Thanks for sharing!!
C++ is a compiled language it doesn’t run on a VM
@@ryanj.s9340 yikes
Well, Dijkstra's Algorithm for optimal paths is the efficient technique, though mapping that Edge List thinking efficiently and clearly to a 2D array of bools or a bitfield is a bit tough to do on the spot. Should make for a fair discussion point with the interviewer.
1) If you more need to validate my knowledge of algorithms and problem solving, then let's use the easy abstractions, and I can tell you what would make v2.0 memory or time efficient
2) If it's my HPC skills you need to validate, then I can spend a LOOOONG time on this.
Damm that first hello sounded scary asf 🤣
so i'm new to coding (a few weeks) and i decided to see if i could make something like this myself... it seems to work, however i'm unsure if this also follows the rule about distances (over and up) versus simply checking the actual distance... here is what i came up with..
#include
class Point {
public:
int x, y;
int diff(int x2,int y2){
return sqrt((pow((x2 - x),2)) + (pow((y2 - y),2)));
}
};
int main() {
Point player{ 1,1 }, point1{ 3,3 }, point2{ 5,5 };
Point closest = player.diff(point1.x, point1.y) < player.diff(point2.x, point2.y) ? point1 : point2;
std::cout
I just wondered how it was the C++ interview?
Clement is that you?
Interviewee keeps interrupting the guy interviewing him trying to explain to him what to do.
My god how Long do they take to correct spelling haha
Guy solving a Codeforces Div 2 - Problem A in 20 minutes.
These are fun to follow along with! Thanks for posting!
I am watching this video and its crazy how someone can pick up on code like that. How does someone pick up how to code this fast. Right now I am going over tutorials but I don't feel this good.
Practice man, an expert is someone who did a lot of "errors". Experience is made of those "errors". Don't give up and keep practicing, knowing your brain will be able to achieve that proficiency.
I wonder if you had pushed Euclidean distance as soon as the flexibility changed would he have allowed that as a heuristic instead of still holding the manhattan distance condition. Because the other conditions are changing with each iteration of the interview. And this is a great opportunity to engineer solutions when being interviewed. Because he is interested if you are seeking to see if you have any new advantages available which you can exploit. Which demonstrates that you are taking control of solving this problem, or at least exploring. I'm learning so much from this. The two men speaking are obviously intelligent and thank you guys for sharing this.
There's a way to keep it more simple: The points are already given, so write a method that calculates like in simple math the distance (square root) between two points.
Call that method in your main code, compare the results to choose the shortest one.
with the square root you save most of your code but its an expensive move
The Distance Theorem (based on Pythagorean Theorem) gives you the *direct* distance between two points. In the grid, you can only move vertically or horizontally not diagonally. This is known as the Manhattan distance because you can imagine being in a city driving along a grid of streets. You can't cut through buildings in the way, you have to drive along the streets. This is why he is finding distance = abs(x1-x0) + abs(y1-y0) rather than distance = sqrt((x1-x0)^2 + (y1-y0)^2).
It's a simple gready algorithm
I think that there are cases that we have many closest points. This is my solution:
#include
#include
#include
class Point {
public:
int x_, y_;
public:
Point(int x, int y) : x_(x), y_(y) {
}
friend std::ostream& operator
github bro
I guess you're now hired at Google sir. congratulations. you now work for the lizard people.
This applicant sounds like Bill Gates. You think he’s trying to get back in the game?
if i could only undrestand what you are doing
you can, but will you?
@@dumbass3618 hahaha man u literally awesome
@@dumbass3618 if everyone is willing to learn it then they can understand it
Am I understanding correctly that the interviewee here is a senior engineer or of equivalent skill?
Hard to tell, just an algorithm problem
Yes, it is just a mock interview.
For the methodology question of competing for coins, interviewee should first ask what the goal is before jumping into a long train of thoughts.
Are you sure this is a true google engineer ?
But the tasks provided is really interesting!
You can tell because he cant spell :P
I dunno for a min I thought it might of been Yahoo...
He's playing stupid for the audience.
It is too easy to make a mistake in C++
True; I don't care if you're a 20 year profession; C++ will allow you to make all kinds of mistakes even ones that will compile, build and run for 10 years before the bug finally pops its ugly head. All this time you should of been calculating `x += y` but you were calculating `x = y` or `x = y + 2` instead of `x = y - 2` etc. Yet there are things that C++ will allow you to do that you shouldn't, but still can.
@@skilz8098 I agree that C++ can be more complicated to debug, but the examples you gave will compile in any language. I think the most complicated thing in C++ would be memory management and the fact that you can reference uninitialized variables.
When you speak more than one natural language its easy to make a mistake in any one of those languages. The same is true for programming languages.
That's why I did mine in Ada 2012 😋 github.com/Lucretia/interview-questions/blob/master/ada/src/nearest_coin.adb if anyone is interested.
@@LusidDreaming A C++ compiler should output "no" on all runs.
I don't like the Interviewee's voice. He seems too self-righteous, but didn't catch his error on using references vs pointers. Not the type of person I'd enjoy working with.
I do not believe this is an actual interview with Google. Perhaps Google has very different hiring bars for different people, because this level of difficulty has no match compared to my friends' Google Interview experience.
What was your friend's experience?
Read the description.
This is a recorded mock interview for training purposes. To help the interviewee show how they can improve in a real interview. Both parties kinda have to take this seriously for this exercise to be helpful
can someone explain to me the difference between if( | ) and if( || )?
i know that they are talking about that in 22:18 but i dont speak english so i dont understand
I waited too long for this guy to spell positions right 😳
Interviewer C++ writing java style braces? My head exploded.
This is going to be in c++ RESPECT!
You should add a spell checker to your site. Obviously.
First interview that didn't seem to hard. Cool to see
It's because the guy being interviewed seems to be a really good programmer, I've never seen someone write c++ in such a readable and concise way. Even the interviewer was impressed.
@@RizzoDaManiac yeah cleancode, like it's supposed to be
And for the competing question, wait for the competitors to grab their coins, when they are done, find the closet to me. :)
my english has improved but not that much...that's why I'm planning a post degree in Dublin.
i came here just to read the comments
the endgame felt like a variation of Kruskal's
Interviewer trierd hard to outsmart the candidate.
As a person who learned C++ in University. I can prove that we have no fucking idea what you talking about
These follow up questions are so weird? You have a vector... O(N) is the only answer why are we talking about how sparse the board is when you already have all the coins??
aaaaand... UHMMMMMMMM uhmmm uhmm uhmm uhmmm AAAAND UHHHHHHHHHHHM UHMMMMMMMMMMMMMM I SAID FUCKING UHHHHHHHMHHMHMHMHMMGMHMHMHMHMHMHMMHMHMHMHMHMHMMHMHMHMHMHMHMHMMHMHMMGMMMMMM
I think he was the one who should be interviewed, not the Google engineer lol.
Yaa really annoying.. Too much!
computer science ideas are complicated to communicate. Obviously you have not studied computer science/engineering.
Agnes Akne ur trying to act like he is only saying ummm so much because his brain is massive like elon musk, but i am studying computer science right now and ive seen plenty of people being capable of talking about this stuff without sounding like their having a seizure every time they open their mouth
OscarR0_ 😐 UHM...
What’s c++?
c++, i too, like to live dangerously
Can you not mutate the class in any way? I would've thought making a distance method or even a helper function would've helped a ton with just code cleanliness. Ah well.
As a dev who mainly writes C++ code, their use of C++ makes me cringe. Why select a language if you barely know it's very basic concepts?
Is that Vitalik Buterin being interviewed? Sound just like him.
all this confuses me as im starting my bachelor studies in computer science this august so i have no idea whats happening
Keep at it - You'll get there eventually - from a former BSc Com Sci Student :)