Kth Largest Sum in a Binary Tree - Leetcode 2583 - Python
Skills:
AI Systems Design80%
Key Takeaways
The video demonstrates how to solve the Kth Largest Sum in a Binary Tree problem using BFS and heaps, with a focus on time complexity analysis and efficient algorithms.
Full Transcript
hey everyone welcome back and let's write some more neat code today so today let's solve a problem K largest sum in a binary tree conceptually pretty simple problem suppose we're given a binary tree that looks like this what we want to do is compute the level sum of each level in the tree so that's relatively simple can you guess which algorithm we're going to use to do that I mean we could use either DFS or BFS those are kind of the main algorithms that we use on trees technically either will work to compute these but I'm going to prefer the BFS approach it's kind of a more natural way to do this so knowing that what do we want to do with those level sums assume we had them we have five here we have 17 here 13 here and we have 10 here well among all of these we want to find the K largest element among these elements so we pretty much removed the part that we needed a tree for now that we have these integers we don't really need to worry about the tree anymore now it's just a matter of finding the K largest element from this set of elements the obvious way to do it is to sort this input so what's the time complexity of that going to be before you think that it's n well let's assume that n is actually the number of nodes in this tree so then you might say well how many levels are going to be in the tree well if it's a balanced tree the height of the tree is going to be log n so the size of this is going to be log n but I'm not going to focus on that case I'm going to consider the worst case where the height of the tree is actually equal to n that would be the case where it's pretty much like a linked list like something like this so I'm going to to be more precise use H for the height of the tree so let's say the length of this is going to be of length H which in the worst case could be equal to n the time complexity to sort that is going to be H log H and of course we're going to have to go through everything in the input so the time complex is going to be n where n is the number of nodes plus h log H that's like the overall time complexity and once we have like sorted input we just return I think the length of like this list minus a k because we want the K largest so that's a perfectly valid way to solve this problem but we can actually do a little bit better let me show you how if we instead of sorting we take this and heapify it we turn it into a heap which if this is of size a we can do that in Big O of H so far the time complexity will be n from traversing the tree plus h from turning this into a heap and then what kind of Heap would we want to make it if we want to return the K largest element let's turn it into a Max heap if we do that we'll only have to pop from that Heap up to K times so we can say k time log H so in the event that K is relatively small this this will be not too bad now one thing I probably should have mentioned earlier is the fact that we might not actually have K levels in the tree for example in this tree like this is Level 1 2 3 4 if we have K = 5 well then we don't have a fifth level and in that case we return a default value of negative 1 so that's pretty easy to handle which is why I wasn't really too focused on that so this Max Heap approach is valid but there is one more approach we can take it's a little bit clever it involves using a Min Heap and I'm going to leave this here this is the max Heap time complexity and we're going to compare it to the Min Heap solution so the Min Heap solution is going to be kind of clever the idea is that we're going to maintain a minimum heap of size K it's always going to be less than or equal to K and the reason we're making it a Min Heap is because every time we push an element like as we're going through this level by level we're going to push this to the Heap we're going to push this to the Heap and let's say k is two in this example we're going to push that to the Heap as well and then since we want the Heap to only be up to size two we are going to remove the minimum element from the Heap so in other words the Min Heap is always going to store the K largest numbers the K largest levels and so if we do it this way once again we're going to get to this level and we're going to see okay now our Heap popped the minimum this is the minimum so this is what our Heap is going to look like at the end and then at the end we want the K largest element if these are the K largest elements we want the minimum among all of those elements that's why we use the men Heap we can get the men element in constant time so in this example that will be 13 so what's the time complexity of this solution well once again we are going to Traverse the tree so it's going to be n plus the size of the Heap is always going to be up to size K so pushing and popping from the Heap is going to be of size K we're going to do that roughly H times one for each level so the overall time complexity of this approach is going to be n + H * log K now let's consider the case where the tree is not balanced well then the H here would turn into an N so this would be n log K and over here this would be K log n so if the tree is not balanced K could also be pretty big like K could be approximately equal to n so I guess like in the worst case both of these time complexities would be roughly similar what about the case where the trees are balanced well in that case h would be approximately log n in which case this time complexity would turn into log n * log K plus that n term and then this time complexity would turn into K * log of log n and I guess like the upper bound of K itself is also equal to log in roughly if like it's a balance tree so I mean at this point I guess we're just kind of confusing ourselves either way I think both of these Solutions are pretty efficient I don't think in a real interview you would be asked to kind of explain why one is slightly more optimal than the other so I'll just leave things here but I thought like this kind of stuff was worth discussing thinking about the worst case and the best case run times I will be coding up uh the men Heap solution I think this trick is worth knowing because it actually comes up in a lot of problems if you're not familiar with this trick I would consider heading over to n code iio and going to the N code 150 list and if you go to the Heap section this is actually literally the first problem in that section will teach you that trick and I have a pretty decent video for that problem okay so now let's get into it the main thing about this problem well there's two aspects it's the BFS the breath for search I have plenty of videos on that so I'm going to be kind of going through that real relatively quickly we use a q in my case I'm going to use a deck in Python I'm going to initialize it with the root because we're guaranteed that the root is going to be non null we can safely do this and I'm also going to declare a Min Heap which initially is going to be an empty array and I'm going to say this is going to be at most size equal to K and then while the Q is non empty we're going to do the breadth for search so for a particular level we want to compute the level sum I'll initialize that to zero now we're going to go through the current level so I'm going to take a snapshot of the length of the Q at this point in time and that's how many times I'm going to iterate so I'm going to have a for Loop for I in range this many times so just going through the current level the reason I'm doing this is because we're actually going to be adding to the que as we go through the current level so that's why it's important to take like a snapshot and that's what this does in Python so now I'm going to pop from the left side of the queue pop left we're going to get a node from that and I want to take that value of the node and add it to the level sum just like this and then I want to consider the two children of this node if they exist I want to add them to the queue it probably doesn't matter which order we add them in but I'm still going to do it left to right so if node. left is non null I'm going to say q. append node. left same thing with the right side and q. append no. write now that we computed the level sum let's go ahead and push it to the Min Heap Heap Q Heap push to the Min Heap this value the level sum it's possible that the size of the Heap became greater than k at this point or maybe it's possible that it didn't either way let's go ahead and check if the length of the Min Heap is greater than K well in that case let's pop from it Heap Q Heap pop from the Min Heap we're almost done with this at this point you might think once we're done with all of this what we can return is the minimum value in the Min Heap at the end of this and in that case what we would do is return this Min Heap at index zero that's almost correct but remember if there aren't K levels in the tree what we actually want to do is return1 so how do we know if there are K levels well the size of the Min heap if it's less than k then we return ne1 cuz that means we never even added K values to the Min Heap in the first place so I'm going to handle that with a Turner operator return ne1 if length of Min Heap is less than K else return the K's smallest integer that's the entire code let's give it a run you can see it works and it's pretty efficient if you found this helpful definitely check out n code. for a lot more thanks for watching and I'll see you soon
Original Description
🚀 https://neetcode.io/ - A better way to prepare for Coding Interviews
🧑💼 LinkedIn: https://www.linkedin.com/in/navdeep-singh-3aaa14161/
🐦 Twitter: https://twitter.com/neetcode1
⭐ BLIND-75 PLAYLIST: https://www.youtube.com/watch?v=KLlXCFG5TnA&list=PLot-Xpze53ldVwtstag2TL4HQhAnC8ATf
Problem Link: https://leetcode.com/problems/kth-largest-sum-in-a-binary-tree/description/
0:00 - Read the problem
0:30 - Drawing Explanation
6:49 - Coding Explanation
leetcode 2583
#neetcode #leetcode #python
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from NeetCodeIO · NeetCodeIO · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Leetcode 149 - Maximum Points on a Line - Python
NeetCodeIO
Design Linked List - Leetcode 707 - Python
NeetCodeIO
Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
NeetCodeIO
Design Browser History - Leetcode 1472 - Python
NeetCodeIO
Number of Good Paths - Leetcode 2421 - Python
NeetCodeIO
Flip String to Monotone Increasing - Leetcode 926 - Python
NeetCodeIO
Maximum Sum Circular Subarray - Leetcode 918 - Python
NeetCodeIO
Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
NeetCodeIO
Concatenated Words - Leetcode 472 - Python
NeetCodeIO
Data Stream as Disjoint Intervals - Leetcode 352 - Python
NeetCodeIO
LFU Cache - Leetcode 460 - Python
NeetCodeIO
N-th Tribonacci Number - Leetcode 1137
NeetCodeIO
Best Team with no Conflicts - Leetcode 1626 - Python
NeetCodeIO
Greatest Common Divisor of Strings - Leetcode 1071 - Python
NeetCodeIO
Shortest Path in a Binary Matrix - Leetcode 1091 - Python
NeetCodeIO
Insert into a Binary Search Tree - Leetcode 701 - Python
NeetCodeIO
Delete Node in a BST - Leetcode 450 - Python
NeetCodeIO
Shuffle the Array (Constant Space) - Leetcode 1470 - Python
NeetCodeIO
Fruits into Basket - Leetcode 904 - Python
NeetCodeIO
Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
NeetCodeIO
Naming a Company - Leetcode 2306 - Python
NeetCodeIO
As Far from Land as Possible - Leetcode 1162 - Python
NeetCodeIO
Shortest Path with Alternating Colors - Leetcode 1129 - Python
NeetCodeIO
Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
NeetCodeIO
Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
NeetCodeIO
Contains Duplicate II - Leetcode 219 - Python
NeetCodeIO
Path with Maximum Probability - Leetcode 1514 - Python
NeetCodeIO
Add to Array-Form of Integer - Leetcode 989 - Python
NeetCodeIO
Unique Paths II - Leetcode 63 - Python
NeetCodeIO
Minimum Distance between BST Nodes - Leetcode 783 - Python
NeetCodeIO
Design Hashmap - Leetcode 706 - Python
NeetCodeIO
Range Sum Query Immutable - Leetcode 303 - Python
NeetCodeIO
Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
NeetCodeIO
Middle of the Linked List - Leetcode 876 - Python
NeetCodeIO
Course Schedule IV - Leetcode 1462 - Python
NeetCodeIO
Single Element in a Sorted Array - Leetcode 540 - Python
NeetCodeIO
Capacity to Ship Packages - Leetcode 1011 - Python
NeetCodeIO
IPO - Leetcode 502 - Python
NeetCodeIO
Minimize Deviation in Array - Leetcode 1675 - Python
NeetCodeIO
Longest Turbulent Array - Leetcode 978 - Python
NeetCodeIO
Last Stone Weight II - Leetcode 1049 - Python
NeetCodeIO
Construct Quad Tree - Leetcode 427 - Python
NeetCodeIO
Find Duplicate Subtrees - Leetcode 652 - Python
NeetCodeIO
Sort an Array - Leetcode 912 - Python
NeetCodeIO
Ones and Zeroes - Leetcode 474 - Python
NeetCodeIO
Remove Duplicates from Sorted Array II - Leetcode 80 - Python
NeetCodeIO
Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
NeetCodeIO
Concatenation of Array - Leetcode 1929 - Python
NeetCodeIO
Symmetric Tree - Leetcode 101 - Python
NeetCodeIO
Check Completeness of a Binary Tree - Leetcode 958 - Python
NeetCodeIO
Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
NeetCodeIO
Find Peak Element - Leetcode 162 - Python
NeetCodeIO
Accounts Merge - Leetcode 721 - Python
NeetCodeIO
Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
NeetCodeIO
Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
NeetCodeIO
Number of Zero-Filled Subarrays - Leetcode 2348 - Python
NeetCodeIO
Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
NeetCodeIO
Sqrt(x) - Leetcode 69 - Python
NeetCodeIO
Successful Pairs of Spells and Potions - Leetcode 2300 - Python
NeetCodeIO
Optimal Partition of String - Leetcode 2405 - Python
NeetCodeIO
More on: AI Systems Design
View skill →Related AI Lessons
⚡
⚡
⚡
⚡
Bloom Filters, Explained Properly
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Medium · Python
Chapters (3)
Read the problem
0:30
Drawing Explanation
6:49
Coding Explanation
🎓
Tutor Explanation
DeepCamp AI