I don’t think this is university’s fault or even student’s. Maybe you took a DS course in 3 rd year and by the end of 4th, you forgot most of it. we all forget most of things they teach in class just days after semester ends, if you don’t believe me, 99% students won’t be able to do basic algebra or trigonometry of class 10. So did school failed us? Idk. That being said, as competition grows, margin of error becomes less and less. If you have an interview coming up, make a list of 50-100 questions and just go through them. Keep adding and removing questions throughout your career. What you can’t answer, you just can’t. Move on to next interview.
I feel the same way. I have been working full-time now for just about 3 years so I graduated not too long ago and yes, initially I did think BFS but had no idea on how to implement it anymore. Thinking about either going over my algorithms class again or just grinding some leetcode.
yep, university /schools are notorious for mostly focusing on breadth and not on depth. Because of this, most of what you learn you don't keep. To learn something really well and 'make it stick' you need to come back to it over and over from all sorts of different angles and over long periods of time. if you don't do it ... well you just lose it which is not necessarily a bad thing. so if college grads go to interview without grinding leetcode and coming back to what they learnt then yeah 90% of them not being able to do it is not surprising at all. But this has more to do with the fact that they didn't prepare well before it and doesn't say as much about the university system.
Stuff like this is simple enough to re-discover if you understand the fundamentals. Like, even if I had forgotten the quadratic formula (I haven't), I'd still be able to reason my way towards "completing the square" and re-derive it. Similarly, figuring out how to walk a tree in a particular way is a pretty simple case of "Can you write an algorithm that walks a tree." Which is just a proxy for "do you understand how pointers work." If someone "forgets" how to walk a tree, they should not be programming professionally, they're a major bug hazard.
yeah, I've been a software engineer myself for years now, barely ever use any algorithms, since most of the time these are needed to optimise heavy computations, but everyone uses already-made databases that have optimisations built in, you simply have to build the query, the rest of the traversal is up to the engine you're using, I've worked on all kinds of projects from super large to super small, you almost never have to use any of these algorithms unless you wanna reinvent something, like implement your own db. I had no idea how to solve that, I know about the different kind of tree traversals but again, never use them, so you won't know what you don't use always.
well it's normal, repetition is the key. We tend to filter things we don't use everyday, more over the academic knowledge and teaching is pretty much theorical which makes us learn things by memory for the sake of the exam only. Obviously the goal would be to "I know where this is going" once we revise what we have forgotten but "studied". Obviously it all depends on how we studied that topic.
I'm more interested why he does phone calls, when people born after 1990 pretty much don't answer phones and don't really like talk to strangers. Especially strangers that ask stupid questions via phone. It's like I would call him and ask him how to solve iterated integral lmao - both questions are stupid and both are easily solvable in person, even on a whiteboard (even though whiteboard interviews are straight up dumb unless you're trying to weed out react bros pretenders after bootcamps.
I have to say this is not something I would ask during a phone screening. This is a task that should be asked during a technical interview so the candidate can have time to think and visualize what is being asked of him. Even if he doesn't know the algorithm, if he has any knowledge of how structures work he should be able to come up with some sort of a solution to the problem. That is why I always encourage candidates in interviews that it is absolutely okay to take time to think and breathe. I'm more interested in the way they think, draw conclusions and if they're able to come up with a solution on the spot since in real world projects you'll always be introduced to new problems that don't necessarily have such a straight forward solution.
Paused at 0:03 to comment how I'd approach this. Recursively traverse the tree (doesn't matter if pre-order, in-order, or post-order) passing a "level" variable that tracks the traversal depth. The level acts as an index into an main array of row arrays that track the node contents. When a node is visited, it's value is added to the row array for the "level", then the next level is processed recursively. Working JS code follows: const root = { d: 1, l: { d: 2, l: { d: 4, l: null, r: null, }, r: null, }, r: { d: 3, l: { d: 5, l: null, r: null, }, r: { d: 6, l: null, r: null, }, }, } const outputs = []; traverse(root, outputs, 0); outputs.forEach((o, i) => console.log(`Line: ${i + 1}: ${o}`)); // function traverse(branch, o, idx) { if (branch) { console.log(branch.d); if (!o[idx]) { o[idx] = []; } o[idx].push(branch.d); traverse(branch.l, o, idx + 1); traverse(branch.r, o, idx + 1); } }
How many developers have worked with binary trees even once in their daily work? 0.0001%? The person tweeting this kind of content clearly has no idea about the realities of the job world.
I dont wanna be mean, BUT THAT IS LIKE THE MOST BASIC STUFF YOU SEE ABOUT ALGOS, if you have gonne to the university tell them that they should give you back you fucking money, if you already have a degree. i havent gone to university myself, i have encounter this problem, even being a frontend developer, im not say that you gotta be an expert, but this is crutial to improbe your programming logic
That's not the problem. The problem is that people are unable to think through and solve a (simple) problem that they've never encountered. They need to be hand held and study algorithms on an individual case by case basis in order to be productive.
There should be no reason you can't figure this out on your own. And also these are CS grads, not random people that have long been detached from their uni courses. They should be well familiar with this as it's part of their coursework. And again, even if it's not, they should atleast be able to solve this with _some_ hand-holding.
I was a CENG so we went through the CS stuff a little slower, but we didn't get to anything more complicated than a linked list until the beginning of my third year.
@TUMiraser for us, queue, stacks, and lists were 100-200 level and anything more complex (like a tree) was 300 level. You could take them at any time as long as you met the prerequisites, but the earliest you could get to trees was probably the beginning of your second year.
@@zacharychristy8928 maybe it has to do with our discrete structures (discrete maths) course where we did a lot of graph theory (e.g. DFS, BFS, Tress, etc.), was defo exhausting for someone who only had sum experience from school in java (not more than arrays, control structures) :D prob that is also the reason for it being THE top university in germany and like 20ish worldwide iirc
Great video with explanation of both DFS and BFS. If you dont want to track depth in BFS, you can modify it to something like this while(queue.length!=0){ const copyQueue=queue; const ray = []; queue=[]; for(let i = 0;i
I feel like looking at portfolio depending on the CS field and judging its quality/complexity is better indicator than these questions. HR can screen the better ones and technical people look at the best ones.
Might as well, for the Kolmogorov complexity: ```js const children = n => [n.left, n.right].filter(n => n); const traverse = (...ns) => ns[0] ? [ns.map(n => n.value), ...traverse(...ns.flatMap(children))] : []; ``` Works for n-ary trees too if you swap `children(node)` function to `n => n.children ?? [n.left, n.right].filter(n => n)` or you can force the tree implementation to have a getter for `children` To get reverse order just swap to [...traverse(...ns.flatMap(children)), ns.map(n => n.value)]
I had to built the Hoffman encoder and decoder from scratch without seeing how to implement. Took me 1 month but ended up knowing how to implement heap without even looking at the screen 🤣
I'd just treat each level as a list of nodes, starting with the root [root], print the values of the current "level" and add all of their children to a new array then recursively call the function with the children.
I’m thrown off by “phone screen” in phone screens I’ve done normally you are talking about the position, basic requirements, making sure your skills, ed, etc. overlap This feels like a question you’d ask in a normal interview where you would screen share on teams or zoom
I work as FE dev for almost 8 years. I never had a problem that required traversing a tree. I spend my fee time learning about algorithms and data structures because I didn’t wanted to be less valuable than programers with CS degree. XD
Actually, if you write code for any frontend framework, you basically define a tree of components, and their lifecycles like mount is a depth first walk in that tree. You don't necessarily think about it this way but it is still this.
Well if you're staying as a frontend "engineer" for 8 years, that's a problem on itself, and it's not about having a 1 to 1 problem to the tree traverse, but it's about the way of thought of how a computer program should be constructed.
@@tvili999 It is but React is declarative in nature. it's abstracted to the point where you realistically don't need to know how it's lifecycles are implemented, only how they behave.
Directly after speaking with Claude: I apologize - I don't think we can print a binary tree in O(n) time with O(1) space using Morris Traversal like I suggested. We would need to either: Use O(h) space with a recursive approach to get O(n) time, or Accept O(n²) time to keep O(1) space Would you like to see an implementation of either approach? Your explanation of re-arranging the tree by keeping track of the levels is good, but it confuses me a bit how the last solution is a queue, if you immediately pop one off, I guess it still is one nonetheless.
This is very hard to believe I’m completely self taught and learned about trees a month into learning js cuz DOM…breadth or depth 1st, recursion or iteration it’s trivial
I use C for my DS .. honestly its kind of tough , because the features you have in JS , do most of the work , like in C you have to calculate the size of array beforehand 😂. So I coded the full solution and it's pretty complicated honestly. Firstly to manage the newline printing part you would need an inner loop to be constantly iterating 1,2,4,8,.. times.. Then you need a queue of min size 2^height of tree , so that it can atleast store all lowest level elements for a tree of height h+1 . For e.g for a tree of height 4 , it would store not 8 but at least 16 elements. Why do we need this ? Explaining... I figured out you need to store the null values at each level as well due to how that inner loop works for the printing of newlines .. otherwise at any level if an element is null , it would print the nodes of the next level in the same line . When it reaches a point where all elements of the queue are null , I break out of the outer loop .
@@noctis_rune doesn't sound like good advice if you have no knowledge of DSA.. They are not gonna think about these algorithms without knowing them first.
did before watching the video (pseudocode): current_nodes = [first_node] next_nodes = [] while current_nodes.length > 0: for node in current_nodes: print(node) next_nodes.append(node.getNextNodes()) current_nodes = next_nodes next_nodes = []
I Live in a 3rd world country and that dude is probable lying. cause this is something we are taught in year 3 for a CS degree. if a CS graduate can't answer its probably means they forgot how to do it or something. and again this is a phone interview, how do you ask that in a phone interview?
Just stated going to college. I opted for Computer Science but now I am wondering if it's even worth it, given the scarecity of jobs and all..😢 I still have 4 years to go but everything looks so uncertain.
Interview questions about algorithm for a backend dev why not but for a frontend I find it silly I am a self taught frontend dev, never learned those fancy algorithms and I don't have any problem to do my job 🤷♀️
@ then maybe stop complaining, this video is about cs students. If you apply and the interview dude wants you to work on the frontend and sees that you got no cs major, he will not ask stupid data structure questions (lucky you)
Good question. But better is: Thair teachers are able to solve that task? Maybe there is a problem. University isn't about know how to deal with problems of that type. Most of staff from real job world, even interviewing process elements you need to learn on your own.
One of the reasons I went into Frontend is because I really dislike algorithms, in general. Some people (myself included) just have a really hard time visualizing these types of structures, simple or complex. On the other hand I love HTML and CSS & the ability to have an immediate visual representation of my code. For other folks it's the other way around - funny how our brains can be wired so differently! Happy new year!
Dude try debugging any lang you are learning, you ll get to see how every statement affects your variables step by step, the same way you see how every css rule changes your html.
Maybe that's the reason why web these days is just sh*tfest? Disliking something doesn't mean you shouldn't have basic understanding of underlying, again, basic CS/math concepts.
I'm working more than 3 years as a frontend developer. I never used bsf or dfs. Does anybody realy using these at job? I have computer science engineering degree btw
honestly, if you're working frontend, u probably use bfs or dfs working through the dom somehow viasome library, but you just don't have to actively understand what's going on every time. frontend is kinda bridging graphic design and cs, rather than pure cs or cs and math or cs and ee, so... i mean you're working with trees and bfs and dfs, you might just be thinking of them differently because there's some more convenient representation. idk that's my opinion tho
i recently just used it, a basic usage as well. for our app, the list of items, each has sub items, so in the DB, each Item row will have parentItemId, they store with reference to the parent. To display this tree in the web, I use a bfs to reconstruct it. probably could have found an NPM that does this for me, but can't be bothered as it is quite easy to implement.
When I want to explain quick concepts to other devs I dont care which project I have open. Create new file and explain, there is no time to waste opening a new window and creating a new context. Brother has his game project up and a random test.js file. 😂
I have another question. Why obsess over these algorithm questions, and how the classical educational system is failing, when in real life, THEY DONT MATTER AT ALL!
i saw this recommended, the idea that 90% of grads can't do this has to be a joke, right? i mean less than 3 seconds of looking at the problem should make this obvious, right?
I mean if you actually went to college these days you would know this is true. Majority of the people in cs these days are dumb as rocks. Speaking from experience
Hi Sir Can You Please make a detailed view or just the steps How to Handle RBAC Authentication In a Multi Tenant Architecture Where each tenant can define it's roles and permission what is data modeling and how react will we make some pages or some sections of page visible Please 🥺
This is not about knowing every algorithm out there, I haven't seen Tree algorithms in couple years and managed to solve this in 2 minutes. I don't what the fuck is a BFS or what ou want to called it. I know how to solve a problem with logic
@@WebDevCody This is how I've done mine in python, as I watched the video lol. class Node: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def levelOrderTraversal(root: Node) -> list[list]: queue = [root] res = []
while queue: level = [] children = [] for node in queue: level.append(node.value) if node.left: children.append(node.left) if node.right: children.append(node.right) queue = children res.append(level)
@@zakariaabdisalam1728you can get rid of level array by pushing a special termination character before moving to next level, so it takes O(N + h) space
@@zakariaabdisalam1728 I've done it without the depth at all and with a string as an output of the function. I just added a to the output before transferring nodes from "children" to the queue
``` queue = deque([root]) while queue: n = len(queue) ans = [] for i in range(n): node = queue.popleft() ans.append(str(node.val)) if node.left: queue.append(node.left) if node.right: queue.append(node.right) print("".join(ans)) ``` Here is the code if anyone needs btw
If I don’t like it, it means I have to type a message to each comment I get to get it off my TH-cam notifications feed so I can filter by comments I have not responded to. I’d have too many to check if I don’t do that. Besides, shouldn’t TH-cam sort by likes?
Within about 5 seconds I identified: just add the elements to a queue in order to process one depth at a time, maybe if you're lazy to obtain an optimized queue implementation, just used an JavaScript Set which is already ordered. Then you brought up depth-first-search and breadth-first-search I was thinking what on earth are these again, I forget what these searches are but like you shouldn't need anything so complicated like a DFS/BFS, just add the nodes to a queue. 7 minutes into a video you implement BFS -- and it's just a queue. I was shocked that a name, one with an acronym, had to be given to such a simple process. I would go so far as to say a graduate from university should be able to identify the solution without having to have ever heard of BFS before or being expected to recite its name in a job interview. I have nothing against naming things, I'm just surprised that the first thing on a phone interview is an expectation of recalling the name of an algorithm for something so simple, rather than just answering it in a few words.
Saying use a queue as your traverse the tree is probably close enough. Having a common naming convention is important in this industry so we all have a common language to talk with
I believe that if you dont know this and you have gone the 5 years of CS you have failed to yourself not being curios enough about understanding the fundamentals of the tech that surrounded you, for example did you know that the React DOM is a tree?, what i want to say is, you dont have to reinvent the wheel, but if you dont know how to create a f wheel youself, is the wheel using you?, or you are using the wheel? (Obviously not to the extreme point )
I don’t think this is university’s fault or even student’s. Maybe you took a DS course in 3 rd year and by the end of 4th, you forgot most of it. we all forget most of things they teach in class just days after semester ends, if you don’t believe me, 99% students won’t be able to do basic algebra or trigonometry of class 10. So did school failed us? Idk.
That being said, as competition grows, margin of error becomes less and less. If you have an interview coming up, make a list of 50-100 questions and just go through them. Keep adding and removing questions throughout your career. What you can’t answer, you just can’t. Move on to next interview.
I feel the same way. I have been working full-time now for just about 3 years so I graduated not too long ago and yes, initially I did think BFS but had no idea on how to implement it anymore.
Thinking about either going over my algorithms class again or just grinding some leetcode.
yep, university /schools are notorious for mostly focusing on breadth and not on depth. Because of this, most of what you learn you don't keep. To learn something really well and 'make it stick' you need to come back to it over and over from all sorts of different angles and over long periods of time. if you don't do it ... well you just lose it which is not necessarily a bad thing. so if college grads go to interview without grinding leetcode and coming back to what they learnt then yeah 90% of them not being able to do it is not surprising at all. But this has more to do with the fact that they didn't prepare well before it and doesn't say as much about the university system.
Stuff like this is simple enough to re-discover if you understand the fundamentals. Like, even if I had forgotten the quadratic formula (I haven't), I'd still be able to reason my way towards "completing the square" and re-derive it. Similarly, figuring out how to walk a tree in a particular way is a pretty simple case of "Can you write an algorithm that walks a tree." Which is just a proxy for "do you understand how pointers work." If someone "forgets" how to walk a tree, they should not be programming professionally, they're a major bug hazard.
yeah, I've been a software engineer myself for years now, barely ever use any algorithms, since most of the time these are needed to optimise heavy computations, but everyone uses already-made databases that have optimisations built in, you simply have to build the query, the rest of the traversal is up to the engine you're using, I've worked on all kinds of projects from super large to super small, you almost never have to use any of these algorithms unless you wanna reinvent something, like implement your own db.
I had no idea how to solve that, I know about the different kind of tree traversals but again, never use them, so you won't know what you don't use always.
well it's normal, repetition is the key. We tend to filter things we don't use everyday, more over the academic knowledge and teaching is pretty much theorical which makes us learn things by memory for the sake of the exam only. Obviously the goal would be to "I know where this is going" once we revise what we have forgotten but "studied". Obviously it all depends on how we studied that topic.
I'm curious to hear how he defines the problem and explains the structure of the nodes during a phone talk
that would genuinely be quite amusing.
I'm more interested why he does phone calls, when people born after 1990 pretty much don't answer phones and don't really like talk to strangers. Especially strangers that ask stupid questions via phone. It's like I would call him and ask him how to solve iterated integral lmao - both questions are stupid and both are easily solvable in person, even on a whiteboard (even though whiteboard interviews are straight up dumb unless you're trying to weed out react bros pretenders after bootcamps.
I would assume he means Zoom/Teams...
Love it! Love you! Happy new year!!!
nobody remember that shit, most people just learn it once and forget about it because its never needed ever again
Well, yeah, but this should take like 1-2 minutes to figure out from scratch if someone attended a basic course in programming.
Did you learn addition by memorizing every single possible combination of two numbers being added together?
it's not just about being able to traverse a tree it's about being able to solve problems in general
Yeah everyone complaining about "who uses trees anyways" or "nobody ever had to do this in a real job" are completely missing the point.
I've finished university 18 years ago, I probably knew it back then, but I have absolutely no idea right now, especially on a phone interview.
Good clickbait, genuinely
Yeah, I mean srs there is no way that tweet is any right
@@yassine-sa should i post the tweet?
@@Bhavishya_est what do you mean??
I have to say this is not something I would ask during a phone screening. This is a task that should be asked during a technical interview so the candidate can have time to think and visualize what is being asked of him. Even if he doesn't know the algorithm, if he has any knowledge of how structures work he should be able to come up with some sort of a solution to the problem. That is why I always encourage candidates in interviews that it is absolutely okay to take time to think and breathe. I'm more interested in the way they think, draw conclusions and if they're able to come up with a solution on the spot since in real world projects you'll always be introduced to new problems that don't necessarily have such a straight forward solution.
No way 90% cant do this
This is fundamental
Paused at 0:03 to comment how I'd approach this. Recursively traverse the tree (doesn't matter if pre-order, in-order, or post-order) passing a "level" variable that tracks the traversal depth. The level acts as an index into an main array of row arrays that track the node contents. When a node is visited, it's value is added to the row array for the "level", then the next level is processed recursively. Working JS code follows:
const root = {
d: 1,
l: {
d: 2,
l: {
d: 4,
l: null,
r: null,
},
r: null,
},
r: {
d: 3,
l: {
d: 5,
l: null,
r: null,
},
r: {
d: 6,
l: null,
r: null,
},
},
}
const outputs = [];
traverse(root, outputs, 0);
outputs.forEach((o, i) => console.log(`Line: ${i + 1}: ${o}`));
//
function traverse(branch, o, idx) {
if (branch) {
console.log(branch.d);
if (!o[idx]) {
o[idx] = [];
}
o[idx].push(branch.d);
traverse(branch.l, o, idx + 1);
traverse(branch.r, o, idx + 1);
}
}
How many developers have worked with binary trees even once in their daily work? 0.0001%? The person tweeting this kind of content clearly has no idea about the realities of the job world.
I dont wanna be mean, BUT THAT IS LIKE THE MOST BASIC STUFF YOU SEE ABOUT ALGOS, if you have gonne to the university tell them that they should give you back you fucking money, if you already have a degree. i havent gone to university myself, i have encounter this problem, even being a frontend developer, im not say that you gotta be an expert, but this is crutial to improbe your programming logic
That's not the problem. The problem is that people are unable to think through and solve a (simple) problem that they've never encountered. They need to be hand held and study algorithms on an individual case by case basis in order to be productive.
@@Deeptunester or use chatgpt, but i dont think its a big problem
There should be no reason you can't figure this out on your own. And also these are CS grads, not random people that have long been detached from their uni courses. They should be well familiar with this as it's part of their coursework. And again, even if it's not, they should atleast be able to solve this with _some_ hand-holding.
sure but not on phone
most "difficult" DS we've learned so far (1½ years of the degree) is a queue.. no trees, tries, hashmaps etc.
I was a CENG so we went through the CS stuff a little slower, but we didn't get to anything more complicated than a linked list until the beginning of my third year.
wtf? we learned that after 4 weeks in introduction to cs (my degree is not even cs but information systems) in germany at TUM
@TUMiraser for us, queue, stacks, and lists were 100-200 level and anything more complex (like a tree) was 300 level. You could take them at any time as long as you met the prerequisites, but the earliest you could get to trees was probably the beginning of your second year.
@@zacharychristy8928 maybe it has to do with our discrete structures (discrete maths) course where we did a lot of graph theory (e.g. DFS, BFS, Tress, etc.), was defo exhausting for someone who only had sum experience from school in java (not more than arrays, control structures) :D prob that is also the reason for it being THE top university in germany and like 20ish worldwide iirc
regarding the pace etc.
Great video with explanation of both DFS and BFS.
If you dont want to track depth in BFS, you can modify it to something like this
while(queue.length!=0){
const copyQueue=queue;
const ray = [];
queue=[];
for(let i = 0;i
I feel like looking at portfolio depending on the CS field and judging its quality/complexity is better indicator than these questions. HR can screen the better ones and technical people look at the best ones.
Might as well, for the Kolmogorov complexity:
```js
const children = n => [n.left, n.right].filter(n => n);
const traverse = (...ns) => ns[0] ? [ns.map(n => n.value), ...traverse(...ns.flatMap(children))] : [];
```
Works for n-ary trees too if you swap `children(node)` function to `n => n.children ?? [n.left, n.right].filter(n => n)` or you can force the tree implementation to have a getter for `children`
To get reverse order just swap to [...traverse(...ns.flatMap(children)), ns.map(n => n.value)]
i guess having the idea and how to approach it is enough because code is everywhere and there are plenty of tools to write the code for the solution
I had to built the Hoffman encoder and decoder from scratch without seeing how to implement. Took me 1 month but ended up knowing how to implement heap without even looking at the screen 🤣
But ai can, then it's not matter if gratuated or not and I never need it in real life in work!
Most tree problems are not as blatant as this, if you rely on AI for all of your work, how will you stay employable?
I'd just treat each level as a list of nodes, starting with the root [root], print the values of the current "level" and add all of their children to a new array then recursively call the function with the children.
function printTrees(trees: Tree[]) {
const subtrees: Tree[] = []
let printVal = '';
for (const t of trees) {
printVal = printVal + t.val;
if (t.l) {
subtrees.push(t.l)
}
if (t.r) {
subtrees.push(t.r)
}
}
console.log(printVal);
if (subtrees.length) {
printTrees(subtrees)
}
}
I’m thrown off by “phone screen” in phone screens I’ve done normally you are talking about the position, basic requirements, making sure your skills, ed, etc. overlap
This feels like a question you’d ask in a normal interview where you would screen share on teams or zoom
Yeah I don’t understand that either
I work as FE dev for almost 8 years. I never had a problem that required traversing a tree.
I spend my fee time learning about algorithms and data structures because I didn’t wanted to be less valuable than programers with CS degree. XD
Actually, if you write code for any frontend framework, you basically define a tree of components, and their lifecycles like mount is a depth first walk in that tree. You don't necessarily think about it this way but it is still this.
@@tvili999 ACKCHYUALLY
Well if you're staying as a frontend "engineer" for 8 years, that's a problem on itself, and it's not about having a 1 to 1 problem to the tree traverse, but it's about the way of thought of how a computer program should be constructed.
@@tvili999 It is but React is declarative in nature. it's abstracted to the point where you realistically don't need to know how it's lifecycles are implemented, only how they behave.
@@FlamurMustafa-l4l Why being a FE Dev a problem?
I am going for a FS position but there plenty of people being fine with staying as FE.
Directly after speaking with Claude:
I apologize - I don't think we can print a binary tree in O(n) time with O(1) space using Morris Traversal like I suggested. We would need to either:
Use O(h) space with a recursive approach to get O(n) time, or
Accept O(n²) time to keep O(1) space
Would you like to see an implementation of either approach?
Your explanation of re-arranging the tree by keeping track of the levels is good, but it confuses me a bit how the last solution is a queue, if you immediately pop one off, I guess it still is one nonetheless.
Child nodes are pushed into the queue later in the function, so the queue is necessary
Happy new year Cody 🎉
This is very hard to believe I’m completely self taught and learned about trees a month into learning js cuz DOM…breadth or depth 1st, recursion or iteration it’s trivial
I use C for my DS .. honestly its kind of tough , because the features you have in JS , do most of the work , like in C you have to calculate the size of array beforehand 😂.
So I coded the full solution and it's pretty complicated honestly. Firstly to manage the newline printing part you would need an inner loop to be constantly iterating 1,2,4,8,.. times..
Then you need a queue of min size 2^height of tree , so that it can atleast store all lowest level elements for a tree of height h+1 . For e.g for a tree of height 4 , it would store not 8 but at least 16 elements. Why do we need this ? Explaining...
I figured out you need to store the null values at each level as well due to how that inner loop works for the printing of newlines .. otherwise at any level if an element is null , it would print the nodes of the next level in the same line .
When it reaches a point where all elements of the queue are null , I break out of the outer loop .
for those us trying to get into tech without a CS degree, what are some of the best resources out here to learn DSA in your opinion?
Grind leetcode
Watch the free codecamp course and start leeting
theres a free course available on frontend masters by primeagen, really worth watching to understand the very basics
neetcode, solve problems and keep on learning as you go there's no other way
@@noctis_rune doesn't sound like good advice if you have no knowledge of DSA..
They are not gonna think about these algorithms without knowing them first.
did before watching the video (pseudocode):
current_nodes = [first_node]
next_nodes = []
while current_nodes.length > 0:
for node in current_nodes:
print(node)
next_nodes.append(node.getNextNodes())
current_nodes = next_nodes
next_nodes = []
Goood boy 👏🎉🎉🎉🎉 now here is your lollipop 🍭
I like
I Live in a 3rd world country and that dude is probable lying. cause this is something we are taught in year 3 for a CS degree. if a CS graduate can't answer its probably means they forgot how to do it or something. and again this is a phone interview, how do you ask that in a phone interview?
Just stated going to college.
I opted for Computer Science but now I am wondering if it's even worth it, given the scarecity of jobs and all..😢
I still have 4 years to go but everything looks so uncertain.
It is worth it if you like the field
It’s worth it
Interview questions about algorithm for a backend dev why not but for a frontend I find it silly
I am a self taught frontend dev, never learned those fancy algorithms and I don't have any problem to do my job 🤷♀️
Were you a cs student?
@@moritz6526 No, I was not a cs student ever
@ then maybe stop complaining, this video is about cs students.
If you apply and the interview dude wants you to work on the frontend and sees that you got no cs major, he will not ask stupid data structure questions (lucky you)
@@moritz6526 is it actually easier to pass interviews if you don't have a degree?
@user-sb5vt8iy5q no, the point is the question becomes less advanced so that the difficulty for you stays the same
Good question. But better is: Thair teachers are able to solve that task? Maybe there is a problem. University isn't about know how to deal with problems of that type. Most of staff from real job world, even interviewing process elements you need to learn on your own.
One of the reasons I went into Frontend is because I really dislike algorithms, in general. Some people (myself included) just have a really hard time visualizing these types of structures, simple or complex. On the other hand I love HTML and CSS & the ability to have an immediate visual representation of my code. For other folks it's the other way around - funny how our brains can be wired so differently! Happy new year!
Dude try debugging any lang you are learning, you ll get to see how every statement affects your variables step by step, the same way you see how every css rule changes your html.
Brother, learn js by manipulating the DOM with it. Once you get that I’m sure you’ll be open to data structures and algorithms
Wait til you realise the DOM is a tree!
Maybe that's the reason why web these days is just sh*tfest? Disliking something doesn't mean you shouldn't have basic understanding of underlying, again, basic CS/math concepts.
@@boccobadz when was the last time you had to run BFS on a DOM tree lol
I'm working more than 3 years as a frontend developer. I never used bsf or dfs. Does anybody realy using these at job? I have computer science engineering degree btw
I used it recently to rewrite one of our go routers to speed up routing.
theyre also used everywhere in frontend libraries for DOM transversal.
@@hamm8934 yeah probably library authors using but I have never used
honestly, if you're working frontend, u probably use bfs or dfs working through the dom somehow viasome library, but you just don't have to actively understand what's going on every time. frontend is kinda bridging graphic design and cs, rather than pure cs or cs and math or cs and ee, so... i mean you're working with trees and bfs and dfs, you might just be thinking of them differently because there's some more convenient representation. idk that's my opinion tho
@@hamm8934 yeah library authors probably using it but me
i recently just used it, a basic usage as well. for our app, the list of items, each has sub items, so in the DB, each Item row will have parentItemId, they store with reference to the parent. To display this tree in the web, I use a bfs to reconstruct it.
probably could have found an NPM that does this for me, but can't be bothered as it is quite easy to implement.
I work as a FE and I've never had to do that.
Does supermaven autocomplete as well?
Yes supermaven auto completes
Happy new year 🎉
When I want to explain quick concepts to other devs I dont care which project I have open. Create new file and explain, there is no time to waste opening a new window and creating a new context. Brother has his game project up and a random test.js file. 😂
People got baited by tweet with random statistic, where 90% come even from? If those cs grads have written code, more than 90% would be able to do it.
I kind of believe him. Most cs grads in my class cheated their way through projects and had no clue how to do basic things
DFS and BFS will work for this problem.
Man I missed your Next videos. Did you moved away from it or has another project currently?
this type of question is easy. If the majority of candidates are doing leetcode questions and cant solve this, they shouldnt be in cs.
I have another question. Why obsess over these algorithm questions, and how the classical educational system is failing, when in real life, THEY DONT MATTER AT ALL!
i saw this recommended, the idea that 90% of grads can't do this has to be a joke, right? i mean less than 3 seconds of looking at the problem should make this obvious, right?
I mean if you actually went to college these days you would know this is true. Majority of the people in cs these days are dumb as rocks. Speaking from experience
I know how to solve the problem with the algorithm bfs but at the moment I am rusty on programming bfs off the top of the head.
Hi Sir
Can You Please make a detailed view or just the steps
How to Handle RBAC Authentication
In a Multi Tenant Architecture
Where each tenant can define it's roles and permission what is data modeling and how react will we make some pages or some sections of page visible
Please 🥺
Please do more algorithms content!
I doubt its 90%. Uni DSA courses usually teach BFS and DFS
This is not about knowing every algorithm out there, I haven't seen Tree algorithms in couple years and managed to solve this in 2 minutes. I don't what the fuck is a BFS or what ou want to called it. I know how to solve a problem with logic
You defined that Node with value "2" has a connection to Node with Value "5", isnt that wrong, according to the graph?
I think it basically works the same way due to the order of the traversal
Actually, there is an elegant way to traverse over the current level by getting rid of the `depth` and `lastDepth`
Paste the code
@@WebDevCody This is how I've done mine in python, as I watched the video lol.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def levelOrderTraversal(root: Node) -> list[list]:
queue = [root]
res = []
while queue:
level = []
children = []
for node in queue:
level.append(node.value)
if node.left: children.append(node.left)
if node.right: children.append(node.right)
queue = children
res.append(level)
return res
root = Node(1, Node(2, Node(4)), Node(3, Node(5), Node(6)))
print(levelOrderTraversal(root))
@@zakariaabdisalam1728you can get rid of level array by pushing a special termination character before moving to next level, so it takes O(N + h) space
No one calls bfs level order traversal except for ai
@@zakariaabdisalam1728 I've done it without the depth at all and with a string as an output of the function. I just added a
to the output before transferring nodes from "children" to the queue
God, these posts and tweets are why I hate the tech industry.
Isnt this called level order traversal ? In which we go level by level instead of bfs dfs
Ask gpt, bfs is level order traversal
"i'm just gonna go ahead and let AI do this for me" made me lose interest.
That sounds like a personal problem
Love the algorithm content, your way of instructing is so good!
What AI are u using ?
Cursor
@@WebDevCody thanks
Great vid
Breadth First Search, duh... Didn't watch the video, not worth the time.
The science of CS.. go!
I thought you said JS was a mistake. what happened lol
```
queue = deque([root])
while queue:
n = len(queue)
ans = []
for i in range(n):
node = queue.popleft()
ans.append(str(node.val))
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
print("".join(ans))
```
Here is the code if anyone needs btw
Please do not like every comment it's like Jira priority everyone choose "highest" and means nothing though
If I don’t like it, it means I have to type a message to each comment I get to get it off my TH-cam notifications feed so I can filter by comments I have not responded to. I’d have too many to check if I don’t do that. Besides, shouldn’t TH-cam sort by likes?
Within about 5 seconds I identified: just add the elements to a queue in order to process one depth at a time, maybe if you're lazy to obtain an optimized queue implementation, just used an JavaScript Set which is already ordered.
Then you brought up depth-first-search and breadth-first-search I was thinking what on earth are these again, I forget what these searches are but like you shouldn't need anything so complicated like a DFS/BFS, just add the nodes to a queue.
7 minutes into a video you implement BFS -- and it's just a queue.
I was shocked that a name, one with an acronym, had to be given to such a simple process.
I would go so far as to say a graduate from university should be able to identify the solution without having to have ever heard of BFS before or being expected to recite its name in a job interview.
I have nothing against naming things, I'm just surprised that the first thing on a phone interview is an expectation of recalling the name of an algorithm for something so simple, rather than just answering it in a few words.
Saying use a queue as your traverse the tree is probably close enough. Having a common naming convention is important in this industry so we all have a common language to talk with
BFS?
I believe that if you dont know this and you have gone the 5 years of CS you have failed to yourself not being curios enough about understanding the fundamentals of the tech that surrounded you, for example did you know that the React DOM is a tree?, what i want to say is, you dont have to reinvent the wheel, but if you dont know how to create a f wheel youself, is the wheel using you?, or you are using the wheel? (Obviously not to the extreme point )
a.k.a bfs
99% can solve it. clickbait
Add react js code refactor videos more...
You can ditch the depth. Here it is in Rust;
use std::collections::VecDeque;
struct TreeNode {
value: i32,
left: Option,
right: Option,
}
impl TreeNode {
fn new(value: i32) -> Self {
TreeNode {
value,
left: None,
right: None,
}
}
fn build() -> Self {
TreeNode {
value: 1,
left: Some(Box::new(TreeNode {
value: 2,
left: Some(Box::new(TreeNode::new(4))),
right: None,
})),
right: Some(Box::new(TreeNode {
value: 3,
left: Some(Box::new(TreeNode::new(5))),
right: Some(Box::new(TreeNode::new(6))),
})),
}
}
fn print(&self) {
let mut queue = VecDeque::new();
queue.push_back(self);
while !queue.is_empty() {
let level_size = queue.len();
let mut current_level = Vec::with_capacity(queue.len());
for _ in 0..level_size {
if let Some(node) = queue.pop_front() {
current_level.push(node.value.to_string());
if let Some(left) = &node.left {
queue.push_back(left);
}
if let Some(right) = &node.right {
queue.push_back(right);
}
}
}
println!("{}", current_level.join(" "));
}
}
}
fn main() {
let tree = TreeNode::build();
tree.print();
}
I think the reason I went for frontend is because I'm too dumb for this 🥲
No you’re not