Find Missing Observations - Leetcode 2028 - Python

NeetCodeIO · Intermediate ·⚡ Algorithms & Data Structures ·1y ago

Key Takeaways

The video solves Leetcode problem 2028, finding missing observations in a set of dice rolls, using a greedy approach with a twist and validating the sum, with a time complexity of O(m + n) and space complexity of O(1). The solution utilizes the pigeon hole principle and iterates over the number of missing slots to calculate the missing sum.

Full Transcript

hey everyone welcome back and let's write some more neat code today so today let's solve the problem find missing observations I just want to quickly mention that I've actually already solved this problem before I even made a video for it and I think that was actually almost 3 years ago but anyways I'll solve it again today but in the future if I don't solve a problem it's worth just searching for it to see if I did it in the past so very long problem description I'll try to make it more simple for you so the idea is we have a dice this is kind of my bad drawing of it but it's six so it'll have a one on one side a two and then a three and all the way up to six so one through six and there were a bunch of rolles for those dices so I guess going through this example here there were six total rolles how do I know there were that many well because they give us a parameter rules that tells us four of them and they gave us the value of each one so that's three for the first and then 2 4 3 and they also tell us here n equals 2 so there were two more roles done we just don't know the value of those roles so that's how I know that in total there are six rows um rolles sorry but our objective here is to guess what these roles could have been not necessarily what they were because there could be multiple correct answers we just need to return a single one so the question is how can we do that it's not quite as complicated as it might seem at first let me break it down for you first of all you pretty much have to know what an average is by average I mean the mean average that's basically taking a bunch of values and then dividing them so one thing you must know you must recognize that if we were to sum all of these values so whatever that sum happened to be and then you divide it by this let's call this m that's uh the number of rols we're given and N the number of rolls we're trying to guess if you divide that by the total number of rows this sum is all of this remember this has to be less than or equal to 6 and greater than or equal to 1 the reason that this is so important is that they actually give us another parameter called the mean it is going to be this value it literally is that value so they actually helped us out because we would not be able to calculate this without the missing values it's impossible so they helped us out they gave us this value in this example the value was four so knowing that the average of all of these is four what are some realistic guesses that we could make here so now it's logical to want to know well what is the sum of all of these values we already know what M and M are so what's the total sum well that's pretty easy to calculate isn't it just take M plus n multiply it by the mean because they already gave us the sum so you know multiply both sides but uh yeah basically just take this multiply it by that this is how many rolls there were this is the average for each roll so multiplying them will give us the total in this example it is going to be 24 so it's going to be the mean was four multiplied by the total number of rols six so this is the total sum okay now it seems pretty logical to take this sum and subtract it from this so that we know well what's the total sum of the missing remaining values okay do that and you'll get this all of these I believe are 12 so we get 24 minus 12 and now we are left with 12 so this is the missing sum it doesn't tell us an individual role but just by looking at this we humans can tell that if it's 12 the only possible values that these could have been are going to be 6 and six okay but how do we do this algorithmically because it's not always going to be this simple so now that we've gone through all of these like six-sided die all this math all this blah blah blah we've reduced this to now Distributing this 12 among n different slots so now we've changed the problem this is very similar I think at least in my opinion it reminds me of like the pigeon hole principle the pigeon hole problem so that's what I'm going to be discussing now to show you how to solve this optimally let's suppose that the missing sum was 10 and we have three dice rolls to fill well okay let's just try to be greedy that always works out for us right let's try to just add the max amount that we can we have 10 here so the max we could add here remember each dice is 1 through six so that's going to be six now we have four remaining okay just be greedy add it all over here four now we have zero remaining okay just be greedy add the zero over here don't you see a problem with this approach How could a dice roll be zero it can't there is another possible problem suppose the missing sum was 19 let's do the same thing six here okay six here and then a six over here well that's the max we could have possibly done but we're still left with a missing sum of one we don't have any more dice rolls so there's two steps to this one is going to be the validation that we do before just with the missing sum value and the second step is going to be the actual like simulation it's going to be similar to a greedy approach but it's going to rely a little bit on like the pigeon hole principle thing I was talking about a second ago so the first thing we're going to do with this sum we can tell that this sum is valid or invalid just by taking this let's say we divide this by three it has to be less than or equal to six it has to it also has to be greater than or equal to 1 suppose we had a missing sum of two and we have three slots to fill well you can't really do it like one of them is going to be a zero no matter what so again the average has to be greater than or equal to 1 less than or equal to six okay now step two this is the more interesting part it's going to be somewhat greedy but the only problem is we kind of saw it earlier if we add like as much as we can here and then as much as we can eventually we run out you don't want to blow your load too quickly so let's make sure that we at least no matter how greedy we are let's at least make sure we have the bare minimum for the rest of the slots to make this more interesting let me add a fourth slot so let's just always make sure we have at least one for the remaining so we're going to do this starting with 10 we're going to add six here now we have four remaining and so now you might again think to be greedy just add that four no we have to make sure that whatever value we have that when we're left over with x that X is enough to fill these slots what's the minimum value that would be enough to fill these well there's two slots so that value has to be two what I'm saying is add the maximum value you can in each spot just make sure you have enough for the remaining spots so in this case it's a very simple formula if I were you I would try to write it out on pen and paper before I do but if you can't this is what it is it's going to be the minimum of six or the current missing sum I'll just call that sum for short minus while we're iterating through this like the code n is going to be this like the total number of slots we have here so here I'm going to do sum minus n and I'm going to do a plus one this plus one is just for the fact of this we just want to make sure that I guess I'll just give you an example of this formula when this is four this calculation is going to become a 4 minus these three + 1 so this calculation will tell us the biggest value we can put here coincidentally this is two and this length is also two this time but this calculation will tell us the biggest value that you can put here such that we at least have one remaining here and one remaining here just a dry run through this one last time maybe with a different example let's call this 13 let's do that calculation what's the minimum value we can put here it's either going to be 6 or it's going to be the sum 13 - 4 + one so that's a 10 so the biggest value we can put here is 10 and then we'd have one remaining in all of these other spots but we know that no dice can be a 10 so we put six instead the minimum of 10 and six the minimum of these two so we put a six here and I'll quickly uh go through the rest of this so now we have a seven so what's the biggest value we can put here I believe it's going to be a five and then we put a one here and then a one here now you don't have to do it this way there's no particular reason you have to put the biggest value this is just one valid answer but I believe the time complexity is going to be m + n one because we need to fill the remaining slots and also we need to compute the sum of the input rolls array space complexity I believe it's constant if you don't actually include these like output values so now let's code it up so I'll try to keep this code pretty readable let's get M that is going to be the length of that rolls parameter next let's get the total sum of everything um among rolles which again we can compute by taking the mean multiplying it by the total number of roles that's going to be m + n and then once we have the total sum it's pretty easy to compute the missing sum that we're looking for just by taking the total sum and subtracting from it the r sum which is just sum of that uh input array now remember the first thing we want to do is that validation step with the missing sum so we want to make sure that taking this dividing it by six it's going to be greater than or dividing it by n sorry is going to be greater than or equal to 6 in this if statement basically I'm going to return early I'm going to say that there isn't a possible solution so we return an empty array so for the equality here I actually don't need that if this is greater if it's strictly greater than six that's when we would return early um and then here we'll do the opposite if the missing sum and this time we actually don't need to divide it because if it's less than n n is the number of missing slots so we need at least one for each of those so this works and this kind of tells me that we can actually change this up we can multiply this side by n and multiply this side by n and then it's a little bit cleaner to have multiplication rather than division so I prefer this though it doesn't really matter too much um but now let's get into the result let's um initialize it here and then return it here but let's actually do the computation somewhere in the middle so I'm going to do this by saying while n the reason I'm using a while loop rather than a for Loop is because we're going to be updating the N variable it tells us the number of missing slots so we're going to be decrementing it by one each time but to get the actual dice in the current position remember we just take the minimum of six as well as the missing sum - n + 1 then we can add it to the result and don't forget to update the missing sum by subtracting The Dice from it so we need to keep this updated and we need to keep n updated alternatively for the condition you actually probably could have just said while the missing sum is not on zero it'll probably work the same in both cases but either way let me give this a run as you can see it works it's pretty efficient I promise you leak cut run times are pretty random this is about as efficient as you can get at least I think in terms of Big O time and space because as you can see we're not doing anything other than iterating over n and technically iterating over the roles by taking the sum of it if you found this helpful 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/find-missing-observations/description/ 0:00 - Read the problem 0:30 - Drawing Explanation 8:47 - Coding Explanation leetcode 2028 #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 Leetcode 149 - Maximum Points on a Line - Python
Leetcode 149 - Maximum Points on a Line - Python
NeetCodeIO
2 Design Linked List - Leetcode 707 - Python
Design Linked List - Leetcode 707 - Python
NeetCodeIO
3 Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
NeetCodeIO
4 Design Browser History - Leetcode 1472 - Python
Design Browser History - Leetcode 1472 - Python
NeetCodeIO
5 Number of Good Paths - Leetcode 2421 - Python
Number of Good Paths - Leetcode 2421 - Python
NeetCodeIO
6 Flip String to Monotone Increasing - Leetcode 926 - Python
Flip String to Monotone Increasing - Leetcode 926 - Python
NeetCodeIO
7 Maximum Sum Circular Subarray - Leetcode 918 - Python
Maximum Sum Circular Subarray - Leetcode 918 - Python
NeetCodeIO
8 Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
NeetCodeIO
9 Concatenated Words - Leetcode 472 - Python
Concatenated Words - Leetcode 472 - Python
NeetCodeIO
10 Data Stream as Disjoint Intervals - Leetcode 352 - Python
Data Stream as Disjoint Intervals - Leetcode 352 - Python
NeetCodeIO
11 LFU Cache - Leetcode 460 - Python
LFU Cache - Leetcode 460 - Python
NeetCodeIO
12 N-th Tribonacci Number - Leetcode 1137
N-th Tribonacci Number - Leetcode 1137
NeetCodeIO
13 Best Team with no Conflicts - Leetcode 1626 - Python
Best Team with no Conflicts - Leetcode 1626 - Python
NeetCodeIO
14 Greatest Common Divisor of Strings - Leetcode 1071 - Python
Greatest Common Divisor of Strings - Leetcode 1071 - Python
NeetCodeIO
15 Shortest Path in a Binary Matrix - Leetcode 1091 - Python
Shortest Path in a Binary Matrix - Leetcode 1091 - Python
NeetCodeIO
16 Insert into a Binary Search Tree - Leetcode 701 - Python
Insert into a Binary Search Tree - Leetcode 701 - Python
NeetCodeIO
17 Delete Node in a BST - Leetcode 450 - Python
Delete Node in a BST - Leetcode 450 - Python
NeetCodeIO
18 Shuffle the Array (Constant Space) - Leetcode 1470 - Python
Shuffle the Array (Constant Space) - Leetcode 1470 - Python
NeetCodeIO
19 Fruits into Basket - Leetcode 904 - Python
Fruits into Basket - Leetcode 904 - Python
NeetCodeIO
20 Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
NeetCodeIO
21 Naming a Company - Leetcode 2306 - Python
Naming a Company - Leetcode 2306 - Python
NeetCodeIO
22 As Far from Land as Possible - Leetcode 1162 - Python
As Far from Land as Possible - Leetcode 1162 - Python
NeetCodeIO
23 Shortest Path with Alternating Colors - Leetcode 1129 - Python
Shortest Path with Alternating Colors - Leetcode 1129 - Python
NeetCodeIO
24 Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
NeetCodeIO
25 Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
NeetCodeIO
26 Contains Duplicate II - Leetcode 219 - Python
Contains Duplicate II - Leetcode 219 - Python
NeetCodeIO
27 Path with Maximum Probability - Leetcode 1514 - Python
Path with Maximum Probability - Leetcode 1514 - Python
NeetCodeIO
28 Add to Array-Form of Integer - Leetcode 989 - Python
Add to Array-Form of Integer - Leetcode 989 - Python
NeetCodeIO
29 Unique Paths II - Leetcode 63 - Python
Unique Paths II - Leetcode 63 - Python
NeetCodeIO
30 Minimum Distance between BST Nodes - Leetcode 783 - Python
Minimum Distance between BST Nodes - Leetcode 783 - Python
NeetCodeIO
31 Design Hashmap - Leetcode 706 - Python
Design Hashmap - Leetcode 706 - Python
NeetCodeIO
32 Range Sum Query Immutable - Leetcode 303 - Python
Range Sum Query Immutable - Leetcode 303 - Python
NeetCodeIO
33 Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
NeetCodeIO
34 Middle of the Linked List - Leetcode 876 - Python
Middle of the Linked List - Leetcode 876 - Python
NeetCodeIO
35 Course Schedule IV - Leetcode 1462 - Python
Course Schedule IV - Leetcode 1462 - Python
NeetCodeIO
36 Single Element in a Sorted Array - Leetcode 540 - Python
Single Element in a Sorted Array - Leetcode 540 - Python
NeetCodeIO
37 Capacity to Ship Packages - Leetcode 1011 - Python
Capacity to Ship Packages - Leetcode 1011 - Python
NeetCodeIO
38 IPO - Leetcode 502 - Python
IPO - Leetcode 502 - Python
NeetCodeIO
39 Minimize Deviation in Array - Leetcode 1675 - Python
Minimize Deviation in Array - Leetcode 1675 - Python
NeetCodeIO
40 Longest Turbulent Array - Leetcode 978 - Python
Longest Turbulent Array - Leetcode 978 - Python
NeetCodeIO
41 Last Stone Weight II - Leetcode 1049 - Python
Last Stone Weight II - Leetcode 1049 - Python
NeetCodeIO
42 Construct Quad Tree - Leetcode 427 - Python
Construct Quad Tree - Leetcode 427 - Python
NeetCodeIO
43 Find Duplicate Subtrees - Leetcode 652 - Python
Find Duplicate Subtrees - Leetcode 652 - Python
NeetCodeIO
44 Sort an Array - Leetcode 912 - Python
Sort an Array - Leetcode 912 - Python
NeetCodeIO
45 Ones and Zeroes - Leetcode 474 - Python
Ones and Zeroes - Leetcode 474 - Python
NeetCodeIO
46 Remove Duplicates from Sorted Array II - Leetcode 80 - Python
Remove Duplicates from Sorted Array II - Leetcode 80 - Python
NeetCodeIO
47 Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
NeetCodeIO
48 Concatenation of Array - Leetcode 1929 - Python
Concatenation of Array - Leetcode 1929 - Python
NeetCodeIO
49 Symmetric Tree - Leetcode 101 - Python
Symmetric Tree - Leetcode 101 - Python
NeetCodeIO
50 Check Completeness of a Binary Tree - Leetcode 958 - Python
Check Completeness of a Binary Tree - Leetcode 958 - Python
NeetCodeIO
51 Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
NeetCodeIO
52 Find Peak Element - Leetcode 162 - Python
Find Peak Element - Leetcode 162 - Python
NeetCodeIO
53 Accounts Merge - Leetcode 721 - Python
Accounts Merge - Leetcode 721 - Python
NeetCodeIO
54 Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
NeetCodeIO
55 Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
NeetCodeIO
56 Number of Zero-Filled Subarrays - Leetcode 2348 - Python
Number of Zero-Filled Subarrays - Leetcode 2348 - Python
NeetCodeIO
57 Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
NeetCodeIO
58 Sqrt(x) - Leetcode 69 - Python
Sqrt(x) - Leetcode 69 - Python
NeetCodeIO
59 Successful Pairs of Spells and Potions - Leetcode 2300 - Python
Successful Pairs of Spells and Potions - Leetcode 2300 - Python
NeetCodeIO
60 Optimal Partition of String - Leetcode 2405 - Python
Optimal Partition of String - Leetcode 2405 - Python
NeetCodeIO

This video teaches how to solve Leetcode problem 2028 by finding missing observations in a set of dice rolls. The solution uses a greedy approach with a twist and validates the sum, resulting in an efficient solution with a time complexity of O(m + n) and space complexity of O(1).

Key Takeaways
  1. Calculate the mean of the given rolls
  2. Multiply the mean by the total number of rolls to find the total sum
  3. Subtract the sum of the given rolls from the total sum to find the missing sum
  4. Distribute the missing sum among n different slots
  5. Validate the sum by checking if it's less than or equal to 6n and greater than or equal to n
  6. Use a greedy approach to add the maximum value to each slot
  7. Make sure that the remaining sum is enough to fill the remaining slots
💡 The pigeon hole principle can be used to solve the problem of distributing a sum among n slots, and a greedy approach with a twist can be used to find the missing observations.

Related Reads

📰
The Run-Length Encoding Trick: How Simple Strings Get Compressed
Learn how Run-Length Encoding (RLE) compresses simple strings, a fundamental technique in programming and data compression, and apply it to optimize storage and transmission of data
Medium · Programming
📰
75 Days of Leetcode — Day 4: #238 — Product of Array Except Self
Solve the Product of Array Except Self problem on LeetCode to improve coding skills and learn array manipulation techniques
Medium · AI
📰
I implemented the algorithm that broke the sorting barrier. Dijkstra still wins.
Learn how the author implemented an algorithm that broke the sorting barrier and compare its performance with Dijkstra's algorithm
Medium · Programming
📰
I implemented the algorithm that broke the sorting barrier. Dijkstra still wins.
Implementing an algorithm that breaks the sorting barrier still can't beat Dijkstra's algorithm in practice, highlighting the importance of real-world testing and optimization.
Medium · Python

Chapters (3)

Read the problem
0:30 Drawing Explanation
8:47 Coding Explanation
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →