id
int64 1
2k
| content
stringlengths 272
88.9k
| title
stringlengths 3
77
| title_slug
stringlengths 3
79
| question_content
stringlengths 230
5k
| question_hints
stringclasses 695
values | tag
stringclasses 618
values | level
stringclasses 3
values | similar_question_ids
stringclasses 822
values |
---|---|---|---|---|---|---|---|---|
468 |
Loot Hello Everybody Welcome To My Channel Today Is The 69 Jun Recording And Problems Validate IP Address To Write The Function Which Is Very Important In This Way Before It Special Dress On The To Fry Also Folder Condition Se 1000K Not Represented S E No Tension Which Consists of Decimal Number Running From 25 subscribe to the Page if you liked The Video then subscribe to The Amazing College Pass Previous Song Again Valid IP Address All To Be Good To Make Sum Leading Zero Is Decimal Digit And Lower Case Characters Interpress On Twitter एक पिक्सिक वी0 दे 0 Interpress On Twitter एक पिक्सिक वी0 दे 0 Interpress On Twitter एक पिक्सिक वी0 दे 0 FROM दिस 08 subscribe Video then subscribe to the Page if you liked The Video then subscribe to The Amazing Cheez Bhilai Ka TV Friends But I Didn't Been Posted As Tourist Places 520 Tours Away From Subscribe Problem Number To The Number 90 Problem Solve this problem with basic approach to what would be a text window will divide this problem increase segment one in this content dot solid my for ipv4 morning check and itv char validation effect content call and endangered pv6 runs otherwise neer wait for It will be considered subscribe validation in just 120 days the student absolutely group plain group lines is creator and not equal to for basically integrator always chant for which means its snow deposit is not a valid id not valid notes will proceed from group in a Sweet Pick Group Banwai One In First Mirch Ek Is The Length Of The First Is Line Length Of The Group From The Group A Better Than Free Liye Zameen Se Zameen To Check Is Effigy Group First Character 0404 Why Is This Group Who 0404 Why Is This Group Who 0404 Why Is This Group Who Is Not equal to one pinch means middling against number two third shares were sold Contents for all BT and only number to the number 210 [ to the number 210 [ to the number 210 that sex verification page no record to 500 to rooms for ipv4 validations loop news18 6 quarter 6 To Do Subscribe My Channel Subscribe To Notice Paltu Uth Services Otherwise Media Group Suna-Suna Another Way Can Go For This Group Suna-Suna Another Way Can Go For This Group Suna-Suna Another Way Can Go For This Group Has Been Created For Validation Of First 1504 2004 Return Forms For ISRO And This Video Channel Subscribe 0 Number 66 Ki NRHM Italy B C D E F G Member Anil Amla Objects Validated Teaching Dress Students This is Approach Let's Start Mediation Center for Implementation Switch to Active Back String Contain Dots and Boys Liquid String Contain A and It's Content 200 Feet Content Two Columns Bride Meanwhile Means and Tablets IP Address in This Village Simply Return on Equity is Neervi on the To-Do List Return on Equity is Neervi on the To-Do List Return on Equity is Neervi on the To-Do List That You Turning Descendants Confirm Dance 24 Look for the Richest Country Only Contents Don't Know What is the Means of the Year Will Click On [ Sangeet] 200 gr aka but it didn't speak subscribe and subscribe the Channel Please subscribe and subscirbe is group no veer we will go in the subscribe to hussain group a 200 billion points us naav first validation mintu for the length is group dance request 204 And That Group Don't Like This Great Dane Free Leaves Means Nishan Hai To Return With The Na One Speed Videsh Will Check Difficult One Speed Videsh Will Check Difficult One Speed Videsh Will Check Difficult 10 10 All my dear red chilli one is divine correct takla supporter is digit myth plus seervi group will used jauhar for group d and conditioner itv 4 9 we will do for politicians and this is a p dot sentence jhal in chief dresses ped jaundice and subscribe must Subscribe to 320GB attempts 12345 sez pe listener subscribe Video string group me and listen first female wendi deng and you is ireland request 204 group a loot that his great dane char send it to log in return me the and will look for each character products In the group also C group-2 products In the group also C group-2 products In the group also C group-2 par are oh that is yes index of history dot inducts of C is equal to - 121 will return of C is equal to - 121 will return of C is equal to - 121 will return starring the other wise Indian below return IPv2 2069 I have also been that this condition is not correct normal At C Ko Check Daughter Compilation Of Power Chord That You History Dot Index Of Which Acts Of Can Not Be Different From Student Of Similar Between The Porn Intakes Home Student Tweet - Screen Dance Song Non Student Tweet - Screen Dance Song Non Student Tweet - Screen Dance Song Non Stick Me Than Nine Types Of Train No Different From String content so spring dot a souvenir singh character daughter shop ok sir english b Find ready standing share 1613 e 162 bane is desh hai a silent compiled a aap ki grading correct answer flat submit ki akho special ki return nida no this letters ki great kar denge husan ipv4 ki great kar denge husan ipv4 ki great kar denge husan ipv4 ko output is ipv4 wishes from rate parts In The Scripters In The State Between 258 A New Good Porn Time Complexity Of This Like Base Plate A Good Thing With Which Can Not The Character 100 Fine Thank You Feel Like In Video Fluid Turn On The Light
|
Validate IP Address
|
validate-ip-address
|
Given a string `queryIP`, return `"IPv4 "` if IP is a valid IPv4 address, `"IPv6 "` if IP is a valid IPv6 address or `"Neither "` if IP is not a correct IP of any type.
**A valid IPv4** address is an IP in the form `"x1.x2.x3.x4 "` where `0 <= xi <= 255` and `xi` **cannot contain** leading zeros. For example, `"192.168.1.1 "` and `"192.168.1.0 "` are valid IPv4 addresses while `"192.168.01.1 "`, `"192.168.1.00 "`, and `"[email protected] "` are invalid IPv4 addresses.
**A valid IPv6** address is an IP in the form `"x1:x2:x3:x4:x5:x6:x7:x8 "` where:
* `1 <= xi.length <= 4`
* `xi` is a **hexadecimal string** which may contain digits, lowercase English letter (`'a'` to `'f'`) and upper-case English letters (`'A'` to `'F'`).
* Leading zeros are allowed in `xi`.
For example, "`2001:0db8:85a3:0000:0000:8a2e:0370:7334 "` and "`2001:db8:85a3:0:0:8A2E:0370:7334 "` are valid IPv6 addresses, while "`2001:0db8:85a3::8A2E:037j:7334 "` and "`02001:0db8:85a3:0000:0000:8a2e:0370:7334 "` are invalid IPv6 addresses.
**Example 1:**
**Input:** queryIP = "172.16.254.1 "
**Output:** "IPv4 "
**Explanation:** This is a valid IPv4 address, return "IPv4 ".
**Example 2:**
**Input:** queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334 "
**Output:** "IPv6 "
**Explanation:** This is a valid IPv6 address, return "IPv6 ".
**Example 3:**
**Input:** queryIP = "256.256.256.256 "
**Output:** "Neither "
**Explanation:** This is neither a IPv4 address nor a IPv6 address.
**Constraints:**
* `queryIP` consists only of English letters, digits and the characters `'.'` and `':'`.
| null |
String
|
Medium
|
752
|
1,357 |
today we're gonna look at li code 1357 apply discounts every n orders so this is a novel to read through and it's not the best English but we'll work through it so let's start with the description there is a sale and a supermarket there will be a discount every n customers there are some products in the supermarket where the idea of the eighth product is products I and the price per unit of that product is prices I and it says the system will count the number of customers so it's gonna keep track of how many customers we've hit and when the nth customer arrives they will receive a discount on the bill and they give that formula therefore the discounted bill so X would be the final bill price and this would be the discounted bill price and then it says it resets the counter and it starts counting customers again so it says the customer orders will contain certain amount of each product or product I is the ID of the product the customer ordered and amount I is the number of units the customer ordered of that product and it says implement the class so we're given a constructor that's going to be 10 of our initializer we're going to be saving all this information and the counter is well to keep track of how many customers we have and then they're gonna call this function here get bill over and over again so there's these sort of system design questions the examples are very tough to read through you can't really get much out of them I'd recommend just repeating the description until you have a better grasp of it let's look at the constraints so in the number of customers per discount is a relatively small number 10 to the 4 the discount itself is pretty small as well we don't have to worry about crazy sizes the number of products is small the IDS themselves that's this one here the IDS are pretty small 1 to 200 you're not worried about overflows or anything on that there's no repeated elements so that's is like a corner case so the majority of these constraints are like edge cases that you should be thinking about and asking and the interviews so like ok we're giving a products array alright are there repetitions is there gonna be could it be null could it be empty do products and prices have the same length that's something we could validate against too and we see here prices dot length equals products that link so that's basically saying no you don't need to check that's already given so basically it's a pretty safe problem there's not much edge casing or validation that we need to do here and there's not really worrying about overflows here this last one here whenever you see something like this within X amount of the actual value will be accepted as correct that's just because we're gonna be using floats right we have some division here whenever you have a division you may get a decimal result right you might not get an integer so that's all that one's saying ok so let's copy these over break them over let's work on just designing cashier first so what do we need to keep track of n the number of customers per discount so n is an integer we don't do that we need to keep track of the discount amount which is also an integer and let's think about this so we do need to keep track of what products and their prices that were given so they give us a an array of products and an array of prices so the products this array is an array of ID's here so it's like this I don't think of it like this so you have your products let's just say that's this array one two three so these are IDs this is an array of ID's and what it's saying is you also have prices and this is an array of doll think of it as the dollar cost of each of the products here so for example the product with ID one two three as the cost of fifty five the product with the IDE five by five has a cost of 12 and so on so I'm just off the bat I'm seeing a hashmap is a good way to keep track of these so on going we can toss that in so I'll call it price map and we're gonna say that's a map of integers and so it's a map with integer keys and energy values so the product IDs themselves have our integers they're only integers and the prices themselves are only integers so that's why we do that's where we choose this map this Maps kind of like product ID and that map's to the price product price okay so that's kind of what's going on here so we give it the key which is the ID and we get the price back oh this is gonna be useful later okay is there anything else we need to keep track of here products prices okay we need to keep a running count of the customer of the customers right see here the system will count the number of customers and then the system will start counting customers again so we have to have a customer count tracker basically and that's just an integer and this is like a running count of how many customers so when we hit in our customer count that's when we'd apply the discount and then we set this back okay so let's say C is cashier object let's fill the fields so n is just whatever they give us here and the discount is gonna be just whatever discounts passed in so products okay so this one let's leave let's just initialize this but let's oh no all right so let's just leave that alone customer count that's fine let's just have that start at zero okay so now we have this and let's return it at the end all right so there's everything's happy now we just need to initialize our price map so we need to go through the products and we need to map them to their prices so let's say for I V and range products and let's say C dot price map see that price map and we'll get the key which is the value and it's equal to the amount or the price is at that index okay so this is totally the same as well as this these are equivalent statements this is the key the Product ID here the product ID is that product I and the price for that product ID is at prices I'm just choosing to use this value here just because it's less characters so we'll go with that okay um that's good okay so I'm happy the constructor for now that should be in good shape so let's move on to the get bill okay so they're gonna call this repeatedly and basically we need to return a bill so let's make some bill and let's set it to zero and let's return it all right so that's the simple life there so what we're given here is a list of products so when we call get bill it's on one customer just one customer okay so we need to be keeping track of the customer count as well so what we can say is if our customer count we access it by seed customer count and we could say if it's equal to CN minus one because we're starting at zero customer count starts at zero so you always need to have that minus one everything with that then we want to apply our discount so let's see what's the discount formula bill is Bill - seedot we need the bill is Bill - seedot we need the bill is Bill - seedot we need the discount and let's put that as a float discount times the bill divided by 100 okay so that's the discounted bill yeah that's the discounted bill there and then we could say we need to reset our customer count as well so see that customer count is one okay so that's the case if we've hit the right amount of customers then we're gonna apply our discount and reset the customer count otherwise we're not gonna do we're not gonna worry about that discount okay so let's get the let's set up the bill here so we want to go through each product let's say we just have one product right so it would be that Product ID would use the product ID we would use C dot price map with that product ID so 1 2 3 for example and then if we just had one of those products that we're buying we'd multiply it by 1 right but what if we have 5 3 or 2 so that's where the amounts array comes in handy so let's iterate through our products for this customer and let's say bill you can just say plus equals and we're gonna say our price map with the key times the amount at that index okay and this won't like it because this is gonna be integers so let's say float so amount is an integer and our price map is also just a bunch of integers so we need to convert that to a float okay so this increases our bill here and we can run that all the way through that's good and then this here checks if our customer count is the correct number here so let's see let's think about this so we want to reset customer count to zero otherwise we just want to increment it so if we should apply our discount what this is checking is okay should I apply my discount if so update our bill and then reset our customer count otherwise we don't want we're not applying this discount so we just want to increment our customer count and then at the end we're returning that bill so let's bring this over I think that's in a good State and this would not be surprised if we get some errors here let's see okay so that did get accepted okay so the main part let's just walk through this gate bill I think the constructors relatively straightforward they're giving you information here you're storing it and instruct that we designed to store that information but let's walk through this gate bill one more time here so we start out with a bill just empty this right here what the work we're doing here is we are basically initializing our bill we're saying for every product that the customer is going to buy we need to add the cost of that product times the amount that we're buying to the bill okay so after we've built up our bill we've got the final bill then we go down here to the customer account we need to check okay have we reached enough customers that we start discounting here so the system will count the number of customers and when the end customer arrives they'll have a discount so basically we're saying okay have we hit the end customer and the reason we have n minus 1 here is just because we chose to start with zero yeah we chose to start with zero up here that's just preference so if we do have the nth customer they're arriving okay that means we need to update our bill and we need to use the formula they gave us right here so X is just the cost that's just the bill and this is just following that formula they gave us and in that case we reset because it says then the system will start counting customers again so we start over and we start counting from zero again otherwise we haven't reached the nth customer so we just increment our customer cap and then finally we're just returning the bill so that's one more time double check it and accidentally change anything here and then we'll try submitting and let's think about the complexity for this here this is just a single loop going on here so this is basically just oh in time complexity the Constructors the same basically it's Owen however many products we have that's our n in this case so just Oliv in there the constructor and just oh of n here on the get bill call and for these system design questions I'm not sure if they're gonna ask about space complexity but we can just think about okay we are taking up we are using cashier struct and what space are we taking up well however many products we are however many products we have we're gonna have an entry in price map so it's basically Bo in as well for this whole system so x Owen and space is Owen as well and that is luke code 1357 apply discounts every N or
|
Apply Discount Every n Orders
|
report-contiguous-dates
|
There is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays `products` and `prices`, where the `ith` product has an ID of `products[i]` and a price of `prices[i]`.
When a customer is paying, their bill is represented as two parallel integer arrays `product` and `amount`, where the `jth` product they purchased has an ID of `product[j]`, and `amount[j]` is how much of the product they bought. Their subtotal is calculated as the sum of each `amount[j] * (price of the jth product)`.
The supermarket decided to have a sale. Every `nth` customer paying for their groceries will be given a **percentage discount**. The discount amount is given by `discount`, where they will be given `discount` percent off their subtotal. More formally, if their subtotal is `bill`, then they would actually pay `bill * ((100 - discount) / 100)`.
Implement the `Cashier` class:
* `Cashier(int n, int discount, int[] products, int[] prices)` Initializes the object with `n`, the `discount`, and the `products` and their `prices`.
* `double getBill(int[] product, int[] amount)` Returns the final total of the bill with the discount applied (if any). Answers within `10-5` of the actual value will be accepted.
**Example 1:**
**Input**
\[ "Cashier ", "getBill ", "getBill ", "getBill ", "getBill ", "getBill ", "getBill ", "getBill "\]
\[\[3,50,\[1,2,3,4,5,6,7\],\[100,200,300,400,300,200,100\]\],\[\[1,2\],\[1,2\]\],\[\[3,7\],\[10,10\]\],\[\[1,2,3,4,5,6,7\],\[1,1,1,1,1,1,1\]\],\[\[4\],\[10\]\],\[\[7,3\],\[10,10\]\],\[\[7,5,3,1,6,4,2\],\[10,10,10,9,9,9,7\]\],\[\[2,3,5\],\[5,3,2\]\]\]
**Output**
\[null,500.0,4000.0,800.0,4000.0,4000.0,7350.0,2500.0\]
**Explanation**
Cashier cashier = new Cashier(3,50,\[1,2,3,4,5,6,7\],\[100,200,300,400,300,200,100\]);
cashier.getBill(\[1,2\],\[1,2\]); // return 500.0. 1st customer, no discount.
// bill = 1 \* 100 + 2 \* 200 = 500.
cashier.getBill(\[3,7\],\[10,10\]); // return 4000.0. 2nd customer, no discount.
// bill = 10 \* 300 + 10 \* 100 = 4000.
cashier.getBill(\[1,2,3,4,5,6,7\],\[1,1,1,1,1,1,1\]); // return 800.0. 3rd customer, 50% discount.
// Original bill = 1600
// Actual bill = 1600 \* ((100 - 50) / 100) = 800.
cashier.getBill(\[4\],\[10\]); // return 4000.0. 4th customer, no discount.
cashier.getBill(\[7,3\],\[10,10\]); // return 4000.0. 5th customer, no discount.
cashier.getBill(\[7,5,3,1,6,4,2\],\[10,10,10,9,9,9,7\]); // return 7350.0. 6th customer, 50% discount.
// Original bill = 14700, but with
// Actual bill = 14700 \* ((100 - 50) / 100) = 7350.
cashier.getBill(\[2,3,5\],\[5,3,2\]); // return 2500.0. 6th customer, no discount.
**Constraints:**
* `1 <= n <= 104`
* `0 <= discount <= 100`
* `1 <= products.length <= 200`
* `prices.length == products.length`
* `1 <= products[i] <= 200`
* `1 <= prices[i] <= 1000`
* The elements in `products` are **unique**.
* `1 <= product.length <= products.length`
* `amount.length == product.length`
* `product[j]` exists in `products`.
* `1 <= amount[j] <= 1000`
* The elements of `product` are **unique**.
* At most `1000` calls will be made to `getBill`.
* Answers within `10-5` of the actual value will be accepted.
| null |
Database
|
Hard
|
1420,1759
|
301 |
hello friends today let's also remove invalid parentheses problem this is a very nice classic problem the reason i want to explain it is that i want to introduce a very useful website i think it will help you to understand the function calling and the operation order in java which is the java visualization visualizer i will attach the link below okay so now let's see the problem statement remove the minimum number of invalid parentheses in order to make the input string valid return all possible results and we should notice the note that the input string may contain letters other than the parentheses so for this example we just keep this a as it is so we can see some hints which is return all possible results that means we can only use brute force or backtracking because we needed to generate all the possible results uh the hard part is that we should first know the what is the minimum number of the invalid parentheses then i we can generate all the possible results and we can see the example for this example we can either remove these close parentheses and this close parenthesis the result is the same just this one but we cannot generate these two i mean we cannot return these two results we can only return one because technically these two are the same so we need to avoid the duplicated results this is one hard part another part is that i think okay let's recall when we solve some problem related to parentheses we can usually use a stack when we meet the open parenthesis we push that character into the stack when we meet the close parentheses we just pop the previous character from the stack but in this case we can sometimes we can also use the integer we can call it counter when we meet the open parenthesis we let the counter increment by one when we close parenthesis we make the um counter decrement by one so for this problem we also use that culture so obviously we need to iterate this string once we just count these parentheses but one thing you should note is that if we meet to an open parenthesis we cannot say it is invalid we need to see the rest apart but if we know currently the closed parenthesis is more than open parenthesis we know it is already invalid so we need to remove redundant close parenthesis so that's the whole point actually when we if we use a pointer start from zero when we arrive here we know it is already invalid we need at least to remove one closed parenthesis so that's the whole idea so when do we know we should stop here that is the stack is already less than zero so once the stack is we call this counter stack when this stack is less than zero we just stop and then we should try to remove these closed parentheses so we need another thing if the stack less than zero we should keep this point here so that means we need a second pointer same point pointer start from the zero to this place we meet this close parenthesis uh parenthesis we just remove it and uh call the whatever function again because we need a recursively to check the rest part okay that's the whole point but you can see we can either remove this closed parenthesis or this close parenthesis but we cannot remove this because if we remove this it will generate a duplicate result so how do we avoid this one i think this part is the same at what we do for the three sound problem once the current character is the same as the previous character we just continue so that's the same idea okay but if what if we do not meet this stack less than zero oh we finish the iteration the first iteration the stack is greater than zero that means we can just uh sync um reversely that means the left the open process is greater than the closed parenthesis we can just switch this to character that means we reverse this string and we also change a switch the open parenthesis and the close parenthesis so this is the beauty of this solution uh thanks for the discussion the first person i learned from this result okay let's continue uh okay if in our case the stark is just a zero that means current string is a result we just add it to the result list uh one thing you need to be careful is the order if current open and close parenthesis is the normal order we just add it to result otherwise we also need to reverse this string okay so i think it should be clear to you what the solution is let's write the code and in the end we will see the visualization okay first we need a result we call it array list and we use a help function it's quite normal we usually call it help function we need the string and we need the two pointers one is from zero and that is also from zero result and as we need to know what is open parenthesis and the closed parenthesis so we would better just surpass it as a array and we return this result let's write this help function pressing the string left right two pointers and that is the result we also need a parenthesis chart so we need a stack start from zero and first we need to move this right pointer to see whether at some time the closed parenthesis is greater than the number of the open parenthesis so right less than i'd like to write which is starlance an underwriter increment by one we get a current chart which is s chart at right if this chart equal to the parenthesis zero which is an open parenthesis then stack increment by one else if c a current charge is parenthesis one we get a stack decrement by one once the stack is less than zero we just break okay so now we are here because we do not always be the stack less than zero maybe stack is just greater than zero all the characters are open presses for example we still need to check if it's less than zero it's a that means we need to remove one close parenthesis so we also need a we move this left we keep the right like here we need to move the left so left equal then write letter increment by one we can see okay right here c equal to s chart at we needed to remove the closed parenthesis so if this chart not equal to the closed parenthesis we just continue so if c not equal to parenthesis one we just continue next we need to remove the duplicate avoid the duplicate so if left greater than zero and s char left equal to s chart add to left or minus one and just continue otherwise we need to remove current character we needed to call this function recursively but the new string what that or what it will be two parts will remove current charge so the substring from zero to left because the this part is exclusive so plus s substring from left plus one do not need to write the second parameters because uh by default in default it is till the end okay so now this is left why does dominator be left plus one because we already removed that character so the current place is original strings left plus one so this is left not left plus one okay right and the result in the pairs not needed to reverse this order else if the stack greater than zero if it's greater than zero we just need to reverse the order how to get the string reverse we need to first convert it to stream builder because stream builder have this function reverse then we convert it to string place is still 0 because if we arrive here that means um all the string should be treated reversely so it's zero and the result this part you should know the parenthesis order has changed so it's close open okay else we just added string to the result but you should first check um if parenthesis 0 equal to the close uh open that means it is the normal order so we just add as if it's reverse order we should add the reversed string so the same we knew converted we build a new stream builder and we reverse it and then we convert it to stream okay yep i think we finished okay let's see the java visualization this uh i think this website is quite good because you can see it's just good this is the example string okay so first they run the main function then they run this remove invalid parentheses and then they call this help function it's just like stack when you call a new function it put it on top of this stack okay you can see the change of the oh sorry change of these uh variables already this system outprint uh current string is what so here just move this right pointer you can see the stack is changed it just do this for loop and once this stack is less than zero when the right is equal to four the stack is there is negative one so it uh break now we are here stack is less than zero we move this left forward we only remove it when the current character is equal to close parenthesis and we remove that we call it help function again so this is the new help function current string is you can see this one because we remove this character and then do the same thing okay but you should notice that next time the this function the right is still i think it's still five um right is five because we need to remove this right left and not change but we move this right forward okay so we find the stack equal to zero because right only move two places from two five two six okay then we go to this part is equal to zero and we check the order it's the normal order so we add the current string to the result which is this one is valid okay and we pop that help function we go here again then we move this left and we find another valid um string which is this one okay so i think you can finish this visualization afterwards i will put this link below okay thank you for watching see you next time
|
Remove Invalid Parentheses
|
remove-invalid-parentheses
|
Given a string `s` that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.
Return _a list of **unique strings** that are valid with the minimum number of removals_. You may return the answer in **any order**.
**Example 1:**
**Input:** s = "()())() "
**Output:** \[ "(())() ", "()()() "\]
**Example 2:**
**Input:** s = "(a)())() "
**Output:** \[ "(a())() ", "(a)()() "\]
**Example 3:**
**Input:** s = ")( "
**Output:** \[ " "\]
**Constraints:**
* `1 <= s.length <= 25`
* `s` consists of lowercase English letters and parentheses `'('` and `')'`.
* There will be at most `20` parentheses in `s`.
|
Since we don't know which of the brackets can possibly be removed, we try out all the options! We can use recursion to try out all possibilities for the given expression. For each of the brackets, we have 2 options:
We keep the bracket and add it to the expression that we are building on the fly during recursion.
OR, we can discard the bracket and move on. The one thing all these valid expressions have in common is that they will all be of the same length i.e. as compared to the original expression, all of these expressions will have the same number of characters removed.
Can we somehow find the number of misplaced parentheses and use it in our solution? For every left parenthesis, we should have a corresponding right parenthesis. We can make use of two counters which keep track of misplaced left and right parenthesis and in one iteration we can find out these two values.
0 1 2 3 4 5 6 7
( ) ) ) ( ( ( )
i = 0, left = 1, right = 0
i = 1, left = 0, right = 0
i = 2, left = 0, right = 1
i = 3, left = 0, right = 2
i = 4, left = 1, right = 2
i = 5, left = 2, right = 2
i = 6, left = 3, right = 2
i = 7, left = 2, right = 2
We have 2 misplaced left and 2 misplaced right parentheses. We found out that the exact number of left and right parenthesis that has to be removed to get a valid expression. So, e.g. in a 1000 parentheses string, if there are 2 misplaced left and 2 misplaced right parentheses, after we are done discarding 2 left and 2 right parentheses, we will have only one option per remaining character in the expression i.e. to consider them. We can't discard them.
|
String,Backtracking,Breadth-First Search
|
Hard
|
20,2095
|
507 |
so we're looking at question 507 uh perfect number um so let's just go through the question we define the perfect number as a positive integer that is equal to the sum of all of its positive divisors except itself now give it an integer and write a function that returns true when it is per i mean it is a perfect number and false when it is not so um when you see the example here 28 it has these divisors 1 2 4 7 14 and the other divisor would be 28 but the question here is to sum up all of its positive divisors except itself so when you add all of this you get 28 so the solution would be divided into two parts first part would be getting all the divisors of a particular number and then adding them up to see if um see if it adds up to num so let's get started so the base case would be if num is equal to one you would just return true and move down true and then let's say in sum is equal to um zero and then you would want to go over all of the divisors so you would start with n i uh and i is equal to two i is less than um my dot square root of num um i plus so you would say if um num summation and automation uh mod i is equal to zero then you would uh what would you do you would add i and you would add the other divisor as well i'm divided by all right so the reason why you're doing square root is that once you do um once you get i you can also get the other divisor that you need to get the number so um this way we're just reducing our calculations um yeah and then you would in the end just return if num is equal to sum uh and the other thing we need to do is actually we need to initialize this to one because we're starting this by two uh so that we don't get one plus twenty eight so this way we're adding one and then starting with two perfect let's just run um one is true hmm i guess oh i'll put expected false i don't know why that's false but okay cool um yeah so the space complexity would be of one because we're not really uh saving anything uh constantly we just have one variable which is the sum and then the uh time well let me know if you have any questions um all right
|
Perfect Number
|
perfect-number
|
A [**perfect number**](https://en.wikipedia.org/wiki/Perfect_number) is a **positive integer** that is equal to the sum of its **positive divisors**, excluding the number itself. A **divisor** of an integer `x` is an integer that can divide `x` evenly.
Given an integer `n`, return `true` _if_ `n` _is a perfect number, otherwise return_ `false`.
**Example 1:**
**Input:** num = 28
**Output:** true
**Explanation:** 28 = 1 + 2 + 4 + 7 + 14
1, 2, 4, 7, and 14 are all divisors of 28.
**Example 2:**
**Input:** num = 7
**Output:** false
**Constraints:**
* `1 <= num <= 108`
| null |
Math
|
Easy
|
728
|
117 |
to look at a legal problem called populating nests right pointers in each node so i did the first question liko 116 in the beginner's bfs video in that video i basically talked about how to solve that problem using breadth first search or a level or traversal this question basically is a little different compared to that question or the first question because in this question we're not given a perfect binder tree right basically perfect binary tree means that for each and every single node we either have two children or we don't have any children at all right for each and every single node but for this tree it's not a perfect binder tree right you can see that this tree this note right here has a right child but does not have a left child right or there could be a situation where we have no child at all we're just or just two children right so in this case um this is not a perfect binary tree right so you can see here that um we basically want to um traverse this tree right and we want to get each and every single notes the next pointer points to the adjacent node right so it's still the same as the previous question right but the thing is that we're not dealing with perfect uh perfect binary tree anymore and the question is that we want to use a constant space complexity to solve this problem so you can see that this in this case this example right here you can see we get each and every single nodes right in this case the nest pointer points to the adjacent node right no 2.03 adjacent node right no 2.03 adjacent node right no 2.03 no 4.05 no 5.07 no 4.05 no 5.07 no 4.05 no 5.07 and you can see that we can have uh we're guaranteed that we're going to have a tree right with less than six thousands of nodes right so there could be a situation where we have no nodes at all right so how can we be able to solve this problem well to solve this problem what we can do is we can do the same thing that we did in the previous question but the previous implementation we're using level or traversal right we're using a queue to get all the elements that we're going to traverse right all the nodes that we're going to traverse onto a queue so that we just traverse that level by level right but the thing is that will not give us a constant time a constant space complexity so to do this using a constant space complexity what we have to do is we have to use pointers right we have to use pointers to uh build our list or in this case try to connect the uh each and every single level using pointers right so how can we do that using pointers well if we think about it for this node if i want to connect um the children right in this case what i can do is that i basically have to build a linked list right to build linked lists we can just use the pointers to point these notes points to the next node right and what we can do is we can have a dummy node right here let's say we're because we know the root level there's no right pointer right there's no adjacent node so we don't have to do anything for the root level but for the children level what we can do is we can have a dummy node and initially we're going to have a temp variable points to the dummy node and then what's going to happen is that if the current or the head node which is the root current root right um if the head node has a left child right which is which it does we're gonna get temp is gonna point to so temp dot nest is point two node two right um so that we get dummy node points to node two and then what's gonna happen is that we're gonna get temp is equal to temp dot nest so then we check to see if current the head node has a right child in this case it does then what's gonna happen is we're gonna continue to build a list right notice that this temp pointer is kind of like a pointer that basically builds built the connection right for the nest level right and then what's going to happen is that we're just going to get uh temp is point to node 3 in this case node 2 is pointing to node 3 now right and then what's going to happen is in this case uh we're going to um get the head node right now we've successfully built this current um subtree right in this case this kind of like this small subtree and then what's going to happen is we're going to get we'll move the head to the json node in this case head.ness to the json node in this case head.ness to the json node in this case head.ness is null so we know the head.ness is null so in so we know the head.ness is null so in so we know the head.ness is null so in this case what's going to happen is we're going to move on to the next level right because we already complete this level already right so we want to move on to next level and the next level how can we get it in this case it's basically dummy.ness right we already have a dummy.ness right we already have a dummy.ness right we already have a variable stores so it's just no two so stores so it's just no two so stores so it's just no two so in this case we're just going to build the nest subtree in this case we have dummy which is have a dummy uh in this case we're going to have temp point dummy down uh temp dot nest as you go to uh check to see if the head right and this is our new head now right let's have a let's write the head so we have our head right and this head is pointing to note2 and we have no uh this temp variable right this temp variable uh you can see we're gonna point to node four right because no 2 does have a left child so we're going to have temp is equal to temp dot nest right so which is no 4 and no 4 in this case we check to see if the head node has a right child in this case the head node does have a right child so we're just going to get temp is equal to head dot right so which is no five right and we of course we're going to say temp dot ness is you know head dot right and then temp dot attempt is equal to 10. which is no five and then what's going to happen is we already complete this subtree right this small subtree then we're just gonna get we're just going to move on to the adjacent node right which is node three so what's gonna happen is we already successfully traversed that so we're gonna get head is equal to head.nest which is basically is equal to head.nest which is basically is equal to head.nest which is basically node three right we already formed this connection the previous level right so now we're just going to move on to the json node and then uh trying to build our list from there right try to build our linked list so now we have no three and notice that temp is still pointing to node five right so in this case what's going to happen is we're just gonna get uh node three right we check node three this is our new head so head dot nest or hit the left is basically no okay so we don't do anything so head dot right is not null so we're gonna get temp right in this case temp we're gonna get temp is dot nest is equal to uh head.right and then temp now should uh head.right and then temp now should uh head.right and then temp now should point to the in this case right temp dot nest is equal to head.right and temp dot nest is equal to head.right and temp dot nest is equal to head.right and then temp is equal to head.right which is no7 and is equal to head.right which is no7 and is equal to head.right which is no7 and then we know that this is like the end so we're just going to get head is equal to head dot nest which is kind of like a null value so we're just going to uh move on to the next level right we know how to do that already like just what we did so we just get we're just going to say head is equal to dummy.nest which is head is equal to dummy.nest which is head is equal to dummy.nest which is basically no four right we basically traversing its nest level right so this is how we basically use pointers to traverse um to traverse the tree right we basically just forming uh we're just gonna going to build our linked list right basically we're just going to build our linked list using a dummy variable and a temp variable right and this temp variable basically um forms that connection build the list and then once we done uh traversing the entire level we're just gonna get head uh this head variable points to the next level right which is dummy.nest right level right which is dummy.nest right level right which is dummy.nest right so let's take a look at how we can do this in code basically it's pretty simple um you can see we have a dummy variable right for each and every single iteration uh we're going to say temp is equal to dummy so like i said we build the link list for our current level um in this case we check to see if head dot left does not equal null if it is we're just going to say temp dot nest which is before initially we're going to have temp is equal to dummy right so temp dot nest is equal to nest uh is equal to head dot left temp is equal to right so in temp is equal to right so in temp is equal to right so in this case we're getting temp is set to the next adjacent node um and then we also check to see if the current head our right does not equal null if it's not null we just going to form that connection as well and get the temp is pointing to the next adjacent node and then you can see that after we do the left we do the right we get head is equal to right we get head is equal to right we get head is equal to right because in this case previous level we already formed that connection but then if the head is null right if there's no more node that's the current node's pointing to right so in this case what we're going to do is we're going to break this loop and once we break the loop we want to traverse the or in this case we want to start from the next level right so we're going to get head is equal to dummy.nest okay get head is equal to dummy.nest okay get head is equal to dummy.nest okay and then in this case what's going to happen is that for nest iteration we same thing we check to see if head is does not equal null right and then in this case we um do the same thing right so we create a dummy we have a we have temp is equal to the dummy right and do the same thing right and at the end we basically return the root which is the head node uh which is sorry yeah which is the root note of the tree right so basically you can see this is how we solve this problem uh using well the space complexity in this case is going to be big o of one right which is constant space complexity and the time complexity in this case is going to be big o of n right so linear time complexity for this algorithm so there you have it and thank you for watching
|
Populating Next Right Pointers in Each Node II
|
populating-next-right-pointers-in-each-node-ii
|
Given a binary tree
struct Node {
int val;
Node \*left;
Node \*right;
Node \*next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`.
Initially, all next pointers are set to `NULL`.
**Example 1:**
**Input:** root = \[1,2,3,4,5,null,7\]
**Output:** \[1,#,2,3,#,4,5,7,#\]
**Explanation:** Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 6000]`.
* `-100 <= Node.val <= 100`
**Follow-up:**
* You may only use constant extra space.
* The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
| null |
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
116
|
354 |
okay 354 Russian doll emblems you have a number of emblems with Griffin Heights given as pair of integers wh-wha number of can fill into another wh-wha number of can fill into another wh-wha number of can fill into another if and only if both the width and height of one ever loop is created anywhere for my general what is the maximum that were members can you wash and door rotation is now okay one thing I was saying is I would really love to know what n is but it's fine okay I mean I but I think this is what they call it longest path in a dag and you could draw it like if you think about in the graph Tom you could draw a lot a directed line from a node which contains W and H to another node if and only if it fits inside that node way and then with dad you get a dag because there's no psychos because there's no way you know if we never would be smooth and physically small they're not a Bueller there's no way to you know make a bigger envelope or like you know what I mean like there's no cycle because you get it was smaller than envelope then the transitive probably will always hold and like there's no real way to be like okay this mini envelope somehow can hold a big ramen okay and it's in this case so gaved directed graph and it's a sink lin and you want the maximum number of emblems which is just the longest path on that dag yeah and there's a standard n square algorithm again maybe but I'm going to just do the N square one yeah which having a standard issue I'll type it out so one posto try solving but let me know if you have any questions okay now first I want to slow down blobs just to make something easier just like some like that cuz I work without the coil in lambda that's what happens when you switch back and forth between languages I was I think I just confused some stuff that's why yeah okay so now it's in increasing order so yeah okay so now you know that the first element is always going to be smaller than yours oh sorry the first index of that of an earlier element will always be smaller and so you only have to check the second index right okay yeah it's the same one because you just have to its second element which is the height it is this is strictly greater yeah I guess it's strictly greater action so you do have to check my back I you know and I don't know love is very hard to type so now mrs. I chose some terrible games in the past a few more there's yellow Technica said that last time Oh Tony may exceed it yeah let's take ten square the entrance to stop two seconds what is the just to make sure that I'm I just assume n square would be fast enough maybe I should be 4,000 I guess what that was should be 4,000 I guess what that was should be 4,000 I guess what that was kind of Thanks so maybe we need a I wish they kind of told you that person then I would not have why make up any story about a little bit it's a greedy hmm I mean I'm just thinking right now I'm thinking about the number candidates and this there's an end like an one but yeah it's kind of annoying to code up maybe yeah I guess you have to okay Frank mission psychos maybe I was near the end okay why sorry dad well I'm also trying to think if just fast enough in another language is it like a sequence po5 fun thing mmm let me just give a quick go don't point it Tenten it goes to doink oh but I hope it's not a Python specific reason let's see I could type this pretty quick I like each other yeah I'm not going in that case anyway I could yeah okay that works yeah this Malcolm ization mark everyone's passing up now to do that but I was typing it mmm it's what faster but Kosovo so I take them to me oh yeah Qi you right thanks there's been another day yeah Wow what happened this is much faster but well it was about six times faster than the pipeline motion I mean there may be space we got done pipeline optimize let's see if that me know yeah forget about this no I don't let me run it in here but not do anything let's be at the - that makes me kind of sad not really bit but I mean I think perform like this I'll get into it I'm now saying so first of all this is a longest half in a dag which again is a dynamic program WOM but this is maybe more standard in that there's probably a Wikipedia entry so you get to have a dag and I say that but I'm not sure but it's one of the most entity ones as soon as you can recognize it and probably straight forward because you're doing N squared time you just have to define the dag and sort it in a clear way which you know if it's a dag then you just have to do a topological sort which in this case the actual excuse me Regulus so it does so first might get away with it's n square time and over and space maybe I should read it so that's kind of de Paume I mean I don't know if this just merits much of a I mean I could clean up some cone I mean there's some like naming things I could be slightly bent about but at the end of the day this is like 15 line function so I not going to get into that I mean you could name things as much as you like it but the point that makes me sad obviously is that my Python code I mean definitely I guess if this is in an actual interview I just yeah if the only looking for a new album just would be good enough and that and it should be good in any language maybe I could do some optimizations here and there no I mean I to be honest I don't know if I am a Python enough expert to know where I could optimize I mean made like a preset there way so that we do a fewer appends but the difference was like a matter of I mean it was a big difference thank you know there's like a 1 second difference between pipeline and seas so I don't know how much I could have optimized that away so let's just assume that this is good enough even though if a test because I want to see motion that's clearly also a sequence motion that's what essentially the same but uh so I don't know that's kind of no it's I mean that's unfortunate wasting me a little time but that's fine but I still think Python you should be able to do yeah so to answer a massive legend I think you should do I think one is you know practice Lee Cove of the purpose of you know understanding the problem and sometimes like I would actually put this under kind of framework problem enough framework because Weymouth means I mean in programming but like it's a LICO platform specific issue for this particular problem so I would still recommend Python for more for you know because it's easier to it yeah makes it harder for you to do dumb things or like just use your syntax right like you don't have to worry about as much though it depends on which scientist wrong type stuff you like cuz like you could do a pen and stuff like that very easy I mean you can do that C++ is STL if you like you can do that C++ is STL if you like you can do that C++ is STL if you like but anyway I generally recommend Python so that you can focus on the alcohol imps and then after that you can focus on I don't know optimizations or afterwards yeah and then it's kind of unfortunate that's kind of this problem highlights it otherwise is a very straightforward problem even though this is on a hard yeah this is a hard I you know I did this for something way similar I mean essentially good there will be similar qualms like this except for maybe like this is essentially the compare function for the dag and I like to see if there's an edge between two nodes and maybe but if they were certain things differently this look like everything would still be the same except with the slide pretty much I mean maybe better naming and stuff like that maybe sorting is a little different but essentially you get to squabbling in different variations so I definitely recommend it and it's something that is relatively textbook II in that there probably could YouTube videos out that would explain this so I'm not gonna deep dive into this too much it is only like join either code but oh yeah I think going back a little bit better is that you know focus on learning the algorithms I think I actually recommend yeah just to imply and focus on albums if you get stuck or you know something you know looks sketchy just you know go discussion forum and ask people and look at but for their answers at least make sure that you know your time and space complexity is roughly the same then at the end of the day you know you learn something from it and it doesn't really like where did you get it submitted correctly is you know it doesn't really matter it's just the numbers on a website somewhere but oh yeah I guess just to kind of complete this problem I think I skipped an icing to analyzing complexity which is so op n square because there's an yeah an N squared little bits and choose to even but you know of n space which I don't think could do better it was active conformation so yeah so and that's pretty standard for longest path in the tag so yeah
|
Russian Doll Envelopes
|
russian-doll-envelopes
|
You are given a 2D array of integers `envelopes` where `envelopes[i] = [wi, hi]` represents the width and the height of an envelope.
One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.
Return _the maximum number of envelopes you can Russian doll (i.e., put one inside the other)_.
**Note:** You cannot rotate an envelope.
**Example 1:**
**Input:** envelopes = \[\[5,4\],\[6,4\],\[6,7\],\[2,3\]\]
**Output:** 3
**Explanation:** The maximum number of envelopes you can Russian doll is `3` (\[2,3\] => \[5,4\] => \[6,7\]).
**Example 2:**
**Input:** envelopes = \[\[1,1\],\[1,1\],\[1,1\]\]
**Output:** 1
**Constraints:**
* `1 <= envelopes.length <= 105`
* `envelopes[i].length == 2`
* `1 <= wi, hi <= 105`
| null |
Array,Binary Search,Dynamic Programming,Sorting
|
Hard
|
300,2123
|
1,727 |
hi everyone welcome back to a new video today's lead code daily challenges largest submatrix with rearrangement this is a medium level question in this question we have been given a matrix of size M byn which is a binary Matrix which means it will only contain zeros and ones right so now they have told that we need to find the maximum or the largest area possible for this Matrix and the largest area will be calculated on the basis of how we can rearrange all the ones together in The Matrix also we can rearrange the column in any order to get the largest value possible okay so if we have a matrix such as 1 0 and one then the largest area that will be possible for this will be four right and if we had a matrix we can say that 1 one and 1 0 so how we can rearrange this we have we can rearrange by one and one will come together right this one is together only so one and for the third one is together only so here the largest Matrix uh area of the Matrix will be 2 * by 3 that is of the Matrix will be 2 * by 3 that is of the Matrix will be 2 * by 3 that is six so now we have the gist of what we have to do in this question right we need to get the maximum value of the area that is possible so let's see the approach to solve this question the easiest approach that I could find for this was using the height and the width right for finding the area we need length and breadth right length and height or we can say height and width so what we'll be doing here is we will be calculating the height of the number of ones that is possible okay so what we will do we will take a DP or we can say one for here we will be using a one dimensional array okay this will be storing the height of total number of ones that are possible in a column right if we have like in the example given here we have 0 1 and 1 okay so what we will do here is we will take a height of length n okay now we will iterate on this Matrix and every time that we find one okay we will increase the value of height at that column index height at this is 0 1 2 okay and 01 2 so we will be iterating across that column okay for every column we will get a proper height so if we have a loop where we are iterating from 0 to n where n is the number of rows and J where J will be the number of columns so here what we have to get the height of each and every column right so the height will be iterating on jth index so here what I will do is I will change this to J right so what we are doing here if I am getting if I have Matrix of i n j is equals to 1 what I will do I will increase the height at that column for that column by one okay now if I don't find one there okay if one is not there then I will change that height index to zero now what I why am I doing this see let's see how and why we are doing this I have this Matrix right 0 1 and 1 right so I have this Matrix given here so what we will do here is after finding the height for every row right like here we have on the Zero row we have height as zero because at first index we don't have one so it will be added as zero then for this index also it will be zero and for the last index it will be increased to one right now at the end of every row after completing each row what we will be doing we will be sorting this height array and we will be storing it so for after completing this Loop what we have to do if we are taking a variable like sorted array or sorted height we will take sorted height so what we have to do here is we will sort the height only the previous one this array the height array will remain the same we will just sort the array and we will store in this right now we have why we are doing this is we are doing this to avoid any discrepancy while calculating the height of the array so that we don't find any problem while calculating the width in the coming forward steps so now on the first index what we have the value of this increases to one and this will increase to two so now we have this as sorted array and again it will be stored here in the same way after every step the sorted height will be stored in the new array and after this all of the rows are for all the rows the height is calculated we come out of the loop and what we do we hydrate from 0o to n where n is the number of columns okay now we have the number of columns what we have to do we have to find the max area and for finding the max area what we have to do we will be using Max function and now here the height ARR is giving us the height at each Index right now we only need the width so if I am on index zero just say so the number of columns left what are those 0 1 two right so the how many number of columns are left two right so what we will do we will multiply the height with the rest of the width so it will become nus I therefore now we have the value as sorted height array at ith index multiply by nus I so now we have this Max area and we will be returning it we will return this Max area let's move on to the code now and I have already solve the questions so I will be explaining the code so whatever doubts are left will be easy to understand so let's see the code now first of all we are checking that if Matrix exist or not now if it does not exist what we will do we will just return zero and now we have the number of rows as M and the number of columns as n right so we are using length of Matrix to store the number of rows and at zero index we are using to uh get the number of columns now after that we are declaring a DP to store the height at F for every column and a Max area which is initialized with zero to calculate the maximum area now after that we are iterating using two loops on the each and every element of the Matrix and what we are doing here is we are calculating the height of consecutive ones which is ending at each cell right what is happening here is if we expand or condense this what we are basically doing is if the Matrix of Matrix at I and J is equals to one we are increasing the height at that index by one otherwise what we are doing the height at that index will becomes as zero now after this we are sorting the heights array in decreasing order whenever we are using sorted function it means that the original array will remain same and the sorted array will be stored in a new variable or a new data structure now after this we have stored the array in sorted Heights right now we will use the J loop again and we will be calculating the max area and for Max area what we have to do we have to store the compare it with Max right so we are getting the sorted height and we are multiplying it with n minus J which gives the width here this is the height here so out after coming out of this Loop we are just returning the max area and which is the answer let's run the code now the sample test cases have been accepted let's submit it now the test cases all of them have been passed so that's it for today guys thank you for watching if the video helped you please subscribe to the channel and hit the Bell icon to stay tuned for the further lead code daily challenges that
|
Largest Submatrix With Rearrangements
|
cat-and-mouse-ii
|
You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order.
Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._
**Example 1:**
**Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\]
**Output:** 4
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.
**Example 2:**
**Input:** matrix = \[\[1,0,1,0,1\]\]
**Output:** 3
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.
**Example 3:**
**Input:** matrix = \[\[1,1,0\],\[1,0,1\]\]
**Output:** 2
**Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m * n <= 105`
* `matrix[i][j]` is either `0` or `1`.
|
Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing.
|
Math,Dynamic Programming,Breadth-First Search,Graph,Memoization,Game Theory
|
Hard
|
805,949
|
167 |
this is question 167 to some 2 input array is sorted so the question is asking us given a list of numbers an array of numbers what are the indexes and also we have to note that the index is starts with one it's a one indexed array which is strange but that's just the question return the index values of the two numbers that sum up to 9 in this example so looking at our first example obviously we can see index position one and two these two values sum up to nine and our output is one and two now look at the second example our Target is six and just by looking at it we know okay this value and this value that sums up to six so we would give okay we'll return one and we'll return three let's look at that last one target of negative one well of course it's just these two values and our output is a list of the one indexed positions right so the naive way to think of this is that okay let's use a for Loop let's start it index position one we're gonna sum we're gonna check okay does that equal to nine yes it is imagine if it doesn't we'll say no and then if we started it here then we would go there and then we would go to the next value and check so that would be a o of n o n squared solution right because we have two nested Loops a better solution because we say the question says this is a sorted array we can use a two-pointer approach where we can use a two-pointer approach where we can use a two-pointer approach where we start with a left and a right pointer so let me go ahead and illustrate how that might look right okay let's see it's 2 7 11 and 15. all right and I'm using the two pointer approach we have our left pointer here and then we have our right pointer all the way here right so we can just say okay we're at Target to nine right left plus right what does that equal that is going to equal 17 which is too big of our from our Target so what we have to do is decrease that total sum right this total sum right now is 17. the only way to decrease it is if we move the right pointer down okay there's no way we can decrease that total sum value if we move to the left pointer up that would just increase it right 7 plus 15 that's going to be even more so we have to decrease our right pointer so the left pointer stays exactly where it is and our right Point here goes here okay well we've decreased that number 2 plus 11 right that's 13 but it is still larger than 9. so with that next iteration our left pointer is going to stay exactly where it is and we're just going to bring that right pointer down right here now we know two plus seven it does equal nine we can return those one indexed values all right now we can even try it well if we did it with two and four that of course is going to immediately give us the solution so this is basically the method that we have to do when we have a sorted array right sorted array of numbers and it's asking us the sum and we can actually use the left and right pointer method if that sum is too large we need to adjust it downwards if that sum is too big then we can adjust it upwards right if for example we were looking for I don't know let's say a solution of let's add these to it by 11 plus 15 that's going to be 26 what if our Target was 26. well we can get rid of all this again we're starting out left and right our Target is 26 now 2 plus 15 that's too small so in this case we need to move our left pointer up to increase the value that right pointer is just going to stay where it is now does 7 plus 15 does that equal 26 no it doesn't so then we're going to increase our left pointer right here and our right pointer stays the same does that equal 26 left 11 plus 15 yes it does now we know these index values and we just have to return it so let's go ahead and code that solution out all right does it there's always okay there's always going to be one solution it says so there's no there's not going to be a scenario where we can't find that sum so as we said let's have our left pointer start at zero and let's have our right pointer start at the numbers as a list right and the index value is going to be length minus one so now we've instantiated where our pointers start and we have our Target right so we can say while left is less than equal to right those two values right now if our numbers left index plus our numbers right index if this is larger than the Target right would we have to decrease our um our sum right we have to decrease that value so we just have to do that we're going to decrease it right now else let's actually have a scenario right here where we can just say actually if we keep doing that we're going to I need to bring that out so I don't keep repeating myself all right so we have our sums so let's just say if sum is equal to the Target what are we returning we're returning the index position but one indexed right so it's going to be L plus one and R plus one because on the left hand side the question says one indexed okay so if the sum is equal to the Target let's return that answer and we're done now if that sum is larger than the target we need to decrease R otherwise as else we have to increase left right and this and we're always going to get a solution so we don't actually have to write anything else after this if statement because eventually it's going into this Branch right here this if statement and then we return our left plus one and our right plus one so let's go ahead and run that accepted all test cases let's submit it perfect we beat 93 and let's look at that solution again remember just to recap we instantiate with our left equals to zero right equals to the length minus one to get that index because the length is going to give us one two three four but to access this element because it's zero indexed it needs to be minus one because this is index three we do this plus one because these the question prompt is asking us to return a one indexed solution all right that's it for this question 167 to some let me know if I went too quickly or if it was a little bit unclear would you prefer me to draw things out I actually prefer to type it out when possible sometimes it's not but this is how I'm going to do it for now for this question thank you
|
Two Sum II - Input Array Is Sorted
|
two-sum-ii-input-array-is-sorted
|
Given a **1-indexed** array of integers `numbers` that is already **_sorted in non-decreasing order_**, find two numbers such that they add up to a specific `target` number. Let these two numbers be `numbers[index1]` and `numbers[index2]` where `1 <= index1 < index2 <= numbers.length`.
Return _the indices of the two numbers,_ `index1` _and_ `index2`_, **added by one** as an integer array_ `[index1, index2]` _of length 2._
The tests are generated such that there is **exactly one solution**. You **may not** use the same element twice.
Your solution must use only constant extra space.
**Example 1:**
**Input:** numbers = \[2,7,11,15\], target = 9
**Output:** \[1,2\]
**Explanation:** The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return \[1, 2\].
**Example 2:**
**Input:** numbers = \[2,3,4\], target = 6
**Output:** \[1,3\]
**Explanation:** The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return \[1, 3\].
**Example 3:**
**Input:** numbers = \[\-1,0\], target = -1
**Output:** \[1,2\]
**Explanation:** The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return \[1, 2\].
**Constraints:**
* `2 <= numbers.length <= 3 * 104`
* `-1000 <= numbers[i] <= 1000`
* `numbers` is sorted in **non-decreasing order**.
* `-1000 <= target <= 1000`
* The tests are generated such that there is **exactly one solution**.
| null |
Array,Two Pointers,Binary Search
|
Medium
|
1,653,1083
|
436 |
welcome to august leco challenge today's problem is find right interval given a set of intervals for each interval i check if there exists an interval j whose start point is bigger than or equal to the endpoint of interval i so we'll take our interval i's end and we'll find the minimum interval for the star point of any interval inside of our list so say that we had this list here you can see the end point for this interval i um interval the first interval here has a start point that's less than or i'm sorry equal to or greater than the endpoint of interval i so we would do zero same thing here two's ending interval um we see that the minimum start interval is one so it's kind of like sorting it in a way but not quite because these intervals could overlap each other something to note is that the end point is always bigger than stop point yeah obviously and none of the intervals have the same start points so what i'm going to do is take this example here and let's just see what it looks like actually i'll take this example this might be a little bit better i apologize for all the noise it's kind of hectic inside my house right now so what i'm going to do is add another interval here the one that's just kind of not in place say like 10 or 11. so what would be the answer to this would be well uh this would end up being three right this would end up being two this would end up being three and this would end up being negative one because obviously this one's endpoint has no start point that's uh greater than or equal to it so uh one way we could solve this problem is just to kind of brute force it so for every index we'll just check all throughout hey find the next point where these the start is greater than um yeah the start is greater than or equal to the endpoint of this interval but make sure it's the smallest one so we can check every single time to see which one's the smallest one if we can't find one we'll just make a negative one otherwise we'll return the index but obviously we're gonna have to do that for every single number right or every single index so that ends up becoming like uh and n squared time complexity so we can do better than that let's think about like how we could structure these uh let's start with getting the starting points so say that this is like starts and this would look something like one two three ten now what about the ends um that would be 4 3 4 11. so one thing to note is these in itself aren't going to really tell us anything we have to also store the index points or the index numbers attached with these starts and ends and the reason for that is what we can do is sort both these starts and ends maybe we can use like a heap structure and pop off while we go through the ends because the ends are what matters we will check to see can we find a start point that's uh greater or equal to this end and let's like so say that we sort this one and now we're going to check all these ends we'll say hey is this one greater than or equal to nope oh this one is so this one attach the row number uh but we don't know the row number here right so we're gonna have to attach these into like some sort of tuple and that way we can create this output that's gonna have the um the index numbers for all these ends and then we will sort that by the index number and output just the um these indexes okay so that's a little bit confusing but it'll start making more sense as i code it out so start by let's say we'll have three structures we'll have the starts the ends and we'll have an output and these will all just be lists but the starts and ends are going to be a heap and i'll use the heat cue method to take care of that so what i'm going to do here is let's see four uh the index number and the start and end in enumerate intervals and the first thing i want to do is heat cue dot heat push into starts i'm going to make a tuple of well the start and the index number and i'll do the same thing with the ends and now these are going to be sorted it's a heaps min heap so that'll be sorted in order of the start and the ends and now we have our structure to help us out here um i'm also going to add something to our starts i'm going to add a final one for this negative in case that we can't find anything so to do that i just will input a tuple of let's say a float and how about a start of infinity the index number negative one so if we get to this point then we know that we should just put negative one for everything else now all right so now we have our structures that we need to get this problem solved uh so while we have ends right because we're gonna be checking the ends to see if we can find the minimum start so while we have the ends let's first pop off the uh start and index number and i'll call that i guess i start let's see so keep q dot heap pop off of our start and we'll check well oh wait we need this in a while loop of course so uh how do we do this so first we'll pop off the end and i end let's say and now we'll have an inner loop that says okay while we have starts and the start is less than the end then we want to continue popping off right so that reminds me i need to also put a start here i'll make that a float of negative in to make sure that we at least enter one time here so what i'll do is pop off the start and i start and now we'll check hey is start greater or equal to greater than or equal to yeah greater or equal to the end because if it is we just break and now uh let's add to our output we'll say output append where we want to append we only care about the index number right we don't care about the actual start and ends at this point so uh what i'll do is i will put in the i uh let me think yeah i guess i'll put in the i end and the i start because when we sort it we want it to be sorted by the index numbers and this is going to be the thing that we return all right i believe that's right so let's first see how that works out so finally i think that might be it so um once we do that i think we just return our output but we're gonna have to restructure it a little bit uh we'll say all right four let's see i1 i2 in sorted output what do we want to return the i2s right or let's see uh i starts all right so let's see if this works i might have messed this up oop expected two arguments got one oh okay starts and i also think i need to change my case here uh let's try this one okay so okay all syntax yup gotta make that tuple okay so that looks like it's working let's go and submit it and accept it so what is the time complexity on this and log n right because all the sorts and all the heaps as far as space complexity goes i believe it's n because we need to have all the starts and ends for inside of our heap so and our output obviously so uh it could be better than this yeah probably but this seems to be good enough so i think i'm gonna end it here thanks for watching my channel and remember do not trust me i know nothing
|
Find Right Interval
|
find-right-interval
|
You are given an array of `intervals`, where `intervals[i] = [starti, endi]` and each `starti` is **unique**.
The **right interval** for an interval `i` is an interval `j` such that `startj >= endi` and `startj` is **minimized**. Note that `i` may equal `j`.
Return _an array of **right interval** indices for each interval `i`_. If no **right interval** exists for interval `i`, then put `-1` at index `i`.
**Example 1:**
**Input:** intervals = \[\[1,2\]\]
**Output:** \[-1\]
**Explanation:** There is only one interval in the collection, so it outputs -1.
**Example 2:**
**Input:** intervals = \[\[3,4\],\[2,3\],\[1,2\]\]
**Output:** \[-1,0,1\]
**Explanation:** There is no right interval for \[3,4\].
The right interval for \[2,3\] is \[3,4\] since start0 = 3 is the smallest start that is >= end1 = 3.
The right interval for \[1,2\] is \[2,3\] since start1 = 2 is the smallest start that is >= end2 = 2.
**Example 3:**
**Input:** intervals = \[\[1,4\],\[2,3\],\[3,4\]\]
**Output:** \[-1,2,-1\]
**Explanation:** There is no right interval for \[1,4\] and \[3,4\].
The right interval for \[2,3\] is \[3,4\] since start2 = 3 is the smallest start that is >= end1 = 3.
**Constraints:**
* `1 <= intervals.length <= 2 * 104`
* `intervals[i].length == 2`
* `-106 <= starti <= endi <= 106`
* The start point of each interval is **unique**.
| null |
Array,Binary Search,Sorting
|
Medium
|
352
|
653 |
hey everybody this is Larry this is day eight uh or day nine alternate day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's Farm to some four input is a BST I mean you don't have to be that descriptive on the title but okay um so what are we doing here so we turned through if there's two elements in the bandage such that the sum is equal to the given Target okay so of course if we do something like linear time linear space that will obviously be good but can we do better right um well for each bonus do we have to look at each node for each node we can um I guess you can maybe do it in linear time constant space with um with what you would call it with uh Morris traversal um on and basically what you're doing is really when you're doing the Traverso is doing you know getting the entire list in Num in a sorted way right meaning that instead of a binary search tree you just have a list and then you do this two um the two pointers thing right one on the biggest one on the thing and then you kind of shrink until you find the target Etc right um so that's gonna be linear time constant space but way not worth the trouble so and if you try to do like yeah I don't know and I guess you can also like walk the like the other linear time in your space one is like what uh walk the tree in the same manner but it's really not worth the effort I don't think to be honest um what I'm gonna do is just like catch the tree and then look it up um yeah and the beauty of that is of course if you want to do multiple queries that also you know saves for that so yeah so now seeing as you're set and then we just uh was it uh fine whatever I don't know um and then scene dot uh know that value and then find node.love I know that and then find node.love I know that and then find node.love I know that right or maybe this is pre-processed by the way pre-processed by the way pre-processed by the way right are they all unique I guess they're not um so that's a little bit possibly trickier um so I mean it's not that much trick here it's just you have to be a little bit careful I mean we can also do it in one sitting because we don't have to pre-process it so yeah let's do it that pre-process it so yeah let's do it that pre-process it so yeah let's do it that way then right so then basically we go okay let's just say found and bring a little bit lazy today or maybe we can just return it then and return Force we go okay if no doubt why you K minus no dot value is insane then we return true otherwise we return this or this of course we have to add you know that raw before recursing pretty much it really I think so yeah and of course this doesn't does not take advantage of the fact that it is um a binary search tree at all but it should be okay linear timed linear space yeah um 922 day streak finally have a quick one for once but yeah but I think um yeah I don't know if you can do I mean I think the spaces don't think you can optimize because you have to uh you have to look at every element anyway for the most part except for early termination but you know you don't know that ahead of time per se um yeah so I think that's pretty much it let me know what you think uh this is all and time o of h space Oh and space because I forgot we have a scene but yeah uh let me know what you think so stay good stay healthy took a mental health if you're doing the contest later good luck to you and good luck to me if I'm doing it uh I'll see you later bye
|
Two Sum IV - Input is a BST
|
two-sum-iv-input-is-a-bst
|
Given the `root` of a binary search tree and an integer `k`, return `true` _if there exist two elements in the BST such that their sum is equal to_ `k`, _or_ `false` _otherwise_.
**Example 1:**
**Input:** root = \[5,3,6,2,4,null,7\], k = 9
**Output:** true
**Example 2:**
**Input:** root = \[5,3,6,2,4,null,7\], k = 28
**Output:** false
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-104 <= Node.val <= 104`
* `root` is guaranteed to be a **valid** binary search tree.
* `-105 <= k <= 105`
| null |
Hash Table,Two Pointers,Tree,Depth-First Search,Breadth-First Search,Binary Search Tree,Binary Tree
|
Easy
|
1,167,170,1150
|
505 |
hey everybody this is Larry this is me doing week two of the Le code weekly challenge uh and apparently I have some code cash hit the like button hit the Subscribe but join me on Discord let me know what you think about this premium problem and it's a little bit sad that we uh kind of have one that I've done before because I've done oh I have not done a lot of Premium problems so whenever I see one it's kind of sad but yeah so okay so there's a b and Maze when did I do this it FS way recent is that this year I guess this is this year huh why did I do it was that a premium PR as well uh but yeah it seems like uh I don't know I just look at the ball and it kind of reminds me already so I think it's just going to be the shortest distance for the board to stop a destination the board cannot stop a destination we return negative one so yeah I mean I think this is a shortest path problem there a couple ways to do it there's a dynamic programming solution there's a BFS solution there a dous or dextrous algorithm solution there number of ways you can do it and all of them are kind of you know not super bad I think you just have to kind of model the problem in a correct way which is to say if you uh um kick the ball or Roll It Whatever uh that it won't stop I think that's the thing that you have to be a little bit careful about and as long as you do that it's pretty fine I think yeah uh yeah I mean I don't really have much to say about it uh to be honest other than that I was just thinking about what else I can leave off or whatever um yeah how do I want to do it which way should I do it I don't even know I'm just kind of lazy today to be honest uh yeah let's just do it with um uh I think the tricky thing with you know you want to do with BFS or something like this is that you don't simulate every time because then that's how you get uh or that's how it's possible to get some like n Square type uh performance if you're not careful and end here is actually not that big but you can definitely still be careful about it uh and okay uh do you have to stop at the go or I guess in this case NOP you have to stop at the go okay uh yeah okay yeah uh yeah there number of ways you can write this I think so uh yeah let's get started I suppose um I'm just going to wait in a funky way maybe with some uh memorization maybe that's what I'll do uh yeah so basically Q isal collection that uh c. aen um yeah maybe I'll WR it out a little bit right and then now just for search Stu you have a destination or distance I suppose uh let's say none or maybe Infinity it's easier and right all right and then now after we have pen distance is y z and now while length of Q is greater than zero we have NX n y is = q. greater than zero we have NX n y is = q. greater than zero we have NX n y is = q. pop left right and then now we just have uh we have directions as well uh we have just the four cor no directions right we don't have any diagonals right I don't think so and then now yeah just basic stuff uh what am I doing right and then now uh and I want to do something like actually um no this is not what I want I this is muscle memory I kind of wrote this but what I actually want is maybe something like uh just do like get XY uh dxdy or something like this right and the reason why I want to do that is then now um we can do a cache right um yeah and you can make this is a weird way to cach it but that's fine right so then now you can do XY dxdy right so then now if Maze of XY is equal to um a w what is a is it a one or zero a one um then we return uh XY oh no wait so NX n y is you go to X Plus DX y + Dy so NX n y is you go to X Plus DX y + Dy so NX n y is you go to X Plus DX y + Dy if this is equal to one then we return that means that the next thing is a award so we return the current one otherwise we return get of um uh nxn y dxdy still right and of course we can just cach this um I'm a little bit lazy of the caching so I hope you know memorization so I'm just going to do the cash here but you can also just like you know just store the input and stuff like that and that should be good for us to uh you know it's a little bit lazy to be honest but this allows us to kind of do it all one time get the next item because every time the second time you go to the same space it'll be cached right so then now if uh distances of NX and Y if this is greater than the distances of XY + 1 greater than the distances of XY + 1 greater than the distances of XY + 1 then distances of NX and Y is equal to this thing and also you want to uh put it on the Q right so then now NX and Y and that's pretty much it and then here we return negative 1 cuz we didn't stop there but otherwise if we stopped at uh if x is equal to y X and Y is equal to u y and we you know this thing that ski to thing so we don't do it we return distances of XY and you can actually return a little bit early as well but that's fine um it's fine as long as I remembered how to write syntax stuff copy and paste laciness uh H oh I guess we just keep on going but wait that shouldn't make sense we always have a wall outside oh okay I misunderstood the inputs it's fine like they don't actually give you the Border War cuz that's why I thought so that's why you know cuz um otherwise yeah I just thought that we were given a border War otherwise you just have to add a thing which is that if um if not uh and right let if that's true and this did I that label that right uh if this is out of the loop we return an XY otherwise if this is true I guess that should be right oh I think that's an or whoops but uh yeah maybe I'm off by live what am I doing that Miss be the problem Oh number of empty spaces okay I miss about the problem so yeah okay I miss about the problem my fault uh so then it yeah you can't do BFS uh I mean you probably can actually uh but now it's a different way because then you don't have to worry about this weird thing you can just do one space at a time and then you just do a direction right okay fine H this is annoying uh yeah maybe like the direction is netive 1 right so here's D um or maybe I'll just call like four uh right so we have someone like that and the reason for just like uh we have one for each of these and then one for like I don't know stop or something like this right so you can maybe have a Unum that's like stopped or something if you want to prefer it to be a little bit more readable and then yeah this doesn't change well this change because has to be n uh what we call it and D is you going to stop the direction then we're going to do right otherwise um okay so if D is equal to stopped then we can do this thing um and so solved a bonus question for y'all today hope y'all enjoy it right uh of course we have to do something like we have to make sure that yeah if and see and uh and that this Mace of nxn Y is not equal to one and okay uh and then now in that case we go to direction right so now New Direction uh we want ND in the enumerate as well um yeah I mean this isn't done yet I'm just runting real quick to see if I have any weird issues like I did just now uh okay right uh not enough numbers to impact uh yeah okay fine uh okay can only can oh yeah uh because this now needs uh right oh yeah okay still uh well actually I think this is this case because this is the one where you oh wait no I think this is fine but it's a little bit awkward maybe uh let me just run it real quick to make sure I don't have any okay I mean this isn't going to be right yet because we didn't do the normal case of roll the ball uh cuz this is only with it's stop if it's not sto then we just keep going right so that means that um distances of okay so that means that NX n y is equal to X or maybe DX Dy is equal to directions of D and then now we can do uh this thing uh maybe there a little bit of copy and paste so maybe we can uh okay I just copy and paste for now I'm a little lazy maybe we could um you know but uh yeah and n d is equ go to D I suppose because we haven't changed Direction uh have some type h that's not Gucci oh I guess here um if you if it goes out of bounds or if it hits a war uh do I think I'm then you know but otherwise then that means that things have changed so then now you want to actually um this is a little bit awkward though for BFS I'm worried about I'm going to get it cuz when you stop you don't use a thing so you have to do like a Preen thing so then now you have to do something like a 01 uh thing which is kind of a little bit awkward to be honest right because now ND is youal to stop right and then now uh what's it called a pen left I think uh oh uh and this your stop no that's right oh this maybe out bound so now we stop so then you have this thing definitely a lot of cases to kind of get wrong on um H if D is stop we do this thing why is this going out of bounds if this is and this is not equal to one okay and this thing what is ND should go from0 to three so that's not it XYZ and D is just stop anyway right X and Y shouldn't change what is the eror again huh which way is which uh which one is it this one okay so it's here but how can it be this is r c and then ND is five right in FY right or like Z to five R print it out that is weird that's a lot of printing uh this is 444 five is the previous one is it we don't change it oh this is NX and Y instead of uh yeah okay cuz we don't change that's why all right that was a silly mistake on my part uh a lot of silly mistakes today a lot of this is a tough one to kind of you know uh let's give a submit hopefully it's right hopefully I don't have any mistakes but still a very annoying problem a very easy one to get one also just because I misread the prom definitely we can do this a little bit better but uh I don't know so what's the complexity here this is going to be all time C * 5 which is all time C because time C * 5 which is all time C because time C * 5 which is all time C because we look at each cell once well or five times I guess one for each Direction uh one of the four directions and stop and not all of them are reachable anyway but we do autate a space for them so it's going to be all time C uh in terms of that's the time and space because we can only pop and push each one into that place uh and we only go look at up down left right so we don't have to worry about anything weird uh for most of those spaces and most of those spaces actually only just do One Direction anyway so yeah um that's all I have for this one let me know what you think and yeah stay good stay healthy to mental health I'll see y all later and take care bye-bye
|
The Maze II
|
the-maze-ii
|
There is a ball in a `maze` with empty spaces (represented as `0`) and walls (represented as `1`). The ball can go through the empty spaces by rolling **up, down, left or right**, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
Given the `m x n` `maze`, the ball's `start` position and the `destination`, where `start = [startrow, startcol]` and `destination = [destinationrow, destinationcol]`, return _the shortest **distance** for the ball to stop at the destination_. If the ball cannot stop at `destination`, return `-1`.
The **distance** is the number of **empty spaces** traveled by the ball from the start position (excluded) to the destination (included).
You may assume that **the borders of the maze are all walls** (see examples).
**Example 1:**
**Input:** maze = \[\[0,0,1,0,0\],\[0,0,0,0,0\],\[0,0,0,1,0\],\[1,1,0,1,1\],\[0,0,0,0,0\]\], start = \[0,4\], destination = \[4,4\]
**Output:** 12
**Explanation:** One possible way is : left -> down -> left -> down -> right -> down -> right.
The length of the path is 1 + 1 + 3 + 1 + 2 + 2 + 2 = 12.
**Example 2:**
**Input:** maze = \[\[0,0,1,0,0\],\[0,0,0,0,0\],\[0,0,0,1,0\],\[1,1,0,1,1\],\[0,0,0,0,0\]\], start = \[0,4\], destination = \[3,2\]
**Output:** -1
**Explanation:** There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there.
**Example 3:**
**Input:** maze = \[\[0,0,0,0,0\],\[1,1,0,0,1\],\[0,0,0,0,0\],\[0,1,0,0,1\],\[0,1,0,0,0\]\], start = \[4,3\], destination = \[0,1\]
**Output:** -1
**Constraints:**
* `m == maze.length`
* `n == maze[i].length`
* `1 <= m, n <= 100`
* `maze[i][j]` is `0` or `1`.
* `start.length == 2`
* `destination.length == 2`
* `0 <= startrow, destinationrow < m`
* `0 <= startcol, destinationcol < n`
* Both the ball and the destination exist in an empty space, and they will not be in the same position initially.
* The maze contains **at least 2 empty spaces**.
| null |
Depth-First Search,Breadth-First Search,Graph,Heap (Priority Queue),Shortest Path
|
Medium
|
490,499
|
83 |
So the name of the question is Remove Duplicates from Sorted Linked List. You will find this question in the late code. Question number is 83. I will put this question in the description in the link. You can solve it by going there. So in the problem statement it is said that you have a sorted list. Link list is ok so its van is its head, its next one is also van and the next one of this van is you, so the first observation is this is a sorted link list, meaning the number in it is ok, so what you have to do. In this link list, your van is being repeated. If your van is a duplicate, then deleting this van means that if you want to remove one of these two vans, then this head will be from ours. Okay, and you have to delete this one. And after that here you will be directly here, this is what you have to return, basically you can return the head of the link list from you, okay but we never delete it, okay we do not delete any note. Basically, what needs to be done in this, I will tell you, this is your van, its next one was also a van and its next one was our 2, so what do we do, we break this link, okay so when this link breaks then we If you update the link and point to it, then this van note has not been deleted, it is still in the memory, but if you have updated the link, then your link list has become as if it is head loaded. He is pointing, so the link list has been updated, okay, it is so clear, so after updating this, you have to return the head of the link list, so now let's go to the approach, okay, I will make the list, this head is ours. This is Van, its next is Van, let's reduce it, okay, take the next N of this, so first tell what will be the answer, see, Van has been A three times, so you have to return only one Van, okay, after that, you are there, so this is the first one. The answer should be clear to you, okay, so now let us look a little carefully at the approach, what approach we are going to do, so first of all tell me one thing whether you will ever have to remove the limit note or not, it is your choice. If there is a head knot, then see which vane is there and if you have to keep one vane, then you will not have to remove the head knot at all, you can do this in the next one, so we are zooming in this algorithm that we start from here. We will do it okay and we are not going to do anything on the head because we have to keep the head, if the WAN number of the head is getting duplicated and we will delete the WAN next to it, okay, then the point is that we We have to start not from the head because the head will never have to be removed, so we reduce it by one. If we have to return the head, we create a new pointer and name it Current, it's okay, and place the current on the head. And let's check the next one of current because it has to be checked from here, like I told that there is no need to remove the head. Okay, so now you have to see that current is your head place and check from . If you want to current is your head place and check from . If you want to current is your head place and check from . If you want to start, then the value of current and next is equal to the value of current, the value of both is van, so now you have to break this link. If there is so much agriculture, then we are going to hand over it. In this case van is ours. In this case, what you have to do is update the next point of the current point, what will happen will be current dot , so we have updated the pointer to , so we have updated the pointer to , so we have updated the pointer to where it will point next. Okay, so when the point is updated, The one who is next to the current is pointing here and you do not touch the current and it does not move the current because I have to check the next of the current again which number is next to the current, okay now you understand. Why is the current pointer still on the head because you don't know which number, so now you will see friend, now this is also WAN, now this is WAN, so what will you have to do, now you will have to break this link also, okay this link also. Now break this van, where will it go and get attached, it will go here and get attached, okay, so look carefully at this line will handle it says that where is the next one of the current one, place it in it. He has done this, he has placed this on you, okay, now we do n't know, although we can see that you have come and touched us, but you will not know like this, otherwise you will have to check, this is why. I have still kept the current on the head, okay, so I reduce it, clean it up a bit, delete this, okay, this is deleted, and let's delete this, okay, link it here. Iteration started but we are updating the next point of the current. Now what you have to see is this current and next. If I check the next element of the current then I will call this then you will come here. Okay so you are there then I know that friend, this is you, so I don't have to update anything and there is no duplicate link, so now finally what am I going to do, I will pick up my current and go from the head to this you because now I know that I will delete anything. If you don't want to do so then move now and what will be the , where will he be what will be the , where will he be what will be the , where will he be pointing, he will basically take where he will point three because now if you are current then what will become of current and next, that 3 Okay, so what is this second condition? If there is no duplicate then update the current pointer and move the current. Make it equal to . If . If both you and three are not matching then you have to Know that this second condition will be your call again, so I am taking the current pointer from you at 3:00, okay at 3:00, okay at 3:00, okay here I have taken it for free and where is pointing to? It and where is pointing to? It and where is pointing to? It will point to the right, before starting the code, write the condition that your current dot next, if it becomes null then your link list is at the end, your link list has ended then stop, it is just simple. What is its time complexity? You are doing reverse. Update the link list. We went from beginning to end. Check all the notes one by one. Reason and single time visit. What will be the space complexity? It will be constant because we have made it current with only one pointer. Okay, we are not doing much, let's quickly look at its code. Let's end the face video. Before starting the court, I am telling you that if you buy any course, it is a very pocket friendly course. If there are courses then you will get 10% discount. are courses then you will get 10% discount. are courses then you will get 10% discount. If you enter this Prakash 10 code then you will go straight to the court. So first of all I have written this line in the code, it means that if the head of the link list is null or head. means there is a single element, head. means there is a single element, head. means there is a single element, so if there is a single element or the linked list is null, then you do not have to do any operation, you directly return it to the head, it is okay and as I told, take the current pointer, it is okay because the last Look, this is to return the head, so take the current pointer, we don't want to move the head Stay like will be null, we have to Stay like will be null, we have to Stay like will be null, we have to stop here, I told you that we reach the end of the links, so here But till you stop, you will keep checking, then see, tell me two points, if the value of the next note is equal to the current note, then this pointer is getting updated, okay, this is the next point, it is getting updated, I have done it. I had shown how it happens and if the value of the next note is not equal to the current one then move it directly. Okay, so in this you have moved the current. The reason is a very simple code but you had to understand a little bit of logic in it. I don't think that two should be used in writing the code. -It is going to take more than three minutes -It is going to take more than three minutes -It is going to take more than three minutes but the instructions given and how you have to explain it in the interview are important, so you pay attention to the concept, the code is very easy, so let's end this video here. It is very important for you to watch this video. -Thank you very much, very important for you to watch this video. -Thank you very much, very important for you to watch this video. -Thank you very much, many lead code videos are going to come on my channel and there are already 120 videos, go and watch and okay, see you in the next video. Bye.
|
Remove Duplicates from Sorted List
|
remove-duplicates-from-sorted-list
|
Given the `head` of a sorted linked list, _delete all duplicates such that each element appears only once_. Return _the linked list **sorted** as well_.
**Example 1:**
**Input:** head = \[1,1,2\]
**Output:** \[1,2\]
**Example 2:**
**Input:** head = \[1,1,2,3,3\]
**Output:** \[1,2,3\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 300]`.
* `-100 <= Node.val <= 100`
* The list is guaranteed to be **sorted** in ascending order.
| null |
Linked List
|
Easy
|
82,1982
|
121 |
this is leak code 121 best time to buy and sell stock you're given an array of prices where the indices represent days and you have to figure out the maximum profit you can make from buying on a single day and selling on a different day in the future so in this example the most you can make is five and you can do that by buying at one and then selling at six there's a major constraint which is that you have to buy before you can sell and this is pretty obvious you can't sell something you don't own and it's really important to deeply conceptualize this idea so in this array if you buy right here you can sell anytime after and then if you sold right here you could have bought anytime before and so this relationship around the timing of buying and selling is key and then our objective is to maximize profit specifically the sell price minus the Buy price so let's consider the first example and on the first day we have the seven and the only thing we can do at this point is buy because remember the constraint you have to buy before you can sell so if we buy at seven we want the highest following price and if we look through we can see that it's six so the most we can make assuming we buy right here is 6 - right here is 6 - right here is 6 - 7-1 which we would ignore because we're 7-1 which we would ignore because we're 7-1 which we would ignore because we're supposed to return zero if we can't make any profit and then we can repeat this process for the rest of the array so at each index we'll assume that we buy that day and then look for the best sell price which will be the highest following price and I realize this perspective is somewhat arbitrary because we could take the opposite view where we assume that we sell on each day and then look back for the Best Buy price which would be the lowest preceding price I'll add a note and set this aside for now because we don't have a good reason to deviate at this moment so let's continue examining the rest of the array if we bought at one the highest falling price would be six so the profit would be 6 - 1 5 if we six so the profit would be 6 - 1 5 if we six so the profit would be 6 - 1 5 if we bought at five the highest falling price would be 6 - 5 is 1 if we bought at would be 6 - 5 is 1 if we bought at would be 6 - 5 is 1 if we bought at three the highest falling price would be 6 - 3 is 3 if we bought at six the 6 - 3 is 3 if we bought at six the 6 - 3 is 3 if we bought at six the highest and only following price would be 4 - 6 is -2 and then we can't buy be 4 - 6 is -2 and then we can't buy be 4 - 6 is -2 and then we can't buy at four cuz there would be no time left to sell so after examining the entire array the highest profit we found was five which is the expected result so the question we're repeatedly asking is if we buy today what's the highest following price and then we just compute the profit and keep track of the highest one let's turn this idea into code so we start by initializing Max profit so far to zero and then for each day that we can buy we initialize the highest following price then we actually have to go find the highest following price so we have to examine the days after I and if we find a new high then we update now we can compute the current profit and if we have a new Max then we save it and then finally we can return our result our space complexity is O of one and then for time the outer loop will run nus1 times and that's because you can't buy on the last day meanwhile the inner loop will always run a different number of times so in this example it would run five times 4 3 2 and then one time and if you average these you'll get three which is precisely n /2 so for our time which is precisely n /2 so for our time which is precisely n /2 so for our time complexity that gives us nus1 for the outer loop times an average of n /2 in outer loop times an average of n /2 in outer loop times an average of n /2 in the Inner Loop and in Big O notation that simplifies to O of n^2 O of n^2 that simplifies to O of n^2 O of n^2 that simplifies to O of n^2 O of n^2 time isn't great so I'm wondering can we do this faster and I want to know could a different perspective help because I'm remembering that we noticed one earlier but didn't fully explore it let's see what it was you could take the opposite view where we assume that we sell on each day and then look back for the Best Buy price which would be the lowest preceding price we could keep examining the problem from different angles but let's take a look at this one first the earliest day we can sell is the second day since we have to buy first and if we sell at one the lowest and only preceding price is 7 so the profit is 1 - 7 -6 and then before we move on to the - 7 -6 and then before we move on to the - 7 -6 and then before we move on to the next day we have to update lowest preceding price because one is lower if we sell at five the most we can make is 5 - 1 4 five isn't smaller so we leave 5 - 1 4 five isn't smaller so we leave 5 - 1 4 five isn't smaller so we leave this alone if we sell at three the most we can make is 3 - 1 2 three isn't we can make is 3 - 1 2 three isn't we can make is 3 - 1 2 three isn't smaller so we leave lowest preceding price alone if we sell at six the most we can make is 6 -15 again we don't have a new low so we -15 again we don't have a new low so we -15 again we don't have a new low so we leave lowest preceding price alone and then if we sell at four the most we can make is 4 - 1 3 and we're done I'm make is 4 - 1 3 and we're done I'm make is 4 - 1 3 and we're done I'm noticing that at each step we don't need to examine all of the previous elements to update lowest preceding price that means each step will take o of one time which will give us o of n time overall a huge improvement over the previous o of n^2 solution and we would still have o n^2 solution and we would still have o n^2 solution and we would still have o of one space too let's turn this idea into code we initialize is Max profit so far and then we initialize lowest preceding price and then for each day that we can sell we compute the most we could make so that's today's sell price minus the lowest preceding price and if our current profit beats Max profit so far we record our new Max and if we have a new low we save it for the next day and then finally we can return our results if you go back to the beginning our line of reasoning started with examining each number and asking if we buy today what's the highest following price and that led us to a Brute Force solution that was slow so we asked can we do this faster and could a different perspective help which led us to The crucial Insight we needed to get oent time and I'm guessing that this problem is labeled easy because the implementation is simple but getting the Insight behind the implement mentation is actually pretty hard that's because you have to be precisely aware of how you're seeing the problem in the first place and then you have to deliberately change that perspective specifically you had to notice that initially we were asking if we buy today what's the highest following price and then you had to flip that to if we sell today what's the lowest preceding price but there's no way to modify the question if you don't see it in the first place
|
Best Time to Buy and Sell Stock
|
best-time-to-buy-and-sell-stock
|
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
You want to maximize your profit by choosing a **single day** to buy one stock and choosing a **different day in the future** to sell that stock.
Return _the maximum profit you can achieve from this transaction_. If you cannot achieve any profit, return `0`.
**Example 1:**
**Input:** prices = \[7,1,5,3,6,4\]
**Output:** 5
**Explanation:** Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
**Example 2:**
**Input:** prices = \[7,6,4,3,1\]
**Output:** 0
**Explanation:** In this case, no transactions are done and the max profit = 0.
**Constraints:**
* `1 <= prices.length <= 105`
* `0 <= prices[i] <= 104`
| null |
Array,Dynamic Programming
|
Easy
|
53,122,123,188,309,2138,2144
|
106 |
hello everyone welcome back to coding intuition today we are going to soil construct binary from in order and post order traversal question on lead code so in this question we are given in order and postolar traversal of a binary query and we need to construct a binary tree using that in order and post order so to understand what is in order post order and what is a binary tree let us move to White so here we are given a binary tree and what is a binary basically a tree which has uh at most two children's right so it can have two or less than two children so we are given a binary here and we are given uh we are not given a binary we are given its in order and poor shoulder traversal so what is an in order to reversal in order reversal as a traversal in which first reverse left then root then right so as we can see here first of all we have reversed the left most element which is 5 then we are going to 3 then we have gone to its right so basically in the sub tray itself we are also doing the same thing we are doing left then root then right so we go left root right we have completed this left so we go to root so we have printed the root then we got again to left root right so that's how in order traversal works and how is post order traversal works so in post our traversal what we do is uh we basically go to left then right then root so as we can see here first of all we have gone to the left then right then root so root comes at last so similarly we will now not go to 2 first we will go to its right first so this is its right so we will go to left again which is 7 right which is eight and four which is the root and at last we will print at this root so basically that's how we form uh an order and post order trivials but in this question we are not given a tree we are just given this in order in first order and we need to determine how do we make a tree from this in order and password so one thing L is very clear from here one intuition we can make very clear from here that the last node inside our post order reversal will always be our root node because as we can see the how this procedure work left right root so root will always come at the last so by using this intuition let us try to come up with a solution so now as we know that our road value will be 2 as we can see here our root is 2 because the last value inside our post order is 2 and we know Left Right fruit so last value in post order will always be our root so we have found our root noun we need to find out what would be in the left part of this and what will be in the right part of this so in order traversal we know that we Traverse it from left then root then from right so if we find out root inside our inordered reversal we can say that whatever is before the 2 is our left up is part of our left sub tree and whatever is after the root is part of our right sub three okay and similarly in the post over traversal now as we know from in order traversal that this and at this index we find the root and before this we have three elements so we can say that uh from the postural intervention we know that first left values will come then right values will come so we can say that as we know there are three values in left to have three so from uh the first three value inside our first order will be the part of the accept tree and next uh how many values are after this root then in order there are three values after the root like we have two and there are three more values after the root which is 2 inside the in order so we will take three more values after this after right 7 8 and 4 and we will exclude this 2. so basically we have this now so we can say that uh and on laptop tree we will have either 5 3 or 6 which is a left part uh from we got it from our inorder traversal and similarly from posterior traversal so now we know that these are left and the right parts of our sub tree but inside the code how we will calculate that let us just look at that quickly so uh whenever uh we know that the last element of our post over traversal will be our root element okay so as soon as we find the last element inside our post or traversal we will try to find it inside in order traversal and we will note the index uh so we find our root in order traversal at index number three so we have noted our index here so to divide that to divide it in the two sub parts in order traversal what we will be doing is in order the first part will be from starting up till this index minus 1 so that have that we have done here after this index minus 1 will become 2 okay so these are five three and six that's how we will calculate inside the code okay and how will we calculate for this uh after this index plus 1 as simple as that so we will move to 4 so that's how we will calculate this part so uh the ending will remain same in this the starting will remain same in this but will change the ending part which will be one before the root and the starting part for this and it would be one after the root okay and how we will calculate it for first order so inside the post order uh what we can say that from thus are starting we need to consider index number of element basically three elements so we will consider uh starting index of the force order plus three elements okay and we will uh subtract minus 1 because it is an index and we only need to consider first three elements and then we will try to find out the starting point of this second array the second starting point of the second array would be right at where we find out are index where we find out a root in order so it will start from this after we have completed the left values right after that we have to consider our right values so our right values will be there so after right after the left values so uh what we'll be doing from starting index plus root index in this case we'll note minus one uh what are we trying to find out here we are trying to find an ending index which is this inside the left in ending index of the left sub array now we are trying to find a starting index of the right sub array so starting index of right sub diagram would be starting position plus root idx and why we are subtracting this from here starting index of in order traversal we are subtracting starting index of window edit references in this case it is simply zero but as we move forward we can see a starting index of in order reversal will change so basically we are moving this elements extra ahead and we have to come this way back that's why we are subtracting this from here so that is basically we will be doing again and again until we find our complete tree so let us just move to next uh next stage in this uh so here as we can see we will again do the same thing last element is 3 which is our root now again so uh we will have we have assigned root here and in this array last element in post order is 4 so we found out another root element so now we have these roots and we will have again do the same thing we will divide it into two so the five will be the left part of this or 6 will be the right part of this and similarly in the post order traversal as we have done before so we are again divided in the array and finally we have found out our complete tree so that's how we will run a recursive code and do whatever we have done the first step again and again to divide the array into subparts and every time find out a new root and a new left and right for each root so I hope that makes contusional algorithm very clear now let us just quickly jump to the code and understand this question completely so now let's just quickly understand the code now so in this code as we can see uh first of all we are finding out the size of the area the size of both our array will be same that they are same number of elements in the tree so there's a total number of elements in the tree we have calculated now well called a recursive function to get our tree so we will pass in order traversal and password reversal with the starting and the ending index of the traversal as we have seen in the example we need that so we have sent the setting and then ending in next of these arrays inside our recursive code so first of all we'll check if the starting index of our Innovative reversal exceeds the end of reversal and similarly with the postal letter vessel we will return null saying that it has exceeded uh and the amount of the array simply and first of all we will find out our root as we know the last element inside the portion reversal will be our root always so we have found out our root then as we have seen on whiteboard we will find out this value whatever is the last value inside the post order traversal inside our inordial reversal so we are trying to find out the index of that value as soon as we find out the index or our index of that in order to reversal value we will say whatever is before this inside the in order is R left so what are what is our left is equal to uh whatever is before that and for post order traversal the for uh the first current uh the first L the how many elements there are inside the inordial reversal that many elements inside the post order traversal we will consider and similarly uh the word will be on right whatever is inside are in order I know reversal after the root is R right and similarly uh how many elements are there in our interversal after the root uh those much elements will uh taken are post over traversal and here one more point to notice that we have done n minus 1 which basically means our last element was root and we have excluded that now that is our note uh will not be the part of our coming to be the last element okay so that's how we will uh run this requires a function again and we will find our answer and this question will run an of n Square time because you are every time you are it will take end time uh and end time to find out the element inside the inordinary traversal and running it again and again for all of the rule of finding all of the elements inside the tree making a completely tree which is of size let us say have node so it will uh run these this one will run uh inside this analog so that it will basically make it n Square time so uh in your interviewer might ask you to reduce this time complexity but you can do that do it by just using one extra space by using an uh nmap so and uh inside an order map in order map it will take of one time to find any value uh basically you will do but you will do you will assign uh the value of in order to reversal to keys and index to a value so you can find the index where you find the root value in of one time and that will reduce the time complexity to O of one uh that simple modification you can also do inside your code so I hope that makes the code and intuition very clear so I hope you like this video thank you so much for watching bye
|
Construct Binary Tree from Inorder and Postorder Traversal
|
construct-binary-tree-from-inorder-and-postorder-traversal
|
Given two integer arrays `inorder` and `postorder` where `inorder` is the inorder traversal of a binary tree and `postorder` is the postorder traversal of the same tree, construct and return _the binary tree_.
**Example 1:**
**Input:** inorder = \[9,3,15,20,7\], postorder = \[9,15,7,20,3\]
**Output:** \[3,9,20,null,null,15,7\]
**Example 2:**
**Input:** inorder = \[-1\], postorder = \[-1\]
**Output:** \[-1\]
**Constraints:**
* `1 <= inorder.length <= 3000`
* `postorder.length == inorder.length`
* `-3000 <= inorder[i], postorder[i] <= 3000`
* `inorder` and `postorder` consist of **unique** values.
* Each value of `postorder` also appears in `inorder`.
* `inorder` is **guaranteed** to be the inorder traversal of the tree.
* `postorder` is **guaranteed** to be the postorder traversal of the tree.
| null |
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
|
Medium
|
105
|
509 |
hello everyone welcome to my channel i am shankar dhyan a final student of computer science and i usually make coding videos and placement related videos so that you can do good in your interviews and like without wasting any time let's get started so today like this is like this week i'll be uploading the dynamic programming questions and this is the third question for this week and if you have not watched the previous two videos you can watch in this link and now if like the last two questions were in python so if you are not good in python or you like this java language more or if you are comfortable with java so you can watch the upcoming videos because the next three videos that is today tomorrow and day after tomorrow they'll be in java so if you are not able to understand like dp if you are not aware of what tp is and if you are completely new to this topic so this is a very easy question and very good question for starting the dynamic programming section so if we see the question is for fibonacci number and the fibonacci sequence and the question is that if we are given any number n then we have to return the nth fibonacci number so like what is a fibonacci number so fibonacci sequence is a sequence in which the next number is the sum of the previous two numbers and it is starting from zero and one so the next number will be zero plus one that is one and then it will be 2 then it will be 1 plus 2 that is 3 then it will be 2 plus 3 5 8 and so on now if we are given any number n we have to return the nth fibonacci number so nth fibonacci number can be calculated as like we can also use recursion that is uh the basic approach for solving this kind of questions that you may have studied so you just check the base cases that is if n is equal to 0 we will return 0 and if n is equal to 1 we will return 1 and else we will return we'll call this function and we'll give the sum of the last two numbers so this is the basic recursive solution that we have for this question and in this the overall time complexity will be linear because of this recursive calls and overall space complexity will also be linear because of the stack space that is taken by the recursive functions and okay now it is accepted and if we like try to use dp in this question so what we can do is we can create an array like it will be first empty and then we will add values of zero and one and then we can iterate like use a for loop to add the new values and the new values will be the sum of the last two values so in this we will add zero plus one that is one and this we will add one plus one that is two and this we will add 1 plus 2 that is 3 and so on so in this way also we can solve this question so we can create an array list of integer and call it as f so this is an error list of integers okay and in this we can append the values so we will first add 0 and 1 and then we will loop up to n so it will start from one and we will add the last value like the last two values so f dot get i minus 2 will be it will start from 2 so 2 minus 2 will be 0 that is the first value and two minus one which is once so f dot get one will return one so in this way we will add all the values and finally we return f dot get n okay and if we see the time and space complexity for this one so in this the time complexity will be big of 30 so which is constant because like if this n is not 30 like here it is limited so if this is not limited so it will be go of n and the space will also be go off and because here we are creating an array so it takes like linear space so both will be linear now in this way also we can solve with this question so this is the basic dp method that we can use but in this if we see that we are only using the last two values so we can also remove this and we can just take two values that is a and b and we can take c as the next variable so this a will be 0 and we will be b will be 1 and for c it will be a plus b and we will check for the basic case that is if n is zero we will return zero and if n is one will return one now uh we have initialized a b and c and we will use a for loop and c will be the sum of a and b and now a will become b and b will become c so that is we are assigning the next values for variables a and b and so like if we try to see the values that we have for i so for example if we have n is equal to 0 or 1 we will return directly if it is 2 so this loop should run for one time so in this way it will be running for one time if n is 2 that is i is equal to 1 and we will calculate these values once and c will become 0 plus 1 which is 1 and finally we return c this is capital n okay now it is submitted and if we see the time and space complexity for this so this is for dp method now in this uh here we can see that we are iterating from i is equal to 1 to n so this will be linear time because i is from 1 to n and other than this we have if conditions so this is constant time and all these assignments are constant time so the overall time will be really a linear because of this for loop and for the space complexity we are creating only three variables that is a b and c and we don't have any array as we did in the last method which was using dp so in this the space will also be uh constant like the space will be constant and the time will be linear so this is of o and this is of one so this is all for this question and if you like the video do like comment share and subscribe the channel and suppose if we are not able to solve this question so we can also see the solution section and here we can see that they have used recursion so which was the initial like it is the basic method uh using which we can solve and then we have a bottom up using memorization and a top-down approach and a top-down approach and a top-down approach and iterative top-down approach and iterative top-down approach and iterative top-down approach now these are all the basic methods and if we try to use some maths in this so we have a matrix exponential method and the time and space for this one is login for both and we have another method that is using some maths formula so we have a golden ratio and we can use this to directly calculate the values in constant time and constant space so these are some of the different methods using which we can solve this question and if we try to see the discussion section and just open the top three solutions so this is a java solution of linear time and constant space so this is using a while loop and having two variables having three variables has a b and sum and it is the method that we used in the end and then we can also solve this using recursion so like there are some basic methods which we can use if we see the other post so it is in python and here also we can see that the various methods and like in java here we can see that all the values are already computed and now if we do this if we run this function so it will return directly the values so it will work in constant time because we have already calculated all the values now it is possible if we have n as a fixed number like here it was 30 so in if it is not 30 then we can't use this method and we can use this method when we have like multiple function calls so this will be more efficient because it is returning in constant time so for example if we have t test cases and there are eighty number of function calls so for like once we will calculate up to the maximum value of n and then we can use just the function call to directly call the values like all the functions and get the values in constant time so this is more efficient for that like that case so that's all for this question and uh i'll be uploading some interview experiences also like in the upcoming weeks uh like some of the people who have already cracked some good companies product based companies and they will be sharing their experiences so do subscribe the channel and wait for some more days for it to come so that's all for this video thank you and goodbye
|
Fibonacci Number
|
inorder-successor-in-bst-ii
|
The **Fibonacci numbers**, commonly denoted `F(n)` form a sequence, called the **Fibonacci sequence**, such that each number is the sum of the two preceding ones, starting from `0` and `1`. That is,
F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.
Given `n`, calculate `F(n)`.
**Example 1:**
**Input:** n = 2
**Output:** 1
**Explanation:** F(2) = F(1) + F(0) = 1 + 0 = 1.
**Example 2:**
**Input:** n = 3
**Output:** 2
**Explanation:** F(3) = F(2) + F(1) = 1 + 1 = 2.
**Example 3:**
**Input:** n = 4
**Output:** 3
**Explanation:** F(4) = F(3) + F(2) = 2 + 1 = 3.
**Constraints:**
* `0 <= n <= 30`
| null |
Tree,Binary Search Tree,Binary Tree
|
Medium
|
285
|
77 |
hello welcome back to my Channel today let's solve another lead called problem number 77 combinations actually this is a daily challenge from the list code so I'm trying to solve this first the problem is switch forward getting to integer NK return all possible combinations of K numbers to learn from the release of 1 to n in Python we have the built-in Library in Python we have the built-in Library in Python we have the built-in Library we can use the combinations but here we are not going to do like that because I'm going to use a backtracking to write the function yeah basically my function will be like this I'm going to write a backtrack function and I'm going to call the backtrack after call I'm going to return my layout I'm going to have a global router link yeah now let me go to the Whiteboard to finish the yeah to finish the explanation and then go to the code 8 Editor to finish the coding now let's go to the Whiteboard to tackle what the problem looks like Yeah so basically when we are going to yeah solve the backtracking of combination of four to two that means from number one to four we are going to choose two numbers and there is no duplicate so how should we solve that this the first step is we should know this problem is about backtracking why should we know that because this is from Mass we needed to choose something and also we can check that and maximum is 20. okay maximum number is n so it means like this kind of problem we can use backtracking and also when we saw the like the permutations or combinations normally we should use backtracking to find all the possible solutions so this is the backtracking now let's go to the Whiteboard so if we are going to truth four numbers one two three four we just need to choose two numbers yeah so the first step there is a empty array after that we can choose one two three and four so this is the backtracking tree and after that for one we can choose two three and four we cannot choose one because there is no duplicate what about the two we can only choose the three what about the three we can only choose four so for two we can choose three and four three we can choose only four so this is the final result but how should we use backtracking we should use a empty array like a answer variable inside the backtracking tree and when we find the answer we should put this answer into our final result and then we're gonna return our results yeah so when surveys how should we find this kind of one two three four so this is basically a for Loop we can use a for Loop to find its bronze and after that we can still use the for Loop for the backtrack industry and what is this one when it goes to 4 we cannot choose five yeah because the maximum of the number is four we cannot choose five it means here there's nothing to return there's nothing we're gonna put it into our result so this is all our result now let me go to the code Editor to finish the coding and for after you see the coding you will yeah you will talk this is basically a backtrack template so a lot of the problems yeah if you did a lot of backtracking problems you will find your pattern at your template normally it should be very easy for such color medium problems sometimes the hard problem maybe yeah it's difficult to find the each of the conditions but for the medium problem of backtracking normally it should not be so hard if you practice a lot yes so for backtracking we're gonna put the variables inside what is the variable we are going to yeah find the so we are giving a n and K so what is the starting point is one two three and four so we are we're going to have our starting point the backtrack we're gonna call this number one so what is this one is our start point I'm going to use a start variable and also I need a empty array because I'm going to put this empty array into my result so what is this empty array I'm going to Define a variable answer for this empty array and then I'm going to write my backtracking function so what is the conditions to return it will find my answer so if the length of the array equals to yeah although this takes a little bit time but it is still okay with us to attack the length of the battery if this length is equal to K it means we find an answer so what should we do we should just put the answer already into our result and here we need a return to let it stop earlier and then we should use our for Loops so for I in Ruins we should just start so spoiler forward follow I we should start from this start and the start is one yeah and 2 and plus one because for the first Loop for the first layer of the backtracking we can only have one two three and four so what about here so this I is only this I can only start from one two three four so this start is one this is four so it means I will start from one two three and four and then we can use the back brackets so what is inside so for the next one as we know that from the Whiteboard let's attack so here is one so for the next one it will be two three and four yeah here if it is a two it will be three and four and then we can write our backtrack function for the next step so it will be start from one yeah because it cannot have duplicates and then we should have ever answer our answers to the plus this index I yeah because for the next back platin we need to put this I so we need to put one two three and four inside it is totally like this one two three and four inside yeah and here we can just append the answers because here we use the Plus for the python it is it means a copy of the answer we can just put it inside if we use the stack we have to append uh copy of the answers now let me submit it to tag if it really works after that I would change it to stack uh let's start if I miss if there is something wrong so here it should be yeah from the I it's not start because for each time as you can see as with if the backtracking from the start there are so many duplicates because with for the next backtracking it's not the start yeah as you can see here also from the Whiteboard for the next one there's not so many answers yeah so it means it's not from the start is from one actually it is a form I because for the first that's working I is zero for the next one it will be what for the first duct practice the I is 1 but for the next I should be two yeah for example here this is one for the next one it is a two and three and four so this is a y here should be I plus one yeah now let me run into two texts if it really works yeah as you can see it really works and it's pretty fast now let me analyze the time complexity for this backtrack entry as we know the number of is 20 and this is basically the depth of the tree it is a 20 and how many numbers how many blondes for you have so the case would be less than 20. so for the combinations of yeah of 20 to a number which would use a mass to calculate yeah it is basically say and pay so the final result will would be dependent on this I believe that is the time complexity uh now let's try to use our stack so if we can put the answers append this eye first and here we should change it to answers because it has already been appended after that we just need to answer the pop yeah because we append AI if we were to use the backtracking go to the next one if we didn't find we have to pop up pop it out so answers should pop yeah now let's here should be copy the answers yeah now let me run it to check if it works yeah as you can see this also works the only difference is here with us to copy the answer result here we use the in place we used this answer Yeah so basically it's the same yeah if we are going to analyze this kind of complexity like let's say a k so it's really dependent on this end and this case yeah so this is the time complexity to compare how many combinations for example this one four times three divided by two there are six without yeah but if this earn is like 20 yeah if this K is like maximum okay maybe 10 yes so the final result would be like um yeah the final allowed would be say 2010 yeah this may be the biggest number for the combinations so let's put say 20 it means 20 and factorial divided by yeah so if it is say 4 2 it is a four times three divided by 2 yeah so here will be fact 20 divided by factorial 10 and factorial 10. yes it is a very large number I didn't know about it but this is basically the time complexity yes thank you for watching if you think this is helpful please like And subscribe I will upload a module called permanent access bye
|
Combinations
|
combinations
|
Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers chosen from the range_ `[1, n]`.
You may return the answer in **any order**.
**Example 1:**
**Input:** n = 4, k = 2
**Output:** \[\[1,2\],\[1,3\],\[1,4\],\[2,3\],\[2,4\],\[3,4\]\]
**Explanation:** There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e., \[1,2\] and \[2,1\] are considered to be the same combination.
**Example 2:**
**Input:** n = 1, k = 1
**Output:** \[\[1\]\]
**Explanation:** There is 1 choose 1 = 1 total combination.
**Constraints:**
* `1 <= n <= 20`
* `1 <= k <= n`
| null |
Backtracking
|
Medium
|
39,46
|
662 |
hello everyone welcome or welcome back to my channel today we are going to discuss another problem but before going forward if you not like the video please like it subscribe to my channel and hit the bell icon so that you get notified when i post a new video so without any further ado let's get started problem is maximum width of binary tree will be given a root of binary tree and we have to return the maximum width of the given tree the maximum width of the tree is the maximum width among all levels right so a width of one level is defined as the length between the end node and nodes that is the left most node at the rightmost node where the null nodes between the end nodes are also counted this is very important point guys where the null nodes between the end nodes are also counted into the length calculation fine um so see over here let's take this example uh so see here we have to find the maximum width we have to find maximum width so here width is one two so here it is two in this level and over here although there are three nodes five six and nine but the width will be four why because this 2's left child which is null will also be taken into account right why we are taking this null into account because they have written here that it is the length between the end nodes where the null node between the end nodes are also counted that is these are the end nodes in a five and nine and between these five and nine there is this null node so this will also be counted so the width will be 4 so maximum width is 4 so output will be 4 here fine right i hope you understood this test case now let's see how we can approach this problem so we have one three two uh let's say we have then five six and nine see guys like when we see this problem now first thing we have to find the width so first approach which comes into mind is the level order traversal we can do fine some what i also thought one approach like the other approach which i thought was one that i was thinking that maybe see here it is so sure like this is sure that the last uh what i was thinking like i'm telling you my thinking so the last level will have the maximum number of nodes because it's the last level right it will have the maximum number of nodes so what i thought was that i will calculate the height of the t so height will be here what one two and three so height is three so what i will do is i will know the last c over here the width was 4 so what i will do 2 raise to per h minus 1 that is 2 raised to the power h is what 3 minus 1 2 raised to power 2 so this will be 4 so this will be the number of nodes in the last level fine and this will be my output so this was i this is what i was thinking that i will find the height of the tree and then i will uh just simply do two raised by h minus one and those will be the number of nodes in the last level and that will be the width maximum width but this approach is not correct fine why see this approach is working in this test case when we have this test case but let's see other test case so over here what i'm doing is i'm just changing this test case a little bit here i have 1 3 2 5 and 6 but 9 is the left child of 2 now guys now see now the width here will be 1 here will be 2 but here it will be three not four why because now these are the inmost nodes now here although here we have null but these are the end nodes of this level five and 9 and here there is no null so nothing needs to be taken into account right this null is outside like this null will not be taken then because here they have written that between the end nodes if there is no node then only take it so here between the end nodes these are the end nodes that is not null so here output will be three but according to if i do this if i follow this height approach like finding the height and the doing 2 raised to by h minus 1 then here also height will come out to be 3 so 2 raised to the power 3 minus 1 will be 2 raised to by 2 so 4 but output is 3 fine so this approach is not correct this is not correct so we this is one thing which we saw that why this approach is not correct now again we can go back to the level order traversal so we will think that okay since we have to find the width of the trina we have to find width so we can go level by level and we can calculate the width that thing we can do so let me draw the tree again so we have one three two five six and nine right this is the tree which we have now guys see what is level order traversal level order reversal we can simply if you are thinking that we can do like this so initially in the when we are here so our one will be in the queue so in level order we use queue right we use q if you're not aware that how level audit reversal works i will highly recommend just go through that first so yeah here first of all in the queue one will be there so width will be what one then when it comes to this level so the q will have three and two fine and the width will be something like uh two there are two nodes so width is two then when it comes to this level then uh width will be what five six now ideally here it should come null right and then it should come nine then only your will come out to be four width will come out to be four and that is the output four fine so what we can conclude from this is that when we are at here when we are adding in the queue so even if the if two is left is null we will have to add it in the queue we have to add it in the queue right so this way we can get the answer right now this is one approach now this approach may not work in another test case so let's take that another test case over here one three five six nine so guys see we are exploring right we are trying different approaches so we have this 2 9 fine and then we can have see now see let's let me change this test case to something like this we have this right now see over here initially we will have what one so which will be one then we go to the second level and in the queue we will have three and two so width will be two now for this 3 we will add 5 and 6 in the queue 5 and 6 and for this 2 we will add what null and null because we if you remember we concluded that even if it is null we have to add it in the queue so for this two both the left and right are null so null will be added null this is for left this is our right child now according to this c according to this width is four there are four elements in the queue but ideally width is only two max weights is two here in this case so what we have to do see there is this k this case that if from the queue the last nodes are null we just do not take them we do not consider them so if you're following this approach what you can do is that in your level in your queue you can just remove uh you can just check if there are nulls from the end so if there are null from the end you can just simply remove them and then whatever is left will be your width right so this is one approach let me know a test case if where you can see that this approach is failing but i think this approach can work so try once the try uh implementing this approach once and let me know so what you can do is like you can check in the queue that if there are nulls from the end just simply remove them fine and then the whatever is left will be your uh here so here when we start from the end there is not null so we just stop there we do not go further so this will be four only because here last was not none so we will just stop here last was null so we go null and then we stop fine so this is one approach right now let's discuss one more approach which is a new learning from this question that is the really interesting approach and that is used many times in different questions so we have one three two five six and nine fine see guys we can use something called as indexes we can do index we can give indexes to the nodes indexes in a binary tree how we can do that see it like an array when we have array what we do we give zero these are the indexes right in the array two three nodes also we can give indexes if you have uh implemented heaps and you know how priority q or heaps are implemented then you might know this uh approach but don't worry if you are not aware we can discuss now so see we are giving indexes to the nodes so initially to the root we will give index 0 fine to the root we will give index 0 and to the left child we give 2 into if the root index c if the root index is i so the left child index will be 2 into i plus 1 that is if here root is the index is 0 so left child which is 3 will have 2 into 0 plus 1 which is 1 so index for this 3 will be 1 and for the right child index will be 2 into i so 2 into y 2 into i plus here it was plus 1 here it is plus 2 fine so here we will have 2 into 0 by y because i is the root index and root index is 0. so 2 into 0 plus 2 so this will be 2 so here we have 2 fine now see now if we go to this left to this node 3 so 5 what will have 5 will have what index 2 into what is the index of the root node here root no like parent node you can say i is the parent node index parent node so here for 5 parent node is three so it had it has index one so two into one plus one this will be three so five has index three and six will have two into parent index is one plus two so this will be 2 into 4 right 4. similarly over here there is no left side so nothing we will do we will just find out the right child index so 2 into parent index is 2 plus since this is right side so 2 so this will be 6 right now see guys now see using these indexes we can find the maximum width of the tree how if you do over here you see this is the last index last node in x2 minus if we do this first node which is three's index which is one and we do plus one because these are indexes right so this will give us two so this will be the mid width of the this level similarly if we do for this level last level so here what will happen last nodes in this level last node is nine so nine's index is what six minus in this level first node is what five its index is what three and plus one we will do because these are indexes so here c what we get 4 which is 4 is the width of this tree what is the uh sorry weight of the level fine i hope you understood this approach you can also try this approach if we have this let's say we have this line something like this the left child then the index for this nine will be what two into uh parent is two plus one which is five so then see what will be the width this is the last node in the level so 5 minus first node index 3 plus 1 so this will be 2 plus 1 3 hence width will be 3 which is correct right so this is one approach we can use to find the maximum width of the binary f of binary tree uh so i hope you understood the approach let's discuss the code once also do try the second approach which we discussed uh the this one let me know if any test case is failing for this approach so see very simple this approach is very simple basic level order traversal is we are doing right basic level order traversal just that with every node we are storing its index right so in the queue in the cube we will have a pair like in the basic uh when we have basic level order traversal what we do we just uh store the like this now the node in the queue but here since we have to find we have to know indexes also of each node like these indexes right so what we will be doing is we will be storing we will have a pair and we will be storing the node and its index in the queue so it will be up here and see initially we are adding in the queue root and index zero so here initially we have taken index as zero for the root fine uh then we are just this is the classic level order reversal c until q is not empty we find the size of the queue fine we find the start index and the end index of the nodes this is the first node in the level this is the last node in the level so see over here what we did for this level we found out the index of the first node this 5 and we found out the index of the last node that is 9 that was 5 then we subtracted them and we did plus one so this was the width of this level so this is what we are doing here we are finding this for the first node in the level q dot front we are finding the second is what the index so start this will be the start will store the index of the starting node in the level and end will store the index of the last node in the level and then we are just updating our answer so answer will be maximum of n minus start plus one fine and then we are what we are doing just we simply we are sampling have this we have simply this for loop and we are just adding in the queue then left and right child of the next like the next level fine this is like a classic level order reversal so we pop the front this front element from the queue uh index so if node left is there node left and two into idx plus one for the left child this index will be there idx is the parent c this is the parent number so with that index we have taken and this is for the right child so i hope you understood this approach if we submit this it's a getting accepted time complexity c over here we have this q right and in the queue uh how many uh times this q will go on so it will be depending on how many number of nodes are there right so it will go for each node so time complexity will be you can say o of n find fine of n uh and for this inner loop um you can say that uh we can basically we can have for this less last level if you see we can have uh let's say we have m nodes for uh or we can say if we have max size maybe we can take as m so we can have n into m time complexity and space complexity will be uh this cues how many nodes will be there in the queue fine uh so i hope you understood the problem and the approach let me know in the comments if any doubt and if you found the video helpful please like it subscribe to my channel and i'll see in the next video
|
Maximum Width of Binary Tree
|
maximum-width-of-binary-tree
|
Given the `root` of a binary tree, return _the **maximum width** of the given tree_.
The **maximum width** of a tree is the maximum **width** among all levels.
The **width** of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.
It is **guaranteed** that the answer will in the range of a **32-bit** signed integer.
**Example 1:**
**Input:** root = \[1,3,2,5,3,null,9\]
**Output:** 4
**Explanation:** The maximum width exists in the third level with length 4 (5,3,null,9).
**Example 2:**
**Input:** root = \[1,3,2,5,null,null,9,6,null,7\]
**Output:** 7
**Explanation:** The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7).
**Example 3:**
**Input:** root = \[1,3,2,5\]
**Output:** 2
**Explanation:** The maximum width exists in the second level with length 2 (3,2).
**Constraints:**
* The number of nodes in the tree is in the range `[1, 3000]`.
* `-100 <= Node.val <= 100`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
35 |
welcome everyone today we're going to solve the number 35 lead code question considered easy called search insert position as you can tell there are a lot of likes meaning that it was indeed very easy question but let's break it down given a sorted array of distinct integers and a target value return the index if the target is found if not return the index where it would be if it were inserted in order you must write an algorithm with o log and runtime complexity okay so as you can tell here if we're given the nums as there are example one two three four five different scenarios as you can tell okay now we're um given the same nums as an input but actually there is a variation of a target then let's take a look at the first example if target is 5 we should return 2 because in this case we have a target inside an array given array we have to return the index of the element which is zero one two okay second if target is two which doesn't exist in here should exist between one and three that's index position one so that should return it what about seven if it's seven still doesn't exist this should be located at the last one so scripture term four zero is the zeroth one and if target is zero and you know okay so that's easy but first let's take a look at the edge cases first edge case in python or a program language means that it's sort of the extreme exceptional cases where we need to take into account and it's better for us to you know think of it um as your kind of barometer cases okay so let's take a look at uh example so let's say what if uh let me see so there are four scenarios first of all um what i'm saying is okay so let's see if target is less than right so given the fact that all these arrays are sorted so there are two scenarios right okay actually there are actually a couple of scenarios let me just write it down here if let's say nums is one three five six scenario one is when the target is less than the minimum of sums of nums i mean in this case okay scenario two is um target is when the target is larger than max of slums then what should we do scenario three is when the target is inside nums scenario 4 when the target is not inside numbers okay so there are four cases here based on the problem uh if the number is one three five six we have the target could be located at the very first which is you know less than the minimum of it or in between some around okay which is not which is inside but you know um yeah inside nums okay actually we have to think inside nums this means target is literally inside norms right in this case it's gonna be like three or five and then the three is uh when the target is not inside nums means it should be located somewhere but it's not exactly the same as one of these values right and the target is larger than max is located at the very last okay let's take a look at the code so when the target is less than mean if target is smaller or less than uh the minimum of nums which is in this case sub num sub zero right as you can tell this is sorted right you can say like mean numbers but i just put it this way to make sure return what i would have to return is um actually zero right because as you can tell is we have to return the indices of that if the target is smaller than the minimum then it should be located at the zero syntax so we should return zero that's what we need to return when the target is larger than max then if target is larger than max means the last element of minus one ring all we need to return length of numbers that's what it needs to be uh located or placed right third when target is inside numbs if target is inside of nums then what we need to do is we definitely need to look through each element and we have to check hey if nums of i is that's just target then we definitely need to return that either index okay what about the last cases if target is not inside of nums okay we already covered these three cases okay first please pay attention to like the reason why i number like this uh because i want to first start with the very exceptional small cases and eliminate those cases and the last one step you know when the program hits like 20 line 26 it really assumes that okay so target is should be located somewhere inside nouns but the target is not necessarily the same as any of the element so if target not in num this means then what i mean by this 4i in range of length of nums meaning when we iterate their nums we should say hey if num sub of i is it greater than target meaning that in this case it's sums of i it's 3 is it greater than target then what we want to is we at that time we want to return i right the reason why it's not checking smaller here is if this is like let's say four there are a lot of elements that are smaller than four but we want to include when the target is just smaller than the num supply meaning we want to actually let me uh speak the other way around i want to like embed the target and in this position where at that value of numbers of i just got greater than the target because that's the exact position in this case zero one okay which is the third three's position so that's why it does let's run it and see if this working i bet it works run time add or return outside function what's going on oh so everything should be indented right doesn't indications matter so much in pocket doesn't seem better watch out for that right now when you do your coding um globe or some target i think i guess i have a typo here target okay these are all good debugging process that helps you understand what's going on nom okay i'll get it should be nums okay so a lot of typos so it's because i could like multitask you have tempted to run code too simply try in a few seconds or subscribe to reduce wait time okay so i guess probably need to wait but in the meantime i just want to point it out that i want to tell you that um these first two scenarios are very obvious sec third is also obvious okay but the last one is uh when the target is not in gnomes i mean if that's not you know if the target is not somewhere in between nums means uh we have to include that target somewhere but actually but we have to find how to do it and this was the key line 28 in terms of sub i is what actually greater than target that's what when we need to return in this case 3 is greater than 2 right target two so we want to include we want to replace this three with two positions and we won't push the three to one right okay that's working i hope it works again it works all right so uh this was working pretty fun and uh please leave ever leave any comments if you have any questions or concerns and please subscribe to my channel i'll keep posting and i hope you have a great day okay bye
|
Search Insert Position
|
search-insert-position
|
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[1,3,5,6\], target = 5
**Output:** 2
**Example 2:**
**Input:** nums = \[1,3,5,6\], target = 2
**Output:** 1
**Example 3:**
**Input:** nums = \[1,3,5,6\], target = 7
**Output:** 4
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `nums` contains **distinct** values sorted in **ascending** order.
* `-104 <= target <= 104`
| null |
Array,Binary Search
|
Easy
|
278
|
871 |
Hello guys welcome gardens medicine maine mirwaiz baby discussion question minimum number of refueling stop this question more position destination with subscribe must subscribe button - subscribe button adhik hai button - subscribe button adhik hai button - subscribe button adhik hai to bhi return - 110 thodi pimple need to bhi return - 110 thodi pimple need to bhi return - 110 thodi pimple need to top tourist destination and see the question is The subscribe to the Page if you liked The Video then subscribe to subscribe Do gas safety from this point Vaikuntha Station Superintendent subscribe to the Page if you liked The Video then subscribe to the Page The Water of Batayenge MS Word 90 in this case which cannot be reduced by doing what will happen in the we tours and tours from this point 2837 from this point reach difficult subscribe to ki vinod To Maximum Difficulty To Address Political Rally Level And Distance From The Great Gatsby To You Love You To The Number Of subscribe this Video subscribe The Video then subscribe to the Page if you liked The Video then subscribe to The Road Target Subscribe In Existence It Will Be Difficult for the Newspaper subscribe The Video then subscribe to the Page if you liked The Video then subscribe to Hai to Acting Chaube Station Near to Find Out What is the Distance Between Using Which Station Regression Withdrawal The Video then subscribe to the Video then subscribe to subscribe Ripping starting from difficulties in between and in the number of cases per liquid subscribe in a reader meaning of the maximum it will be the maximum subscribe And subscribe The Amazing station and subscribe button and equal to value presentation that sleep coordinator status only can We can do this particular result otherwise this channel subscribe person subscribe button - one who can not find any way subscribe button - one who can not find any way subscribe button - one who can not find any way subscribe hai to trans sakta hai school let's make this stop software wrong answer elected as the president has no and in case of way subscribe Video Subscribe Problem Subscribe Competition Subscribe Frustrated To War Maximum Placement In Two Stations Take More Video then subscribe to the Page Select Element Specific You Will Be Amazed At Will Be Holding In Desperate You No Deduction Computer Will Be On The Video subscribe The Video then subscribe to subscribe our ABVP lu oil we are not forget and disgusting mist that causes blood you can know used oil subscribe this Video Please subscribe and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to I will be using priority queue and adding this particular station with station attended increment subscribe And subscribe The Amazing Video subscribe and subscribe the Channel and subscribe Thursday are used in the test will be rs that now electronics code train successfully added this a Pad Submitted Successfully The Time Complexity In The Cases In Writing And Editing Of Any Value To Login Subscribe To Times Of Baroda Hua Hai Kar Do
|
Minimum Number of Refueling Stops
|
keys-and-rooms
|
A car travels from a starting position to a destination which is `target` miles east of the starting position.
There are gas stations along the way. The gas stations are represented as an array `stations` where `stations[i] = [positioni, fueli]` indicates that the `ith` gas station is `positioni` miles east of the starting position and has `fueli` liters of gas.
The car starts with an infinite tank of gas, which initially has `startFuel` liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
Return _the minimum number of refueling stops the car must make in order to reach its destination_. If it cannot reach the destination, return `-1`.
Note that if the car reaches a gas station with `0` fuel left, the car can still refuel there. If the car reaches the destination with `0` fuel left, it is still considered to have arrived.
**Example 1:**
**Input:** target = 1, startFuel = 1, stations = \[\]
**Output:** 0
**Explanation:** We can reach the target without refueling.
**Example 2:**
**Input:** target = 100, startFuel = 1, stations = \[\[10,100\]\]
**Output:** -1
**Explanation:** We can not reach the target (or even the first gas station).
**Example 3:**
**Input:** target = 100, startFuel = 10, stations = \[\[10,60\],\[20,30\],\[30,30\],\[60,40\]\]
**Output:** 2
**Explanation:** We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
**Constraints:**
* `1 <= target, startFuel <= 109`
* `0 <= stations.length <= 500`
* `1 <= positioni < positioni+1 < target`
* `1 <= fueli < 109`
| null |
Depth-First Search,Breadth-First Search,Graph
|
Medium
|
261
|
45 |
hello everyone let's all jump game 2 from lead code let's understand the problem statement you will be given array of elements where each element represents the maximum jump you can make from current index it is always guaranteed that if you are starting from index 0 you can reach last index we need to figure out minimal jumps required if you see here from index 0 I can take one Jam so to reach index 1 from index 1 I can take 3 champ so I can reach last index so the minimal jumps required here is 2. it's a very good technique on greedy algorithm with sliding window let's see how can we do that very simple we take a window from index 0 so that my current window size is 1 starting with index 0. and when you are at index 0 obviously Jeff jump count is 0 and my Max jump index is zero what we are going to do is on every window we figure out the max jump index let's see here I am starting from index 0 so from index 0 I can jump up to index 2. now see that my current jump which is greater than Max jump index so that I can update Max jump and as jump index as 2. and also understand my current index value reaching end of the window whenever it is reaching end of the Indo it means we figure out the maximum gem from current window so update the window index as Max jump index then increment the counter now jump count becomes one then move on to the next window so my next window starting from index 1 to index 2 so we increment our current pointer now my current index is 1 from index 1 I can take current jump till index 4. now we see that my current jump is greater than Max champ index so we update the max jump index as 4. so then we move on to the next index now from index 2 you cannot make any gem because the value is 0. now we also understand that my current iteration reaching end of the window so we calculated a maximum jump we made from a given index so first we update the window indexes Max champ index which is 4 then increment the counter so my jump count becomes 2. as my window index reaching end of the array we just written jump count which is 2 that's it so it's a very good technique on greedy algorithm with sliding window so let's see let me walk through the code so you will be given an array of elements as a first statement we initialize window indexer 0 jump count as 0 then Max jump index has zero we start from index 0 we move until my window index less than last index on every iteration we update the max jump index whenever my current jump is greater than Max jump index that's it whenever my current index reaching end of the window we update the window index as Max jump index then we increment the gem counter on every iteration we just increment the index finally we return the jump count that's it the time complexity obviously be linear we are starting from zeroth index to n minus 1 and space complexity will be constant that's it let me go and submit the solution foreign that's it so hope you like the explanation please do subscribe and share thanks for watching thanks for your time
|
Jump Game II
|
jump-game-ii
|
You are given a **0-indexed** array of integers `nums` of length `n`. You are initially positioned at `nums[0]`.
Each element `nums[i]` represents the maximum length of a forward jump from index `i`. In other words, if you are at `nums[i]`, you can jump to any `nums[i + j]` where:
* `0 <= j <= nums[i]` and
* `i + j < n`
Return _the minimum number of jumps to reach_ `nums[n - 1]`. The test cases are generated such that you can reach `nums[n - 1]`.
**Example 1:**
**Input:** nums = \[2,3,1,1,4\]
**Output:** 2
**Explanation:** The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
**Example 2:**
**Input:** nums = \[2,3,0,1,4\]
**Output:** 2
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 1000`
* It's guaranteed that you can reach `nums[n - 1]`.
| null |
Array,Dynamic Programming,Greedy
|
Medium
|
55,1428,2001
|
1,836 |
Hello everyone, today we will solve the next problem on structures using this algorithm as part of the preparation for a technical interview task number 1836 we need to remove all repeating notes from the unordered link sheet the task is marked as average, it is given a link list and asks to remove all notes that appear more than once in the first example this two does not need to be removed, not only one of the mods needs to be removed both, the note that is there twice here will return only one and three here we select everything completely but yes and we will return an empty link list in the third example we have three found two times two found three times and all they need to be removed, only 14 will remain if you want to think about your answer then press pause on the video and I will come to its solution in order to solve this problem we will go through the sheet twice the first time we will count how many times each knife occurs these values we will write it down in the mayor and values we will write it down in the mayor and values we will write it down in the mayor and the second time we will go through the sheet, do not delete those notes that were encountered more than once, we will immediately create a map that we will put as many coordinates as we have shouted and we will fill this one out, we will help from then which we will also create now, we will call it an accountor and we will transfer it there hit let's implement this method cantor returns them and shmup receiving like this 11 help or forest now let's create m in which we will put all the values now let's go over everything with a bow but also just count how many times fall inside but until repeats until you give me and zero we will continue this is your bow and here inside past we will put either but if for the first time we see some kind of but then we will write the number 1 there and if not then you will add one to those that have a value with the key in the sky it will be value not from which we passed and for the value we will take either the already existing or brothers unit, it will either be the treatment already or will be 0 and to it we will add 1, so we will count how many of each value occurs and will return we are here we have now called this method we counted, we passed it back and now we will continue with the deletion; back and now we will continue with the deletion; back and now we will continue with the deletion; for this we will create auxiliary forest with from zero and then we will pass the next value, we will connect it with the fact that we had a boss, this is the auxiliary who's not we need in order for us to bury the initial value of this when you all will count we will return exactly this one but with its next value because the first value here will be 0 its next value will be exactly what remains of the move that we had at the beginning since we will remove the repeating values we will also add here additional auxiliary nose which we will work it will have to be equal now we will go through the helper corner of the memory we will always have a value so we and here are interesting alpert from nyx now we want to see if the helper that nyx met more than once in the sky when we delete it if it is equal to one once then you just go to the next year we and pass it the key to the port text and see if the value is greater than what the day when we delete this hold up next the index gets the value next that is, we don’t delete it, nothing is, we don’t delete it, nothing is, we don’t delete it, nothing would sit just this arrow removes and rearranged for the next year if we have a value of one then we’ll just move on to look one then we’ll just move on to look one then we’ll just move on to look at the merged and but when you’re done with this at the merged and but when you’re done with this at the merged and but when you’re done with this sculpted fell we will return the ends of which we’ve written down here so I’ll which we’ve written down here so I’ll which we’ve written down here so I’ll start it’s not work why here we need to it’s not work why here we need to it’s not work why here we need to take the shaft on what we want to see what then it will be the value they are simple but here this one we never finish it so we need to put excellent now this is the correct solution let's check one example so that we return empty to super this works these are all the solutions thank you for watching this video if you liked it please put it like see you next video bye
|
Remove Duplicates From an Unsorted Linked List
|
count-ways-to-make-array-with-product
|
Given the `head` of a linked list, find all the values that appear **more than once** in the list and delete the nodes that have any of those values.
Return _the linked list after the deletions._
**Example 1:**
**Input:** head = \[1,2,3,2\]
**Output:** \[1,3\]
**Explanation:** 2 appears twice in the linked list, so all 2's should be deleted. After deleting all 2's, we are left with \[1,3\].
**Example 2:**
**Input:** head = \[2,1,1,2\]
**Output:** \[\]
**Explanation:** 2 and 1 both appear twice. All the elements should be deleted.
**Example 3:**
**Input:** head = \[3,2,2,1,3,2,4\]
**Output:** \[1,4\]
**Explanation:** 3 appears twice and 2 appears three times. After deleting all 3's and 2's, we are left with \[1,4\].
**Constraints:**
* The number of nodes in the list is in the range `[1, 105]`
* `1 <= Node.val <= 105`
|
Prime-factorize ki and count how many ways you can distribute the primes among the ni positions. After prime factorizing ki, suppose there are x amount of prime factor. There are (x + n - 1) choose (n - 1) ways to distribute the x prime factors into k positions, allowing repetitions.
|
Array,Math,Dynamic Programming
|
Hard
| null |
789 |
hey what's good guys it's illa bella here i recorded stuff on youtube chat description for all my information i do all liquid problems uh make sure you subscribe to this channel give me a big thumbs up to support it and this is called escape the ghost you're playing a simplified pacman game you start at the point of zero and your destination is target at the position of zero target one there are several ghosts on the map the add ghost uh starts at ghost i zero and ghost i one each turn you and all ghosts simultaneously may move in one of four cardinal directions north east west or south going from the previous point to a new point one unit of distance away you escape if and only if you can reach the target before any ghost uh reaches you for any given moose the ghost may take if you reach any square including the target at the same time as it goes uh it does not count as an escape return true even only if it's possible to escape well let's look at those examples we got uh ghosts uh the first one zero the second one zero three target zero one and we return true you can directly reach the destination zero one at a time one while the ghost located at one zero or zero three have no way to catch up with you here uh ghost one zero target two zero and we return false you need to reach the destination to zero but the ghost at uh one zero lies between you and the destination here goes uh two zero the target one zero will return false the ghost can reach the target at the same time as you all points have coordinates with absolute value which is less than or equal to ten thousand uh the number of ghosts will not exceed one 100 go ahead first we calculate the manhattan distance of a starting point to the target we take an absolute volume uh let's copy that real quick that target okay at the position of uh zero plus we can copy that again and paste and the target of one and you know guys then manhattan distance means uh the distance between two coordinates between yeah like between two coordinates or between two vectors uh points uh in the grid based on a strictly horizontal and or vertical path and you can imagine a 2d matrix um let's say you got 0 1 2 three and here as well like zero one two and three the point is um all those paths from the bottom left corner to the top right corner have the same distance you're gonna go here and here in order to get to the top uh right corner you can go here right like this uh you can go like this for example yeah you can go like this you know you see these like you know here then here and here or you can go you know you can go here as well yeah or whatever you can go here okay yeah you know what i'm saying um next um you create a for loop and we are looping through those uh goes we can copy that real quick and say goes and at each iteration we calculate the manhattan distance uh between the ghost and the target and d is equal to uh math the absolute volume the ghost the position of zero minus uh you know minus the target um at the position of zero and plus uh we can copy that as well and paste right here but change uh one and one then uh in the case when the absolute distance uh the manhattan distance uh between the ghost and the darker is less than or equal to maximum we return false automatically means that the ghost would eat the pac-man eat the pac-man eat the pac-man right you could notice from the description of this problem otherwise we return true when we're out of that loop that's it let's run this code accept it good let's submit success great um thank you guys for watching leave your comments below i want to know what you think follow me on social medias uh follow me on instagram admin snapchat and have a good one bye
|
Escape The Ghosts
|
kth-largest-element-in-a-stream
|
You are playing a simplified PAC-MAN game on an infinite 2-D grid. You start at the point `[0, 0]`, and you are given a destination point `target = [xtarget, ytarget]` that you are trying to get to. There are several ghosts on the map with their starting positions given as a 2D array `ghosts`, where `ghosts[i] = [xi, yi]` represents the starting position of the `ith` ghost. All inputs are **integral coordinates**.
Each turn, you and all the ghosts may independently choose to either **move 1 unit** in any of the four cardinal directions: north, east, south, or west, or **stay still**. All actions happen **simultaneously**.
You escape if and only if you can reach the target **before** any ghost reaches you. If you reach any square (including the target) at the **same time** as a ghost, it **does not** count as an escape.
Return `true` _if it is possible to escape regardless of how the ghosts move, otherwise return_ `false`_._
**Example 1:**
**Input:** ghosts = \[\[1,0\],\[0,3\]\], target = \[0,1\]
**Output:** true
**Explanation:** You can reach the destination (0, 1) after 1 turn, while the ghosts located at (1, 0) and (0, 3) cannot catch up with you.
**Example 2:**
**Input:** ghosts = \[\[1,0\]\], target = \[2,0\]
**Output:** false
**Explanation:** You need to reach the destination (2, 0), but the ghost at (1, 0) lies between you and the destination.
**Example 3:**
**Input:** ghosts = \[\[2,0\]\], target = \[1,0\]
**Output:** false
**Explanation:** The ghost can reach the target at the same time as you.
**Constraints:**
* `1 <= ghosts.length <= 100`
* `ghosts[i].length == 2`
* `-104 <= xi, yi <= 104`
* There can be **multiple ghosts** in the same location.
* `target.length == 2`
* `-104 <= xtarget, ytarget <= 104`
| null |
Tree,Design,Binary Search Tree,Heap (Priority Queue),Binary Tree,Data Stream
|
Easy
|
215,1953,2207
|
961 |
hello everyone and welcome back to another video so today we're going to be solving the lego question and repeated elements in a size 2 and area all right so we're going to be given an integer area called nums and we have these following properties so the length of it is going to be 2 times n now the number of unique elements we're going to have is going to be n plus 1. now one thing to note i know in all the examples that the unique elements are going to be sequential right so it's one two three and so on but that's not necessarily the case okay and okay so we have that and exactly one of the elements of nums is going to be repeated n times so let's take a look of an example and try to understand it better okay so based on all the properties we just saw let's try to extract as much information as we can so in this case we have this array right and let's just take a look at the length of it so we have 1 2 3 4 5 6 7 8 9 10. so the length of this array is equal to 10. now we want to find what the n value is so we know n is equal to the length of the array divided by 2 or in other words 2n is equal to the length right we just rearranged it so now keeping this in mind that's just 10 by 2 which is well equal to five so n in this case is equal to five so what does that mean so that means that the number of unique elements we have is going to be six so i'm just gonna say six unique elements okay cool so we know this information now how exactly can we find a solution so let's actually first look at the most naive or brute force solution that we can come up with which is we can use a set to keep track of the elements we've visited and if at any point element has already existed in the set that means that well we've already visited at least once before that means it is the repeated value so let's just see what that looks like in code directly since it is pretty straightforward so we're going to define a set over here and now we're going to iterate through each of the numbers so let's just do four num in nums and the first thing we check is if num is in the set now if it is that means well that's the repeated number but if it's not we have to add that number to the set so s dot add we're going to add num so that's it that's going to be our solution for this let's now discuss the time and space complexity of this now how many unique elements are we going to have so let's do everything with respect to n so capital n is going to be the length of the array okay so the number of unique elements we're going to have is going to be n by 2 plus 1. so this over here is the space complexity right which is nothing else but big o of n now let's look at and uh and essentially what that means is we add all of the unique elements to the set right so now let's look at the time complexity as well so now in this case there's a small observation that we can make so we would assume that it would be theta n and we have to iterate through the entire area but we don't right we need to think about how many uni sorry repeated elements are we going to have so the answer is actually n but how do we come up across that right so we know that n plus 1 is a unique element and the length is 2n so that's nothing else but 2n minus n plus 1 but now this is actually going to be 2n minus n plus 1 minus 1. now why are we doing this minus 1 over here now the reason for that is because the repeated value is going to be included in this right so one of the unique elements of the six that we're looking at in this case is the repeated value itself so this over here is just going to simplify to 2n minus n which is equal to n so that means n of the values are actually repeated so in other words let's say we only look at n array right so that's going to be in this case five so let's say we only look at five elements that does not guarantee us to actually find a unique element and this is a perfect example of that right so even if we look at the first n plus one that is not going to guarantee us that we find a repetition because in this case like this is the worst case right but we have one two three four five six all the elements the first n plus one elements are unique and what that really means is there's no repetition so if we look at just one more extra element that means that no matter what there is going to be a repetition of at least two elements right so in this case that is going to be the time complexity right so that is nothing else but n by two plus two extra elements right so plus one is a unique element and we're going to do an extra one then that means we already have seen the unique elements and we're looking at one extra one at least right so this is going to be the worst case time complexity which is again just big o of n so now let's actually try to look at a different solution for this so the basic idea over here is that we know for a fact that n of the elements are repeated okay so let's actually see how we can use this to our advantage so what we're going to do is we're going to take a total sum of this array okay so the total sum is in this case 25. now how exactly can we use this information so a very cool or interesting thing that we can actually do is we can actually get rid of all of the unique elements so what is the sum of the unique elements going to be so a simple way we could do that is we could take a set of this right so sets don't have any repeated values so set of the list and we can take its sum okay now in this case for example we could just do an arithmetic series uh formula but we are not guaranteed that all the unique elements are going to be consecutive okay so this is how we're going to get the sum of all the unique values now what are we going to do with this so the uh this sum is just 1 plus 2 plus 3 plus 4 plus 5 plus 6. so that is actually nothing else but 21 okay so i'll just write it down over here so that's 21 and this is the sum of all the unique elements okay so now what we're going to do is we have the sum of the unique elements and we have the total sum so when we actually find the difference of this so 25 minus 21 which is equal to 4. now this 4 is actually going to be telling us the sum of all the remaining elements now what exactly are the remaining elements well the remaining elements are nothing else but those that are being repeated right so how do we find out what that exact element is so we know how many elements are being repeated right so when we saw that the n there are n numbers that are being repeated but we're actually going to be dividing it by n minus 1. now the reason for that is because one of those values is part of this sum already we have already accounted for one of those values so we only need to account for the remaining n minus one values right so we're just going to do four divided by n minus one which is equal to in this case four by five minus 1 which is 4 by 4 which is 1. so that means that the number 1 is a number that is being repeated and that makes sense right which is correct right so 1 is the rep repeated number so let's look at the time and space complexity for this as well so the time complexity of this is going to be so we have to find the sum of the entire area so that's going to be n then we need to find the sum of the set so that's also going to be big o of n right and that's about it right so that's just going to be big o of 2n or this big o of n okay and now the space complexity over here is well we're actually going to be using a set again right in this case so we're using that set to find the sum so it's going to be the same as before which was you know big o of n so yeah so this is a mathematical solution to this and let's just see what this looks like in code okay so this is going to be our solution so we have the sum of nums and we subtract it with the sum of the unique elements and we divide it by n minus one right so i just did the value of calculation for n over here but instead of storing it in a variable since we're only using it one time i'll just directly substitute it over here okay and that's it so this is the value we're gonna return so that should be it those are two solutions that i did fine and thanks a lot for watching guys and do let me know if you have any questions
|
N-Repeated Element in Size 2N Array
|
long-pressed-name
|
You are given an integer array `nums` with the following properties:
* `nums.length == 2 * n`.
* `nums` contains `n + 1` **unique** elements.
* Exactly one element of `nums` is repeated `n` times.
Return _the element that is repeated_ `n` _times_.
**Example 1:**
**Input:** nums = \[1,2,3,3\]
**Output:** 3
**Example 2:**
**Input:** nums = \[2,1,2,5,3,2\]
**Output:** 2
**Example 3:**
**Input:** nums = \[5,1,5,2,5,3,5,4\]
**Output:** 5
**Constraints:**
* `2 <= n <= 5000`
* `nums.length == 2 * n`
* `0 <= nums[i] <= 104`
* `nums` contains `n + 1` **unique** elements and one of them is repeated exactly `n` times.
| null |
Two Pointers,String
|
Easy
| null |
64 |
hello in this video I'm gonna go over Lee code number 64 which is also called a minimum pad sum and the problem statement is that given an M times n grid filled with non-negative numbers we grid filled with non-negative numbers we grid filled with non-negative numbers we want to find a path from the top left to bottom right which minimizes the sum of all numbers along its path and we can move either down or right at either point in time so if we look at the example input we have a grid and to get from the top left to the bottom right with the minimum sum we would need to take the path from 1 2 3 2 1 and the total Sun would be 7 which is which would be our output so this problem immediately seems to be a DP problem mainly because of the minimum cost part it seems that as we go through the grid we can build off of smaller subproblems to get the final answer so let's explore this idea and let's begin by just considering the 0th column and let's say we wanted to find the minimum cost to get from the top to the bottom well it's obvious that at each point we can add the cost of the current point and the cost to get to the point above it so in this case the cost to get to this point would be 1 plus 1 which would be 2 and then the cost to get to this third point would be 4 plus the cost to get to the second point which is 2 so the total cost would be 6 so in this case we're building off of previous costs and we're constantly taking the cost to get to the point above so now let's look at the elements on the zeroth row let's say we wanted to find the minimum cost to get from the left to the right so in this case we would need to continuously add the costs to get the point on the left instead of the top so to get to this point would be 3 plus 1 and to get to this point would be 1 plus the cost to get to this point which is 4 so then the total cost would be 5 now let's look at an element in the middle so let's say we were looking at this 5 so now we have two options we can take the cost of the element to the left or the top and so in this case it would make sense to take the minimum of these costs because we want to find the overall minimum to get to the bottom right corner in this problem so if you constantly take the minimum then at the end we should get the minimum answer so these observations basically give us approach to solving this problem so again for the 0th column we're constantly taking the element on top for the zeroth row we're constantly taking the element on the left and then for our middle element we're taking the minimum of the element on top and element on left ok so let's go over the code to this problem now so the first thing we're going to do is we're gonna create two variables to represent the number of rows and the number of columns in the grid so in X is equal to grid size and then we know that if the grid size is zero then we can immediately return zero and in Y which is the number of columns would just be grid of zero dot size and then we want to iterate through all the elements because again we want to build off as we go through the elements so let me write the code for that and then again while we're doing this we know that if we're in the 0th column which is when j is equal to zero and i is greater than zero then we want to constantly take the element on top so then grid of i of j would be plus equals grid of i minus one of j and then we know that if we're on the zeroth row so that would be when i is equal to zero and J is greater than zero then we want to take the element on the left so in that case that would be grid of I and then a J minus one and then the last thing is that we know that if we're taking a middle and this would be if I and Angie are greater than zero then we want to take the minimum of the element on top and the element on the left so that would be grid of I of J plus equals minimum of grid of I minus 1 and J and grid of I J minus 1 and so at the end we would just return grid of x -1 and y -1 which would return grid of x -1 and y -1 which would return grid of x -1 and y -1 which would be the bottom-right element and so let's be the bottom-right element and so let's be the bottom-right element and so let's try running this code to see if it works and so we're getting that it's accepted so let's try submitting it and we get that it works so thank you for watching and if you enjoy this video don't forget to Like comment and subscribe
|
Minimum Path Sum
|
minimum-path-sum
|
Given a `m x n` `grid` filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
**Note:** You can only move either down or right at any point in time.
**Example 1:**
**Input:** grid = \[\[1,3,1\],\[1,5,1\],\[4,2,1\]\]
**Output:** 7
**Explanation:** Because the path 1 -> 3 -> 1 -> 1 -> 1 minimizes the sum.
**Example 2:**
**Input:** grid = \[\[1,2,3\],\[4,5,6\]\]
**Output:** 12
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 200`
* `0 <= grid[i][j] <= 100`
| null |
Array,Dynamic Programming,Matrix
|
Medium
|
62,174,741,2067,2192
|
84 |
I hope you're doing great our today's question is largest rectangle and histogram so the question says given n non-negative integers representing the non-negative integers representing the non-negative integers representing the histograms bar height where the width of each bar is 1 find the area of largest rectangle in the histogram so this is the given histogram represented as an array of the height of the bars the answer is this which is 10 which is 5 into 2 because each parts width is 1 right so clearly if we would have intruded for example 1 the maximum height we could have taken would be 1 right so and for example if you would have taken 5 6 & 2 then the maximum have taken 5 6 & 2 then the maximum have taken 5 6 & 2 then the maximum height we could have taken in this rectangle would be 2 because 2 is the height which is common to all the bars that we're considering so that makes it clear that if we have n bars then the rectangle that can be formed using those n bars the height which we can take will be the least of the n bars right ok so this is an unsorted array and we have a couple of techniques that we have listed down to be able to solve unsorted arrays so please pause the video have a look and come back so I think this is pretty easy right we can use a collection in order to store the group of members that we want from the array right which basically reveal our largest rectangle in the histogram and we can just use whichever collection we feel would be act in this so this would be the technique that we would go with to get the answer right so talking about which collection we should use so in this question we clearly know that at any particular bar we cannot define the maximum area looking at just that particular bar height so we need to know whatever elements we have traversed in the bust so as to determine that what is the maximum height that we can store or maximum height that we can use to be able to determine the maximum area of the rectangle right so in such cases stack is always handy so that would be our collection and another thing to note here is that if we get a bar with a height lower than what we have in the stack then it means that we have some bars with a more or a better height than this one and because there's a lesser heighted bar coming it would basically reduce the height of the rectangle that can be formed right so it's always better that we calculate the height or the area using the previous sites that we have seen right so that's what we'll be doing whenever we see an element whose height is less than what we have stored in the stack we remove all the elements from the stack until we get an element which is less than this particular current bar or the stack becomes empty right if we see a bar with height more than what we have right now we'll add it to the stack we'll keep adding and whenever we get a smaller one we'll calculate or if we are exhausted of all the bars we have gone through all the elements in the array then we will calculate okay so that's the approach right also we will be storing the indexes in the stack because when we do the math to calculate the maximum area we need the indexes to be able to understand how much width are they covering the histogram right so that's why we'll be storing the indexes so I'm sure we'll write the solution inhibit will be better so let's quickly get started okay so base conditions first so if Heights dot length equals zero then we have to return zero because we have no bars if Heights dot length sorry length equals one then you have to return heights of zero because that's the only bar so that's the maximum height okay now we need marks cuts and that's zero this is the maximum value that we'll be returning at the end of the function and we take a stack as I just told to store the indices sorry okay so to the stack we just add zero okay that's the index basically we are adding the first element elements index and now we write down a simple for loop so we start from one because we have already added right and less than Heights dot length I plus okay so let's get the current element we are dealing with which will be heights of pi if that's the current value and so if the current value is less than or let's go by the simpler one first so if it is greater than or equal to the oh sorry hi it's of stag dot peak right so we have the index right so that's why these we just look at the stack and we see is this current bigger than the bar whose indexes at the top of the stack if yes we just add this to the stack this meaning I write otherwise what we have to do is that while the stack is not empty okay and current is less than hi its stack dot peak so the same stuff right but only that the while the value current is lesser than whatever we are still seeing in the stacks we just want to pull out all the elements right so what we will do is that we will just get the them in an attempt wherever we will just get its abstract dot walk this time so we are removing it from the stack okay right and yeah so in order to understand what is the range we are for example at the for example I is 0 1 2 3 4 okay and we just popped out this particular index which is 3 so what we do is that we do a 4 right - 3 right so what we do a 4 right - 3 right so what we do a 4 right - 3 right so what we're doing is we basically want to understand how much is the width so what do you do is that we have to do a 4 - do you do is that we have to do a 4 - do you do is that we have to do a 4 - what is on the stack before this and a minus 1 so that it basically give us the length when we pop 5 then at that time for- prior to this if we love like to then the index of that and if the stack becomes empty then we just multiply it by I assuming that is the smallest heighted stack and we just get the entire area that it can form so what will basically do here is that if the stack is empty okay because it could get empty because we have popped an element from it over here so if the stack is empty then we just say that max equals two math dot max of max right and we want to multiply them so we are trying to find the area here into I okay so whatever index this is that we will just use that for example if we when we get a one will have the zero on the stack so we will do a one which is the index for this - so after we pop index for this - so after we pop index for this - so after we pop this out it will be empty so we won't have anything so we'll just do a one into the area of there's the height of this - so that will give us two which is this - so that will give us two which is this - so that will give us two which is actually the maximum area that can be from using this okay so right else if the stack is not empty then max equals two math dot max of max comma M into so as I said I - stack dot comma M into so as I said I - stack dot comma M into so as I said I - stack dot peak so we are not removing the element we just looking at what is there to get the lower end of the boundary and minus one okay so we do this and after we are done with popping out all the elements we have to add this okay so we just add it to the stuff okay so we're done with this loop now it is a possibility that in the given histogram we could get values like for example five six seven eight nine ten right so in that case we'll never see a bar of a lower height and we'll just keep adding them in the stack because of this for loop and you just exit out of the for loop right so we would not return the right answer if we do not check this after completing the follow that if stack is it's not empty okay if the stack is not empty so now similar to this we just want to basically imitate whatever we have done up above over here so we have to is that we'll just put the privacy sake I'll just copy this so we don't need this because we don't have new elements coming or anything like that we just know that there are elements which have not been processed in the stack right so until the stack does not become empty what we will keep doing is that we keep removing one by one elements and then just keep calculating the maximum area that we can form from them so I in this case as Heights dot length because that the elements of the array Heights have all been traversed and since here for I we calculate the previous one and minus the boundary on the other side of the array we were just taking this plus one to make the same calculations okay so I guess that should be it yeah okay and then we just have to return maths yeah let's see that work okay alright so the time complexity for this is off n because each element is being pushed into the stack once and being pulled from the stack only once so it's off in space complexity is orphan as well because we are using a stack to store all the elements so I hope you guys find this video helpful please comment in the section if you want me to create any videos on specific questions and I'll try to make them as soon as possible please like share and subscribe keep calling and take you guys
|
Largest Rectangle in Histogram
|
largest-rectangle-in-histogram
|
Given an array of integers `heights` representing the histogram's bar height where the width of each bar is `1`, return _the area of the largest rectangle in the histogram_.
**Example 1:**
**Input:** heights = \[2,1,5,6,2,3\]
**Output:** 10
**Explanation:** The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.
**Example 2:**
**Input:** heights = \[2,4\]
**Output:** 4
**Constraints:**
* `1 <= heights.length <= 105`
* `0 <= heights[i] <= 104`
| null |
Array,Stack,Monotonic Stack
|
Hard
|
85,1918
|
1,689 |
Hello hello everyone in this particular video music problem number one to zinta minimum number of decimal numbers problem statement this time number is this disciplinary effigy of its age it is here co and that without needing to solve 10851 300 ML number will give number to this number of Meaning this page number 90 and 1000 number one number only two off pimp here also zero and see here also don't think that picture VPN battery praise positive decimal in teaser Returns The minimum number of positive desi finally number doing great job man so gave you one in string Will go that in which will be having it ok then in third tourist format number is 11 assistant in comment k work number landscape will be found 1718 address system will be given latest 3222 tell how many days reminder numbers are needed for the number 10 tamil 3332 3232 example Star Plus 1111 That Radhe Maa Ne Number Because In The Visit Of Each And Every Number In Here CO And Forest Ke 100 32mb Represented By Impress 11000 Match Me Deccan Chronicle 8273 Procam International Ki 1234 This Particular Number 28 Account Number To Representative 238 Mil Will go and 220 Mahendra Court Cases mountain due for immediate and have been a nothing ok 18184 895 unauthorized 530 four cylinder increase of numbers code and five ok is very clear that has no relation with number will give number three layer 808456 output 5 this number one thing Can make egg subscribe and 273 loot 600 800 9 points 3400 press a little good and pipe ride point notice in the giver input's inference find the maximum digit and a reminder de Villiers maximum value fluid how to tell program for example in 2734 the maximum detected Ok morning office 8498 maximum if twist maximum value is nine convention maximum balance not suggest 90950 will give missions maximum website 100 or 125 of 100 noida 123 likes 432 airport 12345 34th is the price slashed lucid end numbers 12321 fountain ki lakshmi lede 120 how are days ho ya hai sudhar album live without ₹3 ko aapke kya karna hai trikudi pradan ₹3 ko aapke kya karna hai trikudi pradan ₹3 ko aapke kya karna hai trikudi pradan hi 19019 and work for representing chini to right 12345 34445 1351 fennel 125 number 12345 will give oo minute a unit-2 look number which can help minute a unit-2 look number which can help minute a unit-2 look number which can help and support and tried To Find The Maximum Digit Index Particular Number Is Wearable To Find Maximum It Surya Edison Twist How To Find Maximum Did In The Giver By Bigg Boss The Input Which Provided Is Given In Spring Government To Er Is Right To Convert School Number Into Interior Decor Exactly This Because they want people to know this page number one is section 120B of the Heroine Act, what is the maximum digit 1628 to end sit and wait, if you are going on a tour from quiet then you have to check and you are getting inputs from it. System hai to ek 274 basic character sahi nahi to convert this particular character * and delete welcome particular character * and delete welcome particular character * and delete welcome back side ke shav candidate don't like this 8 - Introduction विटेट के सके आसे कास होगा है - Positive works for this 8 - Introduction विटेट के सके आसे कास होगा है - Positive works for this 8 - Introduction विटेट के सके आसे कास होगा है - Positive works for interior only this line will only work well In the left and right this is that winters person growing strength will automatically convert this particular and character * Veerval - Character Veerval - Character Veerval - Character Narendra * 7 edit digit mujhe ka yaad 300 Narendra * 7 edit digit mujhe ka yaad 300 Narendra * 7 edit digit mujhe ka yaad 300 edit ok singh and addition agar jaise ATM se 100 kar rahe ho and you are present character Ghrit Function for its function posted in every character and every character in to the calling interior loot number no need to complete that opposition party's numbers are needed my first thing to do is that I c dot length function after all come down lens of history ok and Knees it means a different happened incident from this staff Indore record is favorite is I is not world tour final product get neither buy record's last one non express road ghee milk and then you were getting string gimmick interior would be on the other hand after brother A red character will definitely come then grind the previous high and add ghee to the terminal and enrollment tablespoon ghee to soften it what is the first thing to turn off that in that particular indica character it is left for them further and latest available from This point to - 1 hai available from This point to - 1 hai available from This point to - 1 hai tu is letter can us a what are you doing everything can I dim the screen light ok 534 95961 listen to the play list if the driver does this program then this 534 first method do mysore in paris my jo maximum value It is off the digit - think for yourself till the end, value It is off the digit - think for yourself till the end, value It is off the digit - think for yourself till the end, can any digital minus one ever happen or not, because there is positivity in it, a little Korea Ghaghra, I asked for a small number minus one, what should I do, first of all I have counted it from zero to K. Okay, its length, you take this particular question of ours, there is free leg. See, in this particular tank, first of all I measured that I am the post character, this point is more character, which decimal number is representing it, I have shown this. What did I do and how is it coming out, I have all the characters, both the time is behind the character from Fakaruddin, then the minute number is one or the number will leave the fiber which I have after being soft, they just adjust now I set that if this name is the latest fight is Greater Than - But yes, it is like that, then I said that Than - But yes, it is like that, then I said that Than - But yes, it is like that, then I said that Mexico, I changed my maximum, that is mine now, you must be excited again, so look back, it was 534, I mixed the pipes, I am pointing here, but it is okay. Again this and high value will be kept in the tender, what has come in his 133 2 minute tempo, women have already done, he is extracting the number in ignorance Three - 01 2012 Three - 01 2012 Three - 01 2012 extra return Max Baucus Ashlaghya school had done this greater than 900 nee note here But there will be no extra validity, Chinese will be back in the next rally and 262 days like this has happened, Nami Minister has done it and - happened, Nami Minister has done it and - happened, Nami Minister has done it and - zero's grace setting on it is will remain 23 nothing but for ok and after that I will check back again that One name is letter money mix it is it and spirit and max player max key value five robbers 152 I will not change back to Mexico okay and now after this the value of i will go three so this is our second form will come out nx video com
|
Partitioning Into Minimum Number Of Deci-Binary Numbers
|
detect-pattern-of-length-m-repeated-k-or-more-times
|
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not.
Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** numbers needed so that they sum up to_ `n`_._
**Example 1:**
**Input:** n = "32 "
**Output:** 3
**Explanation:** 10 + 11 + 11 = 32
**Example 2:**
**Input:** n = "82734 "
**Output:** 8
**Example 3:**
**Input:** n = "27346209830709182346 "
**Output:** 9
**Constraints:**
* `1 <= n.length <= 105`
* `n` consists of only digits.
* `n` does not contain any leading zeros and represents a positive integer.
|
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
|
Array,Enumeration
|
Easy
|
1764
|
741 |
cool in an N by n grid representing of field cherries each cell is one of three possible integers zero which in you can pass through one means the cell contains a cherry that you can pick up and pass for or negative one means this now contains a door that blocks away your task is to collect maximum number of cherries possible by the fine rows below start at position zero go to the other corner I'm moving right or down after reaching the bar bottom we turn to zero and then move left I'm going left or up in the router path when passing through a path cell containing a cherry you pick it up and this now becomes an empty cell okay if there's no random paths then no cherries come and collect it okay seems like either dynamic programming or even a BFS our first search how many states okay so it's a 50 by 50 grid and you could be at well one if 50 by 50 areas or that's true that's N squared or about 2500 so I'm making some leaps here some of it I feel like I've seen a variation of this in the past I don't so okay so basically but I think you could reduce this problem a little bit in that because there's gonna be a lot of states if you've had to return and then change the state and you have to keep track of which cherry you picked and stuff like this how many cherries are there it doesn't say so then we'd say it could be a lot of cherries so you could I think you could actually one I mean and in this case it's symmetric that in that you know going from the beginning to the end is the same as going from the end to the beginning in terms of cherry pick up so you so in this case I would simplify this as instead of going from the top to the bottom right to the top oh yeah top from the beginning to the end and then back to the beginning you could think of it as two going twice from the beginning to the end right so that's the first optimization I would think and I think in that case you could run them in parallel and I would say the reason why you could run them in parallel is because well you could just do that in general but why you should is so glad you could keep track of cherries more so that if you somehow are in the same spot you're in the same spot then you only pick up the cherry once so then you have this so your states in this case would be X sub 1 Y sub 1 and X sub 2 y sub 2 right and then yeah so yeah and if they're the same and then you can pick up cherries when you're there's the only edge cases if they're the same if the if X the first coordinate is you go to the second trips coordinate at the same time then you only pick up to this way you don't pick up the cherry more than once is what I'm trying to do here and if they're both in the same place at the same time they and you only can't get cherry once that's why I have this and I think now that I think of it that way because this is obviously an to the four loops which is I'm just using a calculator that's not good which is six point two million which is you know still iffy especially since for each of these how many transitional states are there well I guess they're only four right this the left one can go down well download right and so is the right one so that's just two times two so that's four but that's like 24 million operations I think the other thing to note is that given time but time some time stamps of T so that's a yeah parameter T is equal to time then the corner it's gonna be x 1 t minus X 1 because if you because you're forced to move every turn I guess you're not forced to but you should anyway - kind of it'll help us to should anyway - kind of it'll help us to should anyway - kind of it'll help us to keep track I mean I guess having you're kind of forced to but I mean there's no time constraints I guess in these century is the same but forcing them walk each way will allow us to rewrite the first corner this way because yeah if you yeah because for example you stop to zero and then the second one is gonna be one either one zero or zero one which you know the sum is 1 you could tell and then you're gonna add one every time way to either the x coordinate or the y coordinate so X plus y is it always gonna be T and the reason why this is important is because that allows us to create the second thing in a similar way right yeah and because of this now your states will just be DS which is now n cube I still four times n cube but yeah I think that should be enough so that's 50 to the third times 4 which is 500,000 to the third times 4 which is 500,000 to the third times 4 which is 500,000 to half a mil so that's way faster obviously 50 times faster and then I think that's it there's just breadth-first search and keeping track breadth-first search and keeping track breadth-first search and keeping track of stuff am I good so I'm just right now I'm just thinking of to do anything I'm missing yeah I'm good so let's go okay so I mean you just named to pose I think that's natural maybe this is a time to do it something like this no wow all right this is not even right well I mean it's right for ex-wife the grass mean it's right for ex-wife the grass mean it's right for ex-wife the grass you want to be told you think that we just said we were going to which is just got a pair you've noticed thanks - right okay - Chris okay - Chris okay - Chris we're both ended you can this be civil no Emma Steve it'll then let's take away the same which is terrifying not negative one that's yeah can I start on the cherry I guess they could start red cherry can I pop the cherry on the cueing or under the decoy I guess I'm the killing no God I'm cool like this and the hash table but it is the cherry on top is your gonna cue it up just push right it's okay fine uh where does name there's a tough old top horse - well oh it's not no way oops I think you get to another way but I have a lonesome text on it uh I think that's just convention I don't know oh well I guess it's way good crowd out I'd change something but uh not sure not wait you couldn't buy fine I guess it's been a while well I've always I did I haven't never played along with it so okay all right it's a good point though okay I guess I need a point one actually just to make my mm I think there's actually given like symmetric stuff dad you can make it faster like making sure that x1 is bigger than x2 or some other way around this by first search hmm maybe I could just students of dynamic programming actually now that I think about it yeah okay I'm going to turn on programming wanker yes there's a puss and mr. other one as well M + M + + M you always get to the bottom M + M + + M you always get to the bottom M + M + + M you always get to the bottom okay I just sure don't have it all accounts should be okay and now back shot no I need it okay my no I think one thing right now what I'm doing now is thinking whether I need a three dimensional matrix or to damage our matrix but maybe I'll just do it three dimensional one and then take it off later then you now you have to have two directional huge okay now you have transitions to the max of t minus one max of itself release time tonight t minus 1 X 2 and also figure out when to count the cherries yes you go to great test I'm very obviously like that try to factor into impossible stuff right the cherry is just the sum of these unmask terror in the same price then you just take one okay so this is stiff device something like that maybe you see if it is crashes first okay oh yeah I forgot to track check with that way what hmm that should weigh that should go out track well disk good but because I don't check for bounds I forgot but is shown right to use oh wait that's not right uh like t minus and minus T or something like that oh she could just t because he can't go farther end of it and I wanted to be T yes I do what about time so we said oh because T is oh yeah I mean I just don't check bounced that's why whoo because there's no reason why it should be bigger than you know but okay that's easy to do if not also grandest thing the other day let me see if it works XS under em I'm just confused to end in them and I'm not using these but I know am always that's gonna find me later yeah I'll just use 9 what squared away later I would say dynamic program could often be modeled as a graph problem in some in down like you could look at all these like edges way and you're kind of going through that way so a lot of similarities between them and you could still do in a graph way but the way that I was doing it was Nagma DFS I mean it could actually still quite could be BFS and sometime but then you have to keep track of a few more things and their states might be repeated a little bit and that's what I was kind of worried a little bit about where dynamic programming forces me to kind of do it in one loop oh yeah what would answer your question all right ooh am i doing okay man so this one oh this should be time okay I mean it's progress mocha I mean it's also weird stuff we're like this can't be our bounce but let's fix that actually but this means yes why 1-1 actually but this means yes why 1-1 actually but this means yes why 1-1 right sir okay be quiet but just clean of it also I forget to add cherry Novak's cheery missing a case mostly writer let me see if I'm getting the error from Hades it doesn't take that long well doesn't take a shower either actually just to test my ends and M's might mix them up okay well okay no that was right then oops I'm worried about this huh can they both be iPads I mean next one should be already be here Saudi and it steers me next one next to should already be invested anyway yeah - ok - 1 + 2 is 0 that's wrong mmm - ok - 1 + 2 is 0 that's wrong mmm - ok - 1 + 2 is 0 that's wrong mmm cuz this is Tom okay because poverty should be tea geez ampersand because well no the book should just be and not yeah because you're both X's on both axes that's why okay I mean no not crashing is progress okay like we're also one of these things but we're just like a step away right maybe I'm off by one somewhere as well like n minus one plus my plus this is it - - just takes n steps to go one - - just takes n steps to go one - - just takes n steps to go one direction I'm steps to the other direction then you start at 0 so 1 is 1 so let's do something more basic there's two a paradise of cherries - bye - let me I'm paradise of cherries - bye - let me I'm paradise of cherries - bye - let me I'm just return the wrong index ok times 10 - okay times 10 to that's it - let's take a look at T stop that's it - let's take a look at T stop that's it - let's take a look at T stop casting T should be should have at least got it three to him in service move I also means one and two which is fine - I also means one and two which is fine - I also means one and two which is fine - I got floated out as one - should be got floated out as one - should be got floated out as one - should be called good coordinates but this never goes to the end because of Christ I'm kind of bound checking mystic t needs one most to muster maybe to a muster because more that it's not even executing don't dis may be off by one bit and you're gonna come point hey JJ 1997 it's been a while I mean how long has that been yeah 30 minutes yeah I get it in theory but you know in practice is different this also needs to be plus one but do you know no good - one - one lets me see what no good - one - one lets me see what no good - one - one lets me see what 0 and then go to snow one which is for me goes to 1 I really think I'm just bad at math inputs just to say plus 1 so 0 to 1 which is true I just have one off by one is this just - - maybe it's off by one is this just - - maybe it's off by one is this just - - maybe it's something that somewhere is that ok well still not quite right why dial could 3 things it's not giving me a turret answer always time invalid input that's weird maybe it's the printing no really why's it I said when you give me two answers and not the third one okay now yeah I mean I'll explain it if I could get this right but why isn't that doing this one at all why it's just like really bad like I returned the output at least you know it seems to be wrong does it have to be always end by an foot whoops I actually missed that so actually I don't have to okay so that's actually not a valid input okay once again Larry's reading comprehension has failed him but I put into space but specifically to test that so that's okay yeah my mind works for rectangular quit anyway so maybe not cuz quitting did not get the right answer I'm curious why I don't work for it okay I'm just gonna simmer it and then see pick money big money mmm I pick up the cherry from in Rowlett places I think I don't keep track of that well I gotta keep track of where I'm coming from as well I think that's why Luca because it seems like this is just because you're fenced off from something yes yeah because you're like diagonally fenced off and I still return something whoops okay so if this is America okay I should have to win this differently so that I don't have to do what I'm doing now but it's too late I've committed okay maybe not let me uncommit okay watch out there it's just wet equated I don't know you know this I don't have to write it in order oh maybe it's great these are the combinations okay we can down yes actually gonna be serious that's the chair okay let's give it another whirl actually thought about this case but earlier back in trying to debug it I forgot about it didn't I'm 32 in its nuts Oh what am I doing here that's clearly not okay oh sorry yeah now I got even more answers wrong though that's hmm that's all right oh okay oh that would do it hopefully that's Oh what something Dow is the reason why but uh I think it's because I still do something with cherry okay so I think this is more right but it's still well which is unfortunate okay let me put it some and then stick deep into why and how we could jump over and get one guess that's the tricky thing with dynamic programming versus a breadth-first search in this case it's breadth-first search in this case it's breadth-first search in this case it's because some someone unreachable states sometimes if you're not careful you can reach them by accident because you go forward the states and in this case oh I say in this case it just if it sees us zero it doesn't assume that okay actually I know what I did you don't maybe now just returned a couple hundred but that's fine it's progress well negative something okay we questioned tests good second data contracts I just mean it just means that it's not reachable so the answer is zero which is fine okay so movie enticed you mm I'm going to choose a bigger thing bigger negative we'll just end I guess 50 is fine but why not pick money no whammy ah really hmm I guess I needed to pass the search maybe huh that's unfortunate but this is only n cube unless I did something wrong the math yeah n cube times for it so it's a hundred times I guess and it's actually now a hundred so given the 100 to a third is only a million times for a million as I do it I mean it should be fast enough I don't can I mix them then your app and this code is relatively tight I guess I could do something like because the thing that's the thing with the buffer search that optimizes a little bit is that unreachable states don't cost you anything one in time because you just don't reach them in my case that's we kind of do so I mean this is one by one but that shouldn't change anything I could tell me one more loop hmm now I'm trying to figure with just a way to early terminate I mean there is the way I guess but it's kind of messy okay what's my wedding time here 48 milliseconds yeah I guess I could look at the case Ted gets it oh it's the tree what on the lap does it give you the case that it tells you so it doesn't tell you the case that it time to mix it around because you passed the tree all of them because usually tells you the last test that it doesn't pass or like that it failed on so I guess I'm really close to the limit so I guess I think you might too distant like seriously past poisons probably fast enough but because I didn't all right yeah I'm I think that's just poop no me too is reinforced past that me to be updated this should be false actually quick okay say with some loops there's a fast enough I don't know save shaved for millisecond out that consistent that is actually by now that's y'all know we go haha yeah I'll never go over the new ones is sometimes just about how you feel but ya know that's it apply Chevron buzzer didn't even much stone but uh-oh much faster because can stone but uh-oh much faster because can stone but uh-oh much faster because can we complain when you're running that close into the end of the thing the submission times I mean I'm not giving on the grass that's how stolen is okay I mean I think they equipped I could have done it with the way I was doing actually I mean in the course very similar I could have changed this to that too if I have to but the reason why was I worried about having visit the same state more than once and then updating the best for that but I think actually because of the strict ordering of imposed by this T thing if I wouldn't come up but I wasn't I wanted to save time not proving in terms of like coding time but I maybe that was a mistake because it cost me five minutes like if there's a contest who have cost me four minutes of fixing this and also five minutes for submission so that it cost me 10 minutes and I could easily done whenever it takes on the Q part I should anyway so this end up taking about just short of 50 minutes oh wow huh I mean that sounds like a long time for something that I knew what to do from the beginning so I guess I'll have to watch the tapes to see where my time when I'm Annie I know I have a couple of silly mistakes that I and I'm bracing for minutes here and oh I didn't take a condom which opposed to the state so that add at least 12 minutes but uh what will I know you talk about sorry and plus n oh this well what one is apparently I think one is that it doesn't matter in because it's guaranteed to be n times n so the N and M doesn't really like it doesn't really matter but T by percents the time right so if you think about for me I don't know if you were here in the beginning and I have a thingy here so I have to reduction from so you can think about no here's how I thought about it so the problem asks you to go from the beginning to the end once and then from the end to the beginning back right so there's two tracks having one thing to make it easier for me to think about is instead of doing that you could flip the second path to from the beginning to the end right so instead of going from beginning to the end and then the end to the beginning you could go from the beginning to the end twice so that kind of makes sense right I think that step is like you know it's symmetric so it shouldn't matter either way and then now given that and why do you want to do that it's because it buys us this thing we're now having and to the fourth algorithm because the thing that got to if you do it like sick and chilly the thing you have to do is to keep track of what the first path like what cherries the first path took right and that's really hard or like you know there's a comet Oracle you know craziness there that I you know and I and the reason how I know how to jump into this is it's just kind of I think I've done a similar problem I don't know how long ago so then so that's kind of a reduction so now you get this album and I think that album is like okay you have two paths you have X&Y kind of or you two paths you have X&Y kind of or you two paths you have X&Y kind of or you have coordinated one and corner two running in parallel kind of and going from the beginning to the end right so dad so there is a special case where if you're your first path or the second path at the same time you're kind of think about it running parallel okay at the same place then they gonna only pick up the cherry once and I think I actually have some code here that checks what it is yeah all right if the two corners are the same then you only pick up two cherry once instead of you know two cherry twice because in this place yeah so that because the second time you do it you're not great go in the same way right so if you look at that you think about it that way then the algorithm is going to be n to the fourth just course you know there I mean that's just a way you know I mean I think that point is position so when you see you're kind of do well so let me explain it my way first and then I could kind of maybe answer questions I don't know if because so you understand the N to the fourth way where you have two different paths and you just have two coordinates right and then notice that every step that you take and both paths on or path to and they happen at the same time it's always gonna be +1 to the same time it's always gonna be +1 to the same time it's always gonna be +1 to the x coordinate or +1 to the y coordinate x coordinate or +1 to the y coordinate x coordinate or +1 to the y coordinate way so then if you just don't get the first path then you guys should express the y coordinate you could express the y coordinate with the x-coordinate right I mean I with the x-coordinate right I mean I with the x-coordinate right I mean I think so this pie is where the T comes in and because you're and they're now going to the second path because time moves at the same time and it's you can enforce it because I don't think there's actually just restriction but then yeah so then you could do the same thing with the second coin it because it's the same time step that you're doing it like you literally running it in parallel and then that we do this at 2 NQ is why the reason there and also enforces certain things like you like if they're both at the same place they're gonna be in the same place at the same time right so that kind of is why I did it this way oops yeah so on each time step so now you have those two coordinates and a tea that links them together now you can think about it as each time step you know of to kind of branch or two paths on that and that's kind of how I came into it don't I guess now that because this is actually technically T cube T is actually as you point out and plus 2 n so this it makes two n cube a little bit bigger than the I mean it's o of n cube and you know but yeah and one thing that I could have done actually which I have it which I didn't is actually enforced at X 2 I mean this would actually save a lot of time do I know yeah that's the other it's like early termination is one oops what today one way to kind of shave some constant time but the other one is noticing that X 2 can only be actually from x 1 to t minus 1 I mean because and that just exploits the symmetry of that makes sense which i didn't do in my first submit obviously and that should have time and the reason why this is the case is because yeah I mean you just swap like you can think of it if you have two parallel paths there's one up half an 11 and one on the right and if you know and you can swap them such that I swap your web Oh such that like the left one it's always on the left so that's kind of the reason behind dad I got you know there's a big case I could kind of just seem about submitting well this is well for small ends it fine doesn't come out that much good but it's because I pass everything it doesn't give me the big case let me see actually see if that how much that helps I mean still give me the test case but let me see how much faster this if how that just to okay you actually just 24:50 okay me just to this exercise okay this is PI the worst case oops well maybe not I don't know if I counted right so that's a little sad that's for you to it so maybe and then M is not to say it was something hmm shouldn't get a bounds exception I don't have any anything hard-coded let me try have any anything hard-coded let me try have any anything hard-coded let me try again dang it should buy a generative hood okay yeah so that's 308 and still gives me the right answer and if I had my own code I suspect that it would be a bit longer oh wait yes okay so I would have saved a good amount of time if I had a timeless Asian which I actually I think I've talked about this earlier but I just forgot by the time I submit because I was spending so much time on coding and that's kind of one of the dangers of cook them like everyone can pound on itself I think is the problem let me uh oh hey the worst anchor ever be okay let me speak to that in a second we finished talking about this problem which is it should be in a couple of minutes well yeah we have for this problem I think I mean I think someone else already imagined that if you're in an interview you're probably not gonna be in a happy state and I also I mean I think I would find out this algorithm I would maybe do the first one or yeah Cubase but for surgit I show you my only wonder but yeah but otherwise it's not that bad conceptually to explain to someone if you have got it I don't know it's way too hot when interview for him you ask me it's a fun form it's very time for any problem I think if you do get in as a move on yeah maybe just you know ask to go to the bathroom so you could cry by yourself that's what I would do anyway but uh I mean at some point like I said I think my bow here is that like the EROEI if there's some problems that are so hard that like you know then it is what it is we're like what are you gonna do if you're giving this problem because they just don't like yours I mean I don't know this is not reasonable in a ball like if they would like because there was famous that you could test in this problem dad you could test with a much easier for my the concept was simple enough so in theory like what I always test on it when I'm an interior is around like the fundamentals which is like you know dynamo gramming or maybe a first search and in those cases I could you know ask a problem that of relating to them maybe even in interesting ways but not necessarily like impossibly like tricky to inform anyways right but I think because this takes like there's no hints here but this takes like and you know you walk and you listen to me walk through a little bit I it takes like three or four insights to kind of even get there right so I don't think that's reasonable for you know for like a for even a 45-minute interview to have like even a 45-minute interview to have like even a 45-minute interview to have like all those insights but uh oh my god I think that I don't know is there a tag on this yeah well this is locked so maybe someone could tell me I don't think that's legitimate way uh-huh think that's legitimate way uh-huh think that's legitimate way uh-huh really yeah well I don't know that interviewer from Lulu was having a bad day or maybe just thought it was something cute and when I give it but I think like I mean I've been part of an interview as an interviewer when I do interviews is that I do cat like you have to do calibrations on your interview on this way and that means sometimes you will have something that's way too tough and it will take a couple of times asking that forms before you maybe realize it but still like but that doesn't make it a good problem it just means that in a sad way sometimes you're a little bit of a guinea pig but I mean I think for me like I have done enough interviews to kind of have a good sense of the difficulty I wanted to be and not necessary to be cute I mean I think and then especially nowadays I feel like there's no such thing as never seen in a like if you're your criteria for a prom your interviewing is like upon that the interviewee has not seen before like that's not a reasonable expectation anymore I don't think I mean I think like in the past maybe you say ten years ago you're like ah you saw you've seen this farm that's doing yeah okay but like nowadays like give you know like people practiced a point where like they've seen almost everything and only thing that's new is like some ridiculous craziness and that's not a reasonable standard anyway I mean maybe there's something yeah maybe gonna need to change to interview process but I don't think that's or like in terms of structure but I don't think that's it is what it is I mean no I mean I think you know just to play a little devil's advocate if you were in like some kind of like we were self-driving car and you need like self-driving car and you need like self-driving car and you need like machine or anything or you know some kind of machine vision type thing then you might something like because that a lot of stuff like you maybe you ask something about like machine learning and you asked like machine learning related while it doesn't like you don't need harder basic like harder fundamental ones you need like something more specific whereas I got your machine learning back well or maybe some kind of visual machine visualization whether that's like maybe you know explain some stuff about like fast Fourier transform or someone like that where like something that's like really specific really tap you know deep into what you're learning but not like not necessarily like this idea like it's cute it's fun but like I don't know yeah and yeah you haven't and to your point when you I think actually like when you're a senior engineer you actually I find that yeah she can I would say easier but you don't get like too difficult like album proms at least what I do actually yeah when I do interviews I actually don't give different problems for senior engineers and non senior engineers that much to be honest I mean there's some stuff to be said about like from phenomenality with language and stuff so we might grade you a little bit differently but I get the same problems because that's just the fundamentals right with that said when you're more senior you usually have different types of interviews which behavioral me the behavioral interview means more meaning that no way when you're more junior your behavior may be just like your attitude you're like how do you want to learn and stuff like this where if you're more senior depends on like maybe more conflict resolution or how do you lead a team and so you get more behavioral problems that way and then the system design is definitely depend on the company I think they either don't get a skewed system design or very basic like system design which is when you're seniors about like scalability system and how you scale like infrastructure and like how do you lay different components and you know one of the responsibilities of different components so those things will determine your level more than their algorithm point in my experience and obviously it's not always coming every company because some companies just do things differently so I can't speak all of them but that's how I seen them structured yeah and definitely well also welcome our table yeah that we seen yeah I've had this in the past which I haven't had recently to be honest where the interviewer would give you an np-complete problem and then kind of np-complete problem and then kind of np-complete problem and then kind of like almost just to see what your process is like because they know that is an impossible problem so they would want to see like the thought process and I would go through it so I so that's that for your thing so I would definitely uh and that necessarily like led you know programming but yeah uh hey post-event I mean I thought yeah uh hey post-event I mean I thought yeah uh hey post-event I mean I thought it was okay I had some I spend a lot of time explaining this one and we're still explaining this one and slash some stuff about just interviewing in general I think we actually I think I'm mostly done about talking about is far mostly what you talk about how hard this problem is and how maybe it doesn't come up on interviews as a we sell don't up Helen II Hoover has asked us in the past which is kind of sad but uh but yeah I mean I yeah processed of a should matter and just like how to think about things but uh but here in terms of leveling though I mean definitely process does help a little bit as you get more experience and seeing more plans and so forth but leveling that definitely also relates to the non-coding portion as well like they the non-coding portion as well like they the non-coding portion as well like they rate way much more to be honest yeah and I yeah I think that's one was about our am I done I think I'm I think so I mean you could do this in breadth-first search and there's early breadth-first search and there's early breadth-first search and there's early termination but that's essentially right I think because that's the number of states you have even when you do a play first or so I think that's gonna be right can you do something in n square I don't think so I could be well oh yeah definitely let me know I mean and well one thing I would say is that okay so this is a n cube time but you can actually do this an n square space which I didn't do I was thinking about doing it but it's already hard enough forms I didn't wanted to think about that much and I ended up using I forget what my percent oops I forgot what my percentage tile was for memory usage because I did okay on the memory part I don't remember my percent hour if you know where it was no let me know but uh but you've actually reduced this to N square space which actually ironically you cannot in this case we do per first search you actually need n cube space where in dynamic programming you could actually get away and square space because of how you maybe that's not true maybe you could do something clever with well for search but actually I think you can too but it's a lot trickier but yeah there's a oh really but yeah I took and I'll show you how to do the quadratic spaces data if you look at this equation which is the only thing that updates yeah you could notice that best team - best of T it's always based best team - best of T it's always based best team - best of T it's always based on best of T minus one so you could kind of have basically two n squares a ways and then just kind of go back and forth on them or something like that so that's the quadratic equation and imagine it's that's what the solution will bring up but that's I mean because that's how I would optimize my solution if that makes sense and that's a very common thing to do in dynamic programming instead you notice that you only use the last like nice and sorry that's K for some constants number of previous solutions and then you just keep track of those so then you don't have to keep track of or so of T right because you look at here we never care about anything before t minus 1 like T - till you go forward minus 1 like T - till you go forward minus 1 like T - till you go forward away so that's kind of the idea between dad and then it's just more like maintaining the pointers and indices or whatever and so forth and actually I think there's a the key way to do it is actually so you could do something does this actually tell me to memory when you want it let's see if a second I can't it doesn't actually but helping down okay but you get to work by I think there's a clever way where yeah so if you have just like in a way of two elements you could do something like this even and in this case it's like telling people so someone like that and that would give you the answer I think so there's some weirdness with kind of initializing and stuff like that and kind of cleaning no queening the membrane is for use so you do pay penalties there but in theory is not and then in this case obviously you would just have an array or index two so instead of so this is two T so then you just have to and then this should in theory work this will not work because I do like go for a fall of dinner show they shouldn't crash it's what I mean way so that's kind of just actually end up working my accident I think but uh but yeah but that's how you would to actually change it to of n square space and I did that was actually easier than I thought to maybe I should have done it to begin with let me see I mean this should give me the wrong answer because I don't think I really said anything okay maybe I get lucky again but my point is still that this so but that's roughly how do you wanna out it but that's how wealthy I would uh yeah because you don't have to go through as much memory maybe I don't know but yeah but that's how you would generally do it I think this is still wrong know to be honest could because I don't clean the memory of you well it like initialize everything to zero I was a in this case negative infinity but yeah
|
Cherry Pickup
|
cherry-pickup
|
You are given an `n x n` `grid` representing a field of cherries, each cell is one of three possible integers.
* `0` means the cell is empty, so you can pass through,
* `1` means the cell contains a cherry that you can pick up and pass through, or
* `-1` means the cell contains a thorn that blocks your way.
Return _the maximum number of cherries you can collect by following the rules below_:
* Starting at the position `(0, 0)` and reaching `(n - 1, n - 1)` by moving right or down through valid path cells (cells with value `0` or `1`).
* After reaching `(n - 1, n - 1)`, returning to `(0, 0)` by moving left or up through valid path cells.
* When passing through a path cell containing a cherry, you pick it up, and the cell becomes an empty cell `0`.
* If there is no valid path between `(0, 0)` and `(n - 1, n - 1)`, then no cherries can be collected.
**Example 1:**
**Input:** grid = \[\[0,1,-1\],\[1,0,-1\],\[1,1,1\]\]
**Output:** 5
**Explanation:** The player started at (0, 0) and went down, down, right right to reach (2, 2).
4 cherries were picked up during this single trip, and the matrix becomes \[\[0,1,-1\],\[0,0,-1\],\[0,0,0\]\].
Then, the player went left, up, up, left to return home, picking up one more cherry.
The total number of cherries picked up is 5, and this is the maximum possible.
**Example 2:**
**Input:** grid = \[\[1,1,-1\],\[1,-1,1\],\[-1,1,1\]\]
**Output:** 0
**Constraints:**
* `n == grid.length`
* `n == grid[i].length`
* `1 <= n <= 50`
* `grid[i][j]` is `-1`, `0`, or `1`.
* `grid[0][0] != -1`
* `grid[n - 1][n - 1] != -1`
| null |
Array,Dynamic Programming,Matrix
|
Hard
|
64,174,2189
|
1,941 |
welcome back for another video we are going to do another deco question the question is 1941 check if all characters have equal number of occurrences given a string as return to if s is a good string or force otherwise a string s is good if all the characters that appear in s have the same number of occurrences the same frequency for example one s equal a b a c b c the output is 2 for the explanation the characters that appear in s are a b and c all characters occur two times in s for example two s equal a b the output is false for the explanation the characters that appear in s are a and b a occurs three times while b occurs two times which is not the same number of times now let's work through the code we first initialize a array to represent the frequency of letters we then subtract ascii value of the letter a from the ascii value of the current letter to represent the array index we then compare frequencies of letters if the frequencies do not have the same value you will return force else it will return to time complexity is o n space capacity is o1 and the solution works thank you if this video is helpful please like this video and subscribe to the channel thanks for watching
|
Check if All Characters Have Equal Number of Occurrences
|
minimum-number-of-operations-to-make-string-sorted
|
Given a string `s`, return `true` _if_ `s` _is a **good** string, or_ `false` _otherwise_.
A string `s` is **good** if **all** the characters that appear in `s` have the **same** number of occurrences (i.e., the same frequency).
**Example 1:**
**Input:** s = "abacbc "
**Output:** true
**Explanation:** The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.
**Example 2:**
**Input:** s = "aaabb "
**Output:** false
**Explanation:** The characters that appear in s are 'a' and 'b'.
'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of lowercase English letters.
|
Note that the operations given describe getting the previous permutation of s To solve this problem you need to solve every suffix separately
|
Math,String,Combinatorics
|
Hard
| null |
1,353 |
hello guys welcome back to the channel today we are solving another lead code problem that is one three five three maximum number of event that can be attended before jumping into the solution you should read the problem statement on your own and give at least 15 to 30 minutes before this solution so what problem is asking is attain the maximum event s maximum event to attend the events there is certain condition that they should lie between the start time and the end time and while doing that you can attend only one event at any time see so in order to get the maximum event attended you need to have two things we can see that the star today the end day and day so potent maximum events logically free things she will be would be starting from the event that starts first starts early and but it doesn't mean that start early doesn't mean it we would be able to attend maximum even because and even can stretch much longer so we need to have even that end early and early so foreign how to uh use these observation to solve this problem in order to handle start early sort it according to start because start will make let's clear that it is in increasing order and whichever event we are on it is the minimum for that particular so and how to handle and easily will be prior to you writing why priority you I basically need operatic view because there may be two events starting at the same time but they may not end at the same time so how to get the event that end early is the pay done using priority queue I hope that much is clear now what would be our eligible for solving this problem basic sort according to start why I already discussed Traverse in the condition I is less than n or r Q size is greater than zero while doing that insert all the ends of the end of the event which follow this condition the day the D the start sorry start time is less than the day insert all of them enter the end of them insert Plus increase the index why because we don't want to be on the same event again and again we have to move forward that's why I plus and pop at the top what we would be having is the minimum and so also specify or return or show that this event is finished so when this event is finished increase are event counter take another name result plus that we have done one event also the day is increased that as it is known in particular day one event can be handled and one event is done so day has to increase and while going out delete all the events that are less than 30. because why because that event is gone nothing is to be considered because something that is gone so and also one thing how to determine that day because it is not always start from day one it may start from any other day so take while the priority queue is empty for the very first time take the very first that is present in the vector after it is sorted that much is clear example let's take example into root 3 three four and two sort one two three four how to determine a and paratigue is empty take the very first day is one result is our zero insert how insert is happening less than equal to day is currently 1 these two are one also I increased from here to here I increase from here to here what is the condition of priority U2 to part one day is done also the result when event is done and while going out talk this is for insert nowadays to pop less than a day 2 is not less than that it is equal so it will not be popped again I was here because these two are processed I will be here my bad sorry yeah I would be here again days two this is less than 2 less than or equal to 2 condition is I will be here I think you will be having three is greater than so it will not be inserted but this time this will be popped days three a is three us is to shh I plus this happened is happening priority is okay result is two days three popped whichever is less than equal to data is currently 3 so 3 will not be popped again nowadays three insert this will be inserted eyes over here what is the prioritical condition is this will be part days for task not task event three events are done but I discussed it the condition for going out of this whole computation is that I should be less than an unprediction should be zero one condition is false but this is still true because 4 is still in size again nothing will be inserted because I is over here but what would be done is it will be popped a will be increased and the result will be 4 I added across it the result will be four so I hope I was able to make you understand the algorithm let's see the code very basic things and discuss as discussed you can understand I for iterating the indexes D for day and this event size of events Vector is that how many events we were able to attend priority of mean type while the condition of the computation when for the very first time when the priority group was empty take the d or take the event which is present at first while doing this after doing this not while take all the insert all the events and according to the start which is less than equal to D the current day and popped off the uh event that has been attended plus the result plus the day and also pop the events that have been already ended and keep on doing it till the PQ size is greater than zero or either less than n and after that return the result very basic thing let's submit it and see if it is running or not yeah it is running quite fast quite efficiently so you guys are awesome keep grinding see you in the next one bye
|
Maximum Number of Events That Can Be Attended
|
maximum-number-of-events-that-can-be-attended
|
You are given an array of `events` where `events[i] = [startDayi, endDayi]`. Every event `i` starts at `startDayi` and ends at `endDayi`.
You can attend an event `i` at any day `d` where `startTimei <= d <= endTimei`. You can only attend one event at any time `d`.
Return _the maximum number of events you can attend_.
**Example 1:**
**Input:** events = \[\[1,2\],\[2,3\],\[3,4\]\]
**Output:** 3
**Explanation:** You can attend all the three events.
One way to attend them all is as shown.
Attend the first event on day 1.
Attend the second event on day 2.
Attend the third event on day 3.
**Example 2:**
**Input:** events= \[\[1,2\],\[2,3\],\[3,4\],\[1,2\]\]
**Output:** 4
**Constraints:**
* `1 <= events.length <= 105`
* `events[i].length == 2`
* `1 <= startDayi <= endDayi <= 105`
| null | null |
Medium
| null |
929 |
that's internet Islam Oh new question interface when you edit it okay let's see every email address has a local name and a domain name separated by the @ sign for example is le carré by the @ sign for example is le carré by the @ sign for example is le carré mr. Logan name we call that commerce domain name beside lowercase letters these emails may contain darts and passes if you had periods between characters in the local name part of the email address there we send for it to same addressed 4000 name I guess this is like how Gmail does it now and if you can you see my mouse I guess doesn't show my mouse on the stream okay you've got a purse local name everything after the first pass time with ignore disallow certainly must be filtered so it's much email again this will just not fart on my name it is possible use both of those words at the same time if emails we sent one Gmail to each address and list how many different addresses actually received mail okay so basically yeah it's just you're given a way of email addresses you will what you want to do is normalize them and put in a hash table or something like that has said and just count the size of the hash table I well I do love see when I do when I use I would try to yeah I would definitely try to use distract a little bit I will try to use Python for string parsing stuff just because it's so much easier to manipulate strings and alright let's see how far I can get I'm now when I'm kind of depending what I should use editor or just in cryin I'm I think this is simple enough that on would you need to use my own crime and put client per se and really good exceptions way let's go so the first thing I would do is okay I mean it seems pretty straight for it right so I mean the first thing I would do is tokenize by periods sorry took a nice spider add simple I it's been a while since I use Python so I think so there may be some trying over here but I was saying let me stop the harsh at first and then I would do someone like that and then in this case you just returned you need something like that maybe I don't mind the syntax I could check that later it's been a while usually I would not for these simple functions I'm not used to using these over P like this where no object but that should be okay and now I'll try to find the first the index of the pad sign so wherever names are Heupel now it's to actually never seen this interface so I some curious oops nope if they said like I could one partial encoders I'm going so I could just even something like that I could do some kind of great-aunt wife on it see yeah okay how should I don't know me like doesn't appear let me see if I could find a Python kind of was it good interactive command which I guess I have to show all right so that's this is my console I guess it's more than I just forgot about it when it was in time don't Python so you can say you know as you go to okay so that's what I expect it to do okay I mean that's just now I'm reading the farm statement again just to make sure that these inputs are kind of valid I think something in concept like for example you can imagine a world where they give you examples like some you know conceived or something that I mean so this still pauses but I'm just trying to see if we need to kind of consider that so it doesn't seem like I need to so I just do and so that should be okay fine and then what the hell as you know I'll have to handle the two parts differently the domain I think the domain you actually don't need to and obviously this could be more efficient if I had this could be more efficient about you something like this Joe let me change it back since I'm editing here this could be more efficient we use some kind of like string buffer or something like that instead of just concatenation of strings but I'm just kind of going for typing speed here and now we want to remove all the periods don't remember the string that replace syntax I'm just gonna look that up real quick no high five all right can you see this okay yeah so I thought to this life the Google I would say join an interview as an interviewer I actually don't penalize people for looking up the API in general I mean bouncing a lot of things and everyone knows that how I mean like no I haven't done in a while but it's all about like knowing where to look for friends and stuff like that so it's not a I mean memorizing API it's not that you know like it's not in obscure was everyone just stacks or before anyway so I have something like that so I think in theory before I guess one cause demand went somewhere so I guess I see what happened to everyone code in candy okay well I guess I could do someone like me think yeah okay fine this way I do not want power to any of this okay fine as you can see I'm pretty rusty - okay oh I can see I'm pretty rusty - okay oh I can see I'm pretty rusty - okay oh I forgot the plus sign that's why okay so that's fine and oh yeah so okay so dad removes all the periods I'm now looking at form to make sure that okay everyone out will be forward - that okay everyone out will be forward - that okay everyone out will be forward - OH there tells you about that case whereas period and process so and it does it's just like in theory should matter what's after or it should not be operation dependent so I'm going to try that yeah so that should be okay hmm okay well no they say now I should add some print statements hmm see what's up yeah I am really bad at getting just syntax point way okay today I'm just going why she won't do my thing okay yeah I thought I tested I did before okay that's why I had before what was he complaining about can only can cut this tooth this wooden idea how I'm just being dumb okay so no okay so that seems like it's okay now that I you know you just a proper string manipulation things so I guess Python could be easier if you actually know what you're doing with Python but clearly sometimes you're gonna run into some issues I mean everyone looks okay I guess and there you go that's one problem down told me 15 rates were just long again I like but let's go to another file
|
Unique Email Addresses
|
groups-of-special-equivalent-strings
|
Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`.
* For example, in `"[email protected] "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**.
If you add periods `'.'` between some characters in the **local name** part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule **does not apply** to **domain names**.
* For example, `"[email protected] "` and `"[email protected] "` forward to the same email address.
If you add a plus `'+'` in the **local name**, everything after the first plus sign **will be ignored**. This allows certain emails to be filtered. Note that this rule **does not apply** to **domain names**.
* For example, `"[email protected] "` will be forwarded to `"[email protected] "`.
It is possible to use both of these rules at the same time.
Given an array of strings `emails` where we send one email to each `emails[i]`, return _the number of different addresses that actually receive mails_.
**Example 1:**
**Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\]
**Output:** 2
**Explanation:** "[email protected] " and "[email protected] " actually receive mails.
**Example 2:**
**Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\]
**Output:** 3
**Constraints:**
* `1 <= emails.length <= 100`
* `1 <= emails[i].length <= 100`
* `emails[i]` consist of lowercase English letters, `'+'`, `'.'` and `'@'`.
* Each `emails[i]` contains exactly one `'@'` character.
* All local and domain names are non-empty.
* Local names do not start with a `'+'` character.
* Domain names end with the `".com "` suffix.
| null |
Array,Hash Table,String
|
Medium
| null |
1,029 |
hey guys how's everything going this is Jay sir who is not good at all goodness I'm making these videos to prepare my future interview this video I'm going to take a look at 102 9 2 cities scheduling okay there are two end people and the company is planning to interview the cost of flying I person to a is the first number the cost of flying are threatening the city B is the second number right okay this one so for the first one if you go to a it will cost 10 could because 20 the second one go to a cos 30 go to because 2,200 and then how cos 30 go to because 2,200 and then how cos 30 go to because 2,200 and then how can we return a minimum cost so if I have to a and have to be mm-hmm Wow have to a and have to be mm-hmm Wow have to a and have to be mm-hmm Wow so the general case to consider this problem is that if the price no if the cost is the same all ten then we don't need to do anything just right we just random pick 10 and a half of people and it's done so the cost the more the cost close to each other the less meaningful the separating will be right so if we say okay if you take a look at these people and that the cost go to a is much smaller than B much smaller so actually he or she is very important in determining the minimum cost so of course he must be he or she must be go to a right to drag the cost down the same for this man for this guy he or she must go to be because is the deviation is so big right so this reminds us actually we could determine who go to go determine the people who go to a we're going to be by checking your difference right the more like the more costly if it custom much more than the others to go to B then he go to Moscow to a right to the other way to kind of think of this thing is that let's suppose all people a first right big first go to a now actually we need to pick half of the people to go to be right so how do we choose well if four people a set this these people are from A to B in to attract a track down the cast no it will actually plus ten right hello original cast 10 now it cast 20 so this one that the difference changing these people's path a destination would cost us extra 10 here of course cost an extra one hundred seventy this one - 350 well one hundred seventy this one - 350 well one hundred seventy this one - 350 well so we actually we could choose the top the me mean the smallest difference with possible negative numbers with top end people and that is the target right so this and then we could actually get the sum of the cost right so the idea becomes a little clearer that's a we sum or up to a right and then sort the people with cost one minus cost zero two different ascending take the top and people update cost right so it's done so let's do that okay so first here is a cost to 2 as the return is initialized is zero and now what we do with some up to sum up all the costs with a right yeah and maybe I think we need to use if we could just sort this together just sort this yeah that's just a sword with the origin this one I thought that maybe you could create a new array and the push to push the difference in their new Reyes would either way I think needs it's useless so let's just sort sword a and B when it gets the minimum of the difference right so return difference it means these differences a one that's a zero right this should be subtracted but e 1 minus B 0 so this actually well sort this array with the order of difference with B to a videos anyway ok now what we do we just do through the class right we now get the top end people which would be sent set it to be so for let aquaszero ice more than costs come in right uh-huh than costs come in right uh-huh than costs come in right uh-huh now for the top some top end we use cost B right so clasp cost plus equals I if I a smaller that cost then divide by 2 then and map it's guaranteed to be even so it case within it then you should be use class I won right together tasks i0o and then we can return the cost yeah it's done who submit oh I did this one year ago man well accepted and it's pretty straightforward let's try to analyze the time complexity the sore here for suppose these are n 2 n people right so here is o 2 n log 2 n right so yeah so it's o log lock - and exactly Plus right lock - and exactly Plus right lock - and exactly Plus right - n is Mach 2 plus Wow so it's actually - n is Mach 2 plus Wow so it's actually - n is Mach 2 plus Wow so it's actually I think this is right and then we use log only to end while it's a log n so this is a time complexity but actually I think we can improve a little bit right the thing is that actually for this specific question we don't need to sort them all you see we only get me to get the top n for this kind of thing for this case is that we actually like it to be some kind of sorted but not all of them needs to be sorted we could use prior to queue remember the problem here so this we all sort of all the things right but we only need half of them so this is a problem we don't need to end them all well this is about prior to Q prime Q is very helpful for questions like top cake problems so let's try to use it and okay ma'am this is a priority queue okay are you interested please search of a channel there is a detailed explanation in how to implement a priority queue in JavaScript please search on that and I'll skip this part and in real interview you don't need to implement sporadic you because for Java they have built in product you for JavaScript based no so all you need to do is to tell the interviewers say okay as opposed is prior to you I'll use it directly ok so then here so here I'll create the product you barbecue wait a minute this doesn't work for Frank you were getting the top and then we get that's the okay yeah so let's first miss first a calculate that cost me - all a okay for net cost that cost me - all a okay for net cost that cost me - all a okay for net cost for the equal zero okay that mean was cost zero and for that cost of costs in cost plus 0 now this is all the cost which would you which this is a cost when all people are set to a now we use things apart you to track that the end people that should be set to be right cool what we do yeah we create a product you which we use this one right Q which will keep the minimum so the biggest one the larger numbers will be closer to the root we say the AP what we gonna do for this is the cost so yeah we just say return a one and it's a zero this is a difference and this should be a bigger right bigger than the be bigger than wait a minute it should be bigger than B to put it to could be closer right so it's not ascending to descending uh-huh it's not ascending to descending uh-huh it's not ascending to descending uh-huh I use P 1 to be 0 divide subtractive with a so when a this is bigger then it actually will be put when it is a when it is some +1 mmm-hmm wait a minute wait a second mmm-hmm wait a minute wait a second mmm-hmm wait a minute wait a second this is confusing this is the difference if it is positive it means it has a small 12 be positive so you should be removed first all right so it must be closer to the origin okay yeah I made a mistake it's actually should be like this one more time a has the smaller huh wait a minute if a this means if this is smaller this should be closer to the origin so if you smaller the storage in no limit it's wrong if you disclose or it should be further from the origin because you can be removed mmm this is right okay now we have PQ now to what we just push them into the park you and cost okay now if PQ sighs get the size this is okay this size if the size is bigger than costs then divide by 2 what we do we were Pole right we move the one and pull one now yeah and after this is done we will have exactly n people in our party queue which should be set to the station P right and so now what we do what we will move them to be by updating them in cast okay so while PQ size bigger than zero I said constant cost okay to be okay to a to b TQ poor then main cast should be close to me - then main cast should be close to me - then main cast should be close to me - to a right this is the difference that the moving setting these people to be well this is the cast I'll be dragged down by moving these people choose to be right and then we can remove returning cast so this is clear we first get all the cost by setting all of them to a Twitter party queue traverse through it and keep track of the top end people and then we get the end people update them in cost so pretty stressful right hello we get to fun new ah I forgot to you yeah sorry not a number what family link us should be right Thank You PQ thank you this is right so here's the problem we pull against the cause we say to a to be concussed no the problem is here well this is right actually this is - A - B - a - B - a - y - x cost oh but wait a minute man do something ah costs oh yeah her okay we're good submit okay we're accepted the who looks like this small slower but let's first analyze our time complexity here you're constructing here it doesn't cost any time because the product is initialized to the empty here it will cost us o N and here of course Oh N but for each one we add you relax cost us are this o to n right to it this is 2n oh this is we use 2n before uh I will I just clear the input the previous solution wait a second I'll just restore it fire ah it's stupid I don't need to do that I just click the wait a second let me finish this one okay this one is 2n we add well is ask cut actually cost us the maximum is n right so and log and this is the same log n so this is still o in block it so generally for all this should be L n log n right mm-hmm yeah these two n log n actually mm-hmm yeah these two n log n actually mm-hmm yeah these two n log n actually so it's two three and knockin I'll just if you write it with more details you should be 2n plus this is 2 n log N and Plus this n plus and in this should be yeah would you be better than the previous solution here what we did here is that we swore right this is actually oh I just copy the solution and put here it should be this one is a support first up here it's O 2 n log 2 n right and here is Oh see ya you see time should be o 2 n plus 2 n log to it while comparing to our new solution this is 2 n plus 2 n lock 3 n log n this is a 2 mm it's actually better looks better mmm Wow looks better because you see the case here actually top half of the Edmonds right n 2 m so actually they are proportional it's lost something like top 2 among like 100,000 enemies right top 2 among like 100,000 enemies right top 2 among like 100,000 enemies right it's actually top half so the time complexity doesn't change that much but I think if you talk to interviewers about the product you and I think he will be pleased about this okay so that's all for this one this is another problem that we use pratik you please search my channel if you're you want to know the details about implemented into in JavaScript yeah there is a video about that okay hope it helps see you next time bye
|
Two City Scheduling
|
vertical-order-traversal-of-a-binary-tree
|
A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`.
Return _the minimum cost to fly every person to a city_ such that exactly `n` people arrive in each city.
**Example 1:**
**Input:** costs = \[\[10,20\],\[30,200\],\[400,50\],\[30,20\]\]
**Output:** 110
**Explanation:**
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.
The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
**Example 2:**
**Input:** costs = \[\[259,770\],\[448,54\],\[926,667\],\[184,139\],\[840,118\],\[577,469\]\]
**Output:** 1859
**Example 3:**
**Input:** costs = \[\[515,563\],\[451,713\],\[537,709\],\[343,819\],\[855,779\],\[457,60\],\[650,359\],\[631,42\]\]
**Output:** 3086
**Constraints:**
* `2 * n == costs.length`
* `2 <= costs.length <= 100`
* `costs.length` is even.
* `1 <= aCosti, bCosti <= 1000`
| null |
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Hard
| null |
461 |
Hello Hi Guys How Are You I Am Positive Doing Good Welcome To Calendar Co DC Show Today Score And Skimming Distance And This Vegetable Question Is What Does Sunrise And Happy Return President Of The Number Of Egg Positions Pandit Vishal Different Sunidhi Chauhan Defiant Facility Solution is pet this udayveer vikram 59 bill check safal fiber [ __ ] 10 chapter defeated in the admins have fiber [ __ ] 10 chapter defeated in the admins have fiber [ __ ] 10 chapter defeated in the admins have different position because it because if one and 10 today date ambani a param zero and carry beg you have tomorrow morning simply i hope you know you have planned in Electronic Show Dabi How to learn how to subscribe Vipin So Let's Tweet That Sushma Kitabi So I Will 102 Not Give This 200 Am Just Talking To Variable In This Way Wedding Settled In Five 102 Main Hoon Suno Am Changing In Taste Yaar That Tulsi I Am An Atheist That this I is equal to one takes a text means which is a soccer sahib tip in the binary is to edit this Chinese string that Sonalika select tractors and chatting and vegetable notification is rich 108 Jasbir and Rashmi it was handed over to a Song is a Subsequent this izzat edit and travels market it is banana defeat in the west menu all is the position where two weeks of different sa evidence by take care and don't forget subscribe like this
|
Hamming Distance
|
hamming-distance
|
The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different.
Given two integers `x` and `y`, return _the **Hamming distance** between them_.
**Example 1:**
**Input:** x = 1, y = 4
**Output:** 2
**Explanation:**
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
**Example 2:**
**Input:** x = 3, y = 1
**Output:** 1
**Constraints:**
* `0 <= x, y <= 231 - 1`
| null |
Bit Manipulation
|
Easy
|
191,477
|
949 |
hey what's up guys juan here again and so this time let's take a look at this lead called problem uh number 949 largest time for given digits i mean someone might have may have been surprised oh why you are where you are doing like easy problem you know because i think this problem is very interesting i think it should be like a medium instead of easy you know because it uses like some simple like permutation uh algorithm plus the time the plus the time calculation so i feel like it's a good problem to share with you guys okay so basically given an array of four digits return the largest 24 hours that can be made okay so the smallest 24 hours is that at 12 o'clock right zero and the largest one is the 23 uh and 50 and 20 23 hours and 59 minutes okay cool so and it basically it gives you like a four digits uh four digits and it asks you to return the string that these four digits can conform right the largest time and if the four digit if the four digits cannot form a valid like uh time then we just return empty okay i think the reason for this problem is being like uh to be easy is because the length of the input is only four but trust but believe me the concept behind it is definitely not easy it's a i think to me it should be a medium okay so with these four uh integers okay so the way we should try it right basically you know to be able to find the biggest one basically we have to find all the possibles possible um you know it's not a combination right it should be a permutation in this case right because which basically we just need to uh try all the other permutations of these four digits okay and for each of them right and every time we have like about uh i have a permutations we just calculate the uh the time and then we are comparing okay if this time if the current time is greater than the then the biggest time if it is then we just save it right and then in the end we simply return it okay so the first thing first is how can we calculate the permutation of the end here okay the way we calculate the permutation is we use the backtracking okay and basically the backtracking plus a swap plus swapping so the backtracking method will have like uh have an index basically this index is going to be a starting point okay and starting point is this and every time when we have like backtracking here so basically we uh we just loop through everything from the starting point to end here okay and then we swap uh we swap those two numbers right basically from the eye with the starting point and then once we finish we do a one swap and then we just do another backtracking so what i'm trying to say is that you know so with one two three four right so the first thing is one two three and four right and the second one is like we're gonna swap this one to two one three and four right and then the next one is the uh i believe is one uh two one uh three four and then it's gonna be the three one yeah three two one four because we're gonna base we're gonna swap right everything from the starting point all the way to the end and the second the next one is four two three one okay right so that's the we are this basically the starting point is one and then we just swap everything with one here two three four and then we just move it to two here okay so now this is two so we swap everything with two f from here onward basically to one two uh it's going to be one three two four okay and then the next one is we swap two we is four which is one four three two okay and then the start we will be moving to three here so we have a one uh one two four three okay so i mean the total numbers of the permutations of a length of n will be like what would be a four times three times two times one it's going to be a 20 24 in total right so yeah something like this okay i think i didn't list all of the permutations here but the total number should be 24. so basically we're going to use the backtracking to calculate all the permutations and in the end we just compare them one by one okay let me try to implement the permutations here so basically the way it the permutation works is like this so uh backtrack gonna be a starting point okay and then here uh we have an n right n is the length of a and we just call this a backtrack uh starting from zero okay and then we're gonna have like uh the max time okay equals to uh i'm going to initialize with minus one so basically the way it works is let's see we have i in range starts to end right and we just do a swap basically we just swap the start and i equals to uh i start okay and then we do a backtrack start class one okay and then we just and then we swap it back because like i said we don't want to swap since everything since all the back the recursive card is sharing the same array here that's why when you swap it back okay so why we're doing this from i here from start here not from start plot plus one okay why is that because we still want to keep this one two three four right if we start do a swapping from start from the start plus one here then the original one will be missed basically okay because at the beginning the start is zero right so start from zero the index is zero and we are trying to swap with the uh basically the first thing is we are not swapping anything the zero at the one and one is the swap it doesn't do anything and then we just do a uh start plus we're starting from two here basically this start uh is see it's guaranteeing that we still can get this one two three four or the original other okay so and the second time right so when the i is the same as start we're not swapping anything but then when the i equals to start plus one basically we have one two three four okay so the start is this is start okay and the i is will be uh basically we're trying to swap everything uh with the current s to uh the current is the remaining numbers we swap with this and this okay and uh yeah and so we just and after this swap after the first swap right and then we uh we passed this uh the back tracking right the starting point to here to the start here okay and then from here onward it will try to swap again swap this one with the remaining of this until what until the start is equal to n okay then we know okay we have a valid permutation so basically we have to uh do the swap until we reach the end okay then we have a valid prim a valid permutation so basically this the way this algorithm works is that you know let's say for the first uh basically uh we when we swap uh one with one basically what we're trying to do here is we are trying to get all the permutations starting with one okay one plus something right so that's the first for loop right and the second one is the second loop is the uh we're trying to get all the permutations starting from starting with two okay since we are we're gonna uh swap one and two and uh and then we starting three something okay and then four something okay and so but how can we do how can we uh determine like what are the remaining three numbers right that's why we do a backtracking okay we do a backtracking to fix the remaining three uh letters or you can think of as a recursive call which means that okay we already have the first number fixed now we just need to figure out the ring the remaining three numbers that's why we call the backtracking method itself we start from one since like i said the it's just since the start has already been fixed now we just need to fix the start uh start plus one that's why we do it start plus one and then we are starting from here okay now we just need and then with the remaining numbers we do the same thing here right we fix we try to fix uh those numbers one by do by the swapping and then let's do a backtrack uh we do a recursive call until we have fixed all the numbers which means when the start equals to end then we know we okay we have already fixed all numbers then we know okay did now we have a candidate right of a permutation cool so let me remove this okay so at this time right okay we have a valid permutations now the next step will be uh how can we uh calculate the time and how can we compare the time okay so every time you know when you guys see it when you guys see a time related problem you know the easiest way to compare the different time is always convert time from this like hours and minutes format to its like integer format okay uh i'm gonna do a like compare time how about this okay we do we just do compare time and then i'm going to uh create define compare time here okay so at this time right basically the and let's see so the hours right so how about hours is the basically the first two numbers will make the hours right so the hours equals to and also and they're all integer which need to convert them into like the integer right uh or we can simply do that we can do a like uh like the a 0 right times 10 plus uh plus a1 okay that's one way of doing it or we can just uh you know convert those two numbers into a string and then convert them back to the integer concatenate then and then convert them back to the integer but a word we can just do a like the math calculation and then the minutes right goes to the a two times ten okay i'm gonna use both of those uh ways so this is what i'm talking about basically the string uh now uh a two right plus string a3 okay so this is what i'm talking about basically i convert them into a string can carry them together and then convert them back to the integer i know this one is like more it's more elegant but i'm just showing you guys another way of doing it okay now uh yeah so i mean so i think another thing we need to check here we need to check if this time is a valid or not right basically we check if the hours smaller than 24 and the minutes it's smaller than 60 okay right that's the easy track and then we just uh we do a max dot time equals max time we convert them right how do we do the conversion we just convert them into minutes right hours times 60 plus the minutes okay yeah so now let's uh every time so now the once we have the backtracking right every time we are backtracking we set we update max time and we can simply return right basically uh basically if the max time is equal to minus one right if it's still minus one then it means that we don't we didn't find any valid time which means we need to return empty okay else what else we can return the time but it asks us to find the to return the stream format is uh to this so this to this format right i mean so to convert the time back to its like the string format i mean the hours is what so the hour is the uh it's a max time divided by 60. right that's the hour and the minutes is the max time mod by 60 okay but can we but how uh but if we just return this if we just re return the string uh hours plus this plus string dot minutes right there will be an issue because if the hours and minutes if either of them it's zero okay so instead of zero let's say we have a 12 hours and zero minutes so if we are just uh using this uh simple conversion we're gonna have like 12 colon zero here right instead but instead we need a 12 colon 0 okay so that's why we need to do a little trick of format here and we have to at least have two zeros okay that's uh so in python this is how we do it basically we do this right uh to the i think i almost forgot i think zero two d okay zero to d basically it means that we need to have two zeros digit okay and then the second part is also uh to the zero uh two zeros okay and then dot format okay format and the first one is the hours and second one is the minutes okay so that's how we uh yeah that's how we uh format the final answer here so i think this should just work let me run the code oh yeah uh non-local oh yeah uh non-local oh yeah uh non-local max times okay time cool yeah this should just work yeah all right it's okay it's accepted okay a seed accepted all right so even though as you guys can see it got a lot of up downwards i don't know why but i like this problem you know not only it's ask you to practice the backtracking but also it needs you to be able to convert to compare the time and then convert it back to the uh to the time format i thought i think it's a good problem to practice you know okay yeah just to recap real quick basically you know the way we're doing this is that we just need to get all the permutations of those four numbers the way we're doing the permutations by using the backtrack uh recursive function here and we just fix basically we fix each number on this index right by swapping the we i mean with the rest of the numbers that's how we fix that one because after that we will have like the uh the rest of the numbers to be fixed okay and when we fix all the numbers we now we have a valid permutations then we just need to convert it into a into integer right into the integer value of the current time of course we have to check the validity of this uh time and then we update it in the end simply return it convert it back to its stream format yeah cool i think that's pretty much i want to talk about for this easy quote-unquote problem yeah okay easy quote-unquote problem yeah okay easy quote-unquote problem yeah okay thank you so much for watching the video guys and stay tuned see you guys soon bye
|
Largest Time for Given Digits
|
cat-and-mouse
|
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**.
24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`.
Return _the latest 24-hour time in `"HH:MM "` format_. If no valid time can be made, return an empty string.
**Example 1:**
**Input:** arr = \[1,2,3,4\]
**Output:** "23:41 "
**Explanation:** The valid 24-hour times are "12:34 ", "12:43 ", "13:24 ", "13:42 ", "14:23 ", "14:32 ", "21:34 ", "21:43 ", "23:14 ", and "23:41 ". Of these times, "23:41 " is the latest.
**Example 2:**
**Input:** arr = \[5,5,5,5\]
**Output:** " "
**Explanation:** There are no valid 24-hour times as "55:55 " is not valid.
**Constraints:**
* `arr.length == 4`
* `0 <= arr[i] <= 9`
| null |
Math,Dynamic Programming,Breadth-First Search,Graph,Memoization,Game Theory
|
Hard
|
1727
|
1,074 |
Hello Everyone Welcome To Our Channel Code With Sunny Today I Am Going To Talk About The Problem Number Form Entries Dasham To Target Index Numbers 107 To End Problems Of Ur Heart Problem Sub Delete Good Looking So Let's Discuss The Problem Of Android 2.3 Best Solution For This Android 2.3 Best Solution For This Android 2.3 Best Solution For This Problem Giver Matrix To The Matrix And Get Value Hundred Turn On The Total Number Of Nine MT Sub Matrices Death Shramik And 12312 Ashok Dinda Time Tricks Definition Is Given Year Now Looking And Adapt To Counter Total District Newly Created Subscribe The Video then subscribe to subscribe Video Like Page matrix also and you can absorb matrix given stop this is basically square matrices are interested want to be square matrix you can live with matrix like this one should also maintain given to the matrix in you can that's all matrix of this type oil Sukesh 2019 Counter Terrorism Actresses Looking So Let's Move Forward To Find Out The Country Which Of This Question Solve Sentences Use Phool And Pandey And The Solution Of The Problem Solve Matrix Length That Is Going To Be Like A Number Of Through 200 And Columns Iso * Bell Icon 210 200 And Columns Iso * Bell Icon 210 200 And Columns Iso * Bell Icon 210 B Vo * Solution of Class Six Like and B Vo * Solution of Class Six Like and B Vo * Solution of Class Six Like and Solutions and Subscribe 430 persons So let's move how to find out the variation of this problem that is going to help first solve this problem in the best possible way and find out the best solution Of this problem on cents maaf kar do kuch to kasoor sapoch bhi has been given ali are Rajasthan today they are in the last to find the total number of the recent music liquid to the giver target validated scramble to quote quantity 3D savere shramik one two Three Four One To Front Total Number Of Saver Is Of Which Samiti Vice Chancellor Ok Sirvi 1234 This Saver-Saveri Subscribe Hai - The Target Voice Already Encountered - The Target Voice Already Encountered - The Target Voice Already Encountered Previously Vibrating Sud Address Of Traffic Jams Daily Increment Or Dancer With The Twelve Play List Qualities Map Is Called S MP After Them - K Okay Now Let's Understand How This Is Going To Happen MP After Them - K Okay Now Let's Understand How This Is Going To Happen MP After Them - K Okay Now Let's Understand How This Is Going To Happen In Gower Here Okay So Let's Have Just One And Studd And History And Fear Into Its Beneficial Songs Live One Two Three Idiots Subscribe Again In Counter And This Point Essay On My Subscribe Total number of deaths were using node for all cars and Vishwavijay Storing the traffic sum of the value of the year OK 110 and basic one day approach and use this light modification order cancel use this idea of this world e cancel use this idea of this world e cancel use this idea of this world e approach which can approach this actual problem Updates Total Number of Account of Matrix Foolish Is Teacher Bill-2012 Matrix Foolish Is Teacher Bill-2012 Matrix Foolish Is Teacher Bill-2012 Advocate So Let's Get Out House This Solution Yes This Problem Solved This Approach Is Going To Help For My Technical Problem K So Let's Move Fast Ok So Let's Talk About Amazon Problem Service Broken Matrix Shoot Me Previous Approach Towards a Great Help in This Problem OK Frankly Speaking with Naveen Introduce Problem Justin Like and Not Meet in Order for Tickets of Matrix Likely It's a Distance of Matrix Not Fix This One of the Self Dated Top Quality Water Must Right Corner Off The Matrix Bhed Se Bichhe Dis Jo Alarm Koi Kuch Search Border Total Number Of Date Format Research Top Left Corner Going To Be Like Pic Schezwan Mein That Total Subscribe And Subscribe The Channel Subscribe Skin Subscribe To That If Film Tubelight Shoaib Like When In Contact With The System of This Force for This Tomato Is Unbearable Subject The Total Number of Date subscribe to the Page if you liked The Video then subscribe to subscribe Person Subscribe Like and Share into Something Like and Have Android User Like the Lever Decisive Given to Have Sake So Let's Take A WhatsApp Mode Approach To Solve This Problem And Approach Let's Talk About Approach OK Toilet Me Test Series Dushman Electric Latest Top Notification First Person Stockist Written Under-12 A Person Stockist Written Under-12 A Person Stockist Written Under-12 A Particular And Fighting For The Top Left Corner Updates Matrix Channel Subscribe and use this channel subscribe and subscribe the Channel subscribe like and subscribe in black and white is contest latest content for its ok to add 270 fans ka time like starting from i ab to m image ka number of columns and for Every Year Starts Talking About Writing From G Starting From IIM Up to the Number of Columns and SM OK Solve Vengsakar Complexity and Use This Point to Help First Pandey Recipe Number Format Research Officer's Vent to Get Some Work to Fix Deposit Slip Find the Total Number Of this on blood modify michael today match prediction ok to oil spills the beans residence russia that a dish if actually t-shirt two dish if actually t-shirt two dish if actually t-shirt two basically this point mintu moving from top to bottom and Russian flag meeting dropped by for every time sure time gift base System the test one two and replaced with single valued ball system subscribe now to find the total number of the total subscribe and subscribe the Channel subscribe hua ok later this is not just amazed and going to modify digit sub Matrix Point On Monday April 9, 2012 mp3 And Agro OK Fuel To Find The Total Number Of Paris Amit Chakli Paltoge Its Forms Likesgee All Districts Like This One That Aapke Switch Bhi Like Me Zinta And Matrix Light Bill Disha OK Updates Time No To-Do List Maintain the two lines situated No To-Do List Maintain the two lines situated No To-Do List Maintain the two lines situated enough time for the release of the number of columns and find the total number of subscribe and subscribe the Russia and subscribe channel to your ability and every truth so that you become education mafia in this updater particular level and An Incident Particular I Editor Particular G Anees Apni To Find The Particular Rule Se Role Number One The Amazing Mid Valley Middling - 02 Mid Valley Middling - 02 Mid Valley Middling - 02 A&M Starting Index of This Column At This A&M Starting Index of This Column At This A&M Starting Index of This Column At This Is Why The Subjects Of - Bal Is Why The Subjects Of - Bal Is Why The Subjects Of - Bal Buddhi Sacrificial Fire Shot Particular Rooh Indore Range Subscribe to the channel Like and subscribe button Subscribe to the video Subscribe to the Page Ki kaise jo hai rishto ko data hai Britain ho hai to penis ko * Digit ka number of penis ko * Digit ka number of penis ko * Digit ka number of columns and that point to the number OK Sorry less any this number Fruits and circulated on the number of columns and will be the first to difficult officer appointed to lines and just in the land of the like prominent leaders from one to two subscribe my channel subscribe 9 modern officers on Map for operations in one time ok so let's start 50 ending with student ko safed and placid between the lines between delhi to subscribe like and subscribe like share and subscribe 8051 bird that agar koi why solve this question of also like on balance by total number From house to tail me evicted from land equal to that in that case cross co use this important packet sleep display more channel subscribe my channel subscribe must subscribe and this particular row and system when connected milk committee graphics mode this particular Rocky So Avoid This Total Number Of Matters Will Be Prevented When Entry Of - Target Person Video subscribe The Video then subscribe to How Ten Sports Clubs Are In It To Let Me The Comment Section Of The Video Interview subscribe this Video Share This Video And Subscribe Our YouTube Channel Latest Updates Thank You For Watching This Video
|
Number of Submatrices That Sum to Target
|
high-five
|
Given a `matrix` and a `target`, return the number of non-empty submatrices that sum to target.
A submatrix `x1, y1, x2, y2` is the set of all cells `matrix[x][y]` with `x1 <= x <= x2` and `y1 <= y <= y2`.
Two submatrices `(x1, y1, x2, y2)` and `(x1', y1', x2', y2')` are different if they have some coordinate that is different: for example, if `x1 != x1'`.
**Example 1:**
**Input:** matrix = \[\[0,1,0\],\[1,1,1\],\[0,1,0\]\], target = 0
**Output:** 4
**Explanation:** The four 1x1 submatrices that only contain 0.
**Example 2:**
**Input:** matrix = \[\[1,-1\],\[-1,1\]\], target = 0
**Output:** 5
**Explanation:** The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.
**Example 3:**
**Input:** matrix = \[\[904\]\], target = 0
**Output:** 0
**Constraints:**
* `1 <= matrix.length <= 100`
* `1 <= matrix[0].length <= 100`
* `-1000 <= matrix[i] <= 1000`
* `-10^8 <= target <= 10^8`
|
How can we solve the problem if we have just one student? Given an student sort their grades and get the top 5 average. Generalize the idea to do it for many students.
|
Array,Hash Table,Sorting
|
Easy
| null |
131 |
lead code problem number 131 Pol Drome partitioning so this problem gives us a string and we have to partition it so that every substring of the partition is a palindrome and we to return all the possible par androme partitioning of the string s so what it means by that is let's say this example so we have to partition it so that it all of this are polres right so using all of the characters inside of string s this is the same right this are polr this two is poome and if the character itself is also considered a polr okay pretty straightforward so my solution to this is to use a recursive method a backtracking method using recursion so in the recursion I have this 2D Vector called the result and I have a vector of string which is this that I call current so current is what I will be using to push into result and result is what I will be returning as the answer so when the recursion is first called let's say I have uh s is aab Right using the example here so let's visualize how my recursion would execute so my string is s this will not change but start will change okay start set zero and if start is equals to the size of s in this case it's not this is only when we reach the end of the string and we need to check but since it's not so we can skip this for now here we have a for Loop iterating through the string I is equals to start I equal to zero and then here I straight away check I have a function called is P drum so this takes in a string the left index and the right index and basically just combines uh basically just checks whether or not this string is a palindrome based on the left and right pointers okay it's pretty straightforward a basic for Loop the trating true as long as left is lesser than right left will increment right will decrement and I'm just comparing if at any point they are not this same that means they are not a pandrum I return false otherwise are return true stating that the string is a pandrum okay this function is pretty straightforward but here I'm checking put I'm giving it the string and the start index zero and I is zero that means what it means that it is checking whether or not this character is a pandrum and since a in itself is a pandrum right because uh like I mentioned a character itself it say here no but a character itself can be a pum because the life the left and right which in this case are the same characters right okay so here I subring it right so starting position over here and this is used to count how many characters I am subst stringing so I minus start is 0 - 0 is still 0 Plus one is one so I'm - 0 is still 0 Plus one is one so I'm - 0 is still 0 Plus one is one so I'm only taking one character but let's say I were to be at two 0 1 two at B minus start is zero then it will be two minus 0 1 2 - 0 is 2 + 1 = to three that 0 1 2 - 0 is 2 + 1 = to three that 0 1 2 - 0 is 2 + 1 = to three that means I'm taking three characters here from the start this is an example of how subring Works since a itself is a sub strring let me put up my result and current I'll be pushing back current pushing back the string that I just subring into current so current right now looks like this is a I enter the recursion with I + recursion with I + recursion with I + one which means start is now 0 + 1 which is one I ignore this and then I enter the follow loop again I is equals to one from here I check whether or not this is a palindrome all right so I'm checking start and I so I'm checking this character which is the same character as before so this will be executed be subring you push back another a enter another recursion start is equal to two I is equal to two check palindrome yes B is a palindrome subring it push back okay andent another recursion start is 2+ one is 2+ one is 2+ one is three and here now that start is equal to size right three start is three and the size of s is three as well so that means we have finished iterating through S we have finished the recursion from this route so what we do is we push back current into our result like this so and then we exit return exit here we come back from here so we pop back once we pop back I will increment to three and since it's three this Loop will end because I3 is no longer lesser than S size right so this will return as well exiting this for Loop you come out from here from this recursion pop back and now I will increment to two and now I the starting is one over here and I is now at two so we're now looking at string AB when we check whether or not AB is a polum it is not so we do not do anything but we increment to three since we have reached three so what we do is we exit this for Loop when we exit we return here our current will pop back so now we are back to square one but the difference is I now Plus+ to one but the difference is I now Plus+ to one but the difference is I now Plus+ to one so now our start is zero our I is one so now we're looking at AA since AA is a palindrome we stop string it put push back and then recursion again I start is equals to 1 + 1 which again I start is equals to 1 + 1 which again I start is equals to 1 + 1 which two so now we are checking right we haven't checked anything yet so I is equal to two as well so now we're looking at b as a character itself and since A Single Character can be considered as a poome so we substring it push back like so and another back push back like so and another recursion start is now equals to 2 + 1 recursion start is now equals to 2 + 1 recursion start is now equals to 2 + 1 is three and then since we have reach S size which is three as well we push back current into our result and then return so return here pop back and then increment I to three once is three exit this for Loop exit here and then this will exit we pop back again pop back here and now I we now move to I will now increment sorry to 0 to two so now we're looking at a as a pandrum but since aab is not a palindrome this whole block does not get executed and the for Loop just end after we increment I to three so once it ends we exit here and we return the result which you can see here a b then double A and A single B which is the same as the answer provided in the example okay so overall this problem was pretty straightforward and the answer hopefully was not too confusing nonetheless that's all I have to show thanks
|
Palindrome Partitioning
|
palindrome-partitioning
|
Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1 <= s.length <= 16`
* `s` contains only lowercase English letters.
| null |
String,Dynamic Programming,Backtracking
|
Medium
|
132,1871
|
135 |
and the challenge name is Randy so the challenge statement goes like this there are n children standing in a line each child is assigned a rating value given in a integer array ratings this rating survey will be given to you so each of the element of this ratings array indicates a rating given to a particular child so you are given candies to you have to give candidates to these children satisfying the following requirements each child must having have at least one candy and the child with higher rating than its neighbor will be having more number of candies so you have to return the minimum number of candies that you need to distribute in order to satisfy these two constraints so let's have a look at the uh constraints of the problem so the length of the ratings array will be of order 2 into 10 raised to the power 10 and the values of the ratings will be opponent 2 into 10 raised to power so 10 raised to power 4 actually I and both of these are 2 into 10 raised to power 4 so let's have a look at the approach how we will be solving this problem uh consider this as your given input this is the given ratings array and so this is your input ratings array we will be using a 3D approach what we will do initially we will satisfy the first constraint by giving each other one candy uh this uh the candy array will be used to denote the number of candidates each child will be getting so first we will check for the left Neighbors then we will have a check for right neighbor during the check of left neighbor a child is having let's say this is a particular child you are considering now it is having more rating than its left neighbor so it will be having one more candy than its left neighbor so it left neighbor was having one candy initially so this will have two candies so uh let's move to the next style uh 87 is having more uh relating than it's left uh never now you will also give one more candy to 87 uh then it's uh left neighbor so the left neighbor was having two candies now 87 will have three candies similarly you will keep checking for the left neighbors then you will check for the right Neighbors in a separate uh loop then and you have to implement extra check if there is a child having higher rating then it's right neighbor child is having higher rating then it's right neighbor and is having less or equal number of candies then it's right never then only you will update the candies to write never plus one so this is to settings this is to ensure that you are using least amount of candle if a child is having already having more number of candles than its right neighbor while it was having more fire rating than its right never then you need not to update the candies of the at that particular child while checking for the right neighbors so this will be the two things that you will be doing uh first you will be giving each child uh one candy at least then you will uh updates the update the attendees of your children according to their left and right Neighbors ratings and the candies they are already having so that's pretty much it now let's have a look at the implementation so this is the implementation part uh this maximum rating will be used in case the child is not having a left or right neighbor and this candy array will be used to store the candies each child will be getting according to the requirements and this is the minimum number of candies that will be required to remove minimum friendly required to be distributed so first you will check uh for the left Neighbors uh you will check the rating of the left neighbor and if in case the rating of the current child is more than it will have never then you will update his candies and you will give just one candy extra to the child in order to ensure that minimum candies are being used for the distribution then you will do the same thing for the right neighbor along with this extra check to ensure that only minimum candies are required to distribute uh according to the requirements then you will get the total number of trend is that you will be required to meet the requirements and you will be returning those countries so that's pretty much it for the solution part so the code will be available in both of the languages C plus and Java if you are still having any doubts please feel free to ask them in the comment section thank you for watching thanks
|
Candy
|
candy
|
There are `n` children standing in a line. Each child is assigned a rating value given in the integer array `ratings`.
You are giving candies to these children subjected to the following requirements:
* Each child must have at least one candy.
* Children with a higher rating get more candies than their neighbors.
Return _the minimum number of candies you need to have to distribute the candies to the children_.
**Example 1:**
**Input:** ratings = \[1,0,2\]
**Output:** 5
**Explanation:** You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
**Example 2:**
**Input:** ratings = \[1,2,2\]
**Output:** 4
**Explanation:** You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
**Constraints:**
* `n == ratings.length`
* `1 <= n <= 2 * 104`
* `0 <= ratings[i] <= 2 * 104`
| null |
Array,Greedy
|
Hard
| null |
554 |
hello everyone welcome to coderscam so we are at the 22nd day of april code challenge and the problem we are going to cover today is brick wall so here the input given is list of list and we have to return the minimum number of bricks we crossed by drawing a line so here the problem statement said if your line go through the edges of the brick then the brick is not considered as crossed so you need to find out how to draw a line to cross the least bricks and return the number of crossed bricks so let's understand this problem with an example so here is our given input list of lists our problem statement says there is a rectangular wall where the bricks are there and the height of each brick are going to be same in every row but the width of the bridge changes accordingly so now in the first row the bricks are 1 2 1 and so on so if we are representing the given input in form of bricks and wall it is gonna look something like this so now here they said we cannot draw a vertical line and both the edges we have to draw the line in between the wall so now we are going to draw a line randomly and check how it actually gonna work so let us try drawing a line here so which means it is crossing the first brick one three one two three and one so it has crossed one two three four five six overall six bricks by drawing a vertical line here if suppose we are drawing a line here so they said in problem statement if we are exactly drawing a line between or between the edges of two bricks then in that case we are not crossing that brick so we are not crossing anything in the first line and second line so moving on to the third line we are crossing the brick three which means one and moving to the next line we are crossing the brick four and since it is in between we are not crossing any bricks in line four so here we are going to cross the brick three so far we have crossed three bricks by drawing vertical line here so now we are going to draw exactly here so in first line we are crossing the brick with two and second line there is no brick crossed because it doesn't between edges and third line also we did not cross any bridge sorry bricks and in fourth line we are crossing the brick of width four fifth length no brick crossed because it is in between the edges and last line also no brick crossed so far we have covered two bricks while drawing a line here so this is gonna be the minimum number of bricks that we can cross by drawing a vertical line in this wall so how are we going to approach this so now the idea is to draw the vertical line where most of the edges meet so the last line vertical line we have drawn is here so this is the point where four bridges meet with its edges so that we could cross only two bricks and we cover the least number of bricks here so now we are going to find a point where most of the edges meet so we are going to draw the line exactly at that point so how do we actually find where all the edges meet so as the wall is of a rectangular shape though the width of each brick may change but the overall width of the rectangle is going to be the same in all rows for example here if you sum all the bricks in the last row it is going to give you 6 the same way if you calculate the width of all bricks in every row it is going to sum up to 6. so now we are going to calculate the sum at each step so that wherever the frequency of the sum matches the most frequency then it is going to be the point where our edges meet this may be confusing so let us work out and try for better understanding so starting from the first row of our wall we are going to calculate the prefix sum at each edge or perfect sum of each brick in the wall so let's start from the first row our first brick is gonna be of sum one and the next brick by adding two it is going to be of three and then moving on to the next brick which is two so by adding the sum is going to be five and the next brick it is going to be six by the end anyway it is going to be six in all the rows so starting from the second row it is going to be three four and six and the third row the sum is going to be one four and six the same way the next row is going to have two and six so moving on to the next row which is gonna have three four and 6 and finally it is going to be 1 4 5 and 6. so now we have calculated the prefix sum so our last row is going to be have having all 6 because that is going to be the end of the wall we cannot draw a line there so now we are going to check which sum is most frequent here so if you observe the sum 3 appeared thrice and some 5 appear twice and two appeared once four appeared four times which actually means there are four edges meeting at one single point i did not mean the sum but the occurrence of four that is four times for example if you consider three occurs three times which means there is some point where three edges meet that point is here so at this point you can see three edges meet the same way at this point four edges meet that is what it meant so what the occurrences here denotes that many edges meet at a single point so we are going to take or pick the maximum occurred point so here four is the maximum third point so which means four it just meet at one point so that is the point where we are going to draw a line so if we draw a line what will happen there which means it cross four rows edges and remaining two rows will be the brick we actually cross so now the overall number of rows given here is six there are there is a point where four edges meet which means we did not cross 4 bricks so minus 4 will actually give you the total number of bricks you actually crossed at that point so this is the actual approach we are going to use in this problem so if we always hear about a number and its frequencies we straight away go to a data structure which is hash map so we are going to get the help of hash map to store the prefix sum and its occurrence simultaneously and finally we are going to pick the maximum or most occurred frequency and subtract it from the number of rows given so that we will get the least number of bricks we cross by drawing a vertical line so hope you're understanding the solution so this is going to run in big o of n into l time complexity where n is the number of rows given and l is the average length of the given list or given root so let's go to code now so first as i explained i'm gonna get the help of map to store my prefix sum and the occurrence and i'm gonna have a variable count which is actually gonna hold the count of uh maximum occurrence and i'm gonna have my loop which is gonna iterate the list given here in the input so every time i'm going to initialize my variable sum equal to 0 so that it calculates the new sum for every row so here i'm going to iterate my elements in each list so i am gonna add the elements in list that is so far sum and once i get it i'm gonna update my map so yes every time once we calculate the sum we are going to update our map with the sum and its occurrence so every time we are updating our sum and its occurrence we are going to get the occurrence max at each hydration so our count is going to hold the maximum occurrence of prefix sum so we are going to update math dot max of count comma map dot get off sum so yes once iteration is done our count is going to have the value of maximum occurred sum in the hash map so finally return wall dot size minus count so yes let's run and try let's submit yes the solution is accepted and it runs in 10 milliseconds so thanks for watching the video if you like the video hit like and subscribe thank you
|
Brick Wall
|
brick-wall
|
There is a rectangular brick wall in front of you with `n` rows of bricks. The `ith` row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same.
Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.
Given the 2D array `wall` that contains the information about the wall, return _the minimum number of crossed bricks after drawing such a vertical line_.
**Example 1:**
**Input:** wall = \[\[1,2,2,1\],\[3,1,2\],\[1,3,2\],\[2,4\],\[3,1,2\],\[1,3,1,1\]\]
**Output:** 2
**Example 2:**
**Input:** wall = \[\[1\],\[1\],\[1\]\]
**Output:** 3
**Constraints:**
* `n == wall.length`
* `1 <= n <= 104`
* `1 <= wall[i].length <= 104`
* `1 <= sum(wall[i].length) <= 2 * 104`
* `sum(wall[i])` is the same for each row `i`.
* `1 <= wall[i][j] <= 231 - 1`
| null |
Array,Hash Table
|
Medium
|
2322
|
835 |
Hello hello everyone welcome to my channel it's all the problem image overlap sotu image and where given represented a pyun from it geometry only 10 end values which left geometry only 10 end values which left geometry only 10 end values which left side now them number of units play list on top of the end of the over translation is the number of Position 103 Case Know the Translation of What is the Best Possible Subscribe Clearly Mentioned in the Problem Subscribe What We Can Do the Matrix 1068 Over District Matrix So Let's Check Out Examples and Values of Check Out Examples and Values of Check Out Examples and Values of Kids and Share Subscribe From Subscribe One Place to Know What Is The Place Were First Saw Her And Only Will Be Coming In Chief notes11 Share And Subscribe 560 90 Dabangg-2 Turn On Mode Dainik 560 90 Dabangg-2 Turn On Mode Dainik 560 90 Dabangg-2 Turn On Mode Dainik Swadesh Have Every Time In This Overlapping For This Call Interaction With Arduino With Acid Case Will Right Side Unit And Five What Is the overlap bun hair oil 2000 egg subscribe share like subscribe and a place where a special share let's hear message from the right side like this point to right side ac me and you no vacancy free overlap bun so this is the maximum possible for this To images for this is how they can trigger on images which can move from this is the place where they can start the - don't like please don't like start the - don't like please don't like start the - don't like please don't like subscribe and will start from plus way columns and go to the best all The best all the amazing maximum subscribe to my co worker f-18 the various get beau my co worker f-18 the various get beau my co worker f-18 the various get beau answer these joint cry 128 length - answer these joint cry 128 length - answer these joint cry 128 length - subscribe Vivo roll.no hello plus similarly for long will start from problems from noida land plus one doctors in the middle Of will and toys plus absolutely not patient and subscribe beach role subscribe and jewelry subscribe to hover over all levels will demetrius tree that andy charge and drop set flat settle object and option a that and fair will get discounts for electric office 10 Thursday Ko Again Bhi Tractor Point Late Se Roe From 100 Days Ago From The 8 - Hair 8 - Hair 8 - Hair Yes 210 Will Be The Matrix Our Matrix Started From A And The Second Raware Matrix Which Will Start From Hair Oil Indicative And Method Have To Ramesh From being in the politics of matrix 023 length and will check also possible values of soul will check also possible values of soul will check also possible values of soul will register for vote that and this will become Dheeran Saunf from Noida and Dadri area Virwal start from 0 to examine the plus that Hanno will go for column for in Call start from 0 and call include more than 100 Doppler will check weather department for the real life stop this plus dol set off meeting this district continue and roles rosette is in Greater Noida and Noida that effect as a Greater Noida blank pen will continue To doors on top in middle side and research one side column plus column horizontal widrow 1504 subscribe loot android lustful subscribe plus self midland subscribe The Amazing appointed special done for subscribe to that apps discriminator if we chief row element on row Gopal is one and basically also need to check weather very any one or more images amazon 20 pro plus raw set karo hua hai net school plus call option saudi doll set n will check with British up to two the self in this will increase our in this cream and subscribe Our is 135 compiling and where getting correct answer so let's submit code the city has accepted what is the time complexity of dissolution so this is what we are looking for the day addiction and elements from minor to 0.5 inches for doing job from minor to 0.5 inches for doing job from minor to 0.5 inches for doing job total time complexity and power and subscribe Like button subscribe To My Channel thanks for watching this
|
Image Overlap
|
linked-list-components
|
You are given two images, `img1` and `img2`, represented as binary, square matrices of size `n x n`. A binary matrix has only `0`s and `1`s as values.
We **translate** one image however we choose by sliding all the `1` bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the **overlap** by counting the number of positions that have a `1` in **both** images.
Note also that a translation does **not** include any kind of rotation. Any `1` bits that are translated outside of the matrix borders are erased.
Return _the largest possible overlap_.
**Example 1:**
**Input:** img1 = \[\[1,1,0\],\[0,1,0\],\[0,1,0\]\], img2 = \[\[0,0,0\],\[0,1,1\],\[0,0,1\]\]
**Output:** 3
**Explanation:** We translate img1 to right by 1 unit and down by 1 unit.
The number of positions that have a 1 in both images is 3 (shown in red).
**Example 2:**
**Input:** img1 = \[\[1\]\], img2 = \[\[1\]\]
**Output:** 1
**Example 3:**
**Input:** img1 = \[\[0\]\], img2 = \[\[0\]\]
**Output:** 0
**Constraints:**
* `n == img1.length == img1[i].length`
* `n == img2.length == img2[i].length`
* `1 <= n <= 30`
* `img1[i][j]` is either `0` or `1`.
* `img2[i][j]` is either `0` or `1`.
| null |
Hash Table,Linked List
|
Medium
|
2299
|
3 |
Hello, welcome to another video on my channel, I'm Cassiano And today we're going to solve another challenge of it Could you she challenge number 3 or hide long This type of Federal I prefer to fill up to the largest substring' without the largest substring' without the largest substring' without the meal of characters an announced quite simple given a string S find the size of the largest substrings in which character retention this is a medium level question what would that be like, right so we have an input here ABC baby is the largest substring that we can find it here without character repetition, it has size 3 which would be substring ABC or it could also be BCAA or it could be sehab but it cannot be ABC and because there is it would be repeated here, right And that is the idea of the question is Just a of the question is Just a of the question is Just a frequently asked question on Amazon, there are some bets from Microsoft, there are also bets from Bloomberg, Facebook, Doblô, Apple, Google, Uber, PayPal and Spotify, I think the first way we can think about resolving this here would be with Brute Force So would we actually come here looking for each substring is possible within this strange a doing this check for repeated characters a and checking the largest of them, right then you would come a b c a iva would be until the end here then you say that me again with the letter B then all over again with the letter C And so on and realize that this is a solution that apparently is very expensive it really is and if you are going to bring it to the complexity of algorithms it is a solution in Ao Cubo just to give you an idea of what it is which means think that the bigger the number cubed, the bigger it will be, it seems like God, it 's kind of silly to say that, right, but I want to 's kind of silly to say that, right, but I want to 's kind of silly to say that, right, but I want to tell you that the bigger the size of your subtribe, your stringher, your algorithm, it will scale very badly. a form is very absurd So think about the following if you have 5 to the cube you would have, for example, 125 operations, right, 15 being, for example, the size of your strange, right? Now think that you receive a string of size without So you would have a million operations, now that you have received more train than 500 of size 500 you have to 125 million operations think you understand a thousand characters the times a billion operations Now imagine if you are finally going to 5,000 Our Lady I you are finally going to 5,000 Our Lady I you are finally going to 5,000 Our Lady I didn't even do the math to know but it's a lot big don't realize that this scales very badly in a really bad way and what would be the ideal solution that we have here, right, we can adopt the following, we will work with 2 pointers, one from the left of the right, we will have our Max here, you know, that will save the largest size that we found, we will have a regime that will save this feeling, it will be used to store all the letters that we found and there can be repeated letters within this remainder map and everything will make sense here as the Let's move forward, okay, this pointer on the right, it advances whenever we find a letter that is not within our rest api What is precisely this first case here, right, even filling is empty, so the letter does not exist in our rechnet So we let's add the letter A to our NET, right? Let's update Max to one, ok Because one greater than 0 was the zero is the previous number, right? And we go to the right, we found the letter B. So let's put Bino, medicine, let's update Max only 2 ok so show flap you let's add the system the map and Max now goes up to three because the size of our growth right a and now we really like the letter A but look at the letter It already exists here in our hashtag and This is where the control on the left advances, what do we do with us? We find a repeated letter, we remove this letter from the middle Hatch, and we advance the left pointer in one position, so we, the regime, would look like this, our construction site left and leading to a position This is the control on the right it doesn't advance but now in the next interaction it will advance because it will ask the same question and now the letter doesn't exist so the letter Comes down here we don't need to update Max right, 3 = 3 and don't need to update Max right, 3 = 3 and don't need to update Max right, 3 = 3 and we're going to point out the control on the right, it's one position ahead and continue asking actions the questions now we have the letter B already exists and we do Remove the letter well and advance the control on the left and the control on the right does not advance so it will ask the same question but now there is no letter b we add it works the rest map we will update the Max size and we advance the pointer on the right now we will find letters and we do we remove letters and the rest advance content on the left and now we go to the next interaction now letters it does not exist we activate the letters and here Marcos does not need to be updated we will advance the control on the right we find the letter B exists so we remove the letter b we move the pointer to the left now we go to the next interaction we continue here at b the b does not exist so we add it and there is no need to update Max Payne 3 is equal to 3 and we go to the next position situation position we have the kiss of new so it came there and we are going to do how to remove the baby in a step forward with the advice on the left and let's go to the next interaction now the control on the right continues with the letter b there is no letter b we added the beck to the net 3 And then there is no need to update just that now we have reached the end of our vector and there is nothing left to do, so given the string ABC baby, the output will be three, exactly as it would be if we did a brute force, but we do it in an extremely more efficient way, it is a code that included the script that will bring us this same one, it was the implementation of our algorithm, notice the four variables that we worked on throughout the execution of the merit hash algorithm and the Monster on the left, the advice on the right and the Max size So we will make a loop while the left is smaller than the size of our Sai stringhi ok they have a single condition which is if the letter does not exist we will add that letter to our retimape whatever here the number is not one it is just for the record We are going to implement ours. It gives right and one more and we are going to update a crisis with the largest average size with to say something inside but it would be the same as if I made a wi-fi on if map as if I made a wi-fi on if map as if I made a wi-fi on if map points then if it were bigger than it is more out then you say that Marcos is like a doctor with salts, but then it's different, more elegant than you doing the same thing because this function will return the largest number of these two, right? It has exactly the same effect as making a like here and we will Noel means that the doctor and the letter exist within our map, right, so we're going to delete it at the same time as we make an increment, a post increment here to pull the content from the left to the front and we, at the end, return it to our website and This solution has both time and space, a complexity in me, right, and that being said, we end our life here, I hope you liked it, if you liked it, you can leave a like, I would appreciate it if you could subscribe, if it wasn't here I would also appreciate it, but if you still have any doubt, criticism, suggestion, anything you want to leave in the comment, that's it, thank you, see you
|
Longest Substring Without Repeating Characters
|
longest-substring-without-repeating-characters
|
Given a string `s`, find the length of the **longest** **substring** without repeating characters.
**Example 1:**
**Input:** s = "abcabcbb "
**Output:** 3
**Explanation:** The answer is "abc ", with the length of 3.
**Example 2:**
**Input:** s = "bbbbb "
**Output:** 1
**Explanation:** The answer is "b ", with the length of 1.
**Example 3:**
**Input:** s = "pwwkew "
**Output:** 3
**Explanation:** The answer is "wke ", with the length of 3.
Notice that the answer must be a substring, "pwke " is a subsequence and not a substring.
**Constraints:**
* `0 <= s.length <= 5 * 104`
* `s` consists of English letters, digits, symbols and spaces.
| null |
Hash Table,String,Sliding Window
|
Medium
|
159,340,1034,1813,2209
|
374 |
welcome back to algorgeous today's question is leak code 374 guest number higher or lower so we're playing the guess game the game is as follows I pick a number from 1 to n you have to guess which number I picked every time you guess wrong I'll tell you whether the number I picked is higher or lower than your guess you call a predefined API guess passing in Num which returns three possible results minus one your guess is higher than the number I picked one your guess is lower than the number I picked or zero your guess is equal to the number I picked return the number that I picked okay so in the examples we are given an N value of 10 so this is the amount of numbers that we can choose from we have a pick which is the actual answer that we're looking for and that is six so with this question I've populated this array here as an example we're not actually going to use this array in our solution but it's just for visualization if we didn't have a predefined API guess and we just had an array of numbers and we had to find pick so we had to find six within this array as efficiently as possible how do we go about doing that we'd probably use something like binary search right which would have log n time complexity and that's exactly what we're going to do here the only extra bit of work that we have to do is understand what the guess API does and how to add that into our binary search so let's run through this example we have this array let's say we take left as one right as n so right as 10 we grab the Mid Valley so middle is going to be five we pass this number into our guess API the number is less than pick so it's going to return us 1 right when num is less than pick so I'll write up here the values so we guess five is less than pick num that is less than pick is going to return one so if the answer we get from guess is equal to one then we need to update the left pointer and exclude this section of the binary search because we know that this value right here because it's less than pick anything to the left of that is going to be in the right side of the array so let's update the left pointer we get the middle again now we pass this value at Mid into guess API so we pass 8 in here we get an answer the answer is going to be when num is greater than pick so we're going to get -1 now if it's minus one we need to do -1 now if it's minus one we need to do -1 now if it's minus one we need to do some other logic so we know for a fact pick is not going to be in this side of the array so we need to update the right side to Mid minus one so right goes here mid is going to be math dot floor so mid goes out left and then we can check at this point we can pass this value into the guess API past 6 in 6 is equal to pick so it's going to return as zero and if we have a value of zero returned we can return this value here so that's the basic solution time complexity is going to be as we stated at the start log n and then space is going to be o1 so let's define the left and right pointers as stated in the question left starts at one so we can pick a number from 1 to n that right equal n or left is less than or equal to right we can get the mid value which is going to be left Plus .flow .flow .flow right minus left divide by two now we need to pass in the number we get from mid into our guess API so guess mid and we can add this into a variable now if and is equal to zero we found an answer so we can return mid if ants is equal to -1 to -1 to -1 foreign and then the last option is if answers equal to one we set left equal mid plus one let's give this a run and there you go
|
Guess Number Higher or Lower
|
guess-number-higher-or-lower
|
We are playing the Guess Game. The game is as follows:
I pick a number from `1` to `n`. You have to guess which number I picked.
Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.
You call a pre-defined API `int guess(int num)`, which returns three possible results:
* `-1`: Your guess is higher than the number I picked (i.e. `num > pick`).
* `1`: Your guess is lower than the number I picked (i.e. `num < pick`).
* `0`: your guess is equal to the number I picked (i.e. `num == pick`).
Return _the number that I picked_.
**Example 1:**
**Input:** n = 10, pick = 6
**Output:** 6
**Example 2:**
**Input:** n = 1, pick = 1
**Output:** 1
**Example 3:**
**Input:** n = 2, pick = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 231 - 1`
* `1 <= pick <= n`
| null |
Binary Search,Interactive
|
Easy
|
278,375,658
|
1,595 |
hey what is up guys this is just a disclaimer uh i'm sorry that this explanation wasn't that great i think it still works i think you'll understand the problem by the end of it but um it wasn't as quick and as clear and straightforward as i wanted it to be but i don't have the time to re-record re-record re-record it um but that's that i hope you still guys enjoyed i hope you guys benefit from it if you didn't and just let me know comment below and ways i can improve and let me know seriously if you guys want me to start using diagrams because that's something i've been thinking about for a while now hey what's up guys we're back with another lead code problem we're doing problem number 1595 and it costs to connect two groups of points you're given two groups of points where the first group has size one points the second group has size two points and size one is greater than or equal to size two the cost of a connection between any two points are given in a size one by size two matrix where clause i j is the cross connecting point i of the first group and point j of the second group the groups are connected if each point in both groups is connected to one or more points in the opposite group in other words each point is in the first group must be connected to at least one point in the second group and each point the second group must be connected at least one point in the first group return to minimum cost it takes to connect the two groups so basically this every node in this side has to be connected to each load on this side and it's known in this size we're going to every node and that side so we have the example here cost 15 96 36 2 and we see the minimum cost would be of connecting the two sides would be a 17 so we have 1 to a which is 15 and 2 to b which is 2 and so the desk results in the total cost of 17. okay so how are we going to approach this problem um there's a number of ways that i tried and i ended up failing this was there was two ways that i tried doing and both ways didn't work and then i ended up finding the optimal solution after that but anyways so the first thing that i tried doing was um i thought maybe we'll just act like all the points are connected originally and then i'll start removing all the maximum ones meaning that i'll act like one is connected to a and b is connected to one and two so all the points already there and i'll start removing the edges that have the total cost while keeping all the nodes um intact while keeping all the uh nodes yeah all the other nodes intact i connected each other so basically if i end up removing this uh cost and that means um either of the two nodes uh if i end up removing this edge and that means if either of the two nodes are no longer connected then i can't remove it i will remove it so that's the approach that i took at first i'll link that solution uh below it wasn't really a solution i like that attempt below because i asked the discussion board why that wasn't working and then someone explained to me so it was a good example as to why that wasn't her but that won't work the second approach was i took was okay fine let's just start uh pairing them up so i'll do one i'll grab the minimum cost and i'll have a pair with uh um so one has the edges connected to a and b right and i'll find the one that's minimum and i'll connect that then for two i'll do the same thing and then for anything else i'll keep doing the same thing and then on the right side whatever's left over i'll also do the same thing if anyone has them connected to the left side yet then i'll just grab the minimum cost and i'll start connecting them that also won't work um i kind of walked through as to why his approach as to why that wasn't working for example let's say you have a b and c and then you want to connect to um one and then two so if you connected a to and these are all the edges right so let's say i was grabbing the minimum cost so let's say i connected eight to one or eighty two which one is cheaper these are the two i'll do a to two so i'll say a to two is three instead of doing a hundred right and then i'll connect a to two so imagine a and two are connected then i want to connect b so i connect b with anything i can only be connected to two over here so i could have two so b two that's also that's equal to two right there then i have c left over c is connected only to um uh a over here to one over here so that will be c1 is equal to 101. i s alright that's my problem so that will give me an optimal solution right but let's just say i started from one two first let's say i started from this side first and of course the order doesn't matter i can take an example where this is like this right the order doesn't matter but let's just say i started so in this solution this in this case it would work but now let's say i started from one two so then i'll start from the right side so i say one and i'll say what's the minimum uh cost for one and we have c so i'll pick one a which is a hundred right then i'll go to two which one is minimum of b two which is two right and then i'm done on this side so i'll try to see the leftovers on this side and i see c is still left over so i have to connect c which one can i see so 201 so i'll connect 1c which is 101 and i'm getting something like what 203 or something like 203 which is way more than uh as we saw earlier the minimum cost that we were able to get which was just 106 right which was just 806. so this approach also won't work so the way you're going to approach the solution then is now you're going to have to try all the left pairs with every possible right pair right so i'm going to have to try a with one or so let's just use example for now well it doesn't really matter i'll have to try a with one and then a with two and then b with one and b with two and then c with one and c and two so that's the approach that we're going to have to take okay so i'm gonna try a with one and then i'm gonna see was with b with either one or two and then c with either one or two and then i'll end up with a cost at the end of that and then um i'll save that and i'll see if that and then that will be one possible uh cost and then i'll try again a with instead of starting with one this time i'll start with two this time and same thing with b i'll do one then two and c one and two and i'll get the cost at the end that way okay so we're not back uh take a break but anyway so now how are we going to approach this problem how are we going to code this into remember we talked about that each node in this left side is going to have to connect with each of these nodes on the right side so the way we're going to do this is this so we're going to have a helper function right and it's going to take in the current index on the left side that we're at so whether we're at a or b or c is going to let us know where we're at so that's going to be an index group 1 index meaning we're at either at a or b or c that's what that's going to tell us and then for we're going to grab the node at this index just imagine so we're going to grab this node in the index and we're going to connect it with each node on the right side so we're going to go through all the nodes on the right side for all for node and two in group two right which is the right side we're going to connect um node one at g1 index group one index with and two okay we're going to connect this node with the right node and then what we're going to do then so after we connect that then we need to try the next node and the left side right so i'm going to call helper with group one index plus one meaning i try to connect the a with one of these then i'm gonna track anything b with one of these then i'm gonna check i can see with one of these okay so first a gets connected with one then b will connect with one then c will get connected with one and then eventually if group one index is equal to group two size meaning that we have no more uh notes at c in our group one or our left group then what we can do what we have to do then is we have to go through our nodes on the right side and see which ones haven't been paired yet which ones are left over so we're gonna go through node and two in group two if not paired if they're not paired connect them if they're not protected with the minimum cost we can just connect them with the minimum cost now we can just connect them with the minimum cost at the end of that we're going to get a final cost and we're going to add all these costs up of connecting with all the ones that we connect to a4 and then b and then two and then we're going to save that and that's going to be our final cost for this that current pair of connections and we're going to try that like we talked about with which each node left side connecting to each node on the right side so a is going to fit with 1 then 2 or b 1 2 c 1 2. it's going to try all those out and then it's going to look on the right side at the end of all those recursive calls right our base case once we finish all these it's going to look at all the leftovers over here on the right side on group 2 side and it's going to use the minimum cost and connect them that way so that's how we're going to uh approach the problem i'll look at the code in one second but let's just talk about some things real quick how are we going to keep track whether group two was paired with one something from group one right so we can do this properly one we're going to use a bitmap so we're going to use a bit mask to check whether group 2 has been paired uh already or not because group 2 will only have a limit of size 12 right it won't go past size 12. so we're going to use a bit mask we just flip the bits to check whether they've been paired or not number two how are we going to know what's the minimum cost we don't want to keep going through all the nodes on the left side each time so before we call any of these we're going to go through group two's um edges and we're going to find the minimum cost for each one of these nodes and we're going to save them that's number two and you'll see what i mean by that in just a second um so number one number two oh yes number three is we're going to use a dynamic programming pro programming or memorization to keep track of uh the cost that uh we've already possibly calculated meaning that if i see that i've connected a with one already and then i've connected b with uh two already then i can check when i get when i hit c the second time because let's say the first time i connected a with one and then b with one i start a with one and then b with two and then i get to c so i see now when i'm at c i see a is connected to one already b is connected to two already and that means c is left over and i calculate c the second time i can check again a is i can connect a to two and then b to one remember the first time we take the a to one and b to two and now we're connecting a to two and b to one and then i get the c again and once again i see a is already connected b uh e b is already connected two is already corrected one is already connected and so i already calculated uh the c value for that already so i could just use the previous um calculation already that's what i mean by the dp so if you look here now we're going to walk through this code so i'm going to get the cost of group 1 the size of group 1 and size of group 2. i'm going to create my dp array so it's going to be group one to group two meaning whether group one has been paired with group two already right or not really when this um index over here right this is going to keep track whether group one uh which nodes in group one have been paired right this is also going to keep track of whether which nodes in group two have already been paired but they're going to do it differently group one is going to be uh keeping track of whether we've because if we reach the current index that means everything before it has already been paired so that's how that's going to keep track of it whatever index we were at that means everything before it has already been paired and this one is going to keep track of what notes have impaired by using the bit mask as we talked about meaning whether this int has been seen already so that's that so that's the dp a 2d array then we're going this part over here is going to calculate the minimums as we talked about um for this step connect with the minimum cost remember we said we're going to find them originally at first this is going to find the minimum cost for each of the edges each of the nodes in uh group two and then we're going to call this a helper function i don't really know why i named the dfs it's not really dfs kind of not really what this is going to do well first we're going to check if we calculated this already for this uh for this um node because remember for this group 1 index if we reach this index so far that means everything before we've already calculated so all those nodes in node one have already been uh connected and then same thing for group two we'll use the mask to see if those nodes and node two have already been connected so we've already calculated this uh set before this set of connections that we've seen already before then we'll just turn the answer for that right because the c the rest of the code following is going to be exactly the same as what we calculated before because we've seen these arguments already we've seen those arguments already then uh what i'm going to do is ignore this we're going to come over here as we talked about we're going to go through this node in the left node and we're connected with each of the nodes in the right node so this is what this is doing over here i'm going through all the nodes in the group two or the right side and i'm going to connect it this way this is going to get the cost of the connection right i'm going to connect it with my node my current node on the left side so a with one a with two this is what this hair is doing right and then i'm going to grab the minimum cost for each of those so i'm going to uh either use the minimum cost i already found or i'm going to see if this one had a better connection meaning did a connecting to one and then continuing on was that better than a connecting to two and continuing on right now this is what this is doing so as you can see right here i'll pass in the next group index meaning i'm going to move to b now i'll pass in my new bit mask for my group 2 meaning what this is doing now is um over here you just have to learn bit mask i guess i'm not going to go into explaining this right now it's going to take another five minutes but this is what this is doing i'm setting uh the bit in node in the group two side to true meaning it's been connected right so group two is now connected then i have then i pass in um my uh the cost right the cost uh the same the 2d matrix right i got confused with the cost they should really rename this and then i pass in the dp again as well so these arguments are always going to stay the same what is going to change are these two beginning arguments so anytime we've seen these two arguments already we'll just return the previously computed answer and i save the answer and then i return one then again over here if remember as we talked about if i reach the size already right meaning i finished everything and now i'm at i finish all the notes in group one what i'm going to do then is try to connect the nodes in group to anything that's left over so i'm going to go through all the nodes in group two and i'm going to check if that mask hasn't been set yet meaning it hasn't been connected yet if it hasn't been connected yet i'll connect it with the minimum cost edge to connect it to group one that's that oh man i really should start using diagrams it's super hard to explain this without diagrams but anyways then i connect the minimum cost i add them all up and then i return these some costs for that before i do that i save it as we talked about and then i returned that this is that i don't know what i'm saying at this point i really have started using diagrams um and that's the answer i hope you guys enjoyed
|
Minimum Cost to Connect Two Groups of Points
|
minimum-cost-to-connect-two-groups-of-points
|
You are given two groups of points where the first group has `size1` points, the second group has `size2` points, and `size1 >= size2`.
The `cost` of the connection between any two points are given in an `size1 x size2` matrix where `cost[i][j]` is the cost of connecting point `i` of the first group and point `j` of the second group. The groups are connected if **each point in both groups is connected to one or more points in the opposite group**. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group.
Return _the minimum cost it takes to connect the two groups_.
**Example 1:**
**Input:** cost = \[\[15, 96\], \[36, 2\]\]
**Output:** 17
**Explanation**: The optimal way of connecting the groups is:
1--A
2--B
This results in a total cost of 17.
**Example 2:**
**Input:** cost = \[\[1, 3, 5\], \[4, 1, 1\], \[1, 5, 3\]\]
**Output:** 4
**Explanation**: The optimal way of connecting the groups is:
1--A
2--B
2--C
3--A
This results in a total cost of 4.
Note that there are multiple points connected to point 2 in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost.
**Example 3:**
**Input:** cost = \[\[2, 5, 1\], \[3, 4, 7\], \[8, 1, 2\], \[6, 2, 4\], \[3, 8, 8\]\]
**Output:** 10
**Constraints:**
* `size1 == cost.length`
* `size2 == cost[i].length`
* `1 <= size1, size2 <= 12`
* `size1 >= size2`
* `0 <= cost[i][j] <= 100`
| null | null |
Hard
| null |
752 |
hey what's up guys uh this is juan here so today uh today's daily challenge problem uh number 752 open the lock um so you have a lock and with four circular wheels right so each wheel has 10 slots from number zero to nine and the wheels can rotate freely and wrap around so which means that you know if you're like at nine number nine here you know you can either rotate forward or backward so if you rotate forward knight will become to zero right and then you can always rotate backward which will be knife going back to eight right and each move consists of turning one wheel one slot right so one slot means that you know you can oh you can only uh turn it once right i mean basically it turns two to its neighbors from for example from three you can turn into four or two right again from zero you can turn it to one or nine same thing for nine right so the log starts at this four zeros and you're also given like a list of dead ends so that ends means that you know if the lock is at this state right you cannot turn that lock anymore okay so then you're giving like a target representing the values you want to unlock the lock and return the minimum total number of turns required to open the lock right or minus one if it is not possible so yeah for example this one we have a deck we have a few dead ends that which means we cannot i uh we cannot use then target zero to zero two so in this case we need six uh movements right so here's the uh the path right and so here's like in example three here we have minus one because the target is eight but you know since we have this kind of uh the dead end which means so here the data and block all the other path to this eight to this target that's why we have minus one right and here are some constraints okay so this one you know every time you guys see this kind of minimum total number to reach from one state to another right clearly this problem we have a very clear start date and end date right where the start date is the zero four zeroes and end date is a target and then it asks us to find the minimum uh movements right from the start date to the end date and then this is very clearly a bfs problem right and then so we also have this kind of dead end which means that you know those are the conditions we need to use whenever we try to explore the next path right basically if the next code what if the next value is inside the dead end then we cannot go that route right cool so since we know it's a bfs problem you know we can simply just uh start coding the bfs template right and so the start date is like a queue right so for me i use the uh the queue to do the df the bfs algorithm here and we answer equal to zero and we have a scene equals the stat right and then scene dot add zero four zeros right and then we have a while loop right while q equals to this so the bfs template at least for me i always use this kind of for loop or you can also store the uh the step along with the along with this value inside the queue so that you don't have to maintain this one but for me i personally prefer using this for loop here so we have a current right current is going to be a q dot pop left right and then here we're adding that and then here it's at uh answer plus one and then in the end return minus one you know it's always a good habit you know to finish to write the skeleton first you know at later on we can fill in the logic uh when we try to uh explore into the next scenario next of uh for loops right because you know if you start implementing this one here along the way you know you may forget about this answer plus one and even this one even because you know right now you are thinking about this template and your mind is clear enough to not to make any mistake you know but while you're implementing this kind of logic and you have to you'll be start thinking about okay so how can i convert this in string to integer and the integer back to string something like this right if you start doing that you may forget about this kind of answers and then also this return stuff you may also kind of like i may return answer in the end but instead it should return minus one right and right now it's also like good time to check any corner case right so what is the corn the corner case uh we haven't checked yet it's this one is the example four here where the uh where the starting state that there's four zeros it's part of the dead end which means that you know the uh if that's the case you know we can simply return minus one okay but someone said okay what if the target is also zero right and then that would be the answer but you know here the constraints already tells us you know the target will not be in the list of dead ends right so which means that you know this is like a corner case we need to handle here separately because you know as you guys can see we're assuming that the zero is not we can move from here right so which means you know since we will be using this dead end uh regardless you know i'm going to convert this dead end into a dead set right so that we can use one time to compare okay so basically if the zero is in the data set right then we simply return minus one all right so once we have uh written this the skeleton you know we can start implementing the uh the bfs the logic right where is the so current if the current equals to target right then we return the answer okay otherwise we try to find the next uh path right so since based on the description you know we can move we can turn any uh digits either forward or backward so which means the first loop is going to be the range of four right since we have four digits in total and for each so for each digit we can either uh moving forward or back or backwards okay so i'm just using a new one here you know so to move forward we have this right uh new digits no this is one okay it's going to be the one going to be the uh current i right the current i plus one but first we have to convert it into a into an integer so that we can do a plus one right and then we do a modular by 10 right because for nine we need we want zero right and then we have new a new code right so the new code will be current dot i right plus the string of the new digit one right plus current of i plus one right so this is the new code one basically and if the new code one right not in scene and new code 1 not in the data set right then we add it to the queue okay and then scene dot add new code one okay right so that's moving forward and we there's like another one uh i can pretty much copy everything here new code 2 right i know this code is a little bit duplicated so for turning backwards we should do a minus one right so that's going to be the uh the logic but you know if it's from zero if you do a mine minus one will become minus one divided by ten by uh modulus by 210 modular 10. so in all the other languages this one will give you -1 give you -1 give you -1 so which means we should do a 10 we do a plus ten and then do a minus one right you know but the funny thing is that you know in python this one will give you nine instead of minus one i think that's the difference between the python and other languages because in python if you do a modular you know it will always give you the values that have the hat that have the same sign with this modular but anyway so if you're writing in c plus or java you know you need to do a plus 10 here cool and i believe that's it right so we have two scenarios here right either uh turn forward or turn backward okay so let's try to run the code here okay accept it right cool so it passed right i mean it's just a classic bfs solution so for the to the time complexity for the bfs you know um for the while loop here right we have so the total state we have here is what we have what 4 to the power of 10 right because we have four digits each digit has like 10 possible states so in total we have this kind of state right for yeah 4 to the power of 10. and for each state we have uh so we have a for loop here right so we have four and then inside here we need to do a like oh sorry my mistake so here the first one should be uh should be 10 to the power of four right because we total we have from zero to nine right num uh codes that's why we have 10 to the power of four right and then here for each of this the code here we have um so we have a four here right and then to loop through each state each digit and for each digits we have we need to do some concatenation here right so that's why we have 4 to the power of 2 right because we have 4 and 4 here and yeah that's it right i mean so that's the time complexity oh and plus this one uh indeed at the beginning so basically this is the what this is the so we have what 500 right 500 times 4 right that's 500 times 4. to put everything into the that set yeah so that's the time complexity here right yeah and space complexity we have this kind of dead set right so this is the one of the space we need to use which is the 500 times four and for the others we have this q right or the same set so here we have yes so this one is the space complexity will be dominated by the 10 to the power of four times four right so this one is gone yeah so that's the space complexity uh yeah i think that's it right for this problem it's very uh it's a very classic bfs uh problem and thank you for watching this video guys then stay tuned see you guys soon bye
|
Open the Lock
|
ip-to-cidr
|
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: `'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'`. The wheels can rotate freely and wrap around: for example we can turn `'9'` to be `'0'`, or `'0'` to be `'9'`. Each move consists of turning one wheel one slot.
The lock initially starts at `'0000'`, a string representing the state of the 4 wheels.
You are given a list of `deadends` dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.
Given a `target` representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.
**Example 1:**
**Input:** deadends = \[ "0201 ", "0101 ", "0102 ", "1212 ", "2002 "\], target = "0202 "
**Output:** 6
**Explanation:**
A sequence of valid moves would be "0000 " -> "1000 " -> "1100 " -> "1200 " -> "1201 " -> "1202 " -> "0202 ".
Note that a sequence like "0000 " -> "0001 " -> "0002 " -> "0102 " -> "0202 " would be invalid,
because the wheels of the lock become stuck after the display becomes the dead end "0102 ".
**Example 2:**
**Input:** deadends = \[ "8888 "\], target = "0009 "
**Output:** 1
**Explanation:** We can turn the last wheel in reverse to move from "0000 " -> "0009 ".
**Example 3:**
**Input:** deadends = \[ "8887 ", "8889 ", "8878 ", "8898 ", "8788 ", "8988 ", "7888 ", "9888 "\], target = "8888 "
**Output:** -1
**Explanation:** We cannot reach the target without getting stuck.
**Constraints:**
* `1 <= deadends.length <= 500`
* `deadends[i].length == 4`
* `target.length == 4`
* target **will not be** in the list `deadends`.
* `target` and `deadends[i]` consist of digits only.
|
Convert the ip addresses to and from (long) integers. You want to know what is the most addresses you can put in this block starting from the "start" ip, up to n. It is the smallest between the lowest bit of start and the highest bit of n. Then, repeat this process with a new start and n.
|
String,Bit Manipulation
|
Medium
|
93,468
|
576 |
hey what's up guys this is chung here so today uh number 576 out of boundary path okay so there is like uh m by n to the grid with the ball and the ball is initially at the position start at the column and start row and start column you're allowed to move the bar in four directions right and then you can only move at most at this maximum of moves right and you need to calculate count the number of paths basically the number of ways that you can move the bar out of the grid boundaries and then do a modular by this big number like for example we have this two by two grid and the bar starts at zero right and then the max the total move we can make is two and for this one we have six different paths right that the ball can move out of the boundaries right so one two three four five six within uh max move equals to two right you don't have to use all the moves but you cannot use more than this maximum that's why we have six right and then here's another example right we have a bar like this right and the answer is 12 basically right and here are some constraints right 50. okay so i mean for this kind of counting problem right so percent of time ninety-nine percent of time ninety-nine percent of time ninety-nine percent of times you it's either like a math problem or a dp problem right i think during an interview i think it's gonna be more like a dp problem right because at this one for this one you know if we have like uh a grade here right so what does a dp problem mean right basically you know obviously you know there are like a lot many paths right that can lead to the same location for example this is the start right let's say this end right there are like many paths we can end up with this business location please and go here uh go here right or even go here right there a lot of ways that you can end up to this place and if we just brutal force out of path that will be too much you know that's why you know we can use the dp with some states to uniquely identify a current status right so obviously we have what we have i inj that's part of the two status we need right and the next one is what is the moves right so which means given like the current state and the number of moves we have here you know for example if this one right so here we have one two three four so and here one uh basically this two pass this two paths will lead to the same state because the i and j are the same and the uh the moves are the remaining moves should be should also be the same right so what this dp means it means that you know if i'm standing at i and j and i have this many of moves left okay and then the total number of paths from the state to the to move out of the boundaries is fixed right so this means that as you guys can see so the first time if we follow this path right and we reach here right and then we have like a state here so there's a state here and then and we calculate that right we calculate that and then we move it here we moved out somewhere right after moving out we know okay given this state we have let's say we have 10 pass right starting from here that can move uh out of the boundaries right and then the next time right when that's starting from here when this has follow uh follow a different path right and reach this state the state that has three status no we know okay we don't know okay we have already calculated this state before so that's why we don't have to recalculate it right so obvious right that's why we can use this kind of three uh dimensional state right to uniquely identify state because again given the coordinate and the remaining moves the number of paths to move out of the boundaries it's fixed okay that's why we can use dp to solve this problem okay and for this problem you know i think a top-down dp think a top-down dp think a top-down dp is more intuitive okay yeah and then let's start doing the let's start coding that so the coding is pretty straightforward actually so you know since we're doing the top down dp we have i and j now i have moves right this is the remaining moves basically and i just use this ru cache to help me do the memorization so that i have so that i don't have to write it my own right so the base case obviously the base case is whenever the coordinates is out of the boundary then we stop okay where j is smaller than zero or i either greater than m or j is either greater uh equal greater than n right so if that's it's out of boundary then we return one because return one means that okay we have find a path okay that can lead us to out of the boundary okay and we have some like invalid case right basically if the moves is equal to zero right then we return zero it means that you know if the move is zero and uh we're still in we're still inside the grade and then it means okay so this is not a valid path right that's why we need to return zero otherwise answer is equal to zero and then we have directions okay this two okay and for direction in directions so new i equals to i plus d0 right so this kind of template psi j plus d1 right so now we don't want to check the boundaries right because with our purpose for this problem is to move out of the boundaries so we should never check at that boundary we simply do a dpf new i new j and then move minus one right then we return the answer so that's how we accumulate the answer into four directions i will never this path can this one can lead to a can lead to this outer boundaries it will return one right that's how we accumulate that so that's it right so and we have a modular here plus seven okay and then let's do a dp of start row right we start from here start column and the max move right the wood two modular in the end and that's it yeah so it's passed and yeah so the time complexity uh is what is the uh the number of state multiplied by the spent the time spent for each dp here so the state we have what we have uh there are like all 50 right so it's going to be a 50 cube right so because here is like four right that's why 50 cube and there you go right so i mean a very classic dp problem right you just need to define like find like state that can identify the current status right in our in this case it's the coordinate plus the remaining moves right and then some base case and then the top down dp yeah i guess that's it for this one thank you for watching this video guys and stay tuned see you guys soon bye
|
Out of Boundary Paths
|
out-of-boundary-paths
|
There is an `m x n` grid with a ball. The ball is initially at the position `[startRow, startColumn]`. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply **at most** `maxMove` moves to the ball.
Given the five integers `m`, `n`, `maxMove`, `startRow`, `startColumn`, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0
**Output:** 6
**Example 2:**
**Input:** m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1
**Output:** 12
**Constraints:**
* `1 <= m, n <= 50`
* `0 <= maxMove <= 50`
* `0 <= startRow < m`
* `0 <= startColumn < n`
|
Is traversing every path feasible? There are many possible paths for a small matrix. Try to optimize it. Can we use some space to store the number of paths and update them after every move? One obvious thing: the ball will go out of the boundary only by crossing it. Also, there is only one possible way the ball can go out of the boundary from the boundary cell except for corner cells. From the corner cell, the ball can go out in two different ways.
Can you use this thing to solve the problem?
|
Dynamic Programming
|
Medium
|
688,2239
|
387 |
hello guys welcome back to take those and in this video we will see how to find the first non-repeating character find the first non-repeating character find the first non-repeating character in a stream of characters so let us look at the problem statement let us assume that we are given a stream of characters that is first we will see this first character now we have this first character as our only string now what would be the first non repeating character from the left-hand side in character from the left-hand side in character from the left-hand side in this case it will be a now when this second character comes in then your string becomes a B in this case the first non repeating character from the left hand side is a itself so you will just print here a now when C comes in then your entire string becomes ABC and the first non repeating character from the left hand side is a when this becomes in then your string becomes ABC B and the first non repeating character from the left hand side is still a and you can see here that B has been repeated here now when another becomes in still only B is repeated and this a is the leftmost non repeating character so this will get printed now when a comes in then you can see that a is repeated and B has also been repeated so the first character from the left hand side which has not been repeated is C so we will print here C now when we encounter the next character then it is C itself now every character has now been repeated so when there is no character which has not repeated then we will just print minus 1 so I hope you are able to understand it we are actually taking from the left hand side to the right hand side and this is an online algorithm this is a stream of characters this is not a string okay so in this case I will assume that our alphabet size will be 26 this means that we will see characters from only A to Z and this is all small characters so I hope you understand this alphabet size now a very intuitive way to solve this problem is to maintain a list and in this list we will maintain the list of all the non repeating characters from the left hand side and we will maintain it in order so suppose we saw this a first then we will just maintain here a as a non repeating character we saw B here we will maintain B we saw C here we will push C now again we saw be here then we will search it in our linked list and then we will delete this B since it has been repeated now we again see a B and so we will search it in our linked list now there is no way to find whether this B was repeated or not so in order to keep track of what the elements have repeated we can take a hash so we can take a repeated array or a repeated hash which will be of the size of alphabet size which will be 0 1 to 225 and this will be initially initialized to false all values because we have not seen any character and as soon as a character repeats that is occur for two or more times then we will just make it true and so we can just look at this character and see whether it was repeated earlier so in this case B will be repeated and so it will be true so in this way we can keep track of all the repeated characters now one thing to note here is if an element is not repeated like if the character has occurred for the second time then in the repeated value it will have false and so we will have to source this linked list linearly for this B whether it had occurred for one time or not so this is a linear search and so it will take order of n time but how can we optimize it actually this searching can be optimized if we can just use a hash so that this hash will be storing the addresses of this entered nodes so what will be the size of this hash actually the size of this hash will be equals to alphabet size which will be from 0 to 25 so this will be storing the address of these values so this will be storing the address of the first node a this will be storing the address of this B this 2 will be storing the address of see now this hash can perform as a lookup table and we can just see this hash and make out whether this element had occurred once or not okay so using this hash and repeated array we can just optimize it and each of the queries can just take order of one time because we can check using the random SS in an array and since these both are hash so we can check in just oh one time so let us now solve a example in order to get a better understanding you can see that we have used to hash that is two arrays one it will be storing the address of the nodes in a doubly linked list and another one will be storing whether a given value is repeated or not then first we will see this first character in a stream this is a stream so we will see one character at a time now since we have seen a we will check in this repeated array this is not repeated so when this is not repeated then we will check this address array you can see that ace value will be 0 and how will we calculate it actually whatever the value is let's say the value is current the current character is current and then we will just subtract the base value of the alphabet which is a and then if this current value is a then a minus a will give us the zero value if this current value is Z then Z minus a will give us 25 so this is how we calculate the values now once we have calculated this a will denote 0 so repeated at 0 is false and also address is 0 is pointing to null because initially these all will be null pointers it is not repeated and it has never occurred so this repeated will actually be showing whether it has occurred for greater than equals to 2 times and this address will be showing whether it has occurred for once ok so both these are false and null so we will just insert it in our doubly linked list so a will get inserted and let's say it's address is something X 0 and this will be the head because you will be having a doubly linked list head as well as a tail pointer so head and tail will be pointing to the same location this repeated will still be false but then this address will now contain X naught value okay so from null it will be converted to X naught now this is pointing to this first character a now we will move on to the next character which is B now this B has never been repeated since it is false and since the add value is null this indicates that it has not occurred for at least one time so this is the first time we are saying so whenever we see a node for the first time we will make a new node okay and then we will update this tail value it will be having some address let's say it's X 1 then this address value will be pointing to X 1 now so this is pointing here okay and this will be done and this falls under this third case when the elements are not repeated and they have not occurred for any number of time that is they are occurring for only the first time now what will be the first non repeating character actually the first non repeating character will always be pointed by our head because we are storing in chronological order so head will always be pointing to the first non repeating character from left hand side if the head is null then in that case we will print minus 1 this indicates that there is no character in the stream presently which is not being repeated now we will move to see now you can see that C is also occurring for the first time since this value is false and also the address is null so we will make a new node see we will assign an address to it will have an Associated address now this will be pointing to this so null will be updated to x2 now what will be the first non repeating character it will be head so it will be a itself now we will add here B okay this is the next value so I hope you are understanding this will be a doubly linked list I am NOT making the errors actually so when you see this B then you go to the repeated value it is still false now you go to the address value you can see that it is already pointing to some address x1 since it is false so it has not occurred for 2 times 2 or more times and since this address value is pointing to some address this indicates that there is at least one occurrence of this value since you are seeing the same value here that means we are repeating the value so this falls under this case 2 so when you are repeating the values then this false will become true so this B value repeated value will become true and then we will have to remove this in from our doubly-linked list so this B in from our doubly-linked list so this B in from our doubly-linked list so this B will get removed so this will get removed and now our doubly linked list only contains a and C and from our hash value this will also be updated to null value okay now we move on to the next character which is B itself this B will be checked in or repeated array and you can see that this value is true so this falls under the first case if that current character is already repeated then we won't do anything so we move on to the next element and by the way for this character our head value is already pointing to a so the first non repeating character will be a itself now you have encountered a so we will move on to the repeated it's false we move on to the address it is not null it is pointing to X naught so this indicates that a has already occurred one time so this is occurring for the second time so we will make the repeated as true and then we will remove it from our doubly linked list so this X naught will now become null and this a will be removed and this head will now be pointing to C and tail will also be wanting to see now for this case the first non repeating character will be C itself now we move on to the next character C so for C we have value false and the address for C is not null it is pointing to X 2 this means that C has occurred for at least one time already and so we will make the repeated value as true because this is occurring for the second time and now we will remove it from our doubly linked list so our linked list is now empty and head will now be pointing to null so in this case when we are at this C then our first non repeating character will print the value minus 1 because there is no character in the string which has not been repeated so this is the entire problem of finding the first non repeating character in a given stream of characters I hope this pseudocode is pretty simple to understand it is self-explanatory the to understand it is self-explanatory the to understand it is self-explanatory the time complexity for each query is just 1 because looking this address hash and repeated hash is a random access and it takes only order of one time so for n number of queries that is the string length the stream length of n we will have au n time so the total time is o n I hope I was able to make you understand this problem if you have any type of doubt then feel free to comment below and I will try to help you as soon as possible like and share our video and subscribe to our channel in order to watch more of this programming video see you know next photo thank you
|
First Unique Character in a String
|
first-unique-character-in-a-string
|
Given a string `s`, _find the first non-repeating character in it and return its index_. If it does not exist, return `-1`.
**Example 1:**
**Input:** s = "leetcode"
**Output:** 0
**Example 2:**
**Input:** s = "loveleetcode"
**Output:** 2
**Example 3:**
**Input:** s = "aabb"
**Output:** -1
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of only lowercase English letters.
| null |
Hash Table,String,Queue,Counting
|
Easy
|
451
|
104 |
hello everyone welcome back and today we are looking at question 104 which is maximum depth of a binary tree so we are given the root of a binary tree and want to return the maximum depth of that tree now they are saying that the maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node so let's look at example one we see we have this boiner tree and the root is three and now we see that the longest path from the root to a leaf node is from 3 to 7 or from 3 to 15. this path has three nodes and this path has also three nodes so we know that the maximum depth of this tree is three and we see that the output is three okay now how can we do this let's go to the blackboard and explain how can we tackle this okay here we are in the blackboard and since we have a three right we will be using recursion is one of the best ways to tackle three problems but before we go into the recursion itself let me give you an analogy that would make things much easier let's imagine we are in a cinema room and this cinema room has four rows of seats here is the first row second row third row and fourth roll and of course we have a screen that is you know showing a movie so we have a screen now let's imagine that you were the person watching this video you are sitting right here and now you want to know which row you're sitting in are we sitting in the fifth row sixth row we don't know we want to know okay so how can we do this well we can ask the person in front of us hey which row you're sitting in and that person will say i don't know let me ask the person in front of me right and this person asked okay and now the next person say i also don't know withdrawal man so let me ask the person in front of me so this person asks and finally we reach this person who is saying hey the screen is in front of me so i must be in the first row so i am in the first row so this person says hey i am in the first row now this person is saying if you are in the first row then i must be in the second row since i am one row higher than you so this person is saying i am in the second row right now this person is saying see if you are in the second row then i must be in the third row and now you're the person who's watching this video you'll be saying okay if this person is in the third row then i am in the fourth row since i am one row higher than this person now it's important to note that we kept asking the person in front of us until we reached a certain point and that point was hey we see the screen in front of us right at this point we stop and we knew we are in the first row so in this case in this cinema room setting we know that this is the base case when we can see the screen now we will do something similar to this but with trees okay so let's go and have a look on that here we have this binary tree the same one as the example that we just saw in lead code now before we go before we dive into this stream i want to ask you a question okay since we're using recursion we need the base case in the case of a cinema room we know that the base case was when we will see the screen right okay but what is the base case in uh you know in this binary tree let me ask you this if we have an empty tree right and tree that has nothing absolutely nothing it's an empty tree what is the depth of an mt3 well we know that the depth of an empty tree is always zero so this must be the base case we can say okay we will keep going until we see a node that is null and at that point the depth is zero so this will be the base case of our recursion okay now what if i tell you if we have a leaf node now what is a leaf node it's a node that has no children something like this 9 and 15 and the seven as you can see the children of these nodes are null which means they have no children imagine if we have a leaf node what is the depth of this leaf node same idea as here we go ask the person in front of us this node will ask its children but this node has no children it has nothing it has none right so now we have a left subtree and the right sub tree remember in recursion we make sub problems we have this big tree i know it's consisting of only one node but the concept is the same we have this tree and we want to dive into its left children and right children we are diving into its left subtree and right subtree but we notice that the left subtree is an empty tree and we said that the depth of an empty tree is zero and we have this right subtree which is also empty and we said that the depth of an empty tree is also zero now this node says that both of its children are at depth zero so this node is saying hey if my children are on depth zero i must be in depth one okay so a leaf node has a depth one now let's go to this tree and see what how can we tackle this well of course we will start at the root of the tree what is the depth of this tree from this root well we don't know we need to ask our children this 3 will ask the 9 and the 20. this 3 will ask the left subtree and it will ask the right subtree right we are making sub problems let's dive into the left subtree we see that we have a leaf node and we said that the depth of a leaf node is one okay good now let's go to the right subtree we see that we have 20 15 7 okay but when we go to this 20 is the root of this smaller sub 3 consisting of only 20 15 and 7 so we can make another subtree right here where 20 is the root of this smaller subtree right so we go to this 20 hey 20 what is the depth of you know which depth are you on and this 20 say i don't know let me ask my children so this 20 asked the 15 this 20 asked the 7. now this 15 is a leaf node so we know that the depth is 1. this 7 is a leaf node we know that the depth is 1. this 20 is saying if both of my children are on depth one then i am one level higher than them so i must be in level one plus one which is two and now this three is saying hey one of my children is in depth one but my other child is on depth two so on which depth am i since the question is asking for the maximum depth we need to take the maximum between the height of the left subtree and the height of the right subtree then of course we add one since we will always be one level higher than our child okay we know that the left is one the height of the left sub tree is one the height of the this big green um right sub tree is two the maximum is two and two plus one is three so this node is on depth three and again the highest depth of this three is three here is depth right here is the second one and here is the third one now let's go to lead code so we said we need to take care of the base case so we set the base case once we see a null node right and of course we are starting at the root so we will say hey if the root of the tree is null then we will return zero why because we said that the depth of an empty tree is zero so we return zero and this is the base case of our recursion okay now we said we need to calculate the depth of the left subtree and the depth of the right subtree but of course we have trees so we have sub trees inside of subtrees etc so we will be using recursion so we can say that we will store the height of the left subtree in this variable and we will say okay what is the height of the left subtree we can keep calling this max depth method recursively until we hit the leaf node since its children is null we will be hitting this base case and we will be returning zeros um for the you know null node because we don't have any children for the leaf node and we can come back to the root and we can tell the root hey the depth of this left tree is the following okay so we can say the in left equals max depth which is the name of our method and we can give we can go to the root and we want to know the depth of the left subtree so we can say hey root dot left we will be calling this again this method recursively until we hit the base case and we will do the same thing for the right subtree so end right equals max depth of fruit dot right at this point we know the depth of the left subtree and the depth of the right subtree and of course we know that this three is one level above them and we said we want the maximum depth so we want to know what is the maximum between the left and the right and add one to that you know the depth of this three so we want to return the maximum math.max math.max math.max between the left and the right and of course we said we need to add one because we are always one level higher than our children and that should be it let's run the code and let's submit as you can see faster than 100 so let's look at the time and space complexity starting with the time complexity we saw that we went through all the nodes of the tree assuming that our tree has n nodes the time complexity would be big o of n now the space complexity would be the height of the tree in the worst case our tree will have n nodes like this we will have the root and we will keep getting you know let's say right child all the way so we will have n of those and the height would be in the worst case big o of n now if the tree is balanced right if the tree is a balanced tree for instance like this space complex would be big all of log and thank you guys for watching i hope you guys enjoyed the video best of luck to you and i will see you in the next one
|
Maximum Depth of Binary Tree
|
maximum-depth-of-binary-tree
|
Given the `root` of a binary tree, return _its maximum depth_.
A binary tree's **maximum depth** is the number of nodes along the longest path from the root node down to the farthest leaf node.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** 3
**Example 2:**
**Input:** root = \[1,null,2\]
**Output:** 2
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `-100 <= Node.val <= 100`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
110,111,774,1492
|
35 |
foreign approach so if you remember we covered up to 28 problem today we're gonna go to the next one which is 35th so this is the problem statement says like it says search insert position given an assorted array of distinct integers and a Target value return the index if the target is found not return the index where it would be if it were inserted in the order so you must write an algorithm with the order of login runtime complexity so here you can see one three five six expected Target values of 5. the 5 is available at second index position can find that directly and you can return it the second approach I mean the second example numps one three five six when the target is 2. so if You observe the two values not available in this numbers so you need to find so where exactly is number two can be fit into this position so that here it's like if you see the 2 has to be fit between 1 and 3 which means zeroth index is one and two has to be here at position one that one two three five six in example three nums one three five six seven it says like a Target seven you can say you can see that the largest value is a six so the next element will be 7 which is nothing but 0 1 2 3 and the fourth position has to be refilled with seven so the output index value is 4. well so if your interviewer asks you to write an algorithm with the order of login and if you see that I mean if you understand the pattern it is nothing but it is a search pattern and the data is sorted in your mind you always have to get an idea which is nothing but find a researcher so if the data is assorted and you have to find algorithm within login then always have to go to binary search Google so okay so if we ask this question there's a two pro Solutions I mean currently in my mind it's spiking two solutions one with order of n which is a straightforward order of an approach so you pretty much aware of that so you will search each index I mean each value which is a less than number uh sorry Which is less than our Target if it is equals to Target then return it so what we are doing here is like we keep on compare each numbers with our Target if the target is found we will return if any number which is a greater than Target then that is the position we have to fill if we reach the length of end of the numbers then we have to return n plus 1 is the position of the direct so if we write the three possible solutions here I mean if we try to start writing three possible solutions we onset okay so let's write our first approach which is order of end time complexity algorithm where what we will do here is we will write f for Loop foreign element will keep on continue if I mean total 2 here is will compare each index position and if we find anywhere if index position is greater than our Target okay so that's the position which we need to put that so we'll keep it that in result equals to -1 initially equals to -1 initially equals to -1 initially so result or the insert position we can put a name in connection like this partition as a minus one so when we are reading keep on reading it if number of index which means in this example you can see first we will compare with the one is greater than two no we'll go to the next one 3 is greater than 2 that's the correct one so we have to end our Loop there and we return that value so that's what our index I mean integer position which we take and then we return it uh or else otherwise we can do another approach what we can do here is so let's put this number here okay index position in set position where we will initialize with the zero let's write a while loop while insert position is less than number of length okay so in the loop we always keep on increase our insert position when we are trying to search here if number of insert I mean in the array the insert position which is that index position is that greater than Target we just need to set a Boolean flag let's take Boolean flag is insert position found okay so let's put it initially it's a false so I will put the condition here with it okay so when we get this one we'll keep it that in set position as a true okay but observe here in the second case 3 is greater than 2 so we'll get that insert position as a true and we but we are not breaking that row we keep continue that Loop so that insert position five again five I mean the third element if this is also greater than two and our insert Position will be true but our insert position index which is keep on increasing it so we need to break it so we're gonna put a condition here if I don't find insert position then continue if I find an interest uh sorry one second yeah if I find an insert position then you don't need to continue I mean you don't need to look to further level just return that in inset position as a return value that's it subset here again this will break one case I will come to that one where exactly it will fail but let's see that so what we are trying to do here so here in this case if you see one we are comparing it three we are comparing it uh sorry 1 is greater than five no so we just increase that count then now we will go to 3 is greater than 5 no then it will go to 5 is greater than 5 no that will go to 6 so our condition has to go greater than or equals to so when we compare let's iterate one more time one is greater than 5 No 3 is greater than 5 no 5 is greater than a request of 5 yes true then we are keeping that flag is insert position found is it true okay so when we set that true and negation of true is a false we break this Loop and we return that in set position so let's see the second example one three five six so again we'll compare one with two one is less than or equals to two uh sorry one greater than I requested two it's a false so insert position goes to the next one three greater than or equal to True yes so we found that insert position which is nothing but inside position value we return it so let's see that the last Edge case when the target is greater than the largest value so if you see again we started zeroth index position so 1 greater than or equal to 7 no 3 greater than a equals to seven no five greater than or equal to seven no six greater than or equals to 7 no but if you observe the first condition where insert position less than numbers of length this condition is a false so our while loop break it because they we are keep on increasing that insert position so we reached end of that array so that's why it break there so I will give you get that result as in set position let's run the code and see the result um something is wrong oh it's a Boolean sorry I used C plus and C syntax which is a pool whereas in Java you have to use a Boolean hmm let's see one three five six so zeroth position oh see we are even though if we find this condition we'll keep on increasing that so what we can do if it is let's put it this string in a else condition okay so because you keep on increasing uh anticiple I mean insert position when our data is not found if the data is found that is the position where we need to return okay let's run the code and submit it let's see cool you solve the problem but if You observe this is using the time complexity of order of n but if you object here the interviewer asked especially write an algorithm with order of login as I mentioned previously if the data is sorted and we are doing the search operation and you want to find the result in order of log n then you have to use binary search algorithm so if you are not familiar with the binary search algorithm is a pretty straightforward approach so in a simple case what is a bind research algorithm very simple so if you have like let us assume rather than going with the numbers let's go with a small or let's go with the numbers so assume you have the numbers of like 1 3 5 6 and maybe seven so the binary search will tell you that you don't need to go one by one elements go which middle element and try to compare that middle element so let us assume here we wanted to find 3 okay so if you want to find a 3 so if you give this problem to a small kid what he will do he will go okay we'll check okay one and then he will check three okay I got the three here so he will tell like okay three is available at index position one right so let's put it in index positions here 0 1 2 3 and 4. so now but if you do like a little bit uh I mean like if a 10 years kid so if he gets like a little bit Advanced then he will think like okay why do I need to go search one by one so let us assume we wanted to find 7 here Target is a seven so if it used to seven the kid I mean the kid usually goes like a one three five six seven okay iPhone 7 here like this right so but what does the binary search will tell as it indicates by means like a make your array off and compare so what you need to do you know that this um I mean this array is a sorted order which means your data will be in increasing pattern which is like this right so it's gonna be go in a increasing pattern format so you know that every I plus 1 I mean every I plus 1 value which is always less than 8 plus 2. remember this uh sorry every so every I minus 1 value is less than I because this is the pattern of increasing order right so binary search will tell you find the middle element first check if the middle element is equals to your target return it if a t is not then compare your middle element I mean so if it is not use middle element to identify whether you have to search either first off or second off got it so first check this middle element based on this middle element if it is Middle element is equals to your target value return it if it is not go either of the direction now you can go to either of the direction very simple if your target value I mean your target value is less than your middle value okay then you have to go to this direction right if your target value is a greater than mid value means like let's assume Target is 7 here 7 is greater than 5 so you know that 7 is always existing the right side Direction so you have to go to this direction that's it so we have to use this binary algorithm to find corresponding index position so now you can say that okay binary search algorithm basically we will use to find given element right how do I know that where if the element is not exist and where exactly I can find that corresponding position If You observe here so let us assume uh okay so let's write algorithm I will tell you like what is the A7 I mean one scenario which will gives you more understanding very simple let me tell you this so we'll do that two pointers okay I mean in the complete array will binary search algorithm we take a two pointers one pointer gives like initial position second point it gives like a final position then we will find that middle element and all this operation so let's do that binary operation so when the left pointer crosses the right pointer that is exactly the position where you will get your I mean your the corresponding index position so usually here for the two your left pointer and right pointer crosses at here like that so what we'll do we'll write a simple algorithm order of login approach okay so I'm gonna put I'm gonna comment this code for your understanding purpose now what we'll do we'll write a very simple problem here I'm gonna take in start position okay where it is 0 initially in end position where I'm gonna take nums Dot length or length minus one or yeah either of them you can take so let's I will put a while start is less than equals to end okay I'm gonna make it until they both cross so I'm gonna find into midi equals to my start plus and by 2 and remember this is not the proper way here there is a chance of integer out of bound exception sorry integer auto point exception can occur so you have to use a another format so we'll discuss that later but let's go to this one now if dumps of mid okay if nums are made equals to our Target we'll just return that return mid position that is the where your target is there if it is not okay here comes to our logical pattern where we need to go to which direction whether you have to go to left side direction or right side Direction you'll find here if nums of mid let's use the same pattern okay if the target so which is a target value if our Target is less than our numbers of mid okay then we have to search this pattern right like the first array so if You observe here the start is zero it is always there for the end pointer you have to make your bit minus one so what you need to do here is to make end equals to bit minus 1. else if it is not that case you have to make start pointer because you had to go to the right set pointer right like I mean you have to go to this direction so your start equals to Mid Plus 1. the condition where these two sections will cross that is the where I mean if the number is not available and they both cross it exactly the position where I mean like here in this case two so the start pointer and pointer coupon comes here they will cross here so that is the position where the target is there so let's try I mean I used let's see that what is the expected result so we found this number let's try the second one where the same one with two that's on the core observe the result cool let's try the third case seven so this is what the code we are using order of login rather than keep on searching in a while loop so let's run this code submit it my battery got drained I'm in my laptop getting trained see cool your results also accept it but now this time it is order of login Thank You For Today class I will take another session on next Thursday
|
Search Insert Position
|
search-insert-position
|
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[1,3,5,6\], target = 5
**Output:** 2
**Example 2:**
**Input:** nums = \[1,3,5,6\], target = 2
**Output:** 1
**Example 3:**
**Input:** nums = \[1,3,5,6\], target = 7
**Output:** 4
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `nums` contains **distinct** values sorted in **ascending** order.
* `-104 <= target <= 104`
| null |
Array,Binary Search
|
Easy
|
278
|
57 |
Hello hi gas welcome back tu de 7 of DSL practice and which is our question today insert interval now this question is not at all as simple as it seemed to me and there are two approaches to it, I will tell you the second approach I thought very much. Date it what it expected so look here what is the question saying you are given and are off non overlapping interval right so here I have this one Iraq given is off non overlapping interval something like this one interval became Tu four second interval becomes 729 so there is no overlap means there is no overlap in this way, okay and start and end is given to us and end it is sorted in increasing order by start value so here if you see this In sorted values we have buy start this In sorted values we have buy start this In sorted values we have buy start value and here we are given another input new interval right so we are given another interval insert new interval in d interval are true date interval are this steel shot it and there should not be other overlapping So we have been given another new interval 3 6 so from 3 we have another interval six so what we have to do is we have to insert this new interval inside this our output of true date has come in such a way that it is also overlapping. Should not be there and should also be sorted so here now we had 1 to 4 and new sex so here now overlapapore right this is overlapping right in the middle of this so this part is overlapping so pepper it Given van three so in between it became four and this is its end what happened six so van six then became one and 729 so this 729 became one so this is its output 126 729 gas so you go d question what was the question So the first solution I did was bigo off and using likeless, let me tell you how I did it, what I had given, one, four, seven, 9 and new interval, this is what I had, interval and new interval. 3 6 So what I did is I have created a linked list here because I want to see at the end what the answer is. Okay, so what I am doing now is iterate. I am fine from here to here, fine on the interval and I am first checking whether this is my new interval, its start is less than the start of the input where I am now or not. It means who has to be raised, who is less, okay, this is added to my link list, in the beginning, whatever is the last value that I have, now I will try to pepper it, now how am I merging, I will check. This is the one that is free, this is the one that is 3, is it smaller than this, if Han is correct then it means merging will happen, if not then it means that A goes behind it. For example, if 6 is smaller than 54, no, five is greater than four. So directly 56 goes here, okay, behind this is the link list, but what is the rule of five now, we have 3, okay, so is 3 smaller than 4, Han is smaller, meaning there will be merging and how am I doing it in my will by changing it? I am going to change this value, how is the max of this four or six, which match is it, then I will change this and do sex. Okay, so here I am doing this, so you see here, I have made a link list. If it is zero, then I have directly added the new interval, meaning if the interval is this one, then how is this my interval and this is my new interval and if the new interval is empty then it is empty, then I have added it is okay inside my output, so now here. Either the new interval that I have can be in this way also, okay, or the new interval can be further, it can be anywhere beyond this, okay, or it can also be somewhere in between. Or there can be a in the last, there can be a right anywhere, and in this way also there can be a cross, so anything can happen, so here now I have put a for loop where I am treating all the intervals. Okay, I am attracting on the interval, now what I am checking here is that if the interview has been done till now, if the interview has been done, if I have done this interval, then I just have to keep putting these in the already sorted. Okay, so I am going to insert here, okay, inside my output, whether margin is needed or not, based on the 10 logic which I told you, what is the logic, if I do not have a link list, then just add it if it is. Which is the last element of the link list because it is in sorted so let's go here for example 37 and the new value that I have is, so that means the new value that we have is the start of it. Bad list means just add it directly behind it, otherwise this is the start but the end will change, this is the end and in which way the max will come, either this or this, which of these two is max. Max is okay, so this was my method of insert. Okay, now here if I have done the new interval and I still have the list intervals left, then I am just going to insert them directly. Okay, otherwise if Let's go to the interval of I man right now I was here my index was on this side if this and I'm comparing the new interval because I haven't done that yet I if it's small for example it's small if it's here for Example 2 Common for example so if it is small then I will send it right on insert so this is what I am checking here if my new interval is smaller than the new interval then for whom am I sending the insert I am sending the interval to this one but if this The new interval is small, mine is small, so whom am I sending to insert the new interval and then after that I am sending this interval, first I got this inserted, then I will get this inserted, I am okay, so this one. Using link list was very simple in terms of time complexity but I was having a gut feeling that the interviewer would ask that it can be done through binary search and why because it is said in the question that it is sorted in increasing order and I know this thing that whenever a list is sorted and I have to insert something in the middle or find something, then binary search is done to it and even if you go through the linked list. Will you tell me and if it is fine from time complexity, then only binary search is good for enterprises right because it is in their mind set, so see, I tell the circle, I have solved this interval is in sorted order for us, okay and now this is our for. Example is new interval okay so what we have to do in binary search is find d first and you can say date start interval where it intersect or conflict start overlapping which is the last overlap of this is my last bigo off People, let's have more list for example, it's okay, we have more values, here we have more values, so now I have the overlap index of start and last, so now what will be my output, what will I have in the output? If you have to do it directly, then first let's go for example index one, index two, index three, then the values of these have to be added, three, then the values of these have to be added, three, then the values of these have to be added, index 1, index 2, index 3, okay, what will come out here, minimum of 10, minimum of this. And the maximum of this has to be found out, it is okay, then this one will become a new interval, whatever minimum and max will come, this new interval will be formed and all the subsequent ones after this last one are okay, if we have found out the start and last, then we will have to once We have to traverse and till here we will add all the intervals from the first till the start, then where this first interval was happening in the start and the last, in this way we will generate a new internal interval from i to max and right from the last. Then from Plus Van, we will add all the numbers back to our output, so this thing is make it big go off, so this solution is also bigo, such thoughts, same set of thoughts will be used but it is in the mind of the interviewer, isn't it? Nayi Mandli Search Hai Log And Hoga To De Meet Convince With This Solution Ok So I Have To Implement This Solution But Due To Time Complexity So I Don't Have A Gut Feeling That It Is Okay Due To Time Complexity So This Is Also Acceptable But Steel I feel that the interview may get stuck on binary search but this is the approach which I feel will do it but I have implemented it so can you implement it and comment once? Gas ok so this is mine. Practice is to implement binary search. I hope you gas now also donate and please gas you can paste the solution in the comments. It is a very good question. Ok thank you.
|
Insert Interval
|
insert-interval
|
You are given an array of non-overlapping intervals `intervals` where `intervals[i] = [starti, endi]` represent the start and the end of the `ith` interval and `intervals` is sorted in ascending order by `starti`. You are also given an interval `newInterval = [start, end]` that represents the start and end of another interval.
Insert `newInterval` into `intervals` such that `intervals` is still sorted in ascending order by `starti` and `intervals` still does not have any overlapping intervals (merge overlapping intervals if necessary).
Return `intervals` _after the insertion_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[6,9\]\], newInterval = \[2,5\]
**Output:** \[\[1,5\],\[6,9\]\]
**Example 2:**
**Input:** intervals = \[\[1,2\],\[3,5\],\[6,7\],\[8,10\],\[12,16\]\], newInterval = \[4,8\]
**Output:** \[\[1,2\],\[3,10\],\[12,16\]\]
**Explanation:** Because the new interval \[4,8\] overlaps with \[3,5\],\[6,7\],\[8,10\].
**Constraints:**
* `0 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti <= endi <= 105`
* `intervals` is sorted by `starti` in **ascending** order.
* `newInterval.length == 2`
* `0 <= start <= end <= 105`
| null |
Array
|
Medium
|
56,715
|
39 |
hey guys how's it going in this video i'm going to walk through this decode number 39 combination sum this question was asked by facebook for 17 times for the last six months and other big companies so this question let's take a look at it given an array of distinct integers it's called candidate and target integer uh is called a target and you need to return a list of all unique combinations of candidates where the chosen number uh sum to the target and you may return the combinations in any order so the sum of the same number may be chosen from the candidate uh an unlimited number of times so two combinations are unique if the frequency of at least one of the chosen number is different it is guaranteed that the number of unique combination can sum up to the target is less than 150 combination for the given input so uh let's take a look at this example right here um the candidate that we are given is two three six seven and the target that we are aiming for is seven so uh the output that is required will be two three and seven uh by itself so if we sum this number two and three and that will sum to the target which is seven and seven by itself the sum of seven it will be seven and as the question illustrated earlier so we can use uh the numbers in candidate unlimited times so that's one example second example is two three five and target is eight so we can have a uh output of and two repeat it four times and two three which sums to a and three and five sums to a as well and if we're given candidate of one and only one number of two and the target is one so this number is too big right so there's no way to sum to the target of one so the answer will be an empty list and the fourth example the candidate is one target is one so we have only one and only one answer and canada is one and the target is two and the one can repeat itself and then we can sum it and then it can arrive at the pocket of two so uh we will solve this problem using backtracking and i'm gonna show you two solutions one is the one that i come up with myself another one is from the official solution which is a slightly optimized solution i think my solution will be a able to provide some intuition and which will provide as a stepping stone to help you to understand the next uh little slightly more optimized solution let's start so let's take a look this diagram over here i think is pretty intuitive um this is showcasing how we can use backtracking to solve this problem uh initially we have an empty list and look at the tree over here this is what we're going to build and the candidate we are given for this example three four and five targets eight right so then the first step of the tree of course i should call it the first level of the tree and it will be each one of the elements right so it's a three by itself what comes from the candidate four and five and from here and the combinations are possible will be three and three which is by itself uh the second three comes from the original candidate right so and then the sec and then the second level um or you can call it the third level and will be four and five so basically from here you call back the original candidate right for the second note and four and five and we can have four and three as well but that would be a duplicate that's why these three didn't show that and uh five and could be five and three and five and four and five again this tree didn't show that but possibly we can do that um so in the next level and in here you can see the circle that being blue out would be um the one sums the target right three and five sums to the a four and four sums to a so we are done and we don't have to uh keep going and for the one is below it is three and four uh which is six and seven which is little below eight so we can keep going to the left next level and for the ones is four and five which is nine which is over and five and it's over as well so we don't keep going and for the one that is still below it and then we keep trying three and three which uh is over eight so we don't keep going right so um for the next one three and four and that's over eight so we don't uh we don't keep going down below so uh those that's basically the idea of what we're gonna build for uh by using backtracking of a tree um so for us time complexity uh i don't think so the optimized solution uh the official solution is slightly optimized in terms of time complexity but in the oh in terms of uh oh in the worst case i don't think we are different that much anyway so i'm going to analyze the time complexity right now before we dive into the code and at this point feel free to pause the video and try to code it yourself so basically this is the id so as you can see the time complexity uh let n be in the number of candidates and a t being the target value and m being the minimum value among the candidates so uh the number of um you can read it through by yourself but basically what it's saying is um the number of levels so we go back to the tree right here right the number of levels uh is equal to the target value divided by the minimum value of the candidate in this case it will be the will be eight divided by the smallest guy over here three and eight divided by three is approximately uh three uh we can round it right so if uh three levels plus one which is on the top so uh that's how we determine the number so y is n to the power of number of levels so let's go back to the graph and that's because at each level so for example the first level will be other candidate so that'll be easy and on the second level uh will be um for each one of the candidates we can grab the numbers from the original candidate right so will be so the number of possible notes in the second level will be n square right so the first level with n which is three the second level will be n squared which is nine right so we have a three uh for each one right three plus three and plus three possible notes okay so the second level is a three square so the third level and by that logic will be three to the power of three right so in general term uh n to the power of a number of levels so in that case we talked about will be three to the number of levels um and then and each level it takes a yeah it says it takes a constant time to process except uh the leaf node which should take a linear time to make a copy of the combination and so we can say that the comp compass is linear uh to the number of nodes but i think the most important takeaway will be figure out the tree thing um because that the tree thing is also the same for the space complexity because we will use a recursion uh to do the backtracking and so that's why we have the call stack okay so um and again t divided by m will be the number of uh the levels and that will be um for the space complexity and to get the terminology exact so we is it's called energy tree uh you might you want to use that term in the interval that i might use and so and uh this is they say note in here this is the maximum this is the upper bound right and this is the worst case scenario and that's why um my solution is the official one is we can use the same formula over here okay so now let's dive into the my solution and first thing first i'm gonna sort it right so for all the candidates i'm gonna sort it and i have the scene uh this is actually a dictionary i keep track of all the possible so the key i'm going to walk you through what i use for keith which is kind of uniquely designed when i design a key and you give me a few tries to find the right key to put it to the dictionary and the value will be the list that i'm going to return at the end so at the end i will return the scene dictionary dot values okay and i also need to get them the maximum or the minimum candidate uh which is a little bit uh saving the runtime actually uh i don't actually need the maximum account i just put it over here uh after starter is easy to get them right just look at the index okay and so for all the candidates and if the candidate itself is greater than target and we are done for that take for that candidate so the reason let's look back to this uh example right so if the candidate one of the candidates it was like nine so nice automatically greater than the target so there's no way that we can using a nine to reach to the target right so we are done for that uh candidate of nine so we don't have to do no more and else we call a recursive uh which we do the backtracking we can call the function backtracking whether we want i call it recursor um anyway so uh i have a two arguments for that function one is needed so how many numbers left um needed how many numbers needed to get us to uh the target and also have the list that is basically the answer that we need to return part of the answers okay and at the beginning will be the list has only one and only one element which is the candidate that we're looking at and it will pass through to the recursive okay either needed is exactly zero and we are done so essentially in this case will be um here right the target is seven and that's exactly so for the first call right that's exactly uh if we look at the candidate of seven and target is seven so we are done at the beginning so the needed number is zero so we are done and so how can we push it to the candidate not the candidate the scene dictionary so i have to call the collections.counter collections.counter collections.counter and also sorted the list first and then this basically is a um it generated a statistics of how many um count for each of the members i'm gonna print it off and so we can see how does it look like and then i have the key that basically converted the count statistics to a string so i'm going to print it off so we can see how it looks like and why i need that this the reason why i need something like this is because i need the um answer to be unique that's why i have to um to design the key this way let's run it so as you can see for the last one and this is actually a string once again so this will be the key of the scene dictionary okay this is it's called a counter the number of seven that appears one so also this is so what is one of the solutions and then another solution will be two so as you can see two appears two times and three appears one time so basically this answer so basically this prevents a duplicate solution right which is not allowed because uh in the case where another solution which is exactly the same as this one will be two three and two or three two and two right or three two and yeah three two and two three and two and three and they are actually equivalent so prevent such a duplicate solution in output we can construct something like this to be a key in the scene dictionary right because all of them have the same key right because in this condition over here right if um the scene dictionary has not seen this key before and it did it will push it to the dictionary otherwise it won't do it right so this will prevent the repeated solution and that's why i need to sort it the list to sort it so that they follow a particular order office which is ascending order to force it to be followers ascending order so to make it uniform so this is how i uh this design the key and let's go through the rest of the recursive function if the needed number is less than zero and we're going to return so basically that's um let's say for this example right if there's number that we talked about before uh it would be if the one of the candidate it was eight right if that number eight so the needed number will be less than zero so we turn we're going to return right so we don't have to do the rest and because at that point we know that we got we are going to over it we're going to be over it so we don't have to do the rest of the other combination searching so uh so this is the second condition another connection will be the needed number is greater than zero so we can possibility to do some more searching and if the needed number to get us to um to the target and that new number is smaller than the minimum candidate and in that case we don't have to do the rest as well so basically to fall in this category will be in a case where um for example um for this number of six right and the needed number in this case would be one right because six plus one equals to seven of which is the target right but the one is even less than the minimum value of the candidate which is two in this case so there's no hope for that one so there's no hope for the candidate of six right so we don't have to do the rest because the number is just simply too big okay and if we still don't fall inside this condition and we can do the following m4 and this is where we do the searching right so and this is where we build up the next level which goes from the second level to the third level okay and this is where we how can we go it go for it so if the number um if the candidate number is greater than what we needed remember this candidate has been sorted already if that number immediately is greater than that we don't have to do the rest so this is some trick to make the solution a little bit more efficient on the average case um you don't have to include it and it still can get you uh to pass all the test cases actually but this is just slightly more optimized solution so i have the time list which is a copy of the uh the list that gets given from the phone and at the same time that time list we append the candidate to it and then we passed um the needed number in this case right now we look at the n number right and then um the needed number in total negative number will be reduced by n right because we're adding the number right now at the same time we pass we are passing the temp a temporary list and then make it to the next call and again if that candidate is already too big that means the rest will be too big as well because again this is a ascending order and if it's not too big we can keep building the next level and then keep push back until we if we hit the case where is it needed is zero or if the need is less than zero and at the end after we have the synthetic array we just return the values let me maybe i can print off the syntax scenario so you can see how it looks like so this is exactly what it looks like so the key so you can see the key so for example for this answer over here is two and three which is one of the solutions and the key being a string remember this string which is a counter of a two that appears a two and three appears a one time and another answer will be seven so which is by itself uh the number of seven appears one time okay so this is um actually my solution before i look up uh the official solution so and now i'm gonna go through the official solution with you which is a slightly more optimized way to do it so if you can uh pay attention to this note over here so let me read it for you if you will so if an important detail on choosing the next number for the combinations that we selected candidates in order right where the total candidates are treated as a list once a candidate is added to the current combination we will not look back right this is the way it saved the one time i looked back because i in my solution i still doing some low back which is not the most efficient rate in the world and so in official association we do not look back to the previous candidate in the next explorations so let's look back to this um look back no pun intended um let's look at this graph so three right when we are three right so we can export three and three which is by itself and three and four and three and five right and then we are when we are at four right and it is four and four which is by itself and four and five but we don't look back to four and three as you notice because we have already looked look at four and three over here already and this is where it saves the runtime right and when we are at five and we don't look back at five four and five and three et cetera we just look at five and five by itself right this is to uh save a bit of runtime so let's look at this solution it did not use a for loop which is okay but essentially the idea we already talked about over the graph already under the picture already uh so we have a result that we're going to return at the end okay and then we call functioning then backtrack so there are three um input arguments over here one is remain email is the same of um same as my function is needed which is different name right remain and calm which stands for combinations and starting index and this is where we control the not looking back okay so at the starting point the target is just the target given and the combination is empty list and then the starting position is just zero the zeros index okay and if the remaining is equal to zero we are done so we append the result to the results list and by what we went through before in the time complexity this takes like a linear time so it says pick a deep copy of the current combination and then we turn we so after we hit this terminal point we don't have to do the rest and we talked about before we have something similar in my solution and it else if the remaining is less than zero we are done as well we are over it right we talked about that before as well and now oh here there's a one for loop over here so and this is where we build up the next level right let's level the tree that we looked at so for i in the range of starting index which is given the in the uh in the function input argument and for the length of the other possible candidate so that's the ending index for that range we are adding the number in a combination right calm just append the number to it and then we call the big truck back uh call the backtracker to build the next level so given the current number and another chance rather than moving on yeah that's exactly what it's doing right so the remaining uh number will minus the current candidate that we're looking at also we pass along the combination at the same time we pass along this index and remember this index will be the starting point of the next level that helped us to prevent the look back not prevent uh yeah prevented look back that's exactly it yeah so the index right now would be the starting point of the next level and then we are done with the combination view so we pop it off not that we are done with coming we've done the last element of the combination that's why we pop it off in my solution what i did was i took a copy right so i didn't pop it off at the end but essentially you can do it either way you want i just take a little bit more memory than this but either way it works um okay so that's the two solutions to this problem i hope this is helpful if it is please consider like and subscribe and remember don't trust any of this try yourself thank you so much for watching see you next video
|
Combination Sum
|
combination-sum
|
Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**.
The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input.
**Example 1:**
**Input:** candidates = \[2,3,6,7\], target = 7
**Output:** \[\[2,2,3\],\[7\]\]
**Explanation:**
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
**Example 2:**
**Input:** candidates = \[2,3,5\], target = 8
**Output:** \[\[2,2,2,2\],\[2,3,3\],\[3,5\]\]
**Example 3:**
**Input:** candidates = \[2\], target = 1
**Output:** \[\]
**Constraints:**
* `1 <= candidates.length <= 30`
* `2 <= candidates[i] <= 40`
* All elements of `candidates` are **distinct**.
* `1 <= target <= 40`
| null |
Array,Backtracking
|
Medium
|
17,40,77,216,254,377
|
42 |
4:42 trapping rainwater we're given 4:42 trapping rainwater we're given 4:42 trapping rainwater we're given another negative integers or visiting an elevation map where the width of each parts one computer how much water it is able to trap after raining so here one we can trap water here and here these elevation map is represented by 0 1 0 2 1 0 1 3 2 1 the output should be 6 mm-hmm so actually we need to calculate yeah 4 for each point we need to calculate the maximum of the left part and the maximum of the right part and the choose the main smaller one and calculate the result cut you to the water and some of them are up right let's make it more in a let's thing yet think about it in a more iteration way let's suppose that there is a 2 bar at the first big first 2 bar border which means something like this if we all have to the point which means the borders we can see that the water should be between the water should be like this right yeah if something is bit if we now insert a new bar which is out of this part the water of this doesn't change if you insert a bar here the still water could be trapped here but with an extra part here right yeah if we insert a bar inside it and it's a smaller than both that it still doesn't make any difference with the water could be tracked here yeah I mean yeah the debris amount would be smaller but the basic the place where the water is trapped is unchanged but if it's larger it's something like this then things would be a little different because now the there's a new area of water being trapped here right but the water here doesn't change the water here in this area doesn't change that reminds me that reminds us that actually the border the mean that the smaller border could be ripped up from the graph and it isn't changin thing right yeah suppose there are a lot of waters like this one the minimum that would be like this part we can just tear this down because after we calculate you in the water yeah and tear this down and it did and it has no effects about to rest you see that for a short bar and the right the table are you can just loop through all the borders within them between them and define find the difference after tallest of the height of the bar from the first one because it's smaller so if you mess up with many new bar which is shorter we just calculate to the water until we make something larger like this one then we can just a catch if this area is fixed and we can just rip them up and now the problem become yeah in each in a you know in a recursion way every time we calculate to the outmost water area and rip up the border until we met only until there is only one left yeah and that would be the end of our recursion so this isn't mine remember that we need to start from the smaller border so what do we do just like we analysts about the problem we could place to both borders and insert the borders with then we think within them that reminds us we can use actually first try to tear this border and this port it down right so which one is first of course the shorter one because if supported like 1 2 3 4 5 if you solve this problem from the right side it will not help anything right you can't find any border taller than 5 you will need to track the minimum but if you from the left side it's gonna be easier because I can safely tear this one and then tear this one and tear 2 3 yeah that's what that's why we're using the two cursors let's I equals 0 then J equals height hmm while a I small n J when I meets J this that's the end of this problem so now we need find the smallest one if H R is smaller than hi J there weeks if left one is smaller then we continue continuing searching the next number which is just a bigger than it and stop at the right stop at there stop there now their sum is 1 ok this is that some of the water trapped being trapped now it means that we need to do in a inner loop its inside this safe condition which means I said K equals I mmm yeah K is smarter we will find the next number we will stop at the number where the next number is bigger than it yeah so Wow HK plus one yeah well next one it is small smaller oh not bigger than then I hate I then we just add the water to the summer right it's means because we're comparing to I and I is the border there would be no water I at the point of I so okay just be starting yeah it should be starting with K okay yeah and the water should the amount should be height K if next one is if next one if it is bigger than X 1 I know if the next one is smaller or equal to the height I we should wait a minute we should stop at Wow okay here we should stop at the number which is bigger than height I so K must be checked here I and hide you if it is smaller than it and you will stop at when this one is bigger than it yeah and the sum would be - right and the sum would be - right and the sum would be - right I this is the watery it could be trapped and K plus equals one so I mean seminary yeah it doesn't matter if they are equal yeah any we could place the equal mark here and the K equals J Wow K is smaller than J then some k j but K should be minus one yeah and finally we return some not that difficult right the ad case if there is nothing then it would be nothing here so you to a space to be zero evolution in one your met still be zero time limited ah God my bad we only stop we need to set the I theta J equals K so for these solution time Oh output ah god I have made a mistake here it should be to the right order yeah the time every number is only traveled only once so this should be a land space we only use a few variables to keep the to enable our traversal so you'll be constant let's submit hmm wrong answer why so it says lock the i J um pilot spy and write J there would be I think there is nothing wrong in the idea maybe there are some edge cases that I fail to take into consideration so the first one is zero nine five six and then go to three nine yeah and then go to three eight so the some there should be no problem here five okay we lock the sound o also hides I J okay the first sum is zero and then sum becomes four three nine so here should be four yeah it's right and it should be four and then seven six should be four again yeah and then should we go to this look and you should be six two also lock some cakes um okay 1:07 should be is 6:10 okay 1:07 should be is 6:10 okay 1:07 should be is 6:10 yeah 16 1823 and what why is 24 we've got 10 K would be 10 there's nothing there's no 10 got a lot 9 ah God so actually in this inner loop the i exceeded J yeah K should be smaller than J K should be bigger than I wow this is a tricky bug for my solution attention we should pay attention more about the boundaries about the edge cases about the conditions that we should stop the for loop and yeah that's all for this one so next time bye
|
Trapping Rain Water
|
trapping-rain-water
|
Given `n` non-negative integers representing an elevation map where the width of each bar is `1`, compute how much water it can trap after raining.
**Example 1:**
**Input:** height = \[0,1,0,2,1,0,1,3,2,1,2,1\]
**Output:** 6
**Explanation:** The above elevation map (black section) is represented by array \[0,1,0,2,1,0,1,3,2,1,2,1\]. In this case, 6 units of rain water (blue section) are being trapped.
**Example 2:**
**Input:** height = \[4,2,0,3,2,5\]
**Output:** 9
**Constraints:**
* `n == height.length`
* `1 <= n <= 2 * 104`
* `0 <= height[i] <= 105`
| null |
Array,Two Pointers,Dynamic Programming,Stack,Monotonic Stack
|
Hard
|
11,238,407,756
|
44 |
hello hey guys Welcome to our daily DSA practice and shares this site and today question which I have picked is wild card matching so this question uh is very important question uh as per the top 100 interview questions it's coming on the top uh very much frequently asked so let's see the question it's given an input string so this is an input string which is given to us right and a pattern so this one is the pattern implement the Wild Card pattern matching and pattern can have question and asterisk right so the pattern string can have question or even a stress that's what it is trying to say so question means question matches any single character so what does question says question matches any single character asterisk matches any sequence of character including the empty sequence okay the matching should cover the entire input string okay so the this pattern using this uh wildcards should be able to match the entire string right so this is the question and you know the drill right so what are the steps to follow in the interview when any question comes find the missing use case find The Brute Force approach with time complexity but never code for it find the efficient approach and think out loud while finding the efficient approach write a clean code do dry run before uh and identify the bug before interview two so let's first go with our first step let's find the missing use case so see here the questions look very straightforward in this case to me and but even though interviewer has given me a very simple of question mark a right and with the string equals to CB let me uh take more use cases let's say I'll try to find out a use case one where string is all a let's say I am just taking duplicates and pattern has now also apart from question it is also has asterisk question mark a whatever it has I'm just taking that so now here in this use case this estrus right can be used as a right let us say 4 times a right and this so estrus can be treated as this uh question mark can be treated as empty string empty so means it's uh we kind of ignored it and then a we have so ultimately string is matched so we already have a and this 2 are converted to this one 4 times a and this total 5A or there could be like asterisk can be considered as uh 3A instead of 4 question mark is also considered as 1A and that's it so this is another way to do it right so using this use case uh so this is one of the use case where we can have a multiple way we can find out a solution so both with both the way we can find out a solution but different ways we interpreted the estrus right so another use case too which I am thinking is yo let's say uh CB string pattern is asterisk CB so in this case I am considering question mark As empty string so let's say a pointer is here my pointer is here so I am considering this empty and moving to here so this is considered as empty and then string matches so this look straight forward uh but at least one thing I know that I have two using this missing use case one thing I know that I have to do a recursion because there can be multiple ways asterisk can be interpreted right so now let's jump to a second part Brute Force approach now in The Brute Force approach uh let's say that the same question a what I have taken uh let's say three times a instead of five times let's make it little bit simple and let me take a star question mark a okay so now let's say this is the question and currently my uh s index is zero and pattern index Pi is also zero so both are at zero so they are at this level so what are all the possible uh things can happen the possible things one can happen is I will consider a star as a right so my string index got incremented so this got incremented and my index now become 1. right so now it is here and one thing is I still at estrus itself because there might be more I have to uh considered so I am still at 0 here still question mark a what all the other possible way we can have for Star because currently it's a star I am interpreting for a star so for the star another way for interpreting is uh I have to take it as an empty string because in the use case we found right it can it what if it can be taken as an empty string so here in this case if it is taken as an empty string means it has been skipped I should be here we saw that right I didn't move only this got moved so here my S of I index is still same 0 but pattern index has been moved it become one so s is a so it is still at zero and pattern as now moved to question mark okay similarly for this now it has to be repeated also this is again an asterisk so it will again have a two way ah the same one is I is integrated uh string index is incremented and pattern is not and one is uh string index is not increased and pattern is increased right so this is for the star but what about the question mark now here if you say that we have a question mark what about the question mark so question mark is very simple so it will have only one for the question mark that if it is matched right so what will happen if it is matched then increment both right uh actually there is no point of match also so a question mark can be uh treated as any character right so definitely Whenever there is a question mark increment both so it's it will be plus one and Pi would be plus 1 which is become 2 so as would be uh you are as a string would be come one so it would be here now and P equals to Star question mark a it will reach to this point okay now again uh my after this index what would be the possibility now here there is no star there is no uh wildcard character now it's and character a to a so if they both are matched then go to the next otherwise throw error if they do not match but my major point was I wanted to know how the system behaves when it is an star and when it's a question mark right so now if you see that in a Brute Force approach there is always so worst case could be a and a star so every time a star let's say so every time there would be so in this case every time it would be 2 path correct so what would be the time complexity would be every time there would be two raised to power what would be the depth would be till we don't reach the string length right so it would be 2 raised to power my string length so this is my Brute Force approach using recursion right so let's first so generally here in this case Brute Force approach and time complexity uh now after that we have to go for the efficient one now right so now interview will say that okay can you improve this time complexity a bit from 2 raised to power and yes we can do it's see this question is very much specific to DP right but see I am not a guy uh with very much good at DP but I am a guy who is very much inclined with recursion plus memo uh so this is my uh so I know that all the DP question can also be solved through recursion plus memo as far as I know I might be wrong but generally I am good in recursion plus memo and I might uh sometimes makes a mistake and DP so I always go with recursion plus member but you can also go with the DP approach also so now in the recursion memo what can be done is so here in the Brute Force approach right there might be a use case when a particular index and this is already solved right because we are continuously backtracking and uh solving each one index 0 1 so there might be a possibility that the same index is somewhere solved so here si12 so definitely you will get s i 1 and 2 here also somewhere right so that it should not be recalculated again that's what I am trying to say so that's where we can use a memoization to solve the to store the output of this index when I solve it here so that it can be reused right do you understood so what would be the time complexity which I am saying with memorization is uh so let's say the length of string into length of pattern right so generally I know that in DP you would be creating a pattern length here like this many time and the length so let's say a and a star kind of question mark a and then we will go with all the combinations uh one zero like it's a path or way or not so but what space complexity definitely we are taking a memorization and for each i j for each string index and pattern index we have to store so space complexity is also the length of string into the length of pattern and similarly the time complexity also because we have to go through each iteration each IJ got it so generally the efficient approach in this solution is just whatever the brute force is plus memo right so now let's do a clean coding for it okay so this was the question and we have to build it now let's write it so we have to make a smash string to be match and pattern right so now here uh I am taking uh I am using a memorization one itself so let's say I am taking a 2D because I need to store i j and let's call it uh cash right so it's new and uh let's uh the length would be its uh string to be match dot length and uh pattern Dot length right so it's a cash uh memo I would say that it's uh cache memory okay so now after this one we have to store it here I'm just storing into this is the minus one here so in um my I'm taking one string index from 0 and a string index is less than a string to be matched Dot length string index plus similarly I need to do it for pattern index is zero pattern index is less than pattern length pattern index plus and in my cache memo uh this s index and P index currently I'm storing it minus 1. so uh currently my memo everything is -1 so uh currently my memo everything is -1 so uh currently my memo everything is -1 so nothing is stored here right and now I am calling my uh let's say is match right so is match I am calling uh I'll write another mad third and the value which I am passing a string to be match uh my pattern comma so I am starting from the end right so let's say I have a string right here a so let's say what I am doing now so now you know already know right A let's say star question mark a so I already tell you like for a star what is thing we have to do so for a start there are two ways right so for star two ways where string of index is incremented but pattern is not incremented another is string of indexes not incremented pattern is incremented it is taken as an empty string right so I am moving from back here you can also move from start right so that's why I am moving from back I'll keep telling you uh how it is going so that you can relate properly right so I am going from the back side now huh cache memo so this is the new method which I am going to write here right so it's a private method and uh so this is my string this is your length string length this is your pattern length P length and this is your memoization which we have to use okay so now let's move to that method so first condition is so let's uh plan for the breaking condition here so one thing is so I am starting from here so let's say this is my I this is my J right so one case is so if my index string length is less than zero right means it reached till here this is all completed right so it is less than 0 and J is also completed it is also less than zero means both are completed for example simple a i is here J is the match I become here J become here so initially its length is 0 1 2 so now it's become minus 1 right less than zero so means totally matched up so the first condition is when all when everything matched up when everything matched so if so here you have So currently I would say that it's an index so s index So currently where we are starting and this is my P index so if s index is less than zero and P Index this is also less than zero if both reach till the end completed means it's a happy use case return one okay so another use case is if when pattern is finished but a string is not then it's a invalid use case so here if s index is greater than equals to zero means I is not finished uh string of length is let's say something here but my pattern is finished it was only one pattern is finished so my pattern is less than 0 it is already finished but string of length is not so this is an invalid use case return 0. so another use case is mine if so here if pattern is left so the third uh terminating condition is let's say if pattern is left but this thing is finished so you know right question can be treated as an empty character so that can be done also so here if you see that now I am saying that if a string of index is your less than zero means string is totally finished a string is finished and pattern of index is greater than equals to zero means pattern is not finished so I started from here right and I am here pattern so string of indexes already came minus one it's finished I consider this AAA let's say it is star so with the star it's already done so a pattern is or till now here okay so but the still pattern is left right I am going from back to here so with this star itself I will treat it as a and string length finish but pattern is not yet finished so I just need to now iterate at a pattern and see if it is all star or question mark if it is a star or question mark means then it's uh considered as uh a wild character and it's okay and I think I need to consider only star because it says that matches any single character star matches any sequence of character including the empty sequence so I think I need to consider only uh star so here for int I am taking one index which is currently at my this index and I will go till zero index is greater than equals to zero index minus now if pattern dot character at is ah at this index if it is not equals to star or wild character which I can use means it is invalid else it is valid so these are all my breaking conditions right now since I am using memorization so I'll use my memo like if my memos data is present right so here I will say that if my memo has a string index and pattern index not equals to minus 1 means some value is already present so I will return that one right so I will return cache memo as index and P index means till that it is matched or not it would be one or zero okay so now I we have written our base condition now so now let's write a very simple recursive logic here which we have to do now I told you right in case of question mark and whenever there is a match we have to increment simply one character both so what is that condition if you are string to be matched which is string character add s index equals to your pattern dot character add P index if they both are equal or pattern is equals to question mark right so if this is the case what we have to do is we have to just call it again and increment both right s index so here we are going from back to bottom uh so it would be -1 for back to bottom uh so it would be -1 for back to bottom uh so it would be -1 for both right and ultimately we have two store since we are using a memorization we have to store whatever the one or zero whether it's match or not we have to store it here and return the value of this one from here so this is for this condition very simple another question another condition is if pattern is if the pattern is question mark if pattern is question mark you already know there are two possibilities what can happen right so the two possibility is match string to be match pattern so one possibility is we are incrementing the string so means kind of I we are going from back to bottom so it's a s index minus 1. and P index Remains the Same and it's the cache memo so this r another is we are saying that strict index Remains the Same and P index become -1 index become -1 index become -1 cache memo right so these are the two cases which are possible right if they ask if something is matched up we have to make it minus one right else what we have to do we have to make it here zero means nothing is matched up right so here we'll say that so okay if this is equals to 1 and this is equals to 1. if something got matched up okay and once all done this thing uh so once a files is done so it will return its value and finally once everything is done it will return 0 here because if anything is matched it will return it from here but if at last if nothing is matched it will return 0. Okay cool so this is the implementation so here it get one or zero so here we just write one uh since we have to return uh Boolean right we can write one condition like okay if output is greater than zero return true else false so it's done okay so this is my Approach of solving it through recursion was Memo I definitely want to know about the dp1 approach so I hope you like it guys so thank you very much and good night and see you with the next question tomorrow bye
|
Wildcard Matching
|
wildcard-matching
|
Given an input string (`s`) and a pattern (`p`), implement wildcard pattern matching with support for `'?'` and `'*'` where:
* `'?'` Matches any single character.
* `'*'` Matches any sequence of characters (including the empty sequence).
The matching should cover the **entire** input string (not partial).
**Example 1:**
**Input:** s = "aa ", p = "a "
**Output:** false
**Explanation:** "a " does not match the entire string "aa ".
**Example 2:**
**Input:** s = "aa ", p = "\* "
**Output:** true
**Explanation:** '\*' matches any sequence.
**Example 3:**
**Input:** s = "cb ", p = "?a "
**Output:** false
**Explanation:** '?' matches 'c', but the second letter is 'a', which does not match 'b'.
**Constraints:**
* `0 <= s.length, p.length <= 2000`
* `s` contains only lowercase English letters.
* `p` contains only lowercase English letters, `'?'` or `'*'`.
| null |
String,Dynamic Programming,Greedy,Recursion
|
Hard
|
10
|
279 |
Hello and welcome to the channel again this morning and today we will talk about the medium level problem of lead quote which is perfect square, what is it basically in this we are given an input i.e. we have to tell how many input i.e. we have to tell how many input i.e. we have to tell how many numbers of perfect square we can add by adding 12 We can bring the least number of perfect squares and at least how many perfect squares can be added to get A. So here in the case of 12, if we look at 4 P 4, then the answer will be three, it cannot be less than three. Why because there are minimum three such perfect numbers i.e. minimum three such perfect numbers i.e. minimum three such perfect numbers i.e. if we add four three times then our answer will be 12 and no case can be made if we look at 13 core then 9 ps 4 cannot be less than this i.e. the answer will be two. It i.e. the answer will be two. It i.e. the answer will be two. It cannot be reduced to less than two numbers and both the perfect squares are one of th and one of two. Okay, so its approach is slowly coming to our understanding that we have to add perfect numbers i.e. sorry that we have to add perfect numbers i.e. sorry that we have to add perfect numbers i.e. sorry perfect squares. Okay perfect square. What is brother, square of 1 becomes one, square of 0 becomes our four, okay, square of 3 becomes our nine, square of 4 becomes 16, square of 5 becomes 25, square of 6 becomes 36 and so on, okay so like this Only these perfect squares are formed, so if we take an example and dry run this thing and see what is in it, we will be given n as input and we will have to run a loop and check all the possibilities to find out which such perfect squares. Which can be folded up to make 12 or A. Where all possibilities are discussed, all possibilities are fine. What is our use of deep? Where all possibilities are discussed, deep will be used. Okay, so let's understand by taking an example. Let's assume n = If it is 9, then understand by taking an example. Let's assume n = If it is 9, then understand by taking an example. Let's assume n = If it is 9, then if we try to find out its answer then what will happen if we look at the brother's square, if it is no, then its answer will not be direct, but once we make our recursion function on this, then we will see without making it. Taking the example, it is okay, the solve function is ours is A. Okay, now what we have done is that we also have to count how many numbers will come, that is, if seen, it means how many steps can we take to reach that number, how many steps. How many numbers will we need? Total is ok, so if we see here then which are the perfect squares which can reach to no. If we see, T is 3 only, how is the tooth a perfect square then what is the perfect square of one? Perfect square is one, okay, then subtract it from nine, if that means how much has come, now the recursion function has come, our solve is 8, okay, Psv will also happen here, why if we look at it, why did Plov happen because one will be added to our answer, why? This is being added because being an add means that we have found a number, what is that number, one, okay, let's talk about the second one here, now here, if we look at the second one, then what will happen, how much is the square of our solution. It is four then if we do minus then the answer will be F Solve F In this also we will add one brother why not plus because we have picked one number, what is that number four, okay so one number will be minimum, there will be one in front of it Another case can be yes, what can be the third case, its third case can be that we take the square of direct 3 i.e. no take we take the square of direct 3 i.e. no take we take the square of direct 3 i.e. no take direct, okay then what will happen in that case if we take minus in that case then what is left? If Nan is reduced from then zero will be left. We will take Psv because we have already taken one element, right, these are our three receive calls for the next step and in all we have plus and added before returning each call. Why will we do one because we have already picked one element ? Okay, after that let's move ahead. ? Okay, after that let's move ahead. ? Okay, after that let's move ahead. Now if we look here for the function of eight, then in solve eight we will only take the perfect square of one which is our one and the perfect of two. The square which is our two is four, we can take the same, the perfect square of three will become nine which is bigger than eight, so if we make it by taking the perfect square of one, then if we subtract it, then how much will it become, i.e. 1 plus solves become, i.e. 1 plus solves become, i.e. 1 plus solves 7. Why did we write this one because we have already picked one, okay, the solution is done, if we look at this in this case, then what will come as 1 ps is solved further, because we have already picked four, so what should we add to it which will become our eight? If we add four then solve four, our four is left, for that we again call for sen. Now here we see if it is okay for sen, then in the case of seven again our what is coming and end to end. How much is the square of n? Sorry. Okay, so if we look here now, what should we add to the square of n which comes from our and will be s. So our solution will be 6. Okay, why psv because one more element is added. Then again on Y, what should we do in Solv? If it is formed, then our A3 is left, okay, after that we solve for six on Y, okay, if we solve for Si, then what will be left? Maybe one for one, maybe one for another two. If we can't go till our then one, if we do one, what is the square of n, what is the square of t, then what is the square of f. Okay, so if we do this, how much will our PPS be? Solved. 6 That is, if how much should we add to one, it comes to solve and plus and we will add one more element and that is not this line, not the one on the left side, left, it is being made only by adding new wave. If our end result is then this will not be the answer till now let's solve it and see if the solution is done but in this case if what we do in the four steps is done then our solution will be fine and then again if Let us notice on y, if we solve for five, then in five again if our perfect square of one can come and perfect square of two can come, okay then what to add to one, if f comes then it will be left. Four i.e. n left f comes then it will be left. Four i.e. n left f comes then it will be left. Four i.e. n left 4 and what do we add to four then if f comes then one left i.e. 1 plus solve one left i.e. 1 plus solve one left i.e. 1 plus solve one ok now if we look carefully here what will happen brother again here let's solve for f ok for four If we solve then what can come for four again in four perfect square of one is equal to perfect square of equal to 4 well if four goes to four then what will it give na plus solve zero but if we look here then If one goes, what will it give? Plus solver. Okay, again for us, if we solve the thing, then what will come to us? What can come in three? Brother, only one can come in three because the perfect square of two will become bigger, so this What will happen, na plus solve two, again for two there can be only one, so na plus sorry, na plus solve one, ok, what will happen for one, if we see here, again one can only happen, for one, then one ps solve. It will become zero, this is mine zero and what will come here A E G solve G. Once we solve zero i.e. what will be our base case. If we talk about the base, then i.e. what will be our base case. If we talk about the base, then i.e. what will be our base case. If we talk about the base, then what will be solve zero? Solve zero is simply our return. Next to this, let us take a step. If we can't, then it will return us to zero. Solve what return did zero give? Brother, it did zero and by doing plus and what is the value of this total? What will be the value of this total? What is the return from here? Hu i.e. what is the value of solve one? If we did n Hu i.e. what is the value of solve one? If we did n Hu i.e. what is the value of solve one? If we did n plus y and then what was the return from here? Now what is the value of solve two? What is the value of ? 3 plus and what is the return from here? What is the value of ? 3 plus and what is the return from here? Okay, if we look here, solve zero, what was our value return zero, then we will return zero here, solve zero's zero 0 p.w. solve zero's zero 0 p.w. solve zero's zero 0 p.w. how much What happened is right, so if we look here, in case of four, solve, in case of four, either we will go on this path or we will go on this path, but if we look carefully, we will get minimum steps i.e. minimum number of we will get minimum steps i.e. minimum number of we will get minimum steps i.e. minimum number of returns. From this path, where is the minimum coming from, so we will pick the minimum that will return between these two and here what will we take one i.e. here what will we take one i.e. here what will we take one i.e. what is the value of solve fur one because if we look at fur This can be made only with the help of the square of direct 2. Okay, so this is the value of one, okay and + 1. When we did this, what is and + 1. When we did this, what is and + 1. When we did this, what is five, then what is the return of five? Right there, if we look carefully here. What was the return from side 1 p, what was the value of solve and solve one? If you check here, it was v. The return here was 1 p = 2 i.e. its value is 1 psv and 1 p = 2 i.e. its value is 1 psv and 1 p = 2 i.e. its value is 1 psv and what will be the return of this. It is okay if here these Check the minimum in both of them. Pa and what is the minimum in two? So we will reduce it to two i.e. how much is the value of solv f? What is the we will reduce it to two i.e. how much is the value of solv f? What is the value of solv f? Okay, if we check here, what will the right child return, what was the value of solve to solve two, then it would be clear that over sorry overlapping sub problems are coming here, that is visible. It is okay here, so we will definitely put a memo. Okay, so let's talk again. Yes, what was the value of solve two? So its value is two plus what is done. If it is done then what will it return? Now what is it here? Did that in Solve Six, whether you go this way or this way, only three answers are coming from both the sides, then what will be the value of Solve Six, it will become three, now when the value of Solve 6 becomes three + and then again this is done. Returned + and then again this is done. Returned + and then again this is done. Returned our 4, return this to our four, okay, how much was the value of solve three, if we look here, where is solve three, one minute, where is solve three, yes, okay, how much is the value of solve three? The value of solv is coming, it is ok, so here solv is 3, how much is PSV, what is the return, that is, in the case of sen solve sen also, if we want to go left or we want to go right, from both the sides. The answer is coming four so this will be the answer then okay clear okay so now if we look here then 4 p 5 i.e. what will it return we look here then 4 p 5 i.e. what will it return we look here then 4 p 5 i.e. what will it return f Okay but here if we look at the solve four then our solve was four here and The value of solve four was coming to us. One should be clearly visible here. So, how much will we write the value of solve four? Equal two is okay and when we add Psv, what will happen in it, what will it return? Okay, so now solve 8. If we look carefully in the case of , if we go to this path or the left If we look carefully in the case of , if we go to this path or the left If we look carefully in the case of , if we go to this path or the left child, then how much will we get if we go to the right child, how much will we get if we take the steps from the right child, then what will be the value of our solve at. Two i.e. by adding two perfect what will be the value of our solve at. Two i.e. by adding two perfect what will be the value of our solve at. Two i.e. by adding two perfect squares, what will be 4 P 4, what can we make 8, okay, it is clear, so the value of solve weight has come to two, after that one is added to it, then how much was it, then ultimately What was returned from here? Okay, what was returned from here? What is the value of Solve Five? Brother, look at the value of Solve Five. If we were to come here then the value of Solve Five was coming to us. Solve what is the value of f became two its value became two 2+ 1 3 so what did it return its value became two 2+ 1 3 so what did it return its value became two 2+ 1 3 so what did it return it returned look at the case of three nines nine means sorry nine means ya third case if we see it was zero then it means it returned Did it return zero, did it return one, so what will this total return? Now here there were three cases - square of one, Now here there were three cases - square of one, Now here there were three cases - square of one, square of two and square of r. Which one will we pick among the three cases? We will pick the perfect square of r. Why because it returns There is one and minimum of no, what answer will come, neither solved nor is the answer coming, is this thing clear, you people have nothing to do in this, first of all, what will we do in the recursive function? In the recursive function, we will If I show you here by doing the recursive function then let's assume here is solve n base case what was if n is equal to 0 then what is returning is zero okay then what are we doing then we will run the for loop and We will check how many perfect squares are smaller than this int j equal to where starts from one perfect j in j less than a and equal to ok lesson e a and j ps we will check the perfect square of each number will be small only then It should be smaller or equal, what will we do after that, our answer is equal to the mind of what will we do, we will take the minimum of all, thena mean of solve a minus j in j, it is okay, we have done the perfect square minus, it is okay, what we used to do together, brother, we used to take the plow. Why we because we are picking one element comma answer, the minimum of these two will be stored in our answer. Okay, initially the answer here, before the for loop, answer is equal to two, we will make int max so that the answer starts from maximum. So we can update the minimum values, after this work is done, we will simply return our answer, that is, here we will write return answer, we will run a for loop for each recursive function, okay, that is what we were doing above among those three. We will take the minimum of all three, that is, all the perfect squares that will come, we will store the minimum of them in that number and return the answer in the answer. This is our recursive function. Once we code this thing, let us see how we will perform. Okay. First of all, what do we do on Y, we solve our return function, it just passed, okay, after that we will element our function, we will put it as a base case, E A E G return zero, what is the second one, we will take the answer, our E it max then what are we doing putting the for loop it j ev j in j lesson equal to a j plus ps answer i equal to minimum answer n plus solve a minus j in j ok then what are we simply returning on y The answer is ok, simple, that's all, let's run the recurs function, ok, it will come only after submitting the test case passing, let's see that too, ok, it is a simple thing, brother, ok, so what was happening in it, overlapping all in it. To tackle the problem, let's do vector int dp and what is the size of pv? Let's take comma minus sub and store mine in sub. Pass dp to function. Okay, then we have mentioned dp in the parameter here. It is ok and we will reference it by passing because we need the value to be updated in the DP and the original DP has to be maintained, after that we pass D in all the functions, solve ok, so first pass D in it, comma, one minute, comma, ok. What will we do after that, we will check after the base case, if there is already estimated value, then we will not move further if D P of A is not equal to my return D P of A, okay let's run it once and see for a minute here. But sorry, there is a mistake here, we also have to store it in the depth of A. Yes, now it is correct, OK, so the test cases are passing, if you submit it, the teal will come, maybe tabulation will be used, it will look good or accepted, great OK, so this is accepted. Even if it is not done, then one more thing we can do in this is that we can do this by passing reference to whatever is coming, we mean draw function, so look here at 65, it will increase, okay MS. It will get better, ok, I will submit now, ok, look, it is proved, now we are beating the users at 70, let's do the tabulation, ok, so it is very simple to do the tabulation in this, ok, so what will we do by doing the tabulation, first of all, brother. Store int max in sub in DP because we have to find out the minimum answer. Let's keep it max. After that do we maintain the base case? First of all because what is DP brother, bottom approach is ok so butt approach first maintain it. What was the zero coming on the zero, what were you doing, what were you running, I was running this, what are you doing for each one We are running a loop int of perfect squares, let me copy the above one minute ok now what are we doing inside this for loop d puff aa e equal to minimum of what was the answer what is the answer d puff aa What was the comma? Brother, what was solved? Earlier, instead of returning the answer, we will write 'P' of 'A' because the we will write 'P' of 'A' because the we will write 'P' of 'A' because the answer is green stored in it. It's okay. Let's stubbornly perform the entire function above. This is done. Let's run our tabulation approach and see if there is any problem. One minute, one minute. Okay. But we copied that from above, so here it should be N and not I. Okay, because we are working for every N, we are working for every I. Okay, now let's run it once. Okay, now the test case is passed. We are submitting and let's see, the answer will be a little better, okay, it has become a little better, this time it is better than 93 users, okay, thank you so much for watching this video and if you like the video, then like the video and subscribe to the channel. See you in your next video till then bye
|
Perfect Squares
|
perfect-squares
|
Given an integer `n`, return _the least number of perfect square numbers that sum to_ `n`.
A **perfect square** is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, `1`, `4`, `9`, and `16` are perfect squares while `3` and `11` are not.
**Example 1:**
**Input:** n = 12
**Output:** 3
**Explanation:** 12 = 4 + 4 + 4.
**Example 2:**
**Input:** n = 13
**Output:** 2
**Explanation:** 13 = 4 + 9.
**Constraints:**
* `1 <= n <= 104`
| null |
Math,Dynamic Programming,Breadth-First Search
|
Medium
|
204,264
|
3 |
hello guys this is code in code and this is video editorial for the problem longest substring without repeating characters taken from lead code so let's see what the problem says so the problem statement is you are given a string then find the longest substring without repeating characters for example if the input was this abc bb then the length of the longest substring that you can find where no character repeats is three either it can be abc bc or anything right you don't have to print the whole substring you only have to print the size of the longest substring where we can't find any repeating character so this is the problem statement so moving on so expected time complexity you can start with n log n solution and then you have to optimize it i mean you can optimize it to be go off and when you are solving the problem in any interview uh the best thing is to start with the brute force approach then tell them or tell the interviewer that you can optimize it to like n log n and then you can up optimize it to we go off and so we'll see both of these approach okay so let's see how we'll solve this problem so we'll be solving this problem using two pointer methods so i have two pointers l and r i'm in uh initializing with minus one and l i'll be initializing with zero okay why is that so c when r is smaller than l that means the range is actually in value so we will be starting with an invalid range and y r is initialized with minus one because uh no matter what happens r will be incremented as the first step okay and when that happens the first range we will have as zero that will be valid and that should be the starting point that's why i'm having r as minus 1 mp is actually a map which will keep track of or which will keep uh frequency of each character okay this is a map which will give frequency of each character count is will keeping the will be keeping the count of each invalid character so it will count how many characters are there in your range which is specified by l and r which are actually invalid so what are invalid characters a character whose frequency in the given range is more than one is actually invalid character so this will represent how many characters in your range are invalid so when the count is zero for certain range which is specified by l and r that represents a valid sub array okay or substring you can say that represents a valid substring and hence that can be taken as answer okay and we have to find a substring which is largest in size and is also containing no invalid character so you got the idea right so you'll be able to understand it much better when i'll be explaining this with an example test case so don't worry i'll be explaining and i'll take you through uh solution code as well and i'll be explaining this through an example uh by running it through an example so you will be able to understand it much better so let me tell you or let me explain this whole solution with the help of an example but before that let me ask you one thing have you always dreamt of getting a picture-perfect iit package picture-perfect iit package picture-perfect iit package is it your dream to become resident id person for all tech troubles all you want is someone to call you up at 3 a.m want is someone to call you up at 3 a.m want is someone to call you up at 3 a.m and ask you how to fix your laptop keys or set up a new instagram profile for your grandparents your dream may not be that far fetched if you want a job that pays par with shah magic iit and beta you don't have to bring out the big guns you just need to learn how to work with them and the big guns in question these are product based companies like apple amazon microsoft cred etc these companies may sound a little out of lee but trust me nothing is impossible you can apply to these companies by posting your resume through linkedin or a distant connection might even help you score an interview but the real question arises now how do you stand out from the crowd of thousands just like you wanting the same job that you do this is where reliable by an academy comes in re-level helps you bridge the comes in re-level helps you bridge the comes in re-level helps you bridge the gap between experience and skill set by making it easier for companies to find you rather than other way around the best part is that companies choose to hire people from such platform as it highlights their aptitude and skills your college name can never hold you back not here by giving reliable tests you can skip the tedious job hunting process and get the pay you deserve in all the six figure glory with real level it's your time to shine become everything you ever dreamt of register for reliable test today only for rupees one triple line and the best part is you get 200 rupees off if you use my code cnc 10. so now let's get back to our lecture so how we'll proceed is that i will keep incrementing r as long as count is equals to zero that means in our given range l to r there are no invalid characters if count becomes positive we will keep incrementing l that will reduce the range right and hence reduce the frequency of character which are invalid so let's continue when you are incrementing r you are basically expanding your range or your substring and that means you are adding extra character in your substring right when you are incrementing l you are basically removing characters from your character set or substring type keep that in mind so now since count is equals to zero we will increment r basically we have added a so frequency of a should increase so frequency of a which was initially zero has become one if frequency of certain character becomes two we will increment the count okay so now we'll check whether the count is equals to zero or not yes the count is equals to zero so what we'll do we'll try to maximize result the result is equal to maximum of one comma this current range is containing only one character right so result is equals to max of 1 comma 1 which is clearly 1 so result will become 1. now again next loop what will happen is that count is equals to 0 so you will increment r now we have added b so frequency of b will increment after that we will check whether the frequency of b has become two the answer is no so count would not increment and of course after that we will see uh see whether count is zero or not since count is zero so current range is actually valid range so since the current range is valid range will maximize result to the length of the current right clearly a maximum of one which was earlier result and this is clearly bigger than that so result becomes two now again we will since count was 0 i have incremented r frequency of c i have added right now since we have to check uh since we have incremented or decremented basically frequency of c has changed so we will check whether its frequency has become 2 or not its frequency has not become 2 so count will not increment in case of decrease what will happen i'll tell you in a moment so frequency so basically count will not change so we'll come to the point and we'll check whether count is equal to 0 or not since count is equal to 0 we can maximize result again current length of the substring is equals to 3 so result will become 3 now how is all of this is happening let me explain you with the code so here you see i have two solution right one is uh let me just increase the font size this one or run time is 16 millisecond and the other one is having a runtime only four milliseconds you can also see the difference in their memory used okay so this is analog in solution and this is big off and solution okay so what i'm doing i'm using a map because for each character i have to say the frequency of that right and is the size of the of course a string count is equals to zero result you already know l and r you already know so what we are doing here if count is greater than zero right uh till now we have only seen this case when count is equal to zero so what we do we increment r and then of course when r goes out of boundary will stop right so we will break out of the while loop otherwise we will increment r and what we will do we will increment the frequency of the character current character right if the frequency of current character becomes two right if frequency of any character becomes two we will increment count right that is exactly what we are doing after either incrementing l or we will either increment r right and after that we're checking whether count is equals to zero if count is equals to zero result is equal to maximum of result or length of the current substring that is what is happening i have yet to show you this part so let's continue now r will again increment because count was zero so now i'll increment frequency of a now frequency of a has become two now as soon as frequency of certain character or current character becomes two you have to increment the count so now count will become one right we have done this part now we will come here can we maximize result this is what we are checking since count is not equal to zero that means there is at l there is at least one character which is invalid that means your whole range is actually invalid so i cannot maximize my result right so we'll continue next time what we'll do whether count is zero or greater than zero since the count is greater than zero we will increment l this time here you see since the count is greater than zero we'll increment l this time basically uh to increment l you have to remove this character so before incrementing l what you will do you will reduce the frequency of current character represented by l so basically remove uh reduce frequency of course l has incremented reduce frequency of a right and after that increment l right so what is happening since the frequency of a has changed which was the previous character basically this uh first of all reduce the frequency of the character oh my god reduce the frequency of the character and check whether the frequency has become one now if the frequency becomes one that means it has changed from two to one that means this character has become valid that means you have to reduce the count so reduce count right after that this has done again this process will happen whether i can maximize the um result or not basically current range represented by lr r is valid or not so this process we will keep on repeating till r goes beyond n right basically r goes beyond the valid range and then we will stop if r is equal to n simply break and return the result so to solve this problem we are using map right and insertion uh in the map takes log n time that's why the complexities and log n of this solution and that's why we are getting 16 millisecond running time if i show you this solution i'm simply using frequency array so first of all if you don't want to look it and if you want to solve it yourself go ahead and do that uh try to implement and be go off and solution okay so just keep in mind that the s can contain letters digits symbols and spaces as well so keep these things in mind this is very important so if i show you my uh linear time solution instead of using math what i'm using is integer array of size hundred i'm assuming uh they can be at max 100 unique character okay because if you combine there are 26 english letters some or 10 digits only and then certain symbols so they can combine and they'll be still less than 100 so instead of you using map i'm simply using integer array for storing that frequency here you can see i've changed nothing simply i'm using frequency array and uh here you see instead of using minus a i'm using minus off empty character which is space why is that so or just think about it basically i'm using integer free integer hash math method right to store their frequency integer array to store their frequency instead of using map how is this working and how am i able to translate certain character to a certain integer right how am i able to do that just think about it this is basic hashing okay if you still have some doubt you can ask in the comment section or the people who already know what is happening you can post it down the comment section your solution that why is this working okay otherwise in the next video i'll take a very small video solution and i'll explain how this is working so yeah this was all for this lecture thank you guys for watching until the next videos keep coding thank you
|
Longest Substring Without Repeating Characters
|
longest-substring-without-repeating-characters
|
Given a string `s`, find the length of the **longest** **substring** without repeating characters.
**Example 1:**
**Input:** s = "abcabcbb "
**Output:** 3
**Explanation:** The answer is "abc ", with the length of 3.
**Example 2:**
**Input:** s = "bbbbb "
**Output:** 1
**Explanation:** The answer is "b ", with the length of 1.
**Example 3:**
**Input:** s = "pwwkew "
**Output:** 3
**Explanation:** The answer is "wke ", with the length of 3.
Notice that the answer must be a substring, "pwke " is a subsequence and not a substring.
**Constraints:**
* `0 <= s.length <= 5 * 104`
* `s` consists of English letters, digits, symbols and spaces.
| null |
Hash Table,String,Sliding Window
|
Medium
|
159,340,1034,1813,2209
|
394 |
hello everyone welcome back myself rahul so today we are going to solve a problem related to strings so the problem name is decode string it's a very famous problem and a medium level one so let's go through the problem given an encoded string return its decoded string the encoding rule is k encoded string where the encoded string inside the square brackets is being repeated exactly k times note that k is guaranteed to be a positive integer you may assume that the input string is always valid there are no extra white spaces square brackets are well formed furthermore you may assume that the original data does not contain any digits and the digits are only for those repeat numbers k for example there will be no input like 3a or 2 4 all right so basically if we go through the example 3 a 2 bc right so the characters are given in a square brackets and there is a number before the opening square bracket and we have to repeat whatever is present in the opening and closing parenthesis right so a is present in the opening and closing brackets and before that three is present so we have to repeat a three number of times similarly bc is present in uh opening and closing brackets and two is present before that so we repeat bc two number of times bc similarly three a two c let's try to understand what they are trying to convey over here so let's take the first example it is three a 3 a 2 b c right so this is an example so what they are saying is like whatever is present in opening and closing brackets and before that there would always be a number k right we have to repeat this string k number of times so a would be repeated three number of times similarly bc is one string so we have to repeat bc k number of times k is true which means bc similarly the other example is three a2 and c right so here it's a bit complex string so what we need to do over here is first we consider this one so this c is present in opening and closing brackets and 2 is present before that so basically we have to see repeat c 2 number of times so this part of the string is processed we can ignore this now comes a and this bracket as it is over here in this bracket as it is over here and 3 is over here right so we have now string acc with us and we have to repeat three number of times so it is acc and acc so how are we going to approach these kind of problems is that like they have opening and closing parenthesis involved here so whenever we encounter these kind of problems where we have brackets with us so the first approach that should come to our mind is the concept of stacks let's see if we can solve this or approach this problem using the concept of stacks so let's take this example again 3a to bc 3 a 2 bc so the concept of stacks in the parenthesis cases can be utilized like whenever we encounter any of the index value we just directly push that in onto the stack and whenever like there has to be some popping mechanism as well right so when do we basically pop the element out of the stack so whenever i will encounter the closing brace which means it's the time that i have to pop some of the elements out of the stack right so taking this example 3a to vc let's create the stack so i start from this index this is not a closing bracket if it is not a closing bracket i just directly push whatever is present at that particular index onto the stack so i push three then comes opening bracket is also pushed onto the stack then comes a then comes closing bracket so whenever a closing bracket is encountered we have to make some decisions out of that so when we encounter closing bracket we are going to pop from the stack till i encounter an opening bracket because that is the string that i have to consider right so here as well uh there was an opening bracket here then there was some string over here then comes the closing bracket right so whatever the string was present in this part basically before after the opening bracket so i have to consider that whole string so i am going to pop whatever is present on to the top of the stack till i encounter an opening bracket so a is popped from the stack i get a string a then comes the opening bracket which means this is the string i have to consider just a i will pop the opening bracket as well right but i have to also take into consideration like how many times this string a have to be repeated for that i have to pop another element from the stack so that i will get to know a variable suppose x it is equal to 3 over here which will tell me that i have to repeat this string three number of times so i am going to repeat a over here this is the string generated after repeating 3 three number of times so aaa is a string and whatever string i have got i will just push that string onto the stack again then i will go to the next index which is two then comes opening bracket then comes b then comes c then again comes closing bracket so here or closing bracket came so i have to pop from the stack deny till i encounter an opening bracket so first i uh pop c so this c is popped then i see pop b so whenever i am popping the element right so i am going to offend that popped character onto the front of the string that was already created so we c was already popped then i uh pop b so i appended b to the front of this string then i encounter an opening bracket which means i don't have to pop any further elements apart from the one more time which will tell me how many times i have to repeat this string which i have created so this opening bracket is bob then comes two so i will keep 2 over here which will tell me x value is 2 so i have to repeat bc string 2 number of times which is bc and whatever string i generate i just push that onto the stack so what is the like we have reached the end of the input string so what is the final answer we are going to return vc bc and i will just append a aaa to the front right so this is one of the example i will explain it with another example that is mentioned in the question uh three a to c right so it's a good example let's try to understand using this example so first i'm going to push three i've started from here then comes the opening record i just push it then comes a i just push it two again opening bracket c then comes the closing bracket so whenever i encounter a closing bracket i am just doing two things basically i just pop whatever is present at the top of the stack till i encounter an opening bracket so i pop c from the stack then i encounter opening bracket so which means i don't have to pop further elements from the stack apart from one more time is for the case in which i am going to get the number to tell me how many times i have to repeat this particular string so i will pop this and 2c is the basically x value which i have received is 2 which tells me that i have to repeat c 2 number of time which is cc and whatever string i have created over here i will push it over again here cc and move ahead in the input string so i encounter another closing bracket over here so what i need to do over here is i just need to pop the top of the stack till i encounter opening bracket right so the top of the stack contains string cc this is popped now comes a so a is appended to the uh to this string which i have created so the string becomes acc this is also formed this is opening bracket is also popped and again i have to pop a number right so the number is three like whenever i encounter a opening bracket in a stack i can be rest assured that there will also be a number present below that because it's already mentioned in the question that an opening and closing bracket would always have a number k defined over here so x value is 3 which tells me i have to repeat acc three number of times so the string becomes acc that's the solution over here right let's see how we can code this solution uh i've already written the code for it in the c plus let's try to understand this solution so here i've created a stack of string right because i have to push the elements over here like it can be a character stack but i've created a string stack here so this stack of string has been created i am going to iterate over starting from the starting of the string till the end of the string using this for loop uh as of now let's ignore this if condition i will tell you why it has been used so what i am going to do over here is i am just checking if the current index in the string i am at right so i am suppose at this 3 so it is not an closing bracket right so if it is a not a closing bracket then i just directly push whatever is present on to the stack for that like uh it actually str of i is a character i am basically converting that into a string of length one using this string of length one and this particular character and i am continuing in the loop so i will reach again over here but if it is no if it is a closing brace which means i have to follow these two steps right i have to pop the elements till i encounter a opening bracket and i have to pop one element again so that i will get particular number right so that's what i am doing over here i am creating one string called temp that is used to basically create this string like which has to be repeated these number of times x number of times i'm creating a string called temp and while loop has been created over here so that i can continue pop popping the stack till i encounter an opening bracket right that's what we did over here because the top of the stack was cc right so we popped this cc from the stack then we again popped one of the elements on the stack a then i encountered this opening bracket which means i don't have to pop further arrangement from the stack so the value of this value acc is being held by this temp string and i am going to append whatever is present on the stack at the front of the string like i could have used str dot append but that would have appended to the end of the string i want the top of the stack element to be appended to the front of the string so that's why what i have done over here is whatever the current time string is i'm appending s dot top to the front of that m string and s dot pop is there right so when i'm basically leaving this while loop i have to pop the opening bracket as well so that's why this s dot pop has been taken over here right one of the things over here is uh yeah so after this opening bracket also has been popped i am pretty much sure that the next element present in the stack is a number right but i have created the stack of string right so i need to convert this string three into an integer so for that i am used an stl over here stoi the full form is string to i integer so whatever present value is presented at the top of the stack i am converting that to an integer in a variable x and i am just removing the top of the stack from the stack right and whatever value is present in the m string i have to repeat that temp x number of times so that's what i'm doing over here like i'm written a while loop and creating a new string called y and i'm repeating temp string x number of times using this loop so ultimately this a c whatever string has been generated right this string has been pushed again to the top of the stack that's what is being done over here right ultimately whatever value we have on to the stack so like when we are completely done the iteration over the input string so i need to pop the stack till the stack becomes empty right so in this scenario the stack was actually was uh not in this scenario in this in the first case the stack was uh like after we have completely completed the iteration over the string right so it was a and bc right so this is a stack at the stage when we have reached the final index but we need to create the final string as well so that's what is being done over here till the stack becomes empty we have created one in answer string and appending whatever is present at the top of the stack to the front of this answer string similar to what we had done over here and finally returning the answer uh coming back why this if condition has been used i will tell you one scenario where this will this approach will fail so that is suppose we have number suppose called 100 bc right so according to the current approach what we will do is we will push one zero one to the stack then push zero to the stack then again push zero to the stack then push opening bracket then c b and then c and then the closing bracket comes up we just pop whatever is present c b and like that right so this is not a correct approach because 1 0 these numbers have not to be considered separately like it's not individual characters it's a single number right so that's the check that i put over here like if the element that we are going to process in the iteration if it's a digit so this is digit is also an functionality provided by the c plus already present in the library so it checks if the num character that we are giving as an input to this digit function if it lies between 0 to 9 then it returns true so if it is a digit between 0 to 9 then i am basically accumulating basically creating one string of numbers so i start suppose from 100 this is the example right so i started from here i am basically creating one number out of this so one is a number then i go to this is also a digit so is this digit function will return true so i will append 0 over here and i come over here it is also a digit i will come append zero to this string right so finally whenever when i then i come over here it is not a digit so each digit function will return false so this is the string that i have generated right so this is what i am doing over here so this is the temp string right so whatever temp has been generated i am pushing that temp at once to the stack so instead of pushing this 1 0 what i will do is i will push 100 at once and then this like this and then i encounter a closing brace so i'm going to pop c b then opening brace i have got so i will pop that as well and x value would be 100 so i am going to repeat bc 100 number of times and going to return the value right so this is the code yeah let us try to run it's already tested anyways but let me submit it yeah run time and memory usage are on the bit lower side so we can think of optimizing this solution as well so when i go to the solution tab for this like you can search for the solution of this problem on geeksforgeeks as well so when i check that after having my own solution is that like they have created a stack of characters instead of string and they didn't had to use these stls over here like stoi like this right so that will basically so save a lot of time and uh yeah like you can go through those solutions as well because like this is one of the approaches that i felt uh is correct according to me but there are other solutions available for this problem as well which i feel like are much better so i would recommend like you go through those solutions and uh yeah try to learn from those solutions as well and one more thing is that like it's good that you try to identify the patterns out of the solutions of a problem so suppose this was a problem related to parentheses right so whenever a parenthesis problem comes up so we should have a fair idea that somehow stack can be used in these problems right so try to learn patterns out of the problem so that you don't have to you know remember each problem you can relate whatever problem you have solved in past to the problems that you are currently solving right so yeah keep on learning and i will see you next time with another problem of lead code thank you everyone
|
Decode String
|
decode-string
|
Given an encoded string, return its decoded string.
The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is being repeated exactly `k` times. Note that `k` is guaranteed to be a positive integer.
You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, `k`. For example, there will not be input like `3a` or `2[4]`.
The test cases are generated so that the length of the output will never exceed `105`.
**Example 1:**
**Input:** s = "3\[a\]2\[bc\] "
**Output:** "aaabcbc "
**Example 2:**
**Input:** s = "3\[a2\[c\]\] "
**Output:** "accaccacc "
**Example 3:**
**Input:** s = "2\[abc\]3\[cd\]ef "
**Output:** "abcabccdcdcdef "
**Constraints:**
* `1 <= s.length <= 30`
* `s` consists of lowercase English letters, digits, and square brackets `'[]'`.
* `s` is guaranteed to be **a valid** input.
* All the integers in `s` are in the range `[1, 300]`.
| null |
String,Stack,Recursion
|
Medium
|
471,726,1076
|
1,974 |
hey everybody this is larry this is me going with q1 of the biweekly contest 59 minimum no time to type word using special typewriter so hit the like button in the subscribe button join me on discord especially if you came in right after the contest come hang out and talk about problems i've been talking problems that's why the video's a little late anyway for this one it should be straightforward you can even um you know go up 26 go down 26 if you like when it brew first kind of way because and it's only a hundred but the way that i did it is just doing math right so this is basically you know you have this wrap around math and you're trying to figure out how to go either left or right and so yeah so this is just basically the formula and you can kind of work out why this is the case because um this is just treating it as going over um let's say you're going from uh z to a this means that treating z as oh sorry in this case it means that treating a as um you know the next a like a that is 26 or you know z plus one right so that's the reason behind the star plus 26 and then the star minus 26 is going the other direction right where you go from a to z well in that case you just treat a as um plus 26 and then going and then minus 26 to that direction um so that's basically the idea and you can do this in linear time but if you don't have this function that's fine like i said you can just do another for loop going up or down 26 and that'll give you all of ends length anyway um yeah that's all i have for this one you can watch me solve it live during the contest next it was kind of messy but yeah so initially okay that's not bad do so know what i want to do just coming up nope oh peter said okay that's just not right oh okay that was kind of annoying uh thanks for watching everybody hit the like button the subscribe button join me on discord especially if you like contest problems and stuff like that uh there are a lot of smart people there and also me so yeah um stay good stay healthy i'll see you next problem and to good mental health bye
|
Minimum Time to Type Word Using Special Typewriter
|
find-customers-with-positive-revenue-this-year
|
There is a special typewriter with lowercase English letters `'a'` to `'z'` arranged in a **circle** with a **pointer**. A character can **only** be typed if the pointer is pointing to that character. The pointer is **initially** pointing to the character `'a'`.
Each second, you may perform one of the following operations:
* Move the pointer one character **counterclockwise** or **clockwise**.
* Type the character the pointer is **currently** on.
Given a string `word`, return the **minimum** number of seconds to type out the characters in `word`.
**Example 1:**
**Input:** word = "abc "
**Output:** 5
**Explanation:**
The characters are printed as follows:
- Type the character 'a' in 1 second since the pointer is initially on 'a'.
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer clockwise to 'c' in 1 second.
- Type the character 'c' in 1 second.
**Example 2:**
**Input:** word = "bza "
**Output:** 7
**Explanation:**
The characters are printed as follows:
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer counterclockwise to 'z' in 2 seconds.
- Type the character 'z' in 1 second.
- Move the pointer clockwise to 'a' in 1 second.
- Type the character 'a' in 1 second.
**Example 3:**
**Input:** word = "zjpc "
**Output:** 34
**Explanation:**
The characters are printed as follows:
- Move the pointer counterclockwise to 'z' in 1 second.
- Type the character 'z' in 1 second.
- Move the pointer clockwise to 'j' in 10 seconds.
- Type the character 'j' in 1 second.
- Move the pointer clockwise to 'p' in 6 seconds.
- Type the character 'p' in 1 second.
- Move the pointer counterclockwise to 'c' in 13 seconds.
- Type the character 'c' in 1 second.
**Constraints:**
* `1 <= word.length <= 100`
* `word` consists of lowercase English letters.
| null |
Database
|
Easy
| null |
309 |
learned a lot I'm no longer a fool now this is best time to buy and sell stock with cooldown okay so if you're familiar with this class of problems there's several lead code problems that deal with timing the market right trying to determine what is the best time to buy and the best time to sell maybe you can sell and buy them multiple times maybe you can only buy and sell once whatever but the idea is about optimizing the total month amount of money that you can make right and intuitively that what does that mean that means you try to buy low and you try to sell high or if you're like me you buy high and you sell low but uh yeah intuitively it just means that you're trying to maximize you know that Delta between the price you buy and the price you sell now each of these problems usually have a unique constraint that makes the problem itself unique from the other buy and sell stock problems um but usually it's either going to be dynamic programming or a greedy approach right and that makes sense right greedy makes sense because you're greedily just trying to decide like if I can only buy and sell High Buy Low and so high then greedily I should try to buy as low as possible and then sell as high as possible right and then dynamic programming makes sense because there's this idea of like well the best thing to do here if I sell here well then what's the best time that I could buy before this right based on a system of transaction so these both seem like very um I guess obvious approaches um but let's determine you know which one of these or maybe there's something else that we're going to use to solve this problem so let's go ahead and get right into it so you're given an array prices where price is eyes the price of the given stock on the idea if you've done others uh stock trading problems this is very familiar find the maximum profit you can achieve you may complete as many transactions as you like buy one and sell one share of the stock multiple times okay so the constraint here is you can't like buy a million shares right you can't trade on a margin you can buy a stock and then you can sell that stock and then you can decide to buy again and then you can decide to sell again but you can't sell if you haven't bought and you can't buy something twice right so you either have a share or you don't have a share and I think that's a good enough thing to State as an observation either are holding a stock or you're not holding a stock okay so you're either holding or you're not holding and that will become relevant in a moment okay note you may not engage uh okay bye okay there's so there's one restriction that restriction is after you sell your stock you cannot buy a stock on the next day so why would that be problematic within the context of trading well you know maybe you buy and then you sell and then the very next day after you sell there's a cool down period where you can't buy again but it just so happens on that cooldown period day the price plummets right so plummets to zero and you realize oh wow you know this is a way under valuation of this stock intrinsically so I should buy today but you can't buy today because it's the cooldown day in the movie the next day it goes back up to uh 100 000 billion quadrillion so you missed out on your chance because you were stuck within that cooldown period so a cool down period is what a cool down period another way of stating what that is in terms of something that will make sense later is a period cool down is a day you skip we'll say that is a day you skip okay because on a cooldown period happens after you sell the stock right so you sell the stock so you're not holding a stock currently right because you sold it you're no longer holding it and you can't buy a stock so you basically can't do anything right the only thing you can do after you sell stock is buy a stock right so if you can't buy because it's a cool down you basically skip that day there's nothing you could do the only operation you could do that day is buy and you can't buy so you're essentially skipping that day so cool down is a day you skip right and I guess the third observation which kind of corresponds to this first one is if you're not holding all you can do is buy that's Buy if you're not holding the stock you have two options you can either Buy or continue not holding and all of this will make sense in a moment why I'm playing this weird game of trying to establish all these strange points right if you're not holding the stock what can you do on that day well you can either decide that you want to buy the stock that day or you can decide that you're just going to continue to not hold right you'll say I don't like the price of the stock today I'm just going to continue to the next day and maybe tomorrow I'll consider buying right and if you are holding what can you do you can either sell or continue holding right so those are the only things that you can do within this state right so if you're not holding you can buy or continue if you aren't holding you can sell or continue holding okay these are kind of all the observations you need to solve this problem and uh hopefully it's helpful in a moment so when we look at this example one two three zero two um so we have one two three let's draw this a little bit better so one two three zero two and we'll model this system as a graph right so these are each of our days within this period right and well I guess you know at any of these days you can decide to do a few things right you can decide that you're going to buy the stock and that's going to cost you money so on the first day you can decide that you're going to buy the stock and that's going to cost you one dollar so I'll correspond that to saying it's going to cost you negative one you gain negative one dollars by buying the stock or you can decide on the first day that you're gonna do nothing and that costs zero dollars okay you can decide to sell the stock on the second day buy the stock on the second day or do nothing so again you can buy the stock on this day it'll cost you two dollars if you bought the stock on this day it cost you three dollars if you bought the stock on this day it would cost you zero dollars and if you bought the stock on this day it would cost you two dollars and Gap similarly you could decide that you don't want to buy the stock on this day and you don't want to buy the stock on this day so it's neutral right basically what this is saying is like I look at this day and I say you know what I don't want to buy the stock to stay so cost me nothing I look at this day and I say I don't want to buy the stock and stays it'll cost me nothing I look at this thing and they say oh I do want to buy the stock this day so now it's going to cost me negative three and then the final thing you can do is sell the stock so if I sell it this day I get two dollars if I sell this day I get three dollars so this day I get zero dollars and if I sell this day I get two dollars so I guess the idea here is if you model the system as a graph you'll notice that this is a dynamic programming problem right in a dynamic programming problem where the days are vertices and the edges and their corresponding weights are the what they're the amount of the amount that you get or lose if you decide to sell or buy on that day the problem is though with this graph as well the system would say oh the optimal thing would be this path here and why is that well because we're not distinguishing between the idea of holding or not holding correct because this will say okay I'll just do nothing I'll sell but you can't sell if you haven't bought right because this first statement is saying you are either holding or you're not holding so that information of holding or not holding is not captured within this graph right this is basically saying at any vertices I can sell but I can only sell if what I can only sell if I'm currently holding right I can only access this green node if I'm holding right I can only access this red Edge right I can only access this green Edge if I'm holding and I can only access this red Edge if I'm not holding right I can only buy if I'm not currently holding and I can only sell if I am currently holding so I need to somehow capture that fact within this graph so that information is more clear that way I only can use this Edge if I've spent money at some point buying the stock so what we're going to do instead is slightly shift the way that we model this graph and the way that we'll do that is by removing these links and thinking about you know the states in terms of holding and not holding so either you're holding or your not holding seems simple enough so we'll copy this graph and then now we'll have States so that we know whether we're holding or not holding depending on the vertices that we're at so if we're up here that essentially means that we're holding the stock and if we're down here that means on that day we're not holding the stock so what can you do in the beginning in the very beginning you can decide that you don't want to buy a stock and that costs zero or you can decide that you do want to buy the stock so now you're holding it and that'll cost you negative one if you're holding the stock on day zero here what are the things that you can do well you can either decide I'm just going to continue holding the stock to the next day or I can sell the stock and Gain two dollars on a subsequent day if I sell and then if I decided to continue holding I could walk through that right I can continue holding I could continue holding through the whole system right to the very last day or I could decide to sell on every day right if I'm here then I can sell and I'll get three dollars if I sell here I'll get zero dollars if I sell here I'll get two dollars and if I sell here this will have to be determined in a moment because there's a little bit like most dynamic programming problems right on the edges your recurrence relationship isn't as obvious right versus when you're dealing with you know this the central components to your recurrence relationship makes more sense right like here this isn't pointing the there's no node here and then on this day there's nothing that this points to even though I could technically sell on this day so we'll think about that in a moment okay now let's think about in terms of not holding what can I do if I'm not holding well I can either decide to buy right I can either decide that I'm going to buy the stock for two dollars negative 2 because I'm going to lose two dollars from buying the stock at this day or I can continue to not hold so I cannot hold through the whole system again so it's the same rigamaroo or on each of these days I can decide to sell I mean I can decide to buy because I'm not holding if I'm not holding all I can do is buy or continue not holding so if I buy here it cost me negative three if I buy here it costs zero if I buy here it costs negative two I bought here I guess it would cost I'm not sure we'll think about that again in a moment so this is a classic form of another buy and sell problem right because you're capturing the idea of holding and not holding that way these edges are only accessible if you're in the right state right the problem before was that I could continue to just sell but now that we've you know kind of separated this graph based on holding and not holding and this kind of idea of modeling your system as a graph and then thinking about States can be really useful and intuitive so I definitely recommend that you approach the problem in this manner if you get stuck and you're confident that the problem is dynamic programming right so I'm breaking it up into States and then the edges become clear right because the problem before was that I could continue selling because I didn't make the distinction between holding and not holding okay so now that we're in this state there's a small caveat which is what well you know our second point was if is you know a cool down is a day you skip right the cooldown is a day that you're skipping trading right because the cooldown basically means that you just sold and you can't buy so if you just sold you're not holding and if you can't buy there's nothing you can do but continue to um halt there are not hold so the problem here is this is basically saying okay I could buy Here Sell Here I could buy again here that's not right because if I sold here I can't buy on this day right because I buy here this would become a cool down day I mean sorry if I sold here this would become a cooldown day so I'd have to skip this day right if I sold here this would become a cool down day and I couldn't trade again to the subsequent day so really what happens here is well these links are different right if I decide to sell that's identical to skipping a day right if I decide to sell here I don't get to um what I don't get the to make a decision on the subsequent day because it's a cool down day the cooldown day is I'm taking a break I'm cooling down I'm taking a day off from Trading so I'm not going to get to buy right so since I sold this day I'm actually gonna have to skip a day right so now I have to skip a day I still get two dollars right but I don't get to make a trade on that day since I've decided to sell on that day so since I decided to sell on this day I'm not going to get to trade on this day so now I get the two dollars but I have to skip that trading day hopefully that makes sense right because the idea of a cool day is that you're skipping a day right so I took the cool day by selling but now I can't buy for a subsequent day okay and that means that all of these then I get three the only weird thing is it's no longer the value of the edge I'm pointing at it's the value of the edge that comes before it right I get two but I have to skip that day and the next day I can start trading again is day three so for this solution if we wanted to walk through the problem you're gonna first day I guess you're gonna buy okay then you're instantly going to sell you have a cool day so you have to skip this day you're gonna buy again and then you're gonna sell so you get another cool day where you have to skip day two so what's the total of this where you get negative one plus two is one minus zero plus two is three so now you see how the system works using this idea so basically what we did is we just used this idea of holding and not holding to make a decision about what you can do since you're only either holding or not holding each of the days you're either holding or not holding so if all the days are states there's states where you're holding on that day and there are states where you're not holding on that day and then we thought about what you can do if you're holding or what you can do if you're not holding so in those cases if you're not holding what can you do you can either continue not holding or you can buy if you are holding you either continue to hold or you can sell and then we just caption the fact of a cooldown since there's a cool down period when you sell you actually end up skipping a day because you rest you cool down on that subsequent day so this is then the system model in the graph so if we think about this in terms of the edges in the recurrence relationship right here right what is this in terms of what comes before right the value you get from holding on a day I'm gonna call it h for holding equals the maximum of either you decide to continue holding from the previous day or the value you get from not holding on the previous day Plus the price uh the price or you lose the price on the current day so we'll make that red so I'm gonna try to make this clearer by using different colors so basically What's Happening Here is I'll go through each of the terms individually so the maximum value I can get holding on some certain day this was the day I can either continue holding from the previous day so whatever this maximum value is from the previous day I can or I can take this Edge which corresponds to not holding on the previous day and then I have to spend the money to buy in order to buy on this day okay now what is not holding for any value well for this value say the same day right so if you're not holding on a day what does that mean in terms of your recurrence relationship well it's just based on the nodes that you can access right so same to you here I can either decide to continue not holding and get whatever value I get from that system there so this is the max of not holding on the previous day or I can decide to sell two days before right because this is the day minus one this will be the day minus two so I can decide to get the value that I would get from holding from two previous days right so minus one minus two because I had to take that rest day so that rest day is captured here and then the value I would get is the price at the previous day right here you get two three this is two right here is even though zero value you get would be three from this previous day so I'd get Plus price at the previous day so that's your recurrence relationship in this problem right so I guess the first thing is right the recurrence relationship kind of breaks down right so the first thing is we can just default here right we could say the holding at Day Zero is the value of that day the cost of the stock at that day and not holding at zero is zero because the only thing the only way you could get here is by deciding not to buy right versus in these other states you have options so that's something to think about okay and with that let's go ahead and try to start uh drawing out the solution so we'll say holding and not holding we'll just create them at default dicks all right and then we'll say holding at Day Zero you would get the value it would cost you negative the price is at zero right because if you're holding on Day Zero you had to spend prices at zero dollars and or units or whatever currency you use in order to get that and if you're not holding at Day Zero the best you could get is by not purchasing anything you have no other option if you're not holding on day Zero that means you didn't buy day Zero so that cost you zero so we'll look at each day in range one to length of prices plus two so why did I put plus two here well let's see if it's plus two the problem is well you know I could decide to sell on this day but I could also decide to sell on this day so there's two additional States I think no there's only sorry I'm trying to think about how it's supposed to work there's only one additional state right because this Edge actually corresponds to selling on this day but you have to skip it now since you decided to sell on that day so there's one extra State here at the end if that doesn't make sense just look at this relationship and decide well the last day I could actually sell is this day because originally that would Point here right if I decided to sell on this day um but now I have to skip it because well of course because um we have to skip a cool down day there's a cool down day hopefully that makes a little bit of sense all right so now we just base it off our recurrence relationship here so holding at the day equals holding at the previous day so I'm just going to directly put in this information and the prices of the day okay so holding at this day equals the maximum of deciding to hold on the previous day or we could decide to not hold on the previous day and buy at this day which is going to cost us the price at the current day does that make sense the problem is that this could end up being larger than length of prices because at the end it will be so maybe we'll just say times and day less than length of prices it's kind of ugly but it just makes it a little bit easier but then you'd have to multiply that also by the prices whatever that's fine okay and then not holding on a day because this right this could be outside of the boundary you decide to not hold on the day you either can not hold from the previous day or you sold two days previously so not holding on the day equals the max of not holding on the previous day or you were holding two days ago and you get the price from the previous day as a response right is that right sorry I'm starting to get tired because it's getting late and I'm right I either decide to continue not holding or I sold two days ago so I get the price from yesterday so I sold two days ago because I was holding two whatever I got whatever the max amount of money I could have holding two days ago plus the prices from yesterday because that'll be the money that I get and at the end I would just return not holding right because not holding at uh on the last day okay so um I guess one thing about this problem is like many dynamic programming problems I'm foolish and I did something wrong oh gosh one should be zero is it linked to prices no plus one it should be plus one but then why is one giving me okay so not holding on day one well this is day Zero uh so if I bought here on one not holding zero on day one would be not holding on one not holding on the previous day would be zero holding two previous days the problem is that this is uh because the previous day yikes man what am I doing wrong here okay so let's think about this in terms of one element yikes man I apologize so one you can either decide to sell it or do nothing and I could sell it here and I could get one or I could continue doing nothing so when it gets to one yikes I guess because day minus two is it's not existent right so if I set this to negative Infinity promise it's trying to reference a day that's like back here but there's no day back here so you can't do that so maybe that'll fix it try to get cute and then everything messes up to see how it goes why is it still saying one all right there we go so the thing is we're going to fix this right now I'm sorry that I got the little bug right because if you can't like there's like certain edges in this the way that I have this recurrence relationship set up that you're like basing things off things that don't exist so it shouldn't return zero it should return negative float Infinity to basically specify that this can't exist so don't try to use this as a solution and that's why we encountered a problem here uh but what you'll notice here is that everything's based off of previous days so we don't actually need to keep track of the whole system right it's not like this information is important at this point so I'm going to quickly turn this into a constant space algorithm by getting a little intelligent about how we're going to do this so what I'll do is I'll just use holding and not holding and preve holding okay so I can use these three constants and I can say well holding out a day is the maximum of holding at the previous day not holding the previous days not holding minus this times this okay not holding now is what not holding used to be this would be prev holding at the previous day okay so maybe these should be no because I'll be the value of the first day I'm really screwing up here today guys um all right but then this would need to be done all on the same line that way it's all based off the previous States and then previous holding will just become what holding was before and then the best you could get is whatever not holding is at the end ah come on so I'm basically just taking something that's linear space and turning into constant Space by keeping pointers of the corresponding vertices we need for any compute but I'm worried that there's still going to be that issue of yeah when the length is one so what is called previous holding float negative infinity and I think that'll fix it because previous holding will only get populated once you've yeah okay so there you go so now you've turned this into constant space and you can technically also make this sorry uh three line solution I apologize guys I kind of lost my momentum there at the end hopefully there's some stuff you learned at least the graphic was good but my code was bad because you know there's edge cases with this system right one thing to always think about when you're solving these problems is like just because your recurrence relationship works in the center there can be weird edge cases at the end that you need to think about and you can either split up your cases right you could figure out manually those first cases and then for the meat of it do some standard recurrence relationship and then figure out the values at the end right and then think about you know smaller cases where there's just one thing or two things or whatever or you can just kind of have code that has a general approach where it captures all those edge cases by you know um by creatively setting your initial variables okay so with that said what is the run and space complexity of this problem well let's say n is the number of stock so that you could buy for time well setting this is constant time right it's just three variables that you set and then you're going to look at each day right proportional to the number of days you're going to look at each end days and then you're just gonna do a constant set of operations right you're gonna it's a constant operation to find the max between two things it's a constant operation to find you know the max of two other things and it's a constant operation to set the previous holding value to the current holding value right that's all constant so for All N Things you do something constant this is constant you do n constant things and then you return something which is constant so constant plus n times constants some constant plus constant is just o of n okay for space well we create these three variables and regardless of the number of days that we have we just continue to update these three variables so if there was a million days worth of prices or two days worth of prices we'd always only have these three variables so that's why it's below 4. so essentially what I did is I took you know this recurrence relationship and basically said well you know we could have a case where we keep track of everything but you only really need to keep track of what right for any generic graph right the only thing you really need to keep track of is you need the track of this which is the holding value you need to keep track of this which is the not holding value and then you need to keep track of whatever holding was before right and for those three things you can calculate any you know additional link or whatever Okay so again I apologize for the loss of momentum at the end um that just goes to show that maybe it's not always the best case to try to capture everything in your variables and split it up into like okay for the first values this will be the recurrence relationship for the values in the middle right this would be the current relationship for the last values this will be the record relationship and then just do it like that but this is short and shorter's are short is cool unless you're playing basketball peace out
|
Best Time to Buy and Sell Stock with Cooldown
|
best-time-to-buy-and-sell-stock-with-cooldown
|
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:
* After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).
**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
**Example 1:**
**Input:** prices = \[1,2,3,0,2\]
**Output:** 3
**Explanation:** transactions = \[buy, sell, cooldown, buy, sell\]
**Example 2:**
**Input:** prices = \[1\]
**Output:** 0
**Constraints:**
* `1 <= prices.length <= 5000`
* `0 <= prices[i] <= 1000`
| null |
Array,Dynamic Programming
|
Medium
|
121,122
|
1,877 |
hello and welcome to another video in this video we're going to be working on minimize maximum pair sum in an array and in this problem the pair sum of a pair is equal to a plus b and the maximum pair is the largest pair of all the elements of all the list of pairs and you're trying to basically minimize the maximum pair in this list so you have to pair up every two elements and you're trying to pair it up in a way where the maximum pair is minimized so for example here they pair three and five and two so you get seven second example pair three and five four and six and two so the maximum pair is eight and so when we figure out what algorithm to use for this problem like obviously this one's pretty easy but let's kind of go through the process so first thing we're going to look through the constraints so n is 10 the 5th that means that we can't have like a backtracking or brute force or anything right we have to have an N log in solution or better or a two-dimensional uh two-dimensional two-dimensional uh two-dimensional two-dimensional uh two-dimensional solution but the second dimension has to be pretty small because n^2 would fit be pretty small because n^2 would fit be pretty small because n^2 would fit fail because I think on Le code like 10 the 9th or 10 the e or something fails so anything above that would fail so we are left with something like some kind of DP where our second dimension is small maybe like a two-pointer uh Heat Binary search things two-pointer uh Heat Binary search things two-pointer uh Heat Binary search things like that right and so when we also look we are trying to maximize something so typically when we try to maximize something DP is pretty common but like I said it's kind of hard to figure out like what's another dimension like we'd have to have an index for both the pairs or something and that's kind of difficult like it's going to be very hard to have like a one dimensional so DP is like probably not it now as far as Heap and binary search so you could try to figure out like you could have one thing and you could try to like figure out like let's say I take this number and figure out like what's the best pair for this is there any way to binary search or Heap well let's just think about our sorting or not our sorting are actual pairs like what makes sense to do with the pairs so let's say I have the biggest numbers right let's say I have a bunch of numbers like uh a b c d each is greater than the next so for the biggest number how would I want to maximi like minimize the pair there well I'd probably want to get the biggest number and add it to the smallest number right pair those up and then get the second biggest number and pair it up with the second smallest number and so on so that would ensure my pairs are you know small or as small as I can be it's kind of like a greedy is greedy two-pointer approach and now we greedy two-pointer approach and now we greedy two-pointer approach and now we basically have to figure out like is there anything wrong with that well all we have to do is keep track of like the biggest pair right we don't care about every pair we have we just need to maximize or minimize the biggest pair so we can just keep track of the biggest pair and things we used so what we could do is we could do something like I said we can't really do DP so we can kind of do like a two-pointer but the kind of do like a two-pointer but the kind of do like a two-pointer but the two-pointer the way we're going to do it two-pointer the way we're going to do it two-pointer the way we're going to do it is we're going to sort the array first and that's fine cuz we can have an un lend solution so we're going to sort and then we're just going to have a two-pointer from the start and the end two-pointer from the start and the end two-pointer from the start and the end right so if we have a bunch of numbers like let's just say we have something like this so we have five six let's say we have uh 1 2 3 4 5 6 seven eight numbers then we can just say like okay well let's just pair the biggest element with the smallest and let's move the pointers in let's pair the next two and let's pair the next two because if we're concerning if we're concerned with minimizing then if we pair the eight with anything but a one we'll have a worse result right so it turns out like the and basically the this is kind of like the greedy is where at every single number we just do like what's best now and then for greedy you basically have to check like did what I do kind of work out and so it does work out for this problem where essentially whatever number you have you start from the end you just pair it with the smallest one you have available so we literally just have a left pointer and a right pointer we pair the them together and then we move them in and we can just keep track of like the biggest pair right with some variable like result and we'll just try to maximize well we're not going to actually we are going to maximize the result we'll just keep all the pairs and then whenever we have a pair bigger than our older one all we have to do is keep the maximum pair and that's basically it so essentially we're going to sort and then have this left and right pointer and pair things up like this so one and eight 2 and 7 3 and six and so on and you can kind of get a little intuition from these problems but so we did eliminate a lot of things from the constraints right cuz if like if it was like you know let's say 20 then maybe we could just do like a Brute Force right or something like that but because the number is Big we know that we can eliminate some things like DP you know and things like that um so yeah and then another common one for a big uh a big size is like sliding window but obviously we can't really do a sliding window cuz we're trying to like if our goal is to pair things with the biggest and the smallest it's not really a sliding window it's more of like a two pointer but two pointer and sliding window are also very similar right so there is another solution here that's actually a o n solution but I think in the general case is going to be worse and the idea of this is kind of like we did in the problems in the past recent few days is instead of sorting you can because num's I is 1 to 10 the 5ifth we can instead record every single number and the count of it that we have in the array so like for 3523 for example I'll just briefly talk about this one we're not going to code this up because in general it's going to be worse so for 3523 we're going to say like we're just going to go through this and we'll say like two has a count of one three has a count of two and five has a count of one then maybe we can also record like the biggest and smallest number we found and we're basically going to Loop starting at the bottom and the top right so we'll say like okay well let's just keep looping until we have numbers smallest number is two and the biggest number is five let's take those counts and then depending on those counts we can make a pair right so we'll say like okay two and five can make a pair and then we basically can't we can't sort so we don't know like what other numbers we have so then what would happen is when we make a pair here then we'd have to manually like try other numbers like we'd have to get the smallest number and manually try like oh it's three in here yes it is okay and for the biggest number is three in here yes it is but this is going to be really bad really fast like let's say your numbers are like one two uh 100 and then like 10 to the 5th or something then this is going to get really bad really fast right because one will have one two will have one 100 will have one and 10 to the 5th will have one and basically the problem here is you don't really know what number comes next or yeah you don't really know what number comes next like you can keep track of the keys but the problem is you can't keep track of the keys in a sorted order right cuz your array is not going to be sorted to begin with so you basically have to manually like once you use up this one and 10 to the 5ifth because you kept track of those as your bounds you don't really know what the other numbers are in here because they're not in a sorted order like it could be like this or it could be2 so you can't just Loop through the keys in some order right so basically what you're going to have to do is you're going to have to manually go up like one number at a time and go down one number at a time until you hit the numbers you're looking for and as you can see this is only an array of length four but it's going to get very expensive because you're going to have to manually like go down 10 - 1 - 2 - 3 to manually like go down 10 - 1 - 2 - 3 to manually like go down 10 - 1 - 2 - 3 until you get to this so that is technically an m n plus M solution where n is the length of the array and M is the constraint of the problem like the biggest and the smallest number it's going to be like biggest minus smallest number so for some specific cases like imagine you're a race 10 the 5ifth long and has almost every number for those cases it would basically be an oen solution but for anything else it can get really bad so that's why we're not going to code up this one we're just going do the Sorting one also the Sorting one is obviously a lot more straightforward so let's do that so first we're going to sort our numbers then we're going to have a left and a right and it's just going to be zero and length numb minus one right the first and the last number and we'll have a result so we can call this like biggest pair or something right instead of using result all the time okay so biggest pair and now we can just say like while left is less than right biggest pair equals Max of biggest pair and uh nums right plus nums left and then we will decrement uh or we'll increment left and we'll decrement right so we're going to get every single pair keep track of the biggest one and return the biggest pair and I'm should do it so let's see okay and we have a solution that works and it's pretty good okay um so let's talk about the time and space for this one so essentially for the time and space so for the time it's and log in right because we are sorting and for uh for the space it's going to be o1 because we don't need any other like data structures or anything we just have a left and a right pointer um and yeah I think that's going to be pretty much it for this one pretty easy problem honestly for a medium problem it's kind of closer to an easy problem as long as you can realize the best way to make the pairs where you just pair the biggest numbers with the smallest ones um and yeah that's going to be it for this one hopefully you liked it and if you did then please like the video and subscribe to the channel and I'll see you in the next one thanks for watching
|
Minimize Maximum Pair Sum in Array
|
find-followers-count
|
The **pair sum** of a pair `(a,b)` is equal to `a + b`. The **maximum pair sum** is the largest **pair sum** in a list of pairs.
* For example, if we have pairs `(1,5)`, `(2,3)`, and `(4,4)`, the **maximum pair sum** would be `max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8`.
Given an array `nums` of **even** length `n`, pair up the elements of `nums` into `n / 2` pairs such that:
* Each element of `nums` is in **exactly one** pair, and
* The **maximum pair sum** is **minimized**.
Return _the minimized **maximum pair sum** after optimally pairing up the elements_.
**Example 1:**
**Input:** nums = \[3,5,2,3\]
**Output:** 7
**Explanation:** The elements can be paired up into pairs (3,3) and (5,2).
The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7.
**Example 2:**
**Input:** nums = \[3,5,4,2,4,6\]
**Output:** 8
**Explanation:** The elements can be paired up into pairs (3,5), (4,4), and (6,2).
The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8.
**Constraints:**
* `n == nums.length`
* `2 <= n <= 105`
* `n` is **even**.
* `1 <= nums[i] <= 105`
| null |
Database
|
Easy
| null |
242 |
hello guys myself Amrita welcome back to our channel technosage in today's video we are going to solve lead code question number 242 that is valid anagram so let's get started let's first understand the problem given two strings s and t return true if T is anagram of s and false otherwise so basically you will be given two strings one is this and another one is T you need to check whether T is anagram of s if it is anagram of s then you need to return true if it is not an Enneagram of s then you need to return false so firstly you need to understand what is anagram is a word or phrase formed by rearranging the letters of a different word typically using all the original letters exactly once so if T contains the same number of characters as s then it is an anagram otherwise it is not an anagram so the order could be different but both the strings should contain same number of characters with the same count so in the next example you can see hat and car both the strings are different because they have different characters so the output should be false in this case now let's understand how we are going to solve this problem so let's take the same example we have two strings the first one is anagram and the another one is also anagram but in the different order n a g a r a m right so now let's say if I update the count of each character so in this particular string a is occurring three times then n 1 g 1 r 1 and M is also 1 right so this is the count of characters and then I check in the string p n is occurring 1 a is occurring 3 g 1 R also of Curves 1 and M also occurs one and then I check if the count of all the characters in The String s and t matches then I can say it is the nanogram and I can return true otherwise I can return false right but the problem is how we are going to update the count of the characters let me first remove this so totally how many alphabets we have 26 right so we are going to take one array from 0 1 2 up to so on 25 right so 26 letters that means 0 to 25 and then character by character we are going to update the count so we'll scan the string s we'll see string a so for string a we are going to update the count as 1 but how we are going to check whether we need to update the count at the zeroth index so for that we are going to use S Chi values so each character in the alphabet has its own Sky Value starting from a 97 B is 98 C is 99 up to so on Z has 122 how we are going to increment the count we'll say count amount of s dot character at index I minus character a so that means what is the first character a minus character a so what would be the Sky Value 97 minus 97 it would become 0 so at the zeroth index we need to update the count move on to the next character that is n so similarly here we need to do n minus a so Sky value of n is 1 0 minus a Sky value of a is 97 so it becomes 13 so that means at the 13th position we need to update the count as 1 then move on to the next character again a so a means a minus a that becomes 0 again at the zeroth index we need to update the count as 1. similarly for all the characters we are going to update the count so count of a becomes 3 n becomes 1 some somewhere here it would be G so G also becomes 1 similarly for R and M so there would be 12th index that would be M character so it would become 1. once we update the count of all the characters for the string s when we are scanning the character T we are going to decrease the count for example n was 1 so now n becomes 0. M becomes 0 g becomes minus 1 that becomes 0. similarly when we are scanning a will come three times so 3 minus 1 then 2 one more one came one minus 1 it becomes zero and at the end we are going to scan this complete array if all the values are 0 that means there is no character left with count 1 so that means we can return true these are anagrams if all the values are 0 if any value is 1 then that means it is not an anagram of string s so in that case we are going to return false so this is how we need to solve this problem now let's write the solution for it so this is our class that is value anagram now let's write the method that would be public static Boolean because it is going to return true false is anagram string s and string t right and then firstly we are going to check the length of both the strings if length itself is not equal then it cannot be an anagram right so we can say in m is equals to s dot length and in 10 is equals to T dot length and then let's check if m is not equal to n then we can directly return false else firstly we are going to take one count array of length 26 since we have 26 alphabets and then we are going to scan the first array from 0th till the length I plus and then for each character we need to update the count using the sky values that would be s dot carat I character a plus since we have to increment the value once we update the count of all the characters of string s then we need to scan the another string that is T I less than n i plus and this time we have to decrease the count so that we can make the count of each character as 0 so it would be count T dot carat I minus a minus once we decremented the count so now we have got the count of each character in this array so we are going to check for in times equals to 0 I less than count dot length I plus if any value is not 0 count of I is not equal to 0 if any count is 1 2 or 3 then that means it is not an exam we have to return false otherwise we have to return true correct now let's call our function so let's take first two string guesses anagram and string T is also anagram but in the different order so it is Naga r a m let's write a print statement to call the function is anagram s comma T now let's run the program and see the output so the output is true now let's take another example that was red and car A and R are same but T and C are different so let's run the program and see the output so the output here is false so this is how we need to solve this problem if you have any questions any doubts please let me know in the comment section also provide your feedback in the comment section don't forget to like share and subscribe our Channel thank you for watching
|
Valid Anagram
|
valid-anagram
|
Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** s = "anagram", t = "nagaram"
**Output:** true
**Example 2:**
**Input:** s = "rat", t = "car"
**Output:** false
**Constraints:**
* `1 <= s.length, t.length <= 5 * 104`
* `s` and `t` consist of lowercase English letters.
**Follow up:** What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
| null |
Hash Table,String,Sorting
|
Easy
|
49,266,438
|
264 |
okay so we have ugly number two write a program to find the nth ugly number ugly numbers are positive numbers whose prime factors only include two three and five so this is a continuation of ugly number i just did a video on this i'm gonna link it up here if you guys haven't already watch it we're actually going to reuse some code for the brute force method this video is actually going to be longer because i'm going to go over the brute force method first and then we're going to improve it because brute force method is i mean it's not that good but it yeah you'll see so they want us to return the tenth ugly number so we have one two three four five remember it skips seven because uh seven has a factor of seven which is not included um in these numbers eight nine ten eleven you skip eleven and twelve so twelve is the tenth number and that's what it returns so if we're doing a brute force method we would just have we would do the same thing we did in the first part of ugly number and we would just keep a count so let's hit the count equal to one and if n is equal to one so this is like our base case we just return count and then we're going to have our answer which is what we're gonna turn let's just initialize it to zero and so for this one we're just going to want to check every number and we're going to use the method that we used in the first one but we're going to check every number so we're performing all these calculations for each number until we reach the count so let's go ahead and implement that i less than uh n yeah okay that works and so i'm just gonna copy this basically um so if you guys remember in my other video basically we're just dividing the number as much as possible by the prime numbers that the require for it to be a ugly number and so we're going to come up to if num actually no we have to use a temp we can't change num um and let's see uh oh no this is just so let's use num here that'll make it easier oops and all right so we're gonna have a temp and it's gonna be equal to num so this is what we're gonna change um because we can't we have to be able to set the answer later on if n equals count so this is where we're checking let me update all these real quick and okay so we're doing the exact same thing and then we're gonna see if uh if no this is wrong if temp equals one then we know we have a ugly number so we're going to increment the count first and then we're going to see if count equals n then that's our answer so if count equals n then answer equals num so num isn't changed yet that's why we had to use the temporal temp variable and we're going to break out of the for loop and then i believe it's here we're going to return answer so this should work for the brute force did something wrong okay guys i figured out what i was doing wrong this needs to be count because we need to we're going to be looping through until count is equal to n i was making a mistake i was using num that doesn't make sense because num could be incremented even if um even if we don't increment count even if it's not an ugly number so it would reach n before we reach the correct count so that's what was wrong so i'm going to show you guys this one actually times out because it's just not efficient enough it works it just doesn't work for extremely large numbers so we need to improve it see it times out at 13.52 so i think it see it times out at 13.52 so i think it see it times out at 13.52 so i think it reaches something like 1000 and then it stops working so we need to improve it and okay sorry about that somebody knocked out my door so let's jump back to it i believe i was on the indexes i just filled in all the indexes so that's just i this is the our array of ugly numbers and we have n equals 10 we're doing the example on the in the problem so um what these numbers over here these i2 i3 i5 represent is when we're calculate we're calculating the next ugly number so we're going to calculate 2 times i2 these are all going to start at 0 referring to the 0 index right here so we're doing 2 times 1 and 3 times 1 and 5 times 1 those are the ugly numbers but we want to calculate the math.min of all the math.min of all the math.min of all three of them so let's do that i'm going to fill these in and hopefully it makes more sense as we go through the problem so after we calculate it we're going to set ugly equal to numbers of i and then we're going to have uh if statements we're going to see we have to increment the i2 i3i5 when we when the number equals it so for example if ugly equals nums of i2 times 2 then i2 is incremented and that's gonna go for all three so i'm just going to do dot they're the exact same statement except they're times three and times five so i three plus i five plus um so let's go through this real quick so we have the first what is the min of this statement it's obviously going to be two times one it's less than three times one or five times one so let's fill that in so this is two and we need to increment this so we get i2 equals one and then let's go through what is the next min it's obviously going to be three times we're still at the zero index for i3 so it's going to be three times one so plus one and this is three so the next is going to be two times the index of one which is two so two times two equals four we need to increment this again and this is two i was about to write four um so what is the next it's obviously going to be five times one so we get five let's increment i5 and now here's a interesting example um if we do the index of 2 which is 3 times 2 we get 6. if we do the index of 1 which is 2 times 3 we get six so they're both six um so that means both of these statements are going to execute we're going to have to increment both that's at the same time we want to keep i3 up to date because if we skip it we're gonna i mean our array is just not going to come out right um so we're going to have 6 and we're going to increment i2 and i3 and let's just keep going so um what's important to see here is since we're not doing seven times i7 we're never going to calc uh add seven to the ugly numbers array so that's important to see um i believe the min of the next one is 4 times 2 yeah so it would be 8 and then so plus 1 equals 4. i'm not going to finish well i mean we might as well so we have 3 times three is nine and then we have five times or i wrote five jesus one so we have uh two here times five is ten and then the last number is going to be twelve and this is again one where we need to increment i2 and i3 because we have the index of 4 which is 5 times 2 oh i needed to increment that too because that comes out to uh 10 4 times the 5 times 2. so then we have the index of 5 which is 6 times 2 is 12 but that also occurs for the index of i3 so 4 times three gives us 12 so and so on and that's all i'm going to do so let's code this out now um i know this video is going to be long that's why you guys should stay till the end hopefully so let's create our array of nums new and uh 1690 because we need to pre-compute all n for n pre-compute all n for n pre-compute all n for n um so we know nums of zero is one and so now we need to let me think we need to initialize our variables equals zero so i'm just going to set into ugly equal to zero and i five equals zero okay so now we just wanna loop through and pre-compute everything um so into i equals 0 i less than 1690 i plus show um numbers of i equals we're going off the code that i wrote hopefully it's in the right order of numbs of i2 times two and the names of so ugly equals uh nums of i so we're grabbing the ugly number and then this is where we're going to write our if statement so if ugly equals numbers of i2 times two don't forget to times two then we're going to increment i2 and let me just copy these over to save time and um i believe that i feel like we're missing something we just want to return n minus one because it's zero index and let's see if this works the input one thousand expected oh that's yeah so we gotta start at one because we already said nums is zero equal to one okay so this works this is the dynamic programming um solution to this so i hope this made sense i hope the explanation helps let me know what you guys think if this helped or what i could do better in the comments below if you have any questions like responding to your answers and smash that like button if this helped subscribe if you haven't already i'll be posting videos almost every weekday so that's all i got for you guys i'll see you in the next video
|
Ugly Number II
|
ugly-number-ii
|
An **ugly number** is a positive integer whose prime factors are limited to `2`, `3`, and `5`.
Given an integer `n`, return _the_ `nth` _**ugly number**_.
**Example 1:**
**Input:** n = 10
**Output:** 12
**Explanation:** \[1, 2, 3, 4, 5, 6, 8, 9, 10, 12\] is the sequence of the first 10 ugly numbers.
**Example 2:**
**Input:** n = 1
**Output:** 1
**Explanation:** 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
**Constraints:**
* `1 <= n <= 1690`
|
The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3. Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
|
Hash Table,Math,Dynamic Programming,Heap (Priority Queue)
|
Medium
|
23,204,263,279,313,1307
|
1,025 |
welcome back do you have this problem it's called the officer game it's been asked by Adobe and Bloomberg and Amazon um the problem is and pop tick turns and play in turns playing a game with Alice starting first initially there is a number called in on the uh chalkboard on each player's turn the player makes a move consists of choose any x with its X should be less than n and bigger than zero and n divided by in moderate by X should equals to zero replacing um replacing the number in on the chalkboard with n minus X also if a player cannot make a move they lose the game it'll turn true if only and only Alice wins the game assuming both players play with optimal solution okay so um let's think about this one so um let's just take a minute to think for this one first so first of all we can choose any X and this x will be less than n and also X modded by n should be add up to zero also when replacing the number in on the chalkboard within where we will replace the number within minus X so if we have n if we have this n equals 2 we should return true because LS could choose one because it's the optimal one and Bob has normal moves because Bob can do anything for this one we have three Alice could choose one and Bob also so Bob would could take one because and after that Alice has no moves so at least lost so how you can solve this problem I guess a little think about something that the only solution for Alice to win is if in it's this is the only solution if in model by 2 equals to zero like in add up to uh two this is the only thing all the only uh this is the case is the Alice can work can win it and this is a trick actually if you just recognize this one the problem is pretty easy if you don't recognize it the problem will be really hard so what you should do with that first of all we could create an array let's call it a DB which will equal array of n plus 1 and I will fill it with false okay and after that I will make a loop and by start from one because we can all we only want to reach one and I will say um I less than or equals n and I plus so for each one what I'm going to do I'll just create an array to check each number and I'll return the number of the N because here it is each number is built up on the its previous one so let's just try to do it so the DB of n will equals in modeled by two equals 0 and this is the true false so it should be true or false so we'll continue to Loop until uh until we reach the end so we and also we return DB of n directly so by this one it's just as simple as that it's really simple but just you have just to know the trick so we create an array the race will be the length of n so let's just take this an example if we create an array and it will be the length of lamb plus one so it will be three and after that you will have your sort from the first one and you see DB of N and DV of n should be at the last element basically and it will be equals in multiple two equals zero or not modeled by two equals uh with the motor operator modeled by two equals zero or not and it will be true or false after that I will return it and for each number and uh for each number we're just trying to do it like that so when we reach the end it will be a true false so um yeah that's it for this video and I hope my switch was quite good and it's a pretty mathematic things and actually that the panthematic problems are pretty famous these like in the last two three months I don't know why but they are just they are famous so that's it for this video I hope my social was quite good if you like my content make sure to subscribe and hit the notification Bell so you never miss a video and see you in future problems
|
Divisor Game
|
minimum-cost-for-tickets
|
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of:
* Choosing any `x` with `0 < x < n` and `n % x == 0`.
* Replacing the number `n` on the chalkboard with `n - x`.
Also, if a player cannot make a move, they lose the game.
Return `true` _if and only if Alice wins the game, assuming both players play optimally_.
**Example 1:**
**Input:** n = 2
**Output:** true
**Explanation:** Alice chooses 1, and Bob has no more moves.
**Example 2:**
**Input:** n = 3
**Output:** false
**Explanation:** Alice chooses 1, Bob chooses 1, and Alice has no more moves.
**Constraints:**
* `1 <= n <= 1000`
| null |
Array,Dynamic Programming
|
Medium
|
322
|
129 |
hi everyone today we are going to serve the critical question some route to leave numbers so you are given root of binary tree containing digits from 0 to 9 only each roof root to leave pass in the tree represents a number for example and the route to leave pass one two three representing the number of 123 so return the total sum of all root to leave numbers this case are generated so that the answer will fit in the 32 between integer a leaf node is a node with no children so let's see the example so you are given one two three output is 25 because um so one of uh route to leave should be 12 so this bus should be 12. because first we find one and the next we find two and we reach the leaf node so that's why this passes should be 12. and on the other hand when we go right down so this bus should be starting so plus starting so that's why I'll put should be 25 in this case okay so let me explain with this example one two three four five six so actually uh this question is uh not difficult just a simple text first search Problem and in this case um so we have to create like a 124 that is a one case and uh 125 that's a second number and uh cell number should be 136. for this bus and so total should be 124 plus 225 and 136 should be I think 385 I guess and uh yeah um so but uh problem is so how can we create like a 124 or 125 and 136 so let me explain uh how we can create the numbers so first of all um we are start from root node one and uh let's say we go down left side so we find 12 at the time we have to create a 12. so how can we create a 12 so actually it's easy um okay so let's say our current number we call current number okay now and when we find the two in that case we multiply 10. to current number and then plus the number we found in this case two so in the case a current number is one multiply 10 so this answer should be 10 Plus 2. I equal to 12 right so we can get the correct um number so 12. and now current number is 12 and let's move down the left side and the refine the fourth so client number 12 multiply 10 Plus in this case 4 so this answer is 100 20 plus 4. in that case we can get like a 124 correctly right so that's very easy so actually we do the same thing so if we go through the orange path that this Force should be 5 so we can get like 125 and if we go down the popular path we get like a um first order one multiply 10 and then we find three so get the starting after that um current num should be starting multiply 10 plus the number we found is six so we get a 136 correctly yeah um actually that is a key point and I think uh this algorithm also applied to another problem I forgot the um the question name but uh I'll put the link in the description below so you should check it out yeah so that is a basic idea to solve this question so with that being said let's get into the code okay so let's write the code first of all create an inner function So Def uh divs for such and taking a node current node and a current number and if not nodes in that case just simply return zero if not the case calculates the current number so num equal num multiply 10 plus um so add a current number and so that we can get a new current number after that if not node Dot left and not node dot right in the case just a return current number if not the case that means current node has a child so that's why we take the left side and the right child so return this first search so call this first search function okay and passing the node to left and the current number Plus divs for such and node dot right and the correct number yeah okay that's it after that core this was such function uh from outside so this was such and the fast node should be root and the first number should be zero yeah that's it let me submit it yeah looks good and the time complexity of this solution should be a order of n so N is a number of nodes in the tree so this question is like a standard devs first search traversal so which takes like a o n time complexity and therefore space complexity I think order of like H so H is a maximum depth of 3 so this space is required for like a recursive call stack so in the worst case that 3 is like a skewed like a linear so which means like a height maximum height equal number of nodes so in that case uh we need to uh like a space like that is equal to Oda of n so that's why so let me summarize step by step algorithm this is a step-by-step algorithm of some this is a step-by-step algorithm of some this is a step-by-step algorithm of some root to leave node step one if current node is null return zero step two calculate a new current number with num multiple item plus current value step 3 if current node doesn't have a child then return current number step 4 check left child and the right child yeah that's it I hope this video helps you understand this question well if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
Sum Root to Leaf Numbers
|
sum-root-to-leaf-numbers
|
You are given the `root` of a binary tree containing digits from `0` to `9` only.
Each root-to-leaf path in the tree represents a number.
* For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`.
Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer will fit in a **32-bit** integer.
A **leaf** node is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3\]
**Output:** 25
**Explanation:**
The root-to-leaf path `1->2` represents the number `12`.
The root-to-leaf path `1->3` represents the number `13`.
Therefore, sum = 12 + 13 = `25`.
**Example 2:**
**Input:** root = \[4,9,0,5,1\]
**Output:** 1026
**Explanation:**
The root-to-leaf path `4->9->5` represents the number 495.
The root-to-leaf path `4->9->1` represents the number 491.
The root-to-leaf path `4->0` represents the number 40.
Therefore, sum = 495 + 491 + 40 = `1026`.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `0 <= Node.val <= 9`
* The depth of the tree will not exceed `10`.
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
112,124,1030
|
350 |
welcome to september's lee code challenge today's problem is intersection of two arrays two given two integer arrays nums one and nums two return an array of their intersection each element in the result must appear as many times as it shows in both arrays and you may return the results in any order here we can see the intersection is going to be 2 so notice that we can have duplicates we're not just counting one number by itself just got to make sure that this number is in here as well as this number is in here as well if we had an extra two in here that wouldn't count because there's only two twos here okay so we obviously want to use a hash map uh there's a couple follow-up map uh there's a couple follow-up map uh there's a couple follow-up questions after but let's first solve this what we'll do is create a counter object we're going to call it c and we'll just take one of these either numbers one or numbers two doesn't matter and put it into our counter after that we'll set our output we call an empty list and we'll say four number in nums two we'll check to see if this amount in our counter object is greater than zero and if it is that means we have at least one of these numbers inside numbers 2 or nums 1 so we will output that into our append that to our output and then we're going to decrease our counter by one here so that way we won't return uh duplicate numbers that don't appear as many times after that just return the output and that should be it so let's go ahead and submit that and there we go so this is going to be an o of n time complexity as well as of n it's actually o of n plus m time times time complexity and of n space now uh the follow-up questions are what now uh the follow-up questions are what now uh the follow-up questions are what if the given array is already sorted how would you optimize your algorithm so if it was sorted probably using a hash isn't necessary what we can do is have a two-pointer what we can do is have a two-pointer what we can do is have a two-pointer solution and just iterate down both our arrays until we reach the end of one of them and we'll just increase the pointer if one of them is greater for each side so what i mean by that is let's just have an i and j pointer here i is going to be referring to numbers one and j is going to be referring to number two we'll say while i is less than length of number one and j is less than length of nums two we'll do say if nums one of i let's say it's less than nums two of j then let's increase our i pointer else if nums 1 of i is greater than nums 2 of j let's increase the j pointer else that means these numbers are equal so that means let's add it to our output either one numbers one or nums two of i and we'll increase both pointers because we've counted them out then we turn the output so let's set the output up here let's make sure this works okay it looks like it's working oh no okay um i may have flipped this by accident all right we have to sort it okay sorted nums one sorted numbers two because we're making this assumption that these are sorted let's try that again and that works too even though we do this sorted here so that would be n log n but if it was pre-sorted already n but if it was pre-sorted already n but if it was pre-sorted already obviously this algorithm would be better because it's constant space and it's going to be um the minimum of m plus n time complexity now there are a couple more follow-ups now there are a couple more follow-ups now there are a couple more follow-ups like what if nums one size is small compared to nums two size well if that's the case then probably this algorithm would be better but it really depends on whether it's sorted or not and as for this question what if elements numbs 2 are stored on disk and the memory is limited well maybe we'll do a check to see which well i mean if nums2 stored on disk then we already put numbers one to a counter object right so the first algorithm would be better now i could be wrong about that so you could feel free to correct me in the comments but otherwise this is the solution so thanks for watching my channel and remember do not trust me i know nothing
|
Intersection of Two Arrays II
|
intersection-of-two-arrays-ii
|
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must appear as many times as it shows in both arrays and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2,2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[4,9\]
**Explanation:** \[9,4\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000`
**Follow up:**
* What if the given array is already sorted? How would you optimize your algorithm?
* What if `nums1`'s size is small compared to `nums2`'s size? Which algorithm is better?
* What if elements of `nums2` are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
| null |
Array,Hash Table,Two Pointers,Binary Search,Sorting
|
Easy
|
349,1044,1392,2282
|
5 |
hello and welcome to the fifth video in the Sleek Creed and C sharp Series in this video we're going to be looking at the challenge called longest palindromic substring so let's switch over to our web browser here and let's get started so the challenge is given a string s return the longest palindromic substring so string you're going through it so start here and you go through and you'll check your add one letter set up pattern German no third one is a pedal gym yes no okay longest is this Bab so the first thought of how to do this would be just two four Loops but that's not going to be very efficient so what would be the best way to do that uh I mean may as well do that so we'll start with uh string longest palindrome equals nothing return the longest palindrome for and I equals zero I is less than s dot length I plus then we'll just do another one for integer J equals I plus one J is less than this needs to be less than minus one now this one is instant links J plus so we'll have a string here called current string s i say that we're going to do a current string plus equals SJ if current string dot length greater than longest palindrome the links we will then do the check which would be if current string that links modulus 2 equals zero okay I'm sure there's some easy way to reverse string maybe there's a method that we can use okay well this looks like what we want so I'm just going to grab that Chuck it into here so put that down here so you get the string input convert it to a character array you have the string that you're going to be returning which is reversed you iterate through the character array from luster first and you just build a string like that okay it's nice and straightforward would have been very easy to make but for things like this it's just may as well just copy code like that so if it's if modules two you then do if current string then current string dot length divided by zero to current string divided by two okay so if it's says length four divided by two ether makes it two but you want okay divided between minus one equals reverse kind of string then you do current string divided by two remove the minus one up two tender so if that's true then longest palindrome equals current string but if it's false and I'll just grab this and we can figure out the math for it so if you do divided by two you'll make it two by five but then I'll go to number two so then you'll keep it up minus one then I think you'll do plus one here because oops doing because it's a nint and you'd be five go to 2.5 but then it'll go back down to 2.5 but then it'll go back down to 2.5 but then it'll go back down to two so then you minus one so you get zero one and if it goes down to two which if it's a string of five you don't want that so then you go plus one and I'll go to five that's right you want to do minus ones for these I think that might be all you need for just a basic implementation but let's just run and see how it goes classic forgetting the semicolon and also line 27 okay yep can I implicitly convert type card to string in line six okay foreign this work no need substring that's right still use the python where you can just do stuff like that okay there we go Dot substring and then dot substring here all right then also the same thing here I'm sure there's a prettier way of doing this but I'm not going to worry about doing that at the moment okay let's run all right this is C Sharp we need to type string not Str ICT okay let's go not convert type card to string thoughts you want to be able to do that okay there's just a two string method that makes it nice and easy would have thought you'd be able to cast it but I guess not okay now let's give it a go oh two semicolons okay what's the area index list and length must refer to your position within the string that's where it's length not indexes so first one's index second one's length sorry you want zero okay so you have zero here then I'm not exactly sure how sub the length works for substring because it could be that the number is like the proper length instead of like using index numbers okay actually based on this you can just do the last position and have to go all the way up to there okay so it's using the index of a location for where you want to stop out so let's quickly fix some of this so the last substring is the reverse one we can remove the second parameter so for this I think we don't need to do minus keep it as it is I'm going to do that so zero weep we don't need to do minus I think that should work okay cool that did work so babad Bab cbbd BB let's create another test just in case let's see AE c d c AAA let's see how that goes yep okay that works so because it's it'd be fine to submit which we will do but because it's just too foliage like this it's going to be very inefficient but let's give it a shot anyway and see how it goes interesting didn't work at all for this one it didn't I guess we could do just a default case where like this yeah that's probably the best idea to do so let's just submit that okay time limit exceeded yep okay with a string input like that these two four Loops definitely would not work okay so we actually have to do the more efficient way so let's figure out how we do this so when we're past the halfway point do a check to see if it is still kind of palindrome so let's say you have a six digit number you go zero one two it's on the second one you can just look does the character in three equals one and two yes continue no break out of this Loop then you carry on like that so we can do when you reach a certain length so that's what we'll do the check in here in both of these just have to check it a different way if s dot length minus I okay let's go back to the example six so let's say I equals 2. so you have six you go one a zero one two oh better I equals one yeah so zero one you want to start doing this check when it's two three four no you want to be starting to do that trick on three no because you can have a look this is difficult to figure out and there'll be cases where it's not palindrome once even but it is when it's odd because you can ignore this middle number you need to figure out the math for this we'll take it outside of this we'll go up here if now we'll keep it in here one is that we want to stop I can't think of exactly when you want it to stop foreign minus I think I need to actually record this number oh no so if you go here okay I think I might have it so if J minus I greater or equal to S length if um if s j does not equal SJ minus one and we can break from it I think that's how you'll do it then we need to do another one for here for odd this number would be SJ then stream Mass 2. let's run this and see if it works the test numbers okay so that still worked and the runtime was much less okay that might be the solution I'm still exceeded okay so what else can be done to solve this let's grab this and put into our test case let's take a chunk out of this and see if that does anything we'll work that time so what is it about that which it didn't like okay what other improvements can be made to this maybe the issues with the reverse maybe I don't need to reverse and I can just use this check and then when it's false I can go back and use that I need to do some have to figure out how far away from the middle it is because you've got a large string if you're halfway through you can check these three here but if you have another string you have to go back and go back like this so that's the issue so what we'll do is minus current string wait why am I doing J minus I can just use the current string create a variable for that so we don't have to keep reusing it I think this might be the math for it so it ends up expanding it and this one will be Plus they need to do the same thing down there which will be going let's take a look at what this actually was before so we've got s that's J so this is the one on the right so this one should be plus that this one will be minus then we'll do the same thing down here make sure to add the two back to this so minus two let's run this and see if that works correctly there's a check missing somewhere which allowed for this a to get added one two three four five six seven eight ten eleven twelfths it's that's even so what's wrong with this oh I've realized this doesn't work at all everything I've done is incorrect because when you're performing this check the numbers won't always match up what do you think actually do you have you do have to go back and check it all well I'm gonna create a new function probably get rid of this reverse one so we are going to do a check for gonna do this checks instead of reversing it we're just going to have the string split it into half then use the indexes to do that so instead of reversing the whole thing you can just do it like that I'm just going to copy this into here and then clean it up so that's fine I need this for index equals zero index less than import dot length divided by two index Plus yeah that's fine if input index does not equal input dot links minus one minus index we return false so if it's other zero you've got a string of six zero so it's indexes 0 to 5. zero index six minus one five minus zero five one length six five then I'll take it a four you've got two okay I'm pretty sure that will work four even then do the same thing here but the check for this will have to be different actually I think it's the exact same no matter what yo let's hmm might be easier than I thought I think we can actually get rid of all this if statement stuff and just do if pondering check current string this is where we do this and I'm just gonna just continue it and see if that works I forgot the int okay they're definitely didn't go as expected probably something wrong with the mass pretty sure this won't work but I'm just gonna see if that does anything more than likely when it's zero would be yep that's what I thought just want to run again just in case I was defecting of it anyway yep okay still not working yep and what I thought it would just stop doing this part though sorry I know why it's because it is actually another check I can do to make things faster if the length of this is less than length of this don't need to do anything it's less than or equal to just continue okay I had a feeling that was a problem what I was doing was getting to the very end right here it's going to like I whatever this one is and doing this and then was failing I think there's another Improvement that can be made if s dot length minus I is less than this dot length you can just end it okay well this time it decreased quite a lot you know time to delete all this and you know I'm going to get rid of this function as well I'm just going to put this here so we've got current string change inputs to this and we'll just do a continue otherwise it is and get rid of this mess here let's do another test see if that increase speed and you don't think it will but whatever okay now everything's wrong okay fair enough that should have fixed the problem so thinking was breaking out of not this one but the one outside of there okay that worked let's submit and see if that actually it's finally working speed it up enough that the other ones work oh finally okay well it's pretty slow but hey you did it took a while but we finally got there oh well anyway that was the fifth challenge in late code called the longest palindromic substring from now on the codes out right will be in the GitHub repository in which you can find in the description below if you enjoyed watching this video make sure to like And subscribe so you don't miss out on any new videos that are added to this leak code and C sharp series
|
Longest Palindromic Substring
|
longest-palindromic-substring
|
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`.
**Example 1:**
**Input:** s = "babad "
**Output:** "bab "
**Explanation:** "aba " is also a valid answer.
**Example 2:**
**Input:** s = "cbbd "
**Output:** "bb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consist of only digits and English letters.
|
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint:
If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
|
String,Dynamic Programming
|
Medium
|
214,266,336,516,647
|
121 |
hello and welcome back to the cracking pain youtube channel today we're going to be solving another question for the beginners lead code question number 121 best time to buy and sell stock before we get into the video two things the first please like the video and subscribe to the channel the engagement really helps me grow the channel and two no i am not starting to do dynamic programming questions i know this question technically could be a dynamic programming question but it's an easy it's super straightforward it's not dynamic programming don't worry i haven't lost my mind we're not doing dynamic programming anyway that's enough of that let's read the question prompt you are given an array of prices where prices of i is the price of the given stock on the eighth day you want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock return the maximum profit you can achieve from this transaction if you cannot achieve any profit return zero so let's look at an example here where we have prices seven one five three six four so what is the maximum amount of profit we could get here so i mean let's look at some options we could buy on the first day and sell on the second day that would be a negative six profit we probably don't want to do that we could buy on the first day and sell on the second day but that would still be minus two okay let's scrap the idea what if we bought on the third day and sold or sorry yeah we bought on you know when the price is three and we sold at six that would be a price increase of positive three that's pretty good but it's the best solution is actually to buy when the price is one and to sell when the price is six if only we could see that in the future we'd all be trillionaires but unfortunately it doesn't work that way so in this uh problem there is actually no solution here because we can see that this is a dec uh decreasing sequence which means that no matter when we buy the prices after it will always be lower therefore will be in the negative so our best option is actually just to buy nothing so obviously you can see that we want to pick the smallest value and then sell at the highest value to the right of it but obviously you know how do we figure that out without literally trying every single combination because that's going to be quite expensive uh in terms of solving this question so what we're going to do here and after i erase everything is we are going to keep track of our current price right so we're going to set our original current price to be the first one in the sequence which is in this case seven and we're going to keep track of the profit that we've made so far and obviously we haven't made any profit before we've bought anything so our profit is zero what we're going to do now is we're going to go from left to right over our prices and what we're gonna do is if the current price is less than um sorry if the current price is actually greater than um you know the price that we're storing in current which is going to be representing the value that we actually bought at we're going to say that the current price so let's write that out so if the price is actually less than the price that we originally bought at then our price that we originally bought out might not be the lowest price possible because we've now found a price that's actually lower than it so in this case we actually want to update our buy price to be whatever this price here is so we're going to now set price uh the current price that we're buying at to be this new price here that we just iterated over so for example we start with our current of seven and then we're going to get to the one and we see that actually one is less than seven so that means that this one might be a better entry into the trade so we're going to pretend like we didn't buy at seven and we're actually going to pretend like we bought it one so we're going to update our curr to be one and we're going to continue on to the next price so that's the first case but what if the price is actually equal to um you know the price that we bought at right sorry if the current price that we just got is actually higher than the price that we bought at well then we want to calculate our profit and remember the profit is going to be the difference between the profit that we've you know been able to make so far so we're going to say the maximum of our current profit and whatever the difference in the price is right so that's going to be our price so the current price minus what we bought at and remember cur is our purchase price and price is the current price so obviously the difference between them is going to be the profit and if this value is actually higher than the profit that we've uh booked so far we can actually consider the trade starting at whatever kerr was ending at our current position with price to be a better trade and that will be our max profit and we're going to go from left to right and we're basically going to calculate this profit value now either we're going to find a profit inside of our loop here or we're never going to find it because we have a decreasing sequence uh in that case we will just have profit be 0 and we just return that at the end so hopefully that's not too confusing if it is don't worry when we go to the code editor this is literally 10 lines of code so it should be very easy to walk through and i'll talk you through every step of the way and we'll figure out how to solve this question all right i'll see you in the code editor and let's write the code so let's define our purchase price which is going to be uh you know we're just going to set it to the first item in the prices list because we're going to just pretend like we buy at the very first one so we're going to say purchase price is going to just equal prices of zero right we're just going to pretend like we buy the first one and we're going to need a variable to keep track of our profit so let's define that and set it equal to zero now what we want to do is we want to go through all the prices in our list here so we're going to save for price in prices but we want to be starting from the first index and the reason that we want to start at the first index is obviously we're going to be calculating difference between two prices and we don't want to calculate the difference between the purchase price in itself we're obviously going to get zero so we want to do trades further out in the future because obviously there's no point given that the profit will be zero if we just buy and sell at the same time so now that we have this price what we're going to do is we're going to say if the current price is actually less than our purchase price then it could be the case that we didn't buy at the absolute low which is what we're trying to do we're trying to basically minimize the price that we buy at and we're trying to maximize the price that we sell at so if our current price is actually less than the purchase price then we potentially didn't buy at the best time so we're actually going to now ignore our original purchase and we'll say we're actually going to be purchasing at this new purchase price so the purchase price is going to equal to our current price right otherwise if our price is actually higher than the purchase price obviously we're going to make some profit there so we're going to say that profit is going to be the maximum of whatever the current profit we were able to book so far and the difference between our price and the purchase price obviously that's going to be the profit in this trade so the difference between them is the profit we're gonna make if we buy at whatever the purchase price was and we sell at whatever the current price is so that is how we're gonna book the profit and we're gonna do that for basically all the prices uh in this array so at the end all we need to do is simply return our profit and we're good to go i just want to make sure i haven't misspelled anything here uh okay purchase pro oh purchase price there we go okay that's why i run these make sure okay cool looks like we're good to go so let's submit this and we are good to go so we can see that it runs it's accepted so what is the time and space complexity of this algorithm here well for the time complexity obviously we have to iterate over all of the prices in prices so that is going to be a big o of n operation and inside of our loop we just have an if statement uh which is going to be a big o of one operation so we don't have to worry about that same with taking the maximum that's a big o of one operation so within our loop we all have big o of one operations and we do this n times which is where we get big o of n for the space we don't actually use any extra space here we have two variables purchase price and profit but those are constant space allocations because they're just numbers they're not actually data structures so our space is going to be big o of 1 which is going to be the time and space complexity of this algorithm so that is how you sell this is how you solve best time to buy and sell stock this is a relatively simple question again this is for some of the beginners that might be on the channel obviously a lot of the questions i solve are generally medium to hard questions so i'm expanding it to have a little bit more of those introductory questions uh for people who might be new to the lead code grind i don't want them to feel left out on the channel i want to make content for basically anyone regardless of their ability um because that way i can help the most amount of people so that is how you solve this question if you enjoyed this video please leave a like and a comment like i said in the introduction the engagement really helps the channel grow if you want to see more content like this please subscribe to the channel i have a ton of videos coming out and i'm currently working on a system design series so if you want to learn that for your interview prep definitely stay tuned to the channel otherwise thank you so much for watching and have a great rest of your day
|
Best Time to Buy and Sell Stock
|
best-time-to-buy-and-sell-stock
|
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
You want to maximize your profit by choosing a **single day** to buy one stock and choosing a **different day in the future** to sell that stock.
Return _the maximum profit you can achieve from this transaction_. If you cannot achieve any profit, return `0`.
**Example 1:**
**Input:** prices = \[7,1,5,3,6,4\]
**Output:** 5
**Explanation:** Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
**Example 2:**
**Input:** prices = \[7,6,4,3,1\]
**Output:** 0
**Explanation:** In this case, no transactions are done and the max profit = 0.
**Constraints:**
* `1 <= prices.length <= 105`
* `0 <= prices[i] <= 104`
| null |
Array,Dynamic Programming
|
Easy
|
53,122,123,188,309,2138,2144
|
237 |
hey everyone in today's video we're going to be solving the problem delete node in a linked list so the question says there's a single linked list head and we want to delete a node in it you're given a node to deleted node and you will not be given access to the first node of head all the values of the link list are unique and it is guaranteed to the given node is the last node in the linked list delete the given node no other bit reading the node will not be removed from memory we mean the value of the given node should not exist in the linked list the number of nodes in the linguists should decrease by one all the values before the node should be in the same order and all the values after the row should be in the same order for the input you should provide the entire link list head and the node to be given node should not be the last one of the list and should be an actual node in the list we will build the linked list and pass the node to your function the output will be entire the output will be the entire list after calling your function okay so what the question says is that you're given a linked list like this four Phi 1 and 9 right and you're given a node uh equal to 5 and this node Phi is equal to this node over here inside the linked list okay and you're given access to that current node okay and you need to delete this node from the list such that it's not deleted from memory but it's completely from the linked list such that the fold will point to one which will point at 9 and the number of nodes in the linguist will be also decreased by one okay now just remember one thing when we solved a problem like this you know before on linked list or something like that you were always given access to the head of the linked list right and if you were given access to the head of the linguist like which is 4 over here you would have just easily iterated through the linked list you know you would have found Phi matching to this node over here and you would have just you know made the previous value over here directly pointed the third value over here and you would have just removed that list you know element from the linked list right so that was one way you could have done but you're not given access to the Head the link list you directly given access to the node which needs to be deleted so how can you solve this problem so the problem over here is a pretty straightforward one what we do is we'll just take three pointers in this case right this will be one pointer so this will be 1.0 this will be second so this will be 1.0 this will be second so this will be 1.0 this will be second pointer and this will be the third pointer over here and what we'll do in this over here is we'll just basically take the first pointer point it to the third pointer directly right and how will we do that we'll just replace the value of the first pointer with the second value over here right when it's removed and when it's replaced for the second value over here we'll just make it directly point to the third value and we'll make a second pointer point and none when we make the second point the point in none it'll be basically be a separate entity on its own removed from the linked list and one will Point directly to third okay so this is how we basically just solve the problem it's a pretty straightforward one let me just show you a dry run of this very quickly so you understand what's going to happen so what we'll do is we'll make a first equal to node which is equal to this node over here in the linked list okay so this was actually one and this is five right so we'll just make it equal to node we'll make a second equal to first start next which is equal to 1 so let's just write it over here like this is equal to 5 this is equal to 1 then we'll just do a third equal to Second dot next like this which is equal to 9 and what we'll do now is what we'll just make the value of the first dot value equal to Second dot valve right and we'll just directly make the pointer of first point to Third right we'll just make the pointer first dot next point to third if as done this 5 will now Point directly to 9 over here okay so let's say there's nothing pointing over here but it's going to be something like you know this pointing like this and you know it's five pointing directly to 9 and we'll make the pointer of second dot next one directly to none and when we do that this one over here will basically be just a separate node on its own and it will not point to anything and this Phi will now Point directly to one like this nine over here directly like this and you'll get a link list like this where one is completely deleted from the linked list with the number of nodes also reduced by one so this is how we solve the problem guys and this is what the code of the problem was on its own so let's just run the code yeah it's running and let's submit it and yeah it's submitted guys so yeah that's all for today's video guys and if you like the video do like share and subscribe do let me in the comments if you have any suggestions for more videos on the channel if you have any suggestions for me by teaching Concepts better also let me know and do check out my podcast as well and until next time guys thanks for watching
|
Delete Node in a Linked List
|
delete-node-in-a-linked-list
|
There is a singly-linked list `head` and we want to delete a node `node` in it.
You are given the node to be deleted `node`. You will **not be given access** to the first node of `head`.
All the values of the linked list are **unique**, and it is guaranteed that the given node `node` is not the last node in the linked list.
Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:
* The value of the given node should not exist in the linked list.
* The number of nodes in the linked list should decrease by one.
* All the values before `node` should be in the same order.
* All the values after `node` should be in the same order.
**Custom testing:**
* For the input, you should provide the entire linked list `head` and the node to be given `node`. `node` should not be the last node of the list and should be an actual node in the list.
* We will build the linked list and pass the node to your function.
* The output will be the entire list after calling your function.
**Example 1:**
**Input:** head = \[4,5,1,9\], node = 5
**Output:** \[4,1,9\]
**Explanation:** You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
**Example 2:**
**Input:** head = \[4,5,1,9\], node = 1
**Output:** \[4,5,9\]
**Explanation:** You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
**Constraints:**
* The number of the nodes in the given list is in the range `[2, 1000]`.
* `-1000 <= Node.val <= 1000`
* The value of each node in the list is **unique**.
* The `node` to be deleted is **in the list** and is **not a tail** node.
| null |
Linked List
|
Easy
|
203
|
1,750 |
simulation problems you're ever going to see my friends this is 1750 minimum length of string after deleting similar ends okay so this problem is just a direct simulation I don't know really I don't fully understand why it's classified as a medium um it's more so an easy but I suppose it does really showcase your ability to program right this is one of those problems where it's very easy to conceptually understand what needs to be done but the actual imp mation can be a little bit more difficult because there's these edge cases you have to consider you kind of have to think about all right where the pointer is going to go when do the pointer stop how do I avoid you know an infinite Loop how do I avoid trying to reference a spot that doesn't exist right this is one of those simulation problems although easy conceptually more difficult to actually uh develop the code appropriately okay and you'll see that in a moment when we start this problem okay so you're given a string s consisting only of characters a b and C now before warn the fact that it's only a b and c kind of more relevant um unless there's some solution to this problem that's more efficient but I don't really think there could be but the fact that there's only a and C you're going to notice in a second is kind of uh misleading it like maybe will lead you to think oh maybe there's some other way of solving this but honestly the fact that I only consist of ab and C doesn't really matter but anyways let's avoid that so you asked to apply the following algorithm on the string any number of times you pick a non-empty number of times you pick a non-empty number of times you pick a non-empty prefix from the string s where all the characters in the prefix are equal okay so you take some chunk of characters from the beginning that are all equal you pick a non-empty suffix from the you pick a non-empty suffix from the you pick a non-empty suffix from the string s where all the characters in the suffix are equal prefix meaning you take all the elements from the beginning that are equal and all the elements from the end that are equal right the prefix and the suffix should not intersect at any index okay so they have to be disjoint from each other right I can't have overlap I can't grab this much prefix and this much suffix and there's this overlap right I pick a prefix I pick a suffix they don't touch the characters from the prefix and the suffix must be the same okay so if I select a bunch of A's from the prefix I have to select a bunch of A's from the suffix but they can't over they can't be the same A's that I'm selecting delete both the prefix and the suffix okay return the minimum length of s after performing the above operations any number of times possibly zero all right so this example you'll see you know we have CNA right so what can I do well I can pick a non-empty prefix from s where all the non-empty prefix from s where all the non-empty prefix from s where all the characters are the same where the only prefix I can pick from s is C pick a nonempty suffix from the S where all the characters and suffix are equal well I could pick a oh but wait the characters from the prefix and the suffix have to be the same so there's nothing I can do here right because I need to pick prefaces and suffices right I need to pick characters from the start and characters from the end that are the same and they have to be equal to each other right I have to pick all the same from the left all the same from the right but um they have to be equal and these aren't equal so there's nothing I can do so the length you return is two right because I can't remove any character so this is one of those you know kind of like arbitrary no cause no follow through nothing you can do kind of examples that you sometimes get this one on the other hand may be a little bit more involved so let's think about what we can do here okay all right so I have S equals c a b a c all right now I'm going to pick a non-empty prefix I'm going to pick a non-empty prefix I'm going to pick a non-empty prefix from the string s where all the characters in the prefix are equal okay so I'll pick C that's the only character I can pick right so I'll pick my prefix equals c and my suffix where all characters are equal I my suffix equals c the characters from the prefix and the sum must be the same yep my prefix is C my suffix is C and I delete the both the prefix and the suffix okay so I take this thing and I delete the C and the on the end all right now I play this game again okay I look at my prefix I have a and I have my suffix equal a what I keep putting C here and they're equal so I can remove those two from the system and then I have my prefix equal B and my suffix equal B they're the same so I can remove them and then here's where it gets a little interesting because I have I can actually remove all of them right because I can remove this a I could choose my prefix equaling a and my suffix equaling a and then I delete both things and then it's empty right so the returning string that I end up with is nothing right it's empty because I literally can remove everything and let's do one more here all right so let's play this game again I'm not going to write s equals this all right so in first I could say okay my prefix I could choose just a and just a right so I have actually options here so this is where it kind of gets interesting right and this is where the nature of kind of the greedy you know simulation portion of this problem becomes apparent so it doesn't really specify how many characters I need to choose in the prefix just that the all the same right so technically I could choose my prefix being a and my suffix being a like this right and then the resulting string would be a b c a BB right but then I would have to stop right because now I can only choose a prefix of a and this prefix being B so there's nothing I can do right so this is not a good thing to do here this is a bad idea or what I could do is I could say well let me make my prefix AA right because I can pick any non-empty prefix because I can pick any non-empty prefix because I can pick any non-empty prefix from the string s for all the characters in the prefix are equal and the suffix equaling just a now I would remove they're the same right the quantity doesn't need to be the same but the character itself is the same so I can remove this a and this a so then I result with B CC a BB and then we kind of have the same situation here right I choose the B now I could do suffix equals B and I could remove 1 B and 1 b or I can make the suffix BB and I could remove them both resulting in this and if you did this kind of thing again where you did just one you would notice that it breaks it again and it minimizes the actual things that you can delete right so you want to do this and then here I'm stuck right because it's just CC and a so the length is three okay so what is the point that you can derive what is the kind of the idea here well you should always maximize the prefix you should choose right here we should choose as many A's as we can choose and as many a as you can choose on the right because the idea here is well you know you got to get while the getting is good that's the best way I can describe the kind of greedy approach right and there's probably a formal proof that you can make about why it's always you know probably a proof by contradiction about why this is the optimal way of doing it but kind of intuitively you should get when the getting is good and that's just an expression meaning you should take as many as you can possibly take in the moment that it's available because it may not be available in the future right now I have an a and an a here right that's the situation that I'm in I have two I have a prefix that's an A and a suffix that's an A so I might as well remove as many A's as possible that I can now right not removing all the A's doesn't give me any added benefit right if saying like oh I won't remove all the A's in my prefix I'll just remove one and I'll remove one here what benefit does that add cuz now I just have an A again right and you might say oh well maybe there's an a here maybe it's a like this so I could remove an A in one prefix and an A in another and an A in the next prefix and a in the other right but then it's like well then why do that why not just remove them both at once right in one prefix operation so the point I'm trying to make here is there's really no added benefit to not taking all the A's that you can at once right if you have a prefix you should maximize its length there's no benefit of Trying to minimize it and wait for someone else cuz that can only get worse right the best case situation when I remove one of these A's and not remove them all is that there continues to be A's well if there continues to be A's then I might as well just remove those as well very handwavy way of proving this but what I'm basically saying here is it makes sense to think well you know the best thing I can do is get rid as many characters as possible so I might as well get rid as many as possible when I can there's no added benefit to not getting rid of all the ones that I can get rid of now um in the future it can only get worse so you want to remove as many A's as possible when you do this so how do we do this kind of programmatically that's kind of the idea behind this problem but how do we actually programmatically look at this and solve this problem well one thing we can do is we can say well we'll start with a prefix pointer and we'll have a suffix pointer now we want to get while the getting is good right so we want to start with our prefix pointer pointing at the very left right sorry we want our prefix pointer to be at the very left because that's the beginning of the array and we want our suffix pointer at the very end because that's the end of the array right because that's how the prefix and Su suffixes work so we'll say Okay prefix equals Zer and suffix equals the length of s minus one because that's the index of the last element right now in order for us to remove elements the prefix and the suffix has to be the same right so the prefix s okay s is not the right cuz s is here so let's call it left and right instead right so this is the left pointer and the right pointer in order for us to remove elements right whatever our prefix is the characters from the prefix and the suffix have to be the same right so that means that s l has to equal s of R okay s of L has to equal s ofr because the elements in the prefix must be the same okay so that's this condition here the prefix and suffix should not intersect at any index all right so then they can't overlap with each other so that means that s has to be L has to be less than R right because if L and R are equal or on the other side of each other right that means they're intersecting right these two prefix and suffixes can never intersect with each other so they can never actually equal each other because that would mean there was intersection right so that's kind of captured here so they both have to be the same that's this condition and the prefix and suffix should never intersect well if they never intersect then they're never equal right they're always away from each other okay and then what are we going to do when we go through here well remember I'm trying to get while the getting is good right so if there's a character I'm trying to delete that's of L right and I'm going to just keep moving my prefix right I'm going to remove this a cuz I already I can remove this thing right I know I can remove it because they're equal at their value and then I'm just going to increase L which corresponds to saying okay I can delete this a while I'm looking at the character that I'm going to delete I'm going to keep deleting it right because I'm trying to maximize the size of the prefix so I'm going to say while L is less than R of course right because I can't go all the way to wherever R is and L is s of L equals c I'm going to increase L which basically corresponds to maximizing the size of my prefix right I'm saying okay my prefix started in this position but then I'm going to increase my prefix I'm going to say okay well I can delete one L I can actually delete two L's when I'm done with this the new position of my prefix will be here right when I delete all the A's my L will be in this position so I increase L by one again which is corresponds to is deleting right these two elements okay so basically what's going on here right the point that I'm trying to make is L and R is like I'm kind of cutting up the array without actually deleting the elements I'm just saying okay the new start of my array will be here and the new end of my array will be here at the end so that the at the very end the length of the array is just r- L end the length of the array is just r- L end the length of the array is just r- L + one okay so lus r s of Lal c l plus equal 1 and it's the same game for R right so we're already assuming that these things are equal right because they wouldn't if they weren't equal they wouldn't be in this position so while R is greater than L and S of R equals c well now then we can just keep going back like okay we know they're both equal here and R will end up moving to this position here say okay while there's an a we're going to get while the getting is good because we're both L seeing an a are seeing an A so let's remove all the A's that we see and then we'll start at the next thing here right so on this next position now we have L equal B and r equal B so L will keep removing until it sees something other than b r will keep removing until it see something other than b so R will go here L will be here R will go back again and then we'll have c a and then that'll be it and these resulting strings right just so you can see how this works a b CC a BB a the resulting string from this is a b CC a b actually let's do it uh because they don't really happen in that order you see what I'm saying right so these resulting strings so this L goes all the way up to the C this R goes up to this and we don't need to actually return the string we just need to return the length Okay so this we subtract from R I don't know why this got shifted over and that's pretty much it I think there's a zero case we have to consider but we'll see okay so that's two now this probably has an error right but see this problem is more I mean there's an intuitive idea of like saying like okay there's links and there's you know we should take things as much as possible we're kind of just simulating through this problem right kind of simulating well the best thing to do is just to be greedy and get while the're getting is good um and we're going to simulate through that scenario but the issue with this problem is trying to write you know concise clean code that uh doesn't you know bug out because it is a little bit complicated when you have these two pointer and that's what this problem's classified as right a kind of two- pointer right a kind of two- pointer right a kind of two- pointer approach okay so this problem here is when it actually zeros out right you're going to end up having the strings overlap so if they overlap lap then this is going to be NE 1 so that would be the zero case and there you go all right guys pretty short solution here today um kind of wondering if you could get rid of no trying if I get rid of this line but I'm not going to play that game all right so what's the run in space so let's say any is the length of s so what is our space and time complexity well for time you might be pressured to think oh maybe it's N squared or because you know I have like I go through a loop and then I loop again um but the fact is it's actually o ofen and why is it oen well l&r you only ofen and why is it oen well l&r you only ofen and why is it oen well l&r you only ever increase them or decrease them and if they ever reach each other the loop stops right so I increase l I decrease R but the second they touch the loop stops so I'll never have L and R exceed the length of the array cuz L's going to increase and R is going to increase right like the way you can think about is if you have two people walking right basically what this problem is regardless of how the loop structure looks right if you have these two people walking right when they walk towards each other right regardless of how they do it maybe X is here and he takes a couple steps forward and Y is barely moving at all right and then maybe X takes a few couple steps forth and then they hit each other and then it stops but you notice like this situation when you're walking into each other you never exceed the length between you right if I'm at position zero and you're at position 100 and we're walking towards each other well together will never walk more than at most a 100 steps right 100 positions because I'm walking towards you and you're walking towards me so we're kind of confined within that space and the second that we hit each other we stop so regardless of how this Loop looks you might be pressured to say oh this is n Square cuz there's all these WS inside of WS the way that these things are actually being added together right the way that this condition works is the second they hit each other they're walking towards each other the loop stops so it never is going to exceed the boundaries of which they exist within and there's n spaces that they could walk in right because there's a length of n uh length of n for S okay and then for space well we just create these two variables and then we you know we create this third I guess variable C within the loop so then we just keep you know updating that one variable so we create three variables pretty much and we use those three variables to determine the answer and it doesn't really matter how big the array is right if the array is 10 elements or a million elements we still only use the three variables so that's constant space right doesn't matter what we do in terms of input the number of variables we use is always the same so it's constant and uh yep that's it all right guys peace out
|
Minimum Length of String After Deleting Similar Ends
|
check-if-two-expression-trees-are-equivalent
|
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times:
1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal.
2. Pick a **non-empty** suffix from the string `s` where all the characters in this suffix are equal.
3. The prefix and the suffix should not intersect at any index.
4. The characters from the prefix and suffix must be the same.
5. Delete both the prefix and the suffix.
Return _the **minimum length** of_ `s` _after performing the above operation any number of times (possibly zero times)_.
**Example 1:**
**Input:** s = "ca "
**Output:** 2
**Explanation:** You can't remove any characters, so the string stays as is.
**Example 2:**
**Input:** s = "cabaabac "
**Output:** 0
**Explanation:** An optimal sequence of operations is:
- Take prefix = "c " and suffix = "c " and remove them, s = "abaaba ".
- Take prefix = "a " and suffix = "a " and remove them, s = "baab ".
- Take prefix = "b " and suffix = "b " and remove them, s = "aa ".
- Take prefix = "a " and suffix = "a " and remove them, s = " ".
**Example 3:**
**Input:** s = "aabccabba "
**Output:** 3
**Explanation:** An optimal sequence of operations is:
- Take prefix = "aa " and suffix = "a " and remove them, s = "bccabb ".
- Take prefix = "b " and suffix = "bb " and remove them, s = "cca ".
**Constraints:**
* `1 <= s.length <= 105`
* `s` only consists of characters `'a'`, `'b'`, and `'c'`.
|
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
|
Tree,Depth-First Search,Binary Tree
|
Medium
|
1736
|
100 |
in this problem we are given two binary trees and we have to return whether they are equal or not and by equal we mean they should be structurally equal and here if you see these two trees they are structurally same this one has left and right and this one has left right so they have exact same structure but that is not enough we have to check the values also so 5 is equal to 5 3 is equal to 3 6. so if we flip one of these so 4 comes here 2 goes here structurally they will be same but the left of 3 will hold a value of 4 if we flip it but on this side it's 2 so that ordering is also important it should be exactly same so we will see a recursive and iterative solution for this the recursive solution would be an easy solution and it will be the preferred way of solving it unless you are asked to solve it iteratively the iterative version would be a bit difficult compared to the recursive version and this recursive version will be very simple and you can write it in three lines of code you can even merge them into one line of code if you combine different conditions and in this iterative approach we will take the hint of or breakfast traversal of graphs we will do it in level order fashion but it will be quite some amount of modification will be required into a normal bfs so it will be a bit tougher than that normal bfs so we will see what are the differences first let's look at the recursive way of solving it so clearly uh you will first compare their roots so when you are given a function you are given a tree node you are given two pointers tree node p and tree node q so first thing is that you are given the roots so first root should be same so if one of them is null better both be null otherwise we will return false so if both are null then it is fine both are equal there are no both trees are empty so if p is equal to null and q is equal to null then return true if one of them is not null or one of them is null or q is null then return false so if both are null it will return from here itself so it proceeded here that means both are not null but if one of them is null then that means other is not null because both cannot be null here if both were null we would have returned from here so in this case we return false and now in the next line it means that both are not null if any of them are null or both are null it would have already returned before coming to this line so here we are sure that both are not null so we will check their values so if p dot val or in c plus it will be this arrow is not equal to q dot well then return false otherwise this root is same now what we need to do uh we will check for this left sub tree so if the complete trees are same then this left sub tree should also be same as this left sub tree and this right sub tree should be same as this right sub tree so if it's valid till this point it has not returned from here that means here it's fine for the root it's fine so we return whatever is this function i am calling it f return f b left q left so that will check if this subtree is same as this and the same function we write q write and we are done so what this function will do again recursively call on this and this so first it will match the root if they are same it will recursively call on this and similarly on this and this so when it's called for 2 and 2 it will check roots are same the value is also same both are not null so it will call for its left and this left so both are null so it will come here and it will return true so this will return true to the calling function this will return true to its calling function and it will come back to 2 and these are already same so ultimately it will return true to this part 3 similarly 4 will also return true and finally 3 will return true and 6 will return true so this will return true this will also return true so true and true means true so in this case true will be returned now let's see how we will solve it iteratively so if you are not familiar with breadth first traversal better to review bfs video and see how we can use a queue to do a breakfast traversal or if it's a tree we would do it level order traversal so first route is listed then next level and so on so once you are familiar with bfs you are good to go so there are some subtle differences from normal bfs one definitely is that here we are doing bfs in two uh trees or two graphs simultaneously in parallel in normal bfs we are just having one queue we are doing one bfs so we have one queue for this one let's call it q1 let's call it q2 so what we do we again do the same check compare if we have to add these checks that if one is null others should also be null if only one of them is null return false if their values are same then we are good to go so after that check let's call this part of the code as r equal i'm calling it ae let's put it in a function r equal so check uh in this function we pass p and q so if r equal p and q or rather if are not equal then don't need to proceed further return false so this function will end here itself at the root level but if they are equal that is this condition did not hold true then in q1 push this five this is from this first root node and this is not integer this will be q of tree node or in c plus tree node pointer like this so both are tree node pointers so in this case it's 5 in a circle denotes a tree node structure so q 1 has this 5 q 2 has also 5 then ah here we will not just do level order traversal and not compare level by level for example let's say we are at some level let's say at kth level in first tree and kth level in secondary and here let's say we have 10 20 as two nodes only at this level and here we have child of 5 six and seven this is at kth level in first tree and in second tree we have again 10 20. so if we compare at this level you may be guessing that if we do simple bfs and compare level by level for equality then we are good to go but we are not good to further modification is required in the bfs so here we will see that both are same at this level kth level so at this level it's fine we return true and in fact we are true till this level but let's say here we have 5 then we have six and seven so if we simply uh check for this level and insert their children in a queue so here the queue will have after we finish with this level that you will have 5 6 and 7 these will be the only three nodes in the queue if we are processing level order and here in q2 we will have 5 6 and seven so when we pop first element compare with uh popped element of q2 they are same so we pop next element that is six and compare they are again same next we pop this node seven and compare they are same so we would say that even at this level they are same but we see that they are not same here this 10 has two children 5 and 6 here 10 has just one child 5. here 20 has one child but here 20 has two childs but if we just are concerned about a particular level we would never discover this kind of anomaly maybe that below this everything is same so it will remain as true but we have to return false here so what change is required so instead of doing simple bfs when we pop an element we compare them so when we pop from both q1 and q2 we compare if they are equal using the same logic this function that i wrote are equal where we will add these logic these three checks and apart from that we have to check one more thing that its left child is also equal to its left side and its right side is also equal to its right side so if 10 and 20 are in the queue before processing kth level we would pop 10 from both of these we pop 10 from first queue 10 from second queue they are equal this will return true then we check their left are equal so this will also return true then we will check their right are also equal so if both are null then that's fine this function will return true but here one is not null one is null so this will return false and our check will fail so these are a few changes required to normal bfs so now let's write the code for this in c plus list java and python so you can go through this example these are all very simple examples and here you see that two is left child here two is right child so they are different so just structurally being same is not enough here also the order is changed 2 1 2 so they are false here it's exactly same so first write the recursive and simpler solution that is if not p and not q then return true both are null if not p or not q return false only one of them is null if both are not null then we check their values p dot val not equal to q dot val return false now root is valid its value is also same if it exists so return so let's see if it runs and the solution is accepted so again it's 4 millisecond but if you try a few times it can be 0 millisecond as well and what is the time complexity here so we are traversing this tree once both the trees so if there are n nodes and here there are m nodes it will be order n plus m and what is the space complexity the we are not using any explicit space but uh space will be taken by the stack that is used internally in this recursion recursive stack so it again can be of the order of n so both space and time are of linear order now we will write the iterative way so let's comment it out and you must have noticed that we are checking this multiple times this check so we will put it in a separate function and we will call it is equal and this will also take two nodes three nodes to compare false and then false else return true so this is our ego function now we will start the main code so first we have to check for root so we will do if not is equal p and q then there is violation at the root level itself so return false otherwise we will create two queues let's call them q1 and q2 and then in q1 we will push p and this is q1 and in q two we will push q then p and q are same so we will check while q one is not empty so we pick the first element from both the queues and in c plus front just returns it does not pop out the element so we need to call q one dot pop and q two dot power to also pop those elements then we will check if is equal or rather is not equal this n1 and n2 then return false and after checking the elements we also check their children and we know what is the reason so we saw the reason that just checking the element which is spot from the queue is not enough we have to also check match their children so left with left and right with right they should also be same then only we will push there left and right otherwise we will return from here itself so this nodes are same but that's not enough we will check for their children that is if not is equal so better copy this one so after checking the nodes check their left if they are not equal return false and this n1 can be one of them can be null so we need here null check otherwise we will get bad access this pointer is null so there is some shortcut here in lead code you can select it and press tab so it will shift it if you have a long block of code like this and you want to shift it you select it and press tab and if you want to indent left shift plus tab left so left are same so what we need to do if so left can be same when both are null also so here we add null check q1 dot push n1 left and similarly we have to do for right and then we are good to go finally we will return true here and this iterative approach is also accepted uh so for java and python i will go ahead with this recursive way if you got this idea clear you can try to implement it in java and python whichever is your favorite programming language it would also give you a good practice of bfs and this solution is accepted and here also we are it's zero millisecond but still we are here so maybe we do not have enough accepted submissions so this chart is not available but if we are 0 millisecond we can expect that we are right in the top region and in fact for most people it will be in that region only all the methods are converging to ofn now we will do it in python 3. and the solution is accepted in python as well
|
Same Tree
|
same-tree
|
Given the roots of two binary trees `p` and `q`, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
**Example 1:**
**Input:** p = \[1,2,3\], q = \[1,2,3\]
**Output:** true
**Example 2:**
**Input:** p = \[1,2\], q = \[1,null,2\]
**Output:** false
**Example 3:**
**Input:** p = \[1,2,1\], q = \[1,1,2\]
**Output:** false
**Constraints:**
* The number of nodes in both trees is in the range `[0, 100]`.
* `-104 <= Node.val <= 104`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
69 |
Those who were at that time those who in software to solve police problems cut off marks to isko gas piped water heart brush noise compound give the information middle aged person subscribe 251 subscription for the great khali vve subscribe time complexity to isko not good bye subscribe Like a few lines on different dates for small letters where do subscribe my channel subscribe start way subscribe my channel subscribe hai pimple to end can also be alone more 100 videos school plus and minus start yes brother tu parts of lucknow ki aap jeske soya Money Withdraw So Relax This Day More Mid-1990s Simply Relax This Day More Mid-1990s Simply Relax This Day More Mid-1990s Simply Set A Reminder The Subscribe To Shadow Costume And Saw Your Profile And Plut Swerve Greater Faridabad To Support Simple Solve That This Changes Active And Front Don't Forget To Subscribe And Subscribe Avoid Eating up b id m id subscribe for Live Video Subscribe 2325 Oneplus Ki Request Ubuntu Server Remedies to Right Now I Know What You Want to Give A I am This Article Daily Costume Medicine for Boy to Solidification Is the Android Simply Se Request Mid- De subscribe and Simply Se Request Mid- De subscribe and Simply Se Request Mid- De subscribe and subscribe the Channel Please subscribe and subscribe the Channel to get Dose Honey and Submit facility on Kinnar Select Don Apart from Chakra Favorite Playlist Like and Subscribe Now to Receive New Updates Reviews and Love You
|
Sqrt(x)
|
sqrtx
|
Given a non-negative integer `x`, return _the square root of_ `x` _rounded down to the nearest integer_. The returned integer should be **non-negative** as well.
You **must not use** any built-in exponent function or operator.
* For example, do not use `pow(x, 0.5)` in c++ or `x ** 0.5` in python.
**Example 1:**
**Input:** x = 4
**Output:** 2
**Explanation:** The square root of 4 is 2, so we return 2.
**Example 2:**
**Input:** x = 8
**Output:** 2
**Explanation:** The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.
**Constraints:**
* `0 <= x <= 231 - 1`
|
Try exploring all integers. (Credits: @annujoshi) Use the sorted property of integers to reduced the search space. (Credits: @annujoshi)
|
Math,Binary Search
|
Easy
|
50,367
|
1,313 |
we took over number 13 the compression run length encoding list the question says we are given a list of numbers of integers representing a list compress with run length encoding so we have a list of numbers which is composed of integers consider each a decent pair or they set meaning they're next to each other of elements a and B am P the next to each other in the form of this but is greater than or equal to zero and for each such pair there are a elements with a value B and the decompressed list okay let's look at example we have an input of thumbs array which is 1 2 3 & 4 input of thumbs array which is 1 2 3 & 4 input of thumbs array which is 1 2 3 & 4 & output we have 2 4 so the first & output we have 2 4 so the first & output we have 2 4 so the first pair that we have is 1 & 2 right and pair that we have is 1 & 2 right and pair that we have is 1 & 2 right and this is the pair adjacent pair that the question says over here a and B and this is pretty much equal to nums at index I times 2 comma and noms index I times 2 plus 1 alright so the first number that we have this is going to be frequency and frequency is how many times the number of cards and this number two is the value right so what this is saying is that number two is going to occur only once so for our result for the first loop we are going to have two in our array because two happened once so frequency is how many times the number curse and this is our first look and in the second loop our numbers are 3 & 4 the second loop our numbers are 3 & 4 the second loop our numbers are 3 & 4 right remember this is frequency and this is the value so for happens how many times 3 so that's 4 & 4 right and we're done 3 so that's 4 & 4 right and we're done 3 so that's 4 & 4 right and we're done with our loop and we want to combine these two results and finally whatever quantity get is 2 4 & 4 and if you quantity get is 2 4 & 4 and if you quantity get is 2 4 & 4 and if you look at our output that's what we can over here qinger so let's code our solution the first thing we do always the curl our function which takes in one parameter which is a numbers array and next we're going to do is we're just create a variable named result which is going to store our result and that's all right and we want to look to our array right so we want to use our follow and we're gonna start index here look to our array and this time we're going to increment the eye by 2 and not by 1 and I'll explain why later I'm just gonna make a variable that frequency is equal to noms index I and just gonna make up variable eval and it's going to be Dom's index i + 1 okay and what we're going to index i + 1 okay and what we're going to index i + 1 okay and what we're going to do again is we're going to make another for loop or that is equal to 0 and I is less than frequency and I plus we're going to push and the value and then finally we're going to return our result okay there's an air zone there oh okay so we first in the first little be equal to our array and we increment T or we could be commit I by 2 because if you look go back to our example we want the in pairs right and you don't want to reuse the same numbers again so for the first pair we're gonna use 1 & 2 and the first pair we're gonna use 1 & 2 and the first pair we're gonna use 1 & 2 and the next pair we're not gonna use 2 & 3 next pair we're not gonna use 2 & 3 next pair we're not gonna use 2 & 3 because we already used to we're going to use all 3 & 4 to use all 3 & 4 to use all 3 & 4 that's why we increment I by 2 and we just made a variable for frequency and value and remember that if you look at the problem frequency comes first and then value is next the reason why we're using for loop here is because we want to push in whatever the value is into our results array how many times for the number of times the frequency happens or is so a frequency was two you want to push in value twice that's why we use the second look and if we run out a result we get our solution is 2 4 & 4 result we get our solution is 2 4 & 4 result we get our solution is 2 4 & 4 and that's what we get that's the output get a score I called weapon time so first thing we do is cover a function with chasing one parameter which is an array I'm going to make a result variable which is an empty array and we're going to return that with our for loop is done and now we have a nested for loop and the first full loop is going to basically get the numbers for our frequency and value and this is important here being Kristy I by 2 because remember we want the pairs of a and B and you don't want it to be hard to forget so for example as 1 2 3 & 4 to forget so for example as 1 2 3 & 4 to forget so for example as 1 2 3 & 4 right so first part is going to be born into and if we increased I by 2 index is going to be 2 right and then so the next pair is going to be 3 & 4 we don't want pair is going to be 3 & 4 we don't want pair is going to be 3 & 4 we don't want 1 2 & 3 & 3 4 that's not what the 1 2 & 3 & 3 4 that's not what the 1 2 & 3 & 3 4 that's not what the question is asking so frequency comes first that's why as lanza index I and value is the next value right or the next number so we do I cross want to get Katia next number in the index and after we get our frequency and value so frequency value - we want to push and whatever this - we want to push and whatever this - we want to push and whatever this value is value frequency whatever this value is this number of times so we make another for loop that's going to iterate for the number whichever frequency is and that is going to push in the value to our results array and after we're doing after we're done with that we're going to loop out of this and go back up here and do our full group again then go to our second pair three and four and we're gonna go down to our second full group and then look to look through the whole thing again four times because we have a not four times three times because this is our frequency and we want to push in four three times so we get 2 4 & 4
|
Decompress Run-Length Encoded List
|
count-ways-to-build-rooms-in-an-ant-colony
|
We are given a list `nums` of integers representing a list compressed with run-length encoding.
Consider each adjacent pair of elements `[freq, val] = [nums[2*i], nums[2*i+1]]` (with `i >= 0`). For each such pair, there are `freq` elements with value `val` concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list.
Return the decompressed list.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** \[2,4,4,4\]
**Explanation:** The first pair \[1,2\] means we have freq = 1 and val = 2 so we generate the array \[2\].
The second pair \[3,4\] means we have freq = 3 and val = 4 so we generate \[4,4,4\].
At the end the concatenation \[2\] + \[4,4,4\] is \[2,4,4,4\].
**Example 2:**
**Input:** nums = \[1,1,2,3\]
**Output:** \[1,3,3\]
**Constraints:**
* `2 <= nums.length <= 100`
* `nums.length % 2 == 0`
* `1 <= nums[i] <= 100`
|
Use dynamic programming. Let dp[i] be the number of ways to solve the problem for the subtree of node i. Imagine you are trying to fill an array with the order of traversal, dp[i] equals the multiplications of the number of ways to distribute the subtrees of the children of i on the array using combinatorics, multiplied bu their dp values.
|
Math,Dynamic Programming,Tree,Graph,Topological Sort,Combinatorics
|
Hard
| null |
141 |
hey everyone welcome back and let's write some more neat code today so today let's solve linked list cycle i know that we solved a problem that's pretty much a harder version of this exact problem but in this explanation i'm going to explain why the tortoise and hair algorithm on a linkedlist cycle why exactly it works and why exactly we know for sure that it's a linear time algorithm because i think most people just kind of glance over why exactly this is true so i'm going to go over that today and you can see that this linked list problem is another problem from the blind 75 list a list of 75 problems we've been working through and tracking on the spreadsheet the link to the spreadsheet will be in the description if you want to take a look we are not quite done with this sheet yet even though we have done all pretty much most of the difficult medium and hard problems on this list so basically we're given the head of a linked list and we just want to determine if there exists a cycle in this linked list or not and basically the definition of a cycle is if at some point you know you get to a node and you keep following the pointers along that node eventually you'll get back to the same node and if we get back to the same node we'll be able to do it again and again basically an infinite loop so we return true if there's a cycle we return false if there's no cycle now the first idea you might have is just start at the beginning keep going to the end keep going and eventually let's say that this of this negative four actually pointed to null in that case we know okay we got to the end of a linked list right so in that case we return false no cycle and that's always going to be the case so if there's no cycle it's really easy to detect that there's no cycle because eventually we reach null but if we don't reach null right we go along this node and we get to we get back to the same node we already visited but for some reason we can't detect that so then we go to the next node and keep doing that and from our perspective we're just going to say okay it's just a really long linked list eventually we're going to get to null right but that's not going to be the case if there's a cycle we never get to null we'll never break out of this loop so we really have to determine a way to detect that we're visiting the same node twice so how can we determine if we're visiting the same node twice well we start at the beginning like usual and we maintain a hash map or a hash set in this case where basically we take every single node and we take the node itself and add it to the hash set after we have visited this node we don't add the value because i think in this problem there could be duplicates right like the same value could show up multiple times in multiple nodes so we don't want to detect a loop that way but we'll take the node itself and then add it to the hash set and i think you can do that in most languages you definitely can in python because the node itself is just an object and you usually can hash an object and so in that case we're going to take this visit it take this visit and then eventually we'll get back to a node if we notice that a node has already been visited and now we're visiting it twice that obviously means that there must be a cycle right we can't visit the same node twice so that means there's a cycle we detect that and then we can return true a cycle exists now in this case we're only having to visit each node about once so the time complexity is going to be big o of n the memory complexity is also going to be big o of n because every node potentially is going to be stored in the hash set but there's actually a way that we can do this without using a hash set we can do this in o of one memory and that's the slightly complicated algorithm i'm going to show you that algorithm and i'm going to show you exactly why it works so the idea is simple we're going to start at the beginning of the linked list but we're going to have two pointers this time we're going to have a slow pointer s and we're going to have a fast pointer f and you may have seen this algorithm before it's a pretty simple algorithm once you know it but i'm gonna again show you why exactly it works so the slow pointer each time is just gonna be shifted by one the fast pointer is going to be shifted by two so it's going to be here and so originally they do start at the same position but we're gonna look at every position after we've shifted it and so what's either going to happen obviously the fast pointer is faster than the slow pointer so the if there is the end of a linked list right like for example this points at null the fast pointer is of course gonna reach the end of the linked list first so if we do that then we can return false no link no cycle exists in the linked list but if there is a cycle do you see that this fast pointer and this slow pointer are going to meet again they're going to meet at the exact same position and if they meet at the exact same position that must mean that a cycle exists so i'm just going to run the simulation and then i'm going to show you why it's always going to be the case that these two are going to meet if they ever reach a cycle so we just take one more step with s right we're only shifting it by one f is gonna be shifted by two so first we're gonna go to four and then we're gonna follow the link and reach back to this position right the two position so clearly f made a loop f has gone through the cycle and so far we've shifted each of the pointers twice and so we're going to do one last shift s is going to reach the 4 and our f from over here is gonna be shifted twice again and it's gonna reach the four as well so at this point we're gonna just we're gonna see yes the slow pointer and the fast pointer have met each other how could it be possible that they met each other if the fast pointer was going twice as fast because they were in a cycle and eventually the fast pointer no matter where they start slow is here fast as you're eventually the fast pointer is going to catch up to the slow pointer let me show you why that's always going to be the case and why it's going to happen in linear time so let's say this is our cycle and i'm not drawing it as a linked list it's some kind of circle right and it's a cycle and let's say we're moving clockwise in this cycle first thing to notice is do you know that every gap so let's say you know the distance between slow and fast that's going to be some integer value right it's not going to be a decimal it's going to be an integer value and this portion is also going to be an integer value because the entire length of the cycle is going to be an integer value because you know linked list lengths are integer values right this is an integer one this is an integer two uh also one so the entire list is length two right so we're dealing with integers here not decimals so we're looking at the case where at with a slow and fast pointer are at different positions because obviously if they were already at the same position we're inside the cycle they're at the same position then of course we know we're going to return true but it could be possible that they're at different positions any arbitrary position is what i'm choosing here and we know that the slope pointer on one iteration is going to make one jump right the distance it's gonna do it's gonna move is one we know that the fast pointer is gonna move a distance of two right so clearly in our simulation eventually the fast pointer is going to reach and surpass the slow pointer but why is it true that they are going to meet each other at the exact same spot well let's just give this distance an arbitrary value we know that the fast pointer will catch up to the slow pointer and this is the distance that it's going to have to travel in order to do so this is our gap that we have to close so let's say the length of this gap is 10. if we move the slow pointer by one we're taking the gap and increasing it by one right if the slow pointer gets shifted by one we increased the gap but then the fast pointer is not going to quit it's gonna move by two as well so when we move the fast pointer we're taking the gap and closing it by two so we're saying plus one minus two right do you see how this evaluates to ten minus one which is going to be nine so on a single iteration of the loop the distance between the pointers is being closed by one so then how many iterations is it going to take for the fast pointer to reach the slope pointer well of course whatever this length happens to be right whatever that closing distance happens to be whatever that gap happens to be how big could this gap possibly be it could only be the entire length of the list so you know let's say uh the fast pointer is over here where this distance is one so then the remaining distance is gonna be the entire length of the list let's call that n minus one so then how many iterations is it gonna take to get this to equal to zero of course roughly n so that's why the overall time complexity is n where the length is the distance where n is the length of the cycle which could be the entire linked list right so that's why it's always going to work and it's going to run in linear time and maybe you didn't even care about why exactly it works but that's okay because once you know the fast and slow pointer technique the code is usually pretty easy to write let's get into that now so like i said we're going to start our slow and fast pointer at the same position and the next time that they meet each other is how we know we've detected a loop so obviously they're at the same position now so we don't want to say that there already exists a loop because we don't know that for sure and we're going to be shifting our fast and slow pointers while fast and fast dot next is not null because we need to make sure that fast dot next is not null because remember we're shifting fast by two on each iteration and of course fast is going to reach the end of the linked list before slow does so if it does that then outside of the loop we can return false meaning that there does not exist a cycle but on the inside we're gonna check if there is a cycle so we're gonna take our slow pointer shift it by one slow dot next take our fast pointer shift it by two fast dot next again and now if we if they meet each other we can say if slow ever reaches fast then we can return true there does exist a cycle and you could pretty much write this loop as a do while loop in a lot of other languages but i don't think python supports that so the solution is really as simple as that linear time constant space you can see that the solution works and is efficient so i hope this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon
|
Linked List Cycle
|
linked-list-cycle
|
Given `head`, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to. **Note that `pos` is not passed as a parameter**.
Return `true` _if there is a cycle in the linked list_. Otherwise, return `false`.
**Example 1:**
**Input:** head = \[3,2,0,-4\], pos = 1
**Output:** true
**Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
**Example 2:**
**Input:** head = \[1,2\], pos = 0
**Output:** true
**Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node.
**Example 3:**
**Input:** head = \[1\], pos = -1
**Output:** false
**Explanation:** There is no cycle in the linked list.
**Constraints:**
* The number of the nodes in the list is in the range `[0, 104]`.
* `-105 <= Node.val <= 105`
* `pos` is `-1` or a **valid index** in the linked-list.
**Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
| null |
Hash Table,Linked List,Two Pointers
|
Easy
|
142,202
|
1,921 |
hey everybody this is Larry this is day seven of the Leo d challenge in November hit the like button hit the Subscribe button join me on Discord let me know what you think about this far and explanation and my background right now um yeah I am actually in a covered more in Hiroshima and just got in today uh just walking around getting food and yeah and got food so anyway back to the problem Back to the Future Larry yeah thanks past Larry uh hit the like button hit the Subscribe button while I click through everything uh today's PR is eliminate maximum number of monsters a medium problem uh let's give it a spin I'm still in hirosima uh I man I just woke up I should probably have slept a little bit more let's take a look at uh what the situation is shall we uh yeah all right you're playing a wiow game you're defending your City from a group of Monsters uh okay so the distance and the speed is okay what does the speed do oh okay so they it turn lost okay so I mean I think this seems like a very straightforward sorting problem uh on first glance I mean maybe there's some weird thing but you always want to um you know in a greedy way uh you know attack the monster or kill the monster that is closest it's not closest to you but reaches you in the least amount of time right meaning that it could be really far away but if the speed is really fast then you know it may beat you so I think that's the thing that we can do and then oh and then I guess this is just uh counting the number of things we eliminate and you really can't do much better than that in a greedy kind of way because if you kill the one that is going to that has the least time to you then you know that should be good um so time so distance over speed is time or speed over distance yeah speed over dist oh sorry distance over speed is going to be your time right meters over meters per second yeah so um yeah so let's sort by that I'm trying to think where I can do it without FS right um man every time I do these videos I feel like I'm about to sneeze like but um okay I'm okay but yeah I'm trying to think whether you need to sort by or I mean you sort by the you know distance over speed but I'm trying to think where it is easy to um to do with our throats because that could lead to issues but I guess it doesn't actually matter that much cuz if they're close enough I mean I guess it could really depends but yeah but I think if we do that it should be okay right because then now okay let's just say t is you go right uh so then now for DS in zp this speed right and t. aen D over s right and H I guess we could just also hold DNS just in case we could do a double check I mean I think the solding I don't know I think I get really uh freaked out a little bit with folding Point things because it's just so easy to make a wrong answer if you're not careful um but okay so let's say we have this and now we have four we don't care about the actual time we have the distance and things right uh and maybe the index or time spent right and en numerate oh this is terrible name uh so X for I don't know right uh that means that for the first one Z right that means that uh the current thing moved speed times x right so if this is greater than or equal to D then you die right so uh oh yeah and then you return killed or whatever I don't know otherwise then we can do increment by one I think that should be good uh oh that okay let's give us some mid I'm only woring about folding Point things but uh seems like it's okay because we do try to avoid it by still keeping track of it um I am wondering what I did last time well that just makes some oh why did I do it this way uh maybe that could work actually I don't know but did I just like what oh yeah I tried to fix it and then I still got it well what was the uh man oh because I sorted by I this thing instead so I we turn early that's the kind of thing right is that it's though I think I it seems like I made wrong answer is because I was too careful about uh these and not because I was not careful enough but uh yeah I don't know anyway uh yeah so what's the complexity right this is n l again time uh this is all of end space but can you do now you as soon as you saw it you have to do it uh in that way uh you could also have done it with Heap as well the same idea um in that case you could it's uh it's what you would say output sensitive because it depends on the size of the output but maybe not technically because you only output the number of bit um but yeah uh that's all I have for this one let me know what you think uh yeah and stay tuned for the outro which is I guess just now so yeah thanks for watching hit the like button hit the Subscribe button join me on Discord let me know what you think about today's farm O there was a puddle and today's ice cream is this thing that is supposed to be pure black uh I think that's roughly the translation I don't know how to be Japanese but I could guess at the country a little bit so I don't know but yeah it looks good let's uh let's give it a taste H I don't know what to make of this I mean it tastes very good I just don't know what flavor I think it's supposed to be like a cream bouet flavor uh and I guess it tastes like that in an ice cream form so yeah I would use this again so I would happily enjoy step on another pudle multiple version of this ice cream yeah I'm still in Hiroshima so and now I'm going to call it a night so stay good stay healthy to good mental health I'll see yall later and take care bye-bye
|
Eliminate Maximum Number of Monsters
|
eliminate-maximum-number-of-monsters
|
You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city.
The monsters walk toward the city at a **constant** speed. The speed of each monster is given to you in an integer array `speed` of size `n`, where `speed[i]` is the speed of the `ith` monster in kilometers per minute.
You have a weapon that, once fully charged, can eliminate a **single** monster. However, the weapon takes **one minute** to charge.The weapon is fully charged at the very start.
You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a **loss**, and the game ends before you can use your weapon.
Return _the **maximum** number of monsters that you can eliminate before you lose, or_ `n` _if you can eliminate all the monsters before they reach the city._
**Example 1:**
**Input:** dist = \[1,3,4\], speed = \[1,1,1\]
**Output:** 3
**Explanation:**
In the beginning, the distances of the monsters are \[1,3,4\]. You eliminate the first monster.
After a minute, the distances of the monsters are \[X,2,3\]. You eliminate the second monster.
After a minute, the distances of the monsters are \[X,X,2\]. You eliminate the thrid monster.
All 3 monsters can be eliminated.
**Example 2:**
**Input:** dist = \[1,1,2,3\], speed = \[1,1,1,1\]
**Output:** 1
**Explanation:**
In the beginning, the distances of the monsters are \[1,1,2,3\]. You eliminate the first monster.
After a minute, the distances of the monsters are \[X,0,1,2\], so you lose.
You can only eliminate 1 monster.
**Example 3:**
**Input:** dist = \[3,2,4\], speed = \[5,3,2\]
**Output:** 1
**Explanation:**
In the beginning, the distances of the monsters are \[3,2,4\]. You eliminate the first monster.
After a minute, the distances of the monsters are \[X,0,2\], so you lose.
You can only eliminate 1 monster.
**Constraints:**
* `n == dist.length == speed.length`
* `1 <= n <= 105`
* `1 <= dist[i], speed[i] <= 105`
| null | null |
Medium
| null |
1,732 |
hello everyone here is vanamsen in today's video we will tackle an interesting problem about finding the highest altitude and we are given an array that represents the net gain in altitude between points and our job is to find maximum altitude the biker can reach so let's start coding so first initialize the maximum altitude and current altitude to zero so max altitude will be zero and current altitude will be zero as well and loop through the gain list So 4G in gain add the current gain to the current altitude so current altitude will be G and check if they're current altitude is higher than the max altitude so if current altitude is greater than Max altitude if it is update the max altitude so max altitude will be current altitude and finally return the max altitude so return Max altitude so simple yet efficient implementation so let's run to see if it's working so it's calculating yeah so it's working and we started with a gain of minus five so the altitude are at the highest is just one and in second case is zero so yeah everything's work and so what we did here so we start at a uh sea level so altitude 0 and we keep a record of the highest altitude we have reached uh so far so we then look through the gains list and adding each gain to our current altitude so if any uh points uh the current altitude is higher than our record maximum altitude we just update the maximum altitude so it's really straightforward and yeah so let's see if it's working for unseen test cases and test it so yes it's working and we have completed 21 day of daily challenges so everything's perfect and we beat 80 with respect to run time and also 26 with respects to memory so uh it's really good and yeah our solution work as expected and this problem has a linear time complexity so uh o n and as we are going through the gains list only once so it's relatively simple problem uh once you grasp the concept uh so that's all for today and remember keep practicing and never stop learning uh be motivated and happy coding see you next time
|
Find the Highest Altitude
|
minimum-one-bit-operations-to-make-integers-zero
|
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`.
You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i` and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._
**Example 1:**
**Input:** gain = \[-5,1,5,0,-7\]
**Output:** 1
**Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1.
**Example 2:**
**Input:** gain = \[-4,-3,-2,-1,4,3,2\]
**Output:** 0
**Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0.
**Constraints:**
* `n == gain.length`
* `1 <= n <= 100`
* `-100 <= gain[i] <= 100`
|
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
|
Dynamic Programming,Bit Manipulation,Memoization
|
Hard
|
2119
|
492 |
hey everybody this is Larry this is f 26 I guess maybe well 26 but uh hit the like button hit the Subscribe but join me on Discord let me know what you think about today's extra prom I'm going to do an extra prom today on algo uh Ong with couple of days from leap day hope you're doing something leapy and crazy and whatever let me know in the comments if you have anything in schedule I do not I might just go like you know walk around or something I don't know why I say it like that it defin maybe I'll just go and leap around I don't know but uh yeah all right let's take a look at today's form we have 492 construct rectangle it's a easy PR they think it's not a premium problem actually but a lot of download so we'll see how that goes so a webler needs to know how to design a web page size or given a spec specific rectangular web pages area good job now is design rectangular web page CR length L and width W satisfy the faring requirement the area of the rectangle rectangular web page you design must equal to the given Target area the WID W should not be larger than length L which means L greater than W okay I me I'm not going to remember this the difference between L and W should be as small as possible what are we doing okay so we have four so 2 two of all the possible ways okay so uh what so we want when doing again okay so we want area so we want L * W is okay so we want area so we want L * W is okay so we want area so we want L * W is equal to area okay fine L is bigger than W okay fine or equal to and then the smallest is possible okay I see so this is like u i mean this it's not that bad it's just like a loop through the square root right or from the square root maybe but uh yeah that should be it h it's just like uh and if you uh 10 to 7 a little bit tight I was going to say maybe if you really want you can do like a prime shift type thing but I don't think that's the intent of this problem that could be wrong so we'll see but yeah all right let's just go for it then area right um and then maybe you could do like right so this is one of the sides and then basically if area mod s is equal to zero then we can actually return this right then we return um which one is smaller one so we count this down so the smaller one is actually on the second one so have something like this right that should be it uh and that'll always be true because I guess this should be well true because when s is equal to one this will always be true anyway right maybe I'm well oh what if area is one what why is this wall H am I missing something really oh well I mean that's fine oh this is uh huh this is an in but all right so 37 is a prime so maybe that is why but no that looks good so what is there issue here is it this one why did it infinite Loop oh cuz oh because this is a fraction so maybe this doesn't have a loop and way easy to make silly mistake to make but okay let's try the big case though it shouldn't be okay yeah I mean it is a easy problem after all but yeah it takes some time but pretty okay all right let's go to submit and there we go um that's all I have for this one um I'm not going to go the complexity here is kind of tricky to say because the input size is actually the number of bits not the area you're given right so um so this is kind of like two to the half or like two to the end over two or something like this which is over of two to the end so this is exponential I think but yeah uh that's all I have for this one let me know what you think and yeah stay good stay healthy to mental health I'll see youall later and take care byebye
|
Construct the Rectangle
|
construct-the-rectangle
|
A web developer needs to know how to design a web page's size. So, given a specific rectangular web page's area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:
1. The area of the rectangular web page you designed must equal to the given target area.
2. The width `W` should not be larger than the length `L`, which means `L >= W`.
3. The difference between length `L` and width `W` should be as small as possible.
Return _an array `[L, W]` where `L` and `W` are the length and width of the web page you designed in sequence._
**Example 1:**
**Input:** area = 4
**Output:** \[2,2\]
**Explanation:** The target area is 4, and all the possible ways to construct it are \[1,4\], \[2,2\], \[4,1\].
But according to requirement 2, \[1,4\] is illegal; according to requirement 3, \[4,1\] is not optimal compared to \[2,2\]. So the length L is 2, and the width W is 2.
**Example 2:**
**Input:** area = 37
**Output:** \[37,1\]
**Example 3:**
**Input:** area = 122122
**Output:** \[427,286\]
**Constraints:**
* `1 <= area <= 107`
|
The W is always less than or equal to the square root of the area, so we start searching at sqrt(area) till we find the result.
|
Math
|
Easy
| null |
292 |
hello guys my name is Ursula and welcome back to my channel and today we are going to follow a new lead code question that is name game so we will be solving this question with the help of JavaScript so just before starting solving this question guys do subscribe to the channel hit the like button press the Bell icon button and bookmark the playlist so that you can get the updates from the channel so let's read out the question the questions seeing that the question is saying that you are playing the following name game with your friend initially there is a heap of stone so the table you and your friend will alternate turns so you will take alternate comes you and your friends Miss and you Kofa so uh always we will be going first there is no chance that your friend will be going first always u means we will be going first and that is the condition the first condition is here that P will be going first so that is the key Point here moreover they say that on each turn the person whose turn it will be removing one to three stones from the Heap and the one who removes the last one is the winner given and the number of stones is the Heap return to if you can win the game assuming both you and play optionally otherwise it doesn't fall so we have to return to if we win the game or uh else otherwise false so actually what the condition here is that we will be given a static number and we have to either remove the uh we have to remove the number uh stones from that Heap example like there are four stones and we can either remove one or two or three stones and each chance we get and the other person can also remove one two or three so we have to just uh check for the value in a condition where if we remove the last Stone and means if we remove all the stones from the Heap we will be the winner for example there are four Stones if we can only remove one two or three stones so if we remove one stone from here we the other person will get three stones to remove and he will remove three stones and he will win if we wish to remove two stones and other person will get a chance to remove one or two stones he will remove two stones and win the game and if we get three stones to remove the other person will get one stone to S1 to remove and he will remove first one and will win the game similarly if we get one and definitely we will win because we will always get the first chance similarly if we get two we will always win because we will get uh the first chance and 3 as well so let's start solving this question guys so just before starting solving this question guys do subscribe to the channel hit the like button press the Bell icon button and bookmark the playlist so let's start putting this so my trick here is uh let's see four so the key Point here is four a number you see that if there is a 4 here you are losing why are you losing because in either of the case you are losing means one two three in each of the case you are losing and if you uh if it also take into consideration eight the possibility of you winning is not there because in each case you will be losing if you take one stone if you remove one stone but if in a condition you will get at a point that you will be at a chance to remove stones but you will not be winning so uh either 4 8 12 or 16 and so on means the multiple of all the four well the four numbers there will be the chance of you losing here so let me comment out here that a multiple of 4 You Will be a losing criteria so multiple of 4 will be the losing criteria meaning that if n is equals to a multiple of 4 then we will be losing so let's return that what we will be doing return and mod 4 is equals to 0 means if n is equal N is a multiple of 4 means n Mod 0 is equal is given as a remainder of 0 then we will be winning but we have sorry we will be losing okay so in this condition we will be losing however we have to return a condition where we will be winning so we will simply put a not here for not we will put this value and this is not in JavaScript if you put this we will say that it's not and simply run the code so you see that we have been getting our answer successfully so for four one two let's take some random value here as well and I have taken 412 into concentration report 15 or 16 or eight uh sorry 8 12 all will be working here because we have done it correctly so see if that all has been working correctly let's check for 8 and 12 last two that we are getting a false or not yes uh we are getting false because we will be losing in each condition where uh it is a multiple of four and elsewise we will be winning so that's condition here and that's the logic thank you guys for watching the video if you have any of Doubt ask in the comment section I will try to sort it out so this was all in the video thank you guys for watching it see you next time
|
Nim Game
|
nim-game
|
You are playing the following Nim Game with your friend:
* Initially, there is a heap of stones on the table.
* You and your friend will alternate taking turns, and **you go first**.
* On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.
* The one who removes the last stone is the winner.
Given `n`, the number of stones in the heap, return `true` _if you can win the game assuming both you and your friend play optimally, otherwise return_ `false`.
**Example 1:**
**Input:** n = 4
**Output:** false
**Explanation:** These are the possible outcomes:
1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins.
2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins.
3. You remove 3 stones. Your friend removes the last stone. Your friend wins.
In all outcomes, your friend wins.
**Example 2:**
**Input:** n = 1
**Output:** true
**Example 3:**
**Input:** n = 2
**Output:** true
**Constraints:**
* `1 <= n <= 231 - 1`
|
If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?
|
Math,Brainteaser,Game Theory
|
Easy
|
294
|
399 |
Hello Everyone and Welcome Back to my Channel Algorithm Hk Today I am going to write the code and also explain to you the algorithm to solve this evaluate division problem ch is there in lead code it is a medium level problem and belongs to the graph So let's start the section by taking the name of Shri Krishna, in this we are given a list of strings named Equations, a double array is given values and not a double array is given values and not a double array is given values and not a list of strings is given, queries are ok. So basically the first one is the list of equations which is representing again the equations which means if given a b that means a / ba value of v if given a b that means a / ba value of v if given a b that means a / ba value of v will be 2. Okay, from here we have to correspond like this, okay the values of the array. correspond like this, okay the values of the array. correspond like this, okay the values of the array. And similarly b c is given then the value of b divided b c will be 3 Okay in double here also let's see below here a comma is given that means ama b is given that means a divided by b will be the value values. Zero eighth element of the array then its first element again b divided by c will be 2.5 b c divided by c will be 2.5 b c divided by c will be 2.5 b c divided by c will be 5.0 okay so this is how we have to correspond the 5.0 okay so this is how we have to correspond the 5.0 okay so this is how we have to correspond the equations with values now we are given equations with values now we are given equations with values now we are given some queries okay that means we have to find its value Like here ama b meant a divided by b but its value was already given to us, similarly here the meaning of a c is the same as a divided by c but we have to find out its value, okay in this sometime- Sometimes they will give us such variables in this sometime- Sometimes they will give us such variables in this sometime- Sometimes they will give us such variables in the queries which will not exist in the equations, then what is the value of x divided by x at that time, what do we have to give minus whenever we find any such variable which is not a part of the equations but of the queries. If there is a part, then in every case we have to return -1, like here we have return -1, like here we have return -1, like here we have given a e that is a divide by e. If we want to find out, then in that we have returned -1. we want to find out, then in that we have returned -1. we want to find out, then in that we have returned -1. Okay, so we have a double array of the same length as the queries array. People have to return, okay, it will contain the answers to these queries, okay, like a divided by b, the value of that and b divided by c, the value of c was 3, so what will be the value of a divided by c, 6 okay and how will we get that 2 * By doing 3, if A is divided by B and into * By doing 3, if A is divided by B and into * By doing 3, if A is divided by B and into B is divided by C, then whatever is B and B will be cut and A divided by C will be left, that means 2 * 3 will be left with 6. Okay, by 2 * 3 will be left with 6. Okay, by 2 * 3 will be left with 6. Okay, by doing this, we have to remove it, so if we In graph format, if we make it okay, here we make it is A. Okay, this is B and this is C. Now we are given the value of A divided by B. Okay, then what will be the value of B divided by A. 1 Batu that is 0.5 Similarly we are given B divided by C Ki 3 So C divided by B Ki will be Bi Now whatever value aa is 0.3333 Okay so basically 0.3333 Okay so basically 0.3333 Okay so basically what we have to do is to find A divided by C. a divided by c we can easily find if we take a in b and b in c and multiply both those values, similarly we can find c divided by a if we divide c by b which is the value of Take 1/3 and then 1/3 and then 1/3 and then divide b by find the value of a, which is 1 btu. Okay, so basically whatever equation we want to find the value of, we just have to make sure that we can reach the variable that is that particular second. Whether it is from the first variable or not, then we will make this graph. Adjacency list will be made, so we just have to see that if we have to find A divided by C, then whether we are able to reach it or not. Now how will we reach from A to B? Okay, how much will it cost? Okay, we will do multiplication in this. Now who are the neighbors of C, one is A, okay, but we have already visited that, we came from A and there is one C. Okay, so C is our target note. If we look at it, then how much cost will we have to pay to reach C? So 2 * 3 6 is our cost. So 2 * 3 6 is our cost. So 2 * 3 6 is our cost. From our initial nut, we also reached the target nut from A to C. And by doing this we got our answer. Basically we have to convert this entire question into a graph and from it we have to see whether we are able to reach the target variable from the initial which is our variable or not. Okay. Mostly the coding part will be there, only a little will be there to understand, it is okay so that there is no confusion in it, so I am creating a separate class, it is okay to create neighbor adjacency list, in which there will be a string and which will represent our variable, which is okay. That string will be given double weight which will represent our weight which will be between any two neighbors. Okay, directed graph will be formed. This dot and it are creating TV constructor and others are id. Okay, now our main function has come, okay. This is the one, first of all we will take a map in it of string ok node and list of neighbors which will be its neighbors ok this adjacency list is our new hash map then for in it 0 all then values dot length map then for in it 0 all then values dot length map then for in it 0 all then values dot length values dot length let Take or values dot length let Take or values dot length let Take or equations dot length, equations dot size, actually both are the same thing, okay, considering the edges, we are going to populate the adjacency list, now we will take a list of strings named edges or edge, sorry right, and this It will be equations dot get aa ok, we will consider every Done, okay, so let's take a dot get 0 here, okay and then take the new array list next to it, now it will come here neighbors dot d new neighbor a dot get one and its correspondingly off a okay now same thing. Okay and write it down here and before doing this we also have to put it in the adjacency list so ADJ DPT AGE DUT GET 0 COMMA NBR S OK, after that we will put the new list in Neighbors OK Is correspondingly here this and here pe 1 divided by like if a divided by b which is 2 then b divided by a what will be 1/2 so we are b divided by a what will be 1/2 so we are b divided by a what will be 1/2 so we are taking 1 by values of i Okay now again taking 1 by values of i Okay now again taking 1 by values of i Okay now again here. Add J Dot Put Add Gut 1 And Then Again Neighbors Because This New One Is Neighbors List Not The Old One Okay Now With This For Loop Our Adjacency List Will Be Poplet Okay Now What Will We Do Let's Create A Double Array Which We Will Return In the last answer i is equal to new double is ok and what will be its length queries dot size Now here we have a line corresponding to each query queries dot size i+p ok let's take a queries dot size i+p ok let's take a queries dot size i+p ok let's take a list of string q to extract the element of queries D get a Okay, now first of all let's make sure that the elements in this query are present in our adjacency list, then it will be Q dot get 0 if this is also present and our second element is also present. So then we will populate the answer with a function, that is, answer of aa is ok, let's keep the name of the function solve for now, I will fill in its parameters in a while and otherwise we will put -1.0 in answer of aa, and otherwise we will put -1.0 in answer of aa, and otherwise we will put -1.0 in answer of aa, ok. And at the end we will return the answer, okay, let's write a solve function, how are we going to do it, solve will be on Y, private function will be created, private double, this is okay for those of us who return a spring after every query, so it will be here as string. The node which will remain our current node is given double answer. The answer we have till now is given by multiplication, given set of string visits. Whatever nodes are visited, if we do not want to visit them again, they will have to be stored, hence and then string target and ADJ. We forgot map of string comma list of neighbor AD Okay now first of all we will see that if this element is in the vegetate which is our node then we will return minus and okay because we have got the cycle we basically one then if our Which node is equal to target that means we have found the target then what do we have to return the answer is ok if there is no in both the cases then we will add our current node to the visit ok then for every neighbor we will call this function Will call recursively adj dot get and default node comma new array list then double well is equal to solve and for this function the node will be now neighbor is variable which was taken not answer into neighbor dodle which is wait then visit set then Target and then ADJ Okay, now we will see here if the value that we have just calculated is not equal to mine then we will return well and otherwise we will calculate for the next neighbor also and from all the neighbors if If we don't get the answer, what will we do? Return My P0. Okay, now let's write the solve function here. We have to reach the first element from the zero element in the query. So the value of the node will be dot get 0. Initially our answer will be 1.0. For the given set, we use new hash set, 1.0. For the given set, we use new hash set, 1.0. For the given set, we use new hash set, okay and then the target will be our dr get and then finally adj so this will be our code, let's run it once and see that the sample test cases are passing, submit. Let's try and see that the code is successfully submitted. But before leaving, please don't forget to like the video and subscribe to my channel if you haven't already. Also tell me my improvement points in the comment section. It's for the video Radhe.
|
Evaluate Division
|
evaluate-division
|
You are given an array of variable pairs `equations` and an array of real numbers `values`, where `equations[i] = [Ai, Bi]` and `values[i]` represent the equation `Ai / Bi = values[i]`. Each `Ai` or `Bi` is a string that represents a single variable.
You are also given some `queries`, where `queries[j] = [Cj, Dj]` represents the `jth` query where you must find the answer for `Cj / Dj = ?`.
Return _the answers to all queries_. If a single answer cannot be determined, return `-1.0`.
**Note:** The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
**Example 1:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\]\], values = \[2.0,3.0\], queries = \[\[ "a ", "c "\],\[ "b ", "a "\],\[ "a ", "e "\],\[ "a ", "a "\],\[ "x ", "x "\]\]
**Output:** \[6.00000,0.50000,-1.00000,1.00000,-1.00000\]
**Explanation:**
Given: _a / b = 2.0_, _b / c = 3.0_
queries are: _a / c = ?_, _b / a = ?_, _a / e = ?_, _a / a = ?_, _x / x = ?_
return: \[6.0, 0.5, -1.0, 1.0, -1.0 \]
**Example 2:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\],\[ "bc ", "cd "\]\], values = \[1.5,2.5,5.0\], queries = \[\[ "a ", "c "\],\[ "c ", "b "\],\[ "bc ", "cd "\],\[ "cd ", "bc "\]\]
**Output:** \[3.75000,0.40000,5.00000,0.20000\]
**Example 3:**
**Input:** equations = \[\[ "a ", "b "\]\], values = \[0.5\], queries = \[\[ "a ", "b "\],\[ "b ", "a "\],\[ "a ", "c "\],\[ "x ", "y "\]\]
**Output:** \[0.50000,2.00000,-1.00000,-1.00000\]
**Constraints:**
* `1 <= equations.length <= 20`
* `equations[i].length == 2`
* `1 <= Ai.length, Bi.length <= 5`
* `values.length == equations.length`
* `0.0 < values[i] <= 20.0`
* `1 <= queries.length <= 20`
* `queries[i].length == 2`
* `1 <= Cj.length, Dj.length <= 5`
* `Ai, Bi, Cj, Dj` consist of lower case English letters and digits.
|
Do you recognize this as a graph problem?
|
Array,Depth-First Search,Breadth-First Search,Union Find,Graph,Shortest Path
|
Medium
| null |
88 |
Hello everyone, we are solving the change world 4 number 8, it means let's move on to the description, we are given 2 arrays One and two numbers to these arrays that represent the actual numbers that we will work with in our task, that is, 3 here means that from the beginning We take the first three elements that we need will perform some actions, respectively, here the same thing and actions need to make a new array which will be sorted in increasing order and I note that initially we were given an array also in increasing order. So we need to get such an array, actually by combining two of which we will also get a sorted array, that means what solution comes to mind to use pointers? We will need a pointer to the end with which we will actually work, that is, a pointer to conditionally this three and conditionally this six, and at each iteration we will compare our six with the end of this pointer and write down in fact, our number is in another pointer which will be the end of the array that we need to create, and we will create the array based on the actual numbers that we will work with, that is, this is for us with the first one as indicated in the task and the actual implementation, we need to steal the method, we do it this way and for us we need the right Pointer about us, one that will point to m since we have an array, then minus one and for us C2 is N -1 and We need a pointer Y C2 is N -1 and We need a pointer Y C2 is N -1 and We need a pointer Y Pointer and which will point to us with dot like -1 is the Pointer that us with dot like -1 is the Pointer that us with dot like -1 is the Pointer that will be indicate where we will need to insert a larger number from under these pointers, respectively. We work according to what principle As long as our right pointer is not equal to zero Why is this because we are working while we need to insert something since we are inserting the second array first, this means that if in the second array there is nothing left 1 will no longer change logically means the conditions are simple if let's start from the first if the first pointer is also not equal to zero This means that we should not insert anything else and if ours is with 1 from under RP Enter more or equal to us with from under rp2 then what should we do we should place in us with and ours directly to us from 1 to intern 1 Well, it’s clear. Here we have a pointer to the 1 Well, it’s clear. Here we have a pointer to the 1 Well, it’s clear. Here we have a pointer to the end where we insert all our data that passes our conditions and directly the number which passed This condition then our number from under the rules of Ponter is greater than the number from the second array of the left pointer of the second by Inter if she passed this condition Let's repeat again if without a word from under the first array it is greater then we insert a Pointer that is, at the end our number will not be repeated This is the number And after that we must reduce our pointer by one accordingly and the pointer to the end because it has also shifted accordingly otherwise LS When we have C2 more we must do Similarly here I forgot one we need make us from 1 to interpretation that it is equal to us 2 by Enter to us 2 So, accordingly, we correct our pointers this is to reduce 2 pointer and reduce the pointer to the end of our array, our algorithm is all ready We need to check it how is this possible Let's pay extra comrade Let's yes live which means at the 2nd iteration it shoots again on the Internet. Actually, here it should not be equal. And greater than and equal to 0 is logically correct because I said that we should have at least something. So now here. What error if by Enter, in general, here the same thing should be the theory o Now everything is correct, excellent, but the logical mistake was that we need to have at least something to shift And this corresponds to the expression greater than or equal to 0 and not equal to 0 cancels these options in the form of zero, that’s how we get one hundred percent of the bits, but I think it’s easy to achieve that there’s think it’s easy to achieve that there’s think it’s easy to achieve that there’s a lot of variety here and here it’s 86 a lot of variety here and here it’s 86 a lot of variety here and here it’s 86 percent Thank you all for watching I hope it was clear So if you have anything, write and call
|
Merge Sorted Array
|
merge-sorted-array
|
You are given two integer arrays `nums1` and `nums2`, sorted in **non-decreasing order**, and two integers `m` and `n`, representing the number of elements in `nums1` and `nums2` respectively.
**Merge** `nums1` and `nums2` into a single array sorted in **non-decreasing order**.
The final sorted array should not be returned by the function, but instead be _stored inside the array_ `nums1`. To accommodate this, `nums1` has a length of `m + n`, where the first `m` elements denote the elements that should be merged, and the last `n` elements are set to `0` and should be ignored. `nums2` has a length of `n`.
**Example 1:**
**Input:** nums1 = \[1,2,3,0,0,0\], m = 3, nums2 = \[2,5,6\], n = 3
**Output:** \[1,2,2,3,5,6\]
**Explanation:** The arrays we are merging are \[1,2,3\] and \[2,5,6\].
The result of the merge is \[1,2,2,3,5,6\] with the underlined elements coming from nums1.
**Example 2:**
**Input:** nums1 = \[1\], m = 1, nums2 = \[\], n = 0
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[1\] and \[\].
The result of the merge is \[1\].
**Example 3:**
**Input:** nums1 = \[0\], m = 0, nums2 = \[1\], n = 1
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[\] and \[1\].
The result of the merge is \[1\].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
**Constraints:**
* `nums1.length == m + n`
* `nums2.length == n`
* `0 <= m, n <= 200`
* `1 <= m + n <= 200`
* `-109 <= nums1[i], nums2[j] <= 109`
**Follow up:** Can you come up with an algorithm that runs in `O(m + n)` time?
|
You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution? If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution.
|
Array,Two Pointers,Sorting
|
Easy
|
21,1019,1028
|
117 |
hey everybody this is larry this is me going over day 12 of the madeliko daily challenge hit the like button hit the subscribe button join me on discord let me know what uh day 13 maybe i can't do math anymore oh i can't look at the calendar uh anyway hit the like button hit the subscriber and drama and discord let me know what you think about today's prom probably nick's right point is in each note too um okay so basically there's no next right no the next note should be set to none all the next pointers are set to no okay what does that mean so four should point to five and five should point to seven and some should point to no is that it um okay um so it seems like the way i would do it is by using breadth first search i don't know if there's a quick cleaner way of doing it but or that i mean i'm going to do breakfast search but another variation of the breakfast search is going to be the level first search so i think that's what i'm going to do and what's this to say about it right i don't think i have anything much to say about it except for i'm just gonna do it and then yeah and first we're gonna do and but basically the idea is just um the idea is just doing it just looking at each note and then we would do a breakfast search um or a post-order traversal a post-order traversal a post-order traversal um yeah it should be okay so let's get started on that um i want to think about how i want to handle the levels but maybe that's fine but yeah say root and 0 as the root level and then now while length of q is greater than zero current is the code or current node or node current level is equal to q dot pop left and then we go um well there are a couple things we need to do right one is obviously append the left and the right um you know if no dot left is not none or maybe we can just even say for next node in uh node.left node.right uh node.left node.right uh node.left node.right make it slightly you know if next node is not none then we append next node and current level plus one um yeah so that's basically processing the afterwards um and then here we go so we can take a quick peek at the top so if length of q is equal to zero then we can take a you know q sub zero uh maybe next node next level maybe basically this and then if current level is equal to next node level maybe the next level is a little confusing actually next node level um then that means that we're in the same level and they're the next on the breakfast search right so then here we can do note that is it right or no next is to go to next node um and that should be good i think they're already starting with nodes or none in our case so if we don't i don't think we have to change anything and we have to return to root maybe so let's return the route right doesn't actually say uh that's silly why would you not assume that because you would assume that the q is whatever so yeah that's still silly though but okay oh that's the follow-up is using nah but oh that's the follow-up is using nah but oh that's the follow-up is using nah but that's okay i don't oh no could be none oh i guess for this one no that's not that's a little bit silly but okay fine um yeah so now let's give it something i might oh i hope i don't have the wrong the right the same wrong answer but okay 77 73 days streak uh looks good i mean this is gonna be linear time linear space this is just silly like basically just saying doing recursion without um yeah in terms of extra space i mean you i guess you could do like uh morris traversal type thing i mean i don't know it just to get i mean yeah and then get something on the next level or something like that i don't know if that's really the point so well like i don't value it that much how do i not test this wasn't if this was the input okay well and i did the last time i did it with a level um search it seems like so yeah level depth search no level first search or something like that but yeah so it should be okay yeah and today i did a more breakfast search um yeah cool i'm gonna gotta run let me know what you think hit the like button hit the subscribe button join me on discord i'll see you later and take care bye no wait yeah to good mental health i think that's what i always like to say and i don't want i don't like missing that one so to go mental health i'll see you later bye
|
Populating Next Right Pointers in Each Node II
|
populating-next-right-pointers-in-each-node-ii
|
Given a binary tree
struct Node {
int val;
Node \*left;
Node \*right;
Node \*next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`.
Initially, all next pointers are set to `NULL`.
**Example 1:**
**Input:** root = \[1,2,3,4,5,null,7\]
**Output:** \[1,#,2,3,#,4,5,7,#\]
**Explanation:** Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 6000]`.
* `-100 <= Node.val <= 100`
**Follow-up:**
* You may only use constant extra space.
* The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
| null |
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
116
|
1,268 |
hey what's up guys uh this is chung here again so this time uh today's daily challenge problem uh number 1268 search suggestions system right so given like an array of strings products and a string search word so we want to design a system that suggests at most three product names from the products after each character of search word is typed right so obviously you know the search word should have the result you know the suggested products should have like common prefix with a search word right and if there are like more than three products with a prefix we return the three lexicographically minimum products right and we need to return the list of lists uh where the uh of the suggested products after each character of search word is typed right so for example uh so i think this one is it's just like similarized like a google search right basically every time if you search like a word in the google every time when you type in the word it will give you some uh suggestions along the way right so for example so this is the products we have right and then the search word is mouse so which means so at the first time we have a search word is m right so for m we have like this kind of three words right second time we have m and o right typed in there and then we have some other like search word and then this next one is mou right so when it comes to mou we only have like two uh suggestive products right and then i'm ous and the m o u s e in the end that's everything we have right so yeah i mean obviously if there's nothing matched we simply return like empty string or empty list right um so here are some constraints we have so the product the total product is like 2 times 10 to the power of 4 and this the word length is 1000 right and all characters are lower letters so this one you know obviously you know the first one the first solution will be the prefix tree right so basically we uh we simply just build a prefix tree uh using this kind of like uh all the products right and then we insert all the other words into the prefix tree and then uh after that we basically will use we'll loop through all the prefix right from the search word we look through m o u and so on and so forth and we use each of the prefix and then we do a dfi search right from the prefix tree and then we will get all the uh all the possible other possible uh words right who have the same prefix and then we do a sort and then we return the first one after sorting right so that's the first one and yeah and we'll implement that and actually there's another solution for this one which will be using the binary search but let's try to code that first one right which is the prefix tree so i prefer to create a separate three node class right to store everything i need into the prefix no tree node so this one we have the children right the children will be like dictionary right and then we have this word equals to false right so here i mean um we can either store the word string or not because you know because things we need to return the actual string the actual word itself you know while we're well building like this word here no let's say we have uh a b and c right so at the c here you know we can store abc or we don't have to store it you know because i store it just for the sake of uh code will be simpler because you know if we don't store it i actually know while we're building like this kind of like uh dfs here you know we can just uh concatenate each letters along the way so in the end when there's no children right we simply we can also get abc right by storing this abc along in at each of the leaf node you know the space complexity will be a little bit high right but i'll just stick with this one you know since that's how i implement this right and so once we have that uh um yeah uh we can also create like a separate uh try class or we can just put everything into this like one solution right i think we can just put everything into the solution here uh so we have a root right root will be the tree node right and then we have two we need to have two functions first one is add a word right it's going to be the word so the current one is going to be the root right and then for c in word if c not in the node.children if c not in the node.children if c not in the node.children right we do a node.children.c right we do a node.children.c right we do a node.children.c equals the tree node right that's how we implement the prefix tree and then we have node equal then we move the node forward to the next one and we got children dot c so in the end we can have like note dot is word right notes our current equals to true and then the current dot word string equals to because the word right so that's how we add the word yeah and then for the search right so we have a search word so for search word all we need is a prefix right so we have prefix so the first thing is that you know we need to do a uh the current is also we start from the roots right and then we find all the nodes right actually we find the nodes that is the end of the prefix right because we need to find we need to consume all the prefix and then from here onward we can just gather all the uh all the leaf nodes that has the same prefix that's why when you start from the root and then so for c similarly similar to the add word function in the prefix right we have this one if c uh in node in current.children then we keep moving in current.children then we keep moving in current.children then we keep moving forward so current will be the current.children.c be the current.children.c be the current.children.c right else you know if we cannot find uh any letters from in the prefix tree existing in the ladder in the prefix stream in the prefix tree and then we know okay there's no valid suggestion which we me which means we can simply return empty list right otherwise if we have find all these letters in the inside prefix then we can do a dfs starting from here right um because here you know if we do a dfs from the current one no so basically this means that you know let's see if we have a b c right again a b and c so the prefix is this right a b and c so after a b and c right after this photo pier you know it's current the current one is pointing to this one right because that's how we uh do the current.children right current.children right current.children right and starting from here we could have different like letters right we have a d e f or something like this right so could be a then a d b it doesn't really matter right so basically starting from here we want to find all the leaf nodes right starting uh the leaf node uh who has who is the parent node starting from here that's why we have to scatter it around we have scatter it and then we do a dfs starting from here and yeah and after dfs right after dfs here we have a candidate right from this dfs and then we do a sort right we do a candidates dot sort and we do a return candidates uh the first three right so that's how we do this thing here and in terms of the uh in terms of the dfs right so let's uh then let's just define that dfs here so we have a dfs and it's going to be the node i'm assuming right and if the nodes even node is a word right we have find a leaf node not actually it's not a leaf node you know i think my mistake could be also like right in the middle right because you know so we have some node right this one could be a valid letter and this one could also be a valid letter that's why you know so it shouldn't be a leaf node basically any node who has this flag equals to true right yeah so which means that you know actually we should not return from here we should just keep doing because you know if this one is a word you know maybe the next one is also a word right maybe there's another like another child right that's why i see so in this case yeah let's do this okay i'm going to move this dfs inside the search word here okay because here i'm going to have like an answer right i mean so in this case the candidate should be at the beginning it will be equal to this empty okay and so indeed so in inside this dfs okay inside dfs you know whenever the word is true and then we set candidates right we append these candidates with the current with the node.workstring right with the node.workstring right with the node.workstring right since we also store the word along with this uh this flag along with the node and then for child in node.children node.children node.children right it's a dfs we do a dfs of the node dot children dot child right it's simple dfs we just uh dfs traverse all the other nodes after this current nodes and after this one we have candidates right and then we just do a sort and then we do return yeah so that's the basic that's all the uh the power functions here you know and when it comes to the main logic uh we simply just do a uh so do a first for word right in products we first build the uh the prefix tree right so we have add word right word you add a word and we have answer right and then for each of the uh for each of the search string right so we have this prefix right empty right so for c in search word right so prefix plus c right and then we do a search so the result is going to be simply just a pen right and this kind of search oh this is the they're the same actually you know let's do add and search in this case since we have the same name here as a variable yeah so i think here we'll just add a search right so we search this prefix yeah then we return the answer yeah i think that's it so let's run the code accept it yeah cool so it passed right and yeah nothing fancy right it's a very classic uh prefix three implementation so and so for the time and space complexity i mean um so we have word here right so to build the prefix tree uh we need do you basically we need to enumerate towards all the other words and for each word we have to do another for loop to traverse each character so to build the prefix tree we have all of uh so i can use a big m here right so big m means that this is the total characters among all the products and then to search to do a search right to do a search you know the search word is it's like one 1000 right because the search word is like the it should be uh smaller than the then each of the products right now i mean not smarter actually it's their length here the product lens and okay so here's a search for this 1000 right and then for each of the prefix we do a search so the time complexity first do a search is so first we'll do a photo here right to find each of the to find the last letter the last note after doing this kind of uh prefix and then from there onwards we're gonna do a dfs right so the dfs here you know dfs you know the worst case scenario you know we could will basically traverse all the possible notes in the uh in this tree right so the possible nodes in the tree will be the number of the products and yeah so for this one you know so the first one we have one thousand but in inside of search here right we uh we also need to uh do a like four loop up here so it's gonna be a like one thousand times 1000 right and then in terms of the dfs right i mean after this one you know we have like we have dfs and so the dfs can the dfs the number of dfs is also up uh up to the uh the number bounded or dominated by the number of products so that's why you know the total time complexity for this one is going to be uh you know o of m right i would say this basically of m plus this is m of m square yeah and since this one is like 1000 and the oh so this big m is it's right here it's 10 times 10 to the power of 4. then this one is 10 to the power of 6 yeah so actually so basically this one is dominated by this kind of iron square so that's the uh total time complexity for the first solution right and yeah and for the second one right i mean for the second solution you know we like i said we can use binary search to solve this problem and how can we do it right so basically you know since we have a prefix right so we have prefix and then we have a bunch of words that we want to search on you know so for example if we have like this kind of bag right so if we have like abc you know abd right and a b e abf okay and if our search string is like this a is a b okay and let's see if we have a b a c okay right so if this is the word and if we try to search the prefix is the prefix right it's eight it's a b so what are we expecting to get right so we're expecting to get abc abd and abe right and why is that okay so let's assume if we sort right if we sort these products from the smallest uh from the smallest to the biggest and as we can see that you know our starting point of our answer has to be at least has to be greater than this a b it's obvious right because you know since we need to get the prefix right so which means that you know it has to be either equal or greater than the current one because let's say for example is a b right you know this one i would definitely smaller than a b so which means you know if we do a binary search uh on this sorted products and we use this when we search this uh this prefix we have a we will get an index so the index will be what so index will be uh will be the first letter sorry will be the first word who is greater than this a b okay and then all we need to do is that let's say if we have index so all we need to do is that we just need to check the next three words from this index if there if they have a prefix of this a b right and why is why we only need to check the next three one because obviously this one you know we have a b c a b d and a b that's why these three are the answer you know let's say if the young if the next one is like this if this one is like it's ace right and this is a acd remember we have already sort this words right in this case you know okay so we're starting from abc and abd right uh and the abc is right abd is also right it's also has a prefix but the ace does not have it's not does not have like prefix so which means that you know if this one doesn't have a prefix of a b then it means that the next one will definitely not have would definitely not have the prefix as a b because again right because the number can only be increasing sorry not the string can only be become uh will only be becoming bigger and bigger that's why you know for this one if it has like a and c this one the next one will also have like a and c and this one can only become bigger that's why you know we only need to check the next three uh strings if they are like if they have the prefix or not right so i think that so that's it and let me come out this long code here and we can write some pretty neat uh codes here so all we need to do is that you know like i said we need to do a products.sort products.sort products.sort right and then oops and then we have the answer like this one and then for uh again we need the prefix right so similar for prefix equals this one proceed in search word prefix plus c and then we have index so we do index of by sect right left so we search from the sorted products and we search this prefix and from this index right we just do this we can just simply do this uh answer that append also write like a combined code here uh or let's just do this for i in range of three okay so if right if the products right okay so if the products i plus offset okay start with right start with the prefix and then we know the uh so this is the answer here we need like another list to store the current answer right let's use the uh how to use suggestions okay let me do a suggestions right that append this uh this product right and then the answer dot append the suggestions then return the answer yeah index here okay uh yeah so i see so i think here i think i made a mistake here um i guess i can do this so we have instead of doing this one we can just do a slicing of the products here right yeah i think this one's better it was slicing from products from the index to the to index plus three okay so now i just need to do this p here okay and then i just add this p here okay because with the slicing here you know the slicing will take care of we'll take care of the uh if this index plus three has reached is bigger than the length then it will just simply ignore that those things yeah so now it works so submit yeah so as you guys can see this one is much faster than the prefix tree because i think it's because the uh the sorting here we have a we have what we have let's see this n right so this is the unlogin right then log n and we have this kind of m here maybe so the word is like this is m let's see actually they're the same but this one is um m uh so binary search this one is it's log n right because the length of the product is log n so this one is log and then yeah and then we have this kind of like this one is of off one because it's a only three four loop here but we have this kind of p start with and this one is also like m right because we need to find the prefix from this word here so i'll say this one is also like m square right so i think this one is kind of m squared times log n so because this one will dominate the overall time complexity yeah i think it's faster than the previous one right um yeah so i think that's pretty much everything i want to talk about for this problem and yeah i will stop here thank you for watching this video guys and stay tuned see you guys soon bye
|
Search Suggestions System
|
market-analysis-i
|
You are given an array of strings `products` and a string `searchWord`.
Design a system that suggests at most three product names from `products` after each character of `searchWord` is typed. Suggested products should have common prefix with `searchWord`. If there are more than three products with a common prefix return the three lexicographically minimums products.
Return _a list of lists of the suggested products after each character of_ `searchWord` _is typed_.
**Example 1:**
**Input:** products = \[ "mobile ", "mouse ", "moneypot ", "monitor ", "mousepad "\], searchWord = "mouse "
**Output:** \[\[ "mobile ", "moneypot ", "monitor "\],\[ "mobile ", "moneypot ", "monitor "\],\[ "mouse ", "mousepad "\],\[ "mouse ", "mousepad "\],\[ "mouse ", "mousepad "\]\]
**Explanation:** products sorted lexicographically = \[ "mobile ", "moneypot ", "monitor ", "mouse ", "mousepad "\].
After typing m and mo all products match and we show user \[ "mobile ", "moneypot ", "monitor "\].
After typing mou, mous and mouse the system suggests \[ "mouse ", "mousepad "\].
**Example 2:**
**Input:** products = \[ "havana "\], searchWord = "havana "
**Output:** \[\[ "havana "\],\[ "havana "\],\[ "havana "\],\[ "havana "\],\[ "havana "\],\[ "havana "\]\]
**Explanation:** The only word "havana " will be always suggested while typing the search word.
**Constraints:**
* `1 <= products.length <= 1000`
* `1 <= products[i].length <= 3000`
* `1 <= sum(products[i].length) <= 2 * 104`
* All the strings of `products` are **unique**.
* `products[i]` consists of lowercase English letters.
* `1 <= searchWord.length <= 1000`
* `searchWord` consists of lowercase English letters.
| null |
Database
|
Medium
| null |
1,761 |
hey what's up guys this is sean here so today uh number 1761 minimum degree of a connected trio in a graph so you're given like an undirected graph right and then you have an integer n and uh and the list of edges for the graph and you need to find uh all the connected trail which is a set of three nodes where each node is connected to each other basically you need to find like a size of three a strong connected uh graph right and then for each of the strong connected uh three uh side three uh graph here you need to find the degree of that so the degree of that is basically uh is the address right that's not uh belong to this uh connect strong connected graph itself right so for example here uh so we have a trio right which is a one two and three right because those three are connected to each other and the degree for this trill is like is three basically anything that's uh we remove the connected uh address inside and then all the other the rest will be the uh the final answer that's why the answer is three okay and we need to find the minimum degree basically we need to find all the possible trill right in this graph and we which get uh we just need to get the minimum degree among all of them and remember so the graph cannot it may not be a connected graph right so for example this one right the uh we have a trill here so this one the degree for this one is obviously zero and on the right side we have two trio basically we have two four seven so we have two five six and a five six seven and either of those two trill have degree of two right so for example we have two five and six so the degree is like this one and this one that's why the degree is two and the range is like the size of this end is like 400 and the uh yeah and that's it right so the address will be like the uh within this range cool so i mean so for this problem you know i mean the intuition is pretty straightforward basically um at the beginning we just took to create a graph right which we create a graph uh undirected graph here and then if we just for each of the note here we'll try to find uh the trio uh that includes the cart node right so the way we're doing it we can uh we can simply do a nested for loop here so for each of the node right so we try all the possible name uh we tried to other possible neighbors for this one for this card note here for example if we have uh the what the one has like three notes right we have two three and four basically we try all the combinations of those uh of those two of the neighbors and then if those basically would the current one is not it's number one right so we have a uh the current one is that know the one and then we'll try to find all the combinations uh of node two and node three right among all the uh node one's neighbors and then among all those kind each of the combinations here we check uh if basically if n2 is in the ring is in the neighbor is the neighbor of n3 which means that if there's like graph right so if n2 is in the name in if it is the neighbor of n3 then we know okay so we have a we have like a trill right because since the n two n is the neighbor of uh both n2 and n3 are the neighbors or the neighbor of n1 right and then if n2 and n3i is neighbor then we find the trio okay so yeah i think that's a pretty straightforward right and let's try to implement that but you know the problem with that approach that for this problem tle i think that's why this one got a lot of downloads because it's simply just tle yeah um so we have default right default dictionary as a set okay i'll just do it and then f4 dot u v in address right and then we just create a graph of u and v so i'm just implementing the first approach just to show you guys the idea and then we'll try to uh improve a little bit on that so that we can uh overcome that tle so now we have a graph right we have undirected graph here and for n1 in range of one to m uh n plus one right so for each of the node uh we're gonna basically uh enumerate all its neighbors the combinations of the neighbors by selecting unto in graph of n1 and then for n3 in graph of n1 okay and if n3 is in the graph of is the neighbor of n2 you can also do a n2 is a neighbor of is in the graph of n3 either one works fine right and then we have like this uh council equals the minimum of the answer dot of dot what we have a length of the uh so once we have finds three nodes here right we just need to add accumulate uh all the degrees right all the degrees for the for those three uh notes here and then we said in we just do in the end which is subtract six because you know we have three edges i basically we have six edges so this one has two edges this one also has two this one has two uh we just need to subtract the six out of the total degrees and then we have our answer so here i mean the uh it's going to be a length of one right plus length of graph dot n2 plus length of the graph of n3 right and then in the end we subtract six and then return right else minus one so this one will work basically you know but if we submit it you'll see tle yeah so i don't know it tlc's in a way because you know for some reason right it's just like the uh i think the main reason it tle this time out is because you know we're basically duplicating uh we are double counting uh those trills multiple times right for example if we have uh one two three you know we may have two one three and then we have three two one basically since the this like these edges are undirected right so that's why you know we're gonna basically calculate uh those each trial uh multiple times so how can we improve that right how can we only maybe uh only calculate that trial once trio trill ones right um so the trick for this problem is that you know we can convert uh this undirected graph to a directed graph so that you know we'll basically will remove the address by half right so in that case you know when we loop through the uh those two for loops here we will basically cut the total for loop by half okay and how can we convert this uh undefeated graph to a directed graph right i mean we cannot simply do this right i mean if we do this in if we do it in this way you know basically there will be an issue the reason being is that you know it has to be a graph that without uh like the uh side a circle otherwise we'll have issue for example let's uh we have one two three right so we have one two and three so it cannot have a circle basically if this is the adjacent we're building here right so freaking this is a circle right if we only just blindly do this uh u to v here you know in case we have like a circle here this one will not work basically we'll not find this uh did this trill because uh no matter how we which node we choose here right if we choose one here will not have so basically we will only find either two or three will not find two neighbors that's why you know so we will not find a two and three at the same time so which means that you know it had it cannot have cannot be a like circle so how can we make sure the graph doesn't have a circle uh we can make a rule here you know so the edge is always pointing from the smaller number to the bigger number so in that case we're gonna have like this one right so in this case we'll have this one we have one two one three and two three in this case you know this is not like a circle so that you know we can make sure we'll always find uh the trio because for example oh of course you when you look through when you loop two here you will not find the trio but when you are at this one here we have two neighbors right so we have two and three and then since we are like looping through all the possible combinations right so basically so this one could be two this one could be three right in so in this case you know three is in the three in the like neighbor of two right on the other side right so this one can be a two and three right since we have a full for loop here that's why uh we can just only need to check this one once wait and we don't need to worry about n2 of n3 because uh there will always be a the case that we have loop through we have the number two is two and then n3 is three so we can only uh do this one if check here right so yeah but since we also need to do this kind of like degrees in the final calculations and since we have already cut the address by half right if we still using this like uh the length of the graph here you know we'll not get the correct answer uh so that's why we're gonna have like another degree dictionary here so default dictionary.int so default dictionary.int so default dictionary.int right so then we're always pointing from the smaller number to the bigger number right so it's going to be this one and then max of u and v and for the degree right we have u plus 1 degree of v plus 1. so now we can just do this right degree of this and this yep so if we run the code again oh so that's not we don't need this length anymore okay accept it so submit okay cool so this time it's passed right because we cut basically we cut the run time the time complexity by half by only uh maintaining one edge between two notes right so that we can uh reduce the uh the for loops here but still right that's the time complexity for this problem it's still in cube right because we have this kind of an acid for up here yep so i think that's it right so the idea is pretty straightforward the tricky part is that how can we uh somehow uh reduce the time complexity the runtime for this basically we are instead of building a undirected graph here we're building like directed graph but we cannot blindly assign the edge from one to another we have to make sure there's no circle in this graph right that's why we're making a rule here we're always building the adds from a smaller notes to a bigger note in that way we can make sure we can guarantee that there's no circle and the rest is pretty much the same yep i guess i'll just stop here and thank you for watching this video guys stay tuned see you guys soon bye
|
Minimum Degree of a Connected Trio in a Graph
|
count-sorted-vowel-strings
|
You are given an undirected graph. You are given an integer `n` which is the number of nodes in the graph and an array `edges`, where each `edges[i] = [ui, vi]` indicates that there is an undirected edge between `ui` and `vi`.
A **connected trio** is a set of **three** nodes where there is an edge between **every** pair of them.
The **degree of a connected trio** is the number of edges where one endpoint is in the trio, and the other is not.
Return _the **minimum** degree of a connected trio in the graph, or_ `-1` _if the graph has no connected trios._
**Example 1:**
**Input:** n = 6, edges = \[\[1,2\],\[1,3\],\[3,2\],\[4,1\],\[5,2\],\[3,6\]\]
**Output:** 3
**Explanation:** There is exactly one trio, which is \[1,2,3\]. The edges that form its degree are bolded in the figure above.
**Example 2:**
**Input:** n = 7, edges = \[\[1,3\],\[4,1\],\[4,3\],\[2,5\],\[5,6\],\[6,7\],\[7,5\],\[2,6\]\]
**Output:** 0
**Explanation:** There are exactly three trios:
1) \[1,4,3\] with degree 0.
2) \[2,5,6\] with degree 2.
3) \[5,6,7\] with degree 2.
**Constraints:**
* `2 <= n <= 400`
* `edges[i].length == 2`
* `1 <= edges.length <= n * (n-1) / 2`
* `1 <= ui, vi <= n`
* `ui != vi`
* There are no repeated edges.
|
For each character, its possible values will depend on the value of its previous character, because it needs to be not smaller than it. Think backtracking. Build a recursive function count(n, last_character) that counts the number of valid strings of length n and whose first characters are not less than last_character. In this recursive function, iterate on the possible characters for the first character, which will be all the vowels not less than last_character, and for each possible value c, increase the answer by count(n-1, c).
|
Dynamic Programming
|
Medium
| null |
96 |
present in jhala and how many unique binary search trees that we can form from andhra stupid and numbers so let's see how the algorithms are so let's see for example also have for numbers 1234 and make to how in how C1 is the source next nlin right is Two three and four bluetooth setting case 2011 is left hands free port who is right on this route 120 left 4017 fix for isro 1231 left for this channel 220 pocket sonawane reprint series servi hotel combination scan difficult servi 90 to c2c two drops even and shyam Noddy Flex The Number Of Trees In 7043 Is Line Three To Is The Number Of Industries And Restore Should You Specifically Ashraf Aggression Going 03 Dad I'm Tasty Abstraction Going Back Waters J - 151 The Softest Remake Abstraction Going Back Waters J - 151 The Softest Remake Abstraction Going Back Waters J - 151 The Softest Remake Dark And With R And Plus One That IOA Reports That MBA Feel Every Year A 200 A & B Mode Vaikuntha Zero Bhi Only One Case A & B Mode Vaikuntha Zero Bhi Only One Case A & B Mode Vaikuntha Zero Bhi Only One Case Study Abroad In This 11111 K Is Diet Roti Is One Should Be Left In The Dock More Than A Day Let Me To Make Some C 3210 Two Three Layer Forward Loot And inside and BJP leaders andar loop quit from adobe date to high fennel 125 you slept peon and liver algorithm oil ministry and throws - mind solve every ministry and throws - mind solve every ministry and throws - mind solve every time you wi-fi and will return dhundhuli pier time you wi-fi and will return dhundhuli pier time you wi-fi and will return dhundhuli pier aav hai so dandak ud loot to abhi arthritis and 59 For Any Issue Related Spinach And Basically Career Problem Share In Vacancy Edison Diamond We Are You Alive Previous Value Store
|
Unique Binary Search Trees
|
unique-binary-search-trees
|
Given an integer `n`, return _the number of structurally unique **BST'**s (binary search trees) which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`.
**Example 1:**
**Input:** n = 3
**Output:** 5
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 19`
| null |
Math,Dynamic Programming,Tree,Binary Search Tree,Binary Tree
|
Medium
|
95
|
283 |
hello and welcome back to the cracking fan YouTube channel today we're doing an easy problem for some of those people that may just be starting out on their lead code Journey we're solving 283 move zeros given an integer array nums move all the zeros to the end of it while maintaining the relative order of the nonzero elements note that you must do this in place without making a copy of the array let's look at a basic example to see what they want us to do we're given this array 0 1 0312 and as we're told we want to move all the zeros to the end while maintaining the relative order here so basically these zeros would have to go to the end of the array and we need to make sure that 1 comes before three and three comes before 12 so as you can see the answer here is 1 3 12 0 because we moved the two zeros to the end here now this question is really easy to visualize because obviously it's quite simple you just kind of move the zeros to the end but executing it in code is a little bit more complic licated now let's get rid of all of this text here and think about how we can actually solve this um in code okay so we looked at a very basic example and it's quite simple visually looking at it but how do we actually solve this problem and the way that we're going to do this is we're actually going to keep track of where our last zero was and as soon as we see an element that's not a zero we're going to swap it with the um position of that zero and we're going to do this for every single element as we Traverse from left to right over the array now let's see what variables we need we're going to need the position of our last zero so we're going to say the last zero is at the beginning we haven't actually seen any zeros so we'll just set it to minus one then what we want to do is we want to iterate over our array from left to right and there's obviously going to be two cases here and the first case is going to be that we see a zero so see a zero and the second case is c a non zero right okay so what happens when we see a zero well if this is the first zero we've seen then we want to make note of it and actually update our last zero location and the reason we only care about the leftmost zero is because we obviously want to make the swap with the zero that comes first we don't want to do it with something that comes later so if we haven't seen a zero and we know this is the case because last zero will still be at minus one we want to update it so when we get to this first zero we'll say that it actually occurs at the zeroth index now let's continue through the array we're going to get to our one and when we see a non-zero element there's two we see a non-zero element there's two we see a non-zero element there's two questions we have to ask ourselves the first is have we seen a zero before seen zero or two which is actually the easier case uh not seen yet if we haven't seen a zero then that means that there's no swap that we can make excuse me and we don't have to do anything so this is the easy case if we've seen a zero then we have to make the swap so we look at what the position of our last zero was and we swap the two indexes so when we swap these two our array will now be 1 0 uh 0 3 and 12 so we are good there now we are at this index still so now our last zero we need to update it um to be here right so our last zero is at the first index now what we want to do is we want to go to the next element which is a zero and remember we've already seen a zero so there's no reason for us to update this because we always want the leftmost zero to be what's pointed at in this variable here so we're going to continue and we're going to get to R3 here so what we're going to do now is we're going to say that okay we've seen a zero before and that's at the first index so we need to make a swap here so we're going to swap the elements again so we're going to say the three is going to get swapped with the zero uh and vice versa so it's going to be 1 3 0 and 12 right that is going to be our current array and now of course we've swapped the position of our zero and it's now the earliest zero is actually going to be the one at index two so our last zero is at two now we're going to continue through the array our we were at index two before now we're at index 3 it's a zero but obviously we've already seen a zero and it's at index two so we don't have to do anything then we get to this final element which is 12 and again we're going to ask ourselves have we seen a zero yes we have what index is it two so let's make the swap so after we do the swap we're going to say that the array will look like 1 3 12 and 0 Z so we have now moved um all of our zeros to the end and obviously 12 was the last element we needed to uh iterate over in our array so we're actually going to finish and then you see that our answer as expected is 1 3 12 0 so that's the general intuition now let's actually go code this up using the exact same algorithm that I just detailed here I'll see you in the code editor we are in the code editor let's type this up so remember that we need to keep track of whatever our last zero was right so we're going to say that the last zero is currently at minus one because we haven't even started iterating so we're just going to set it to minus one now we need to go over index by index and number by number through our array so we're going to say for I num in enumerate um nums we're going to say if not num so basically if the current number is a zero then we go into our case where we have to handle the zero so let's do that now so we're going to say if the first zero sorry the last zero that we've seen is actually at the minus1 index that means that this current number that we're at this current zero is actually the first zero so we're going to say that the uh the first zero that we've seen or we'll just say the last zero uh because we use that as our variable is going to equal to uh I so the very last zero that we've seen is that index I otherwise if it's a zero but we've actually seen one that comes before it um then we don't need to do anything because we want to get always the leftmost zero uh that we're working with so we're simply just going to continue here all right so that is the case where the number is a zero what happens if it's non zero well we need to swap it if um we have seen a zero and if we haven't seen a zero so far then we don't actually have to do anything so let's do the simple case first and that is if the uh last zero actually equals to minus one again this means that we haven't seen a zero yet so we can just continue because there's no swap that needs to be done otherwise we swap the two numbers so we're going to say nums of I and nums of whatever last zero is uh is going to equal to obviously we're swapping with zero and num so this will swap the two numbers so there we go okay now what we want to do is remember we actually need to update the position of our last zero right so we're going to say while um last zero is less than the length of nums so we're going to move its position up and we obviously have to make sure that we don't accidentally move it outside of the array and that the nums of the last zero uh doesn't equal to zero then we want to update uh the position of our uh zero right so we're going to say at last zero uh plus equals 2 one so this will be moving uh the position of our last zero up okay so that is actually all we need to do uh we don't return anything here obviously we're just modifying it in place so let me just run this make sure I didn't make any syntax bugs looks fine let's submit it and accept it okay perfect so uh how do I get rid of this is weird new I okay so now what we want to do is as always we want to talk about the time and space complexity so for the time obviously what we're doing is we're iterating over the array um from left to right and we're swapping things as we do the swaps are always going to be kind of uh o of one operations so our total time complexity here is going to be Big O of n for space complexity as you can see we don't use any extra space so what this means is that our space complexity is just Big O of one and that's how you solve the problem move zeros a bit tricky if you haven't seen it before it's a little bit annoying to get your head around but it's a good easy problem to kind of get you into that lead code mindset anyway thank you so much for watching if you found the video helpful why not subscribe to the channel and leave me a like it really helps me grow and I will see you in the next one bye
|
Move Zeroes
|
move-zeroes
|
Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements.
**Note** that you must do this in-place without making a copy of the array.
**Example 1:**
**Input:** nums = \[0,1,0,3,12\]
**Output:** \[1,3,12,0,0\]
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[0\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-231 <= nums[i] <= 231 - 1`
**Follow up:** Could you minimize the total number of operations done?
|
In-place means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually. A two-pointer approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array.
|
Array,Two Pointers
|
Easy
|
27
|
724 |
Hello, welcome to the channel, you are doing 90 days ac prep with me, this is the question lead code 724 find pivot index, question number 19 or lead code 75, so what the question says is that you have to return the pivot index. What does it mean, the sum of its left sides should be equal to its right sides 13656 We have been given an example, let me explain it 173 656 01 2 3 4 5 Okay, so for each index, think about the sum of its left sides, like if I say this If I think about the left index, there is no one to its left, so their sum is row. The sum of the people on the right is 7 3 10 16 7 310 + 6 16 + 5 21 + 6 27. So this is 310 + 6 16 + 5 21 + 6 27. So this is 310 + 6 16 + 5 21 + 6 27. So this is not a pivot index because the sum of the people on the left is h. The sum of the ones on the right is 27. If I talk here, there is only one number on the left side, its sum is one and the sum of the ones on the right is 3 6 9 5 14 and 6 20, so it is not equal. If I talk about the next point, let's talk about the next point. What should I do, is that the pivot index? So let's see the sum of the left ones is 17. The sum of the right ones is 656 so 8 and there is 17 so that is also not the pivot index. Pivot index will be. Let's see. Now let's look at this number and the sum of the left ones. The number on the right is 173, the number on the right is 56, the number on the left is also 11, the even on the right is also 11, so its index is three, the Pavant index, so we had to do this question, how will we do it, see, I was not finding this question so difficult. So how I did it, I found out this at every index, created a new array at every index, there can be other ways, how I did it, I created a new array, I call it the sum of the ones before that, like A B Let me explain the term of CD: A B like A B Let me explain the term of CD: A B like A B Let me explain the term of CD: A B CD, the sum of the first ones is the new array, so the sum of the ones before A is zero, the loop is started from here, the loop is started from Y, so I know what was put here in this pot. But I have to put a sum before b, so what did I put, what is this, the sum of the ones before a, and this is a plus this value, so here it is like what is the value for this number, let me say this again. The value represents the sum of the ones before B, this is B, so the first one, this is the sum of these ones, here I got plus B, then A P B, here, look for this value, what will I do, so original. The array and this one have to be valued, see why this one represents the value, the sum of the ones before them and this represents the array so A P B P C like here I want the sum of the ones before that is I want A B cd inside this same array that I am calling, inside the prefix array the previous value is a + b + c which represents the sum of the ones before d value is a + b + c which represents the sum of the ones before d value is a + b + c which represents the sum of the ones before d so if I add this value which represents the sum of the ones before d If I add d to it then I will get a + b + c + d, so then I will get a + b + c + d, so then I will get a + b + c + d, so I have made it Prefix Sumre Okay, so first see the formation of Prefix Sumre once, if you look at the rest of the code later, then forget it. Forget it for once, forget it, then see what I have prepared, put pre of 0, put zero before the zero element, otherwise their sum is zero, then ran the loop from one to the last, p of i -1 and If I ran the loop from one to the last, p of i -1 and If I ran the loop from one to the last, p of i -1 and If I add the names of i -1, then p of i will come. add the names of i -1, then p of i will come. add the names of i -1, then p of i will come. What is the sum of the ones before i and p of i -1, what is there on p of i -1? of i -1, what is there on p of i -1? of i -1, what is there on p of i -1? What is the sum of the ones before i - 1? So, What is the sum of the ones before i - 1? So, What is the sum of the ones before i - 1? So, when I added the i - 1 to the sum of the ones before i - 1. What is the when I added the i - 1 to the sum of the ones before i - 1. What is the sum of the ones before i - 1? So, when I added the i - 1 to the sum of the ones before i - 1, then sum of the ones before i - 1? So, when I added the i - 1 to the sum of the ones before i - 1, then sum of the ones before i - 1? So, when I added the i - 1 to the sum of the ones before i - 1, then my The first one became a sum, which I put in the previous one, pre of a, okay, when I was calculating this, I also found out the sum of all the elements, so in the beginning, I put zero in the sum and then going through each element, I added them all. After adding, I got the sum of all the elements and from what I have read in the pre-of a, I have sum of all the elements and from what I have read in the pre-of a, I have sum of all the elements and from what I have read in the pre-of a, I have read the sum of the left ones. Okay, look, now I will tell you again what I have done. Ready, this was the original A B C D e. Original Array: original A B C D e. Original Array: original A B C D e. Original Array: I have prepared a pre array, here is row, here is a + b, here is row, here is a + b, here is row, here is a + b, here is a + b + c and here is a + b here is a + b + c and here is a + b here is a + b + c and here is a + b + c + d and I have found out the overall sum. + c + d and I have found out the overall sum. + c + d and I have found out the overall sum. Taken my sum is a + b + c + d + e Looped again is a + b + c + d + e Looped again is a + b + c + d + e Looped again So now I am coming to any spot So what am I testing Coming to any spot So what am I testing Basically, when I reach point c, I want to check the sum of left and right sides, whether they are equal or not, I have to check if I am fine, then how can I find the sum of left and right sides? It is not very difficult, like if I reach C then the sum of the left ones will give me a pre. Like if I reach C and I have to check the even of the left ones, then I will get the sum of the left ones, then this is the pre off on you, if this has come. So pre of a will give me the sum of the left ones, that is a p b will give that now I need d p e of the right so how to get that from the total sum, take the total sum minus the left ones and c minus itself. If you do this then only the ones on the right side will be left, then a p b p c p d, if you minus a p b and c, then minus a p b my c, then if you cut this out, then p c will be left which is on the right side. So if the left one and the right one are equal then this is your answer then see the second loop what I have done is a very simple loop and put the second loop if any spot p of a i to sum minus sum is the sum of all out of that the numbers of a are Minus kiya and pre of aa means before aa or take the ones before i and if i is also minus then the ones after i are left na pre of aa was the sum of the ones before i and aa if after If the sum of them is equal then return the same index Return aa other wise Return -1 There is a loop of O twice The code of O is Return -1 There is a loop of O twice The code of O is Return -1 There is a loop of O twice The code of O is looped twice So beats everything I hope you have understood this question, so today we have discussed a lot. All the questions have been solved. This was 19th from lead code 75. I think decent progress. Seven-eight code 75. I think decent progress. Seven-eight code 75. I think decent progress. Seven-eight questions are left for the day. Let's do more. It is fun to teach on this page.
|
Find Pivot Index
|
find-pivot-index
|
Given an array of integers `nums`, calculate the **pivot index** of this array.
The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right.
If the index is on the left edge of the array, then the left sum is `0` because there are no elements to the left. This also applies to the right edge of the array.
Return _the **leftmost pivot index**_. If no such index exists, return `-1`.
**Example 1:**
**Input:** nums = \[1,7,3,6,5,6\]
**Output:** 3
**Explanation:**
The pivot index is 3.
Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11
Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** -1
**Explanation:**
There is no index that satisfies the conditions in the problem statement.
**Example 3:**
**Input:** nums = \[2,1,-1\]
**Output:** 0
**Explanation:**
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0
**Constraints:**
* `1 <= nums.length <= 104`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/)
|
We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1].
Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i].
|
Array,Prefix Sum
|
Easy
|
560,2102,2369
|
787 |
okay any thoughts on this problem first of all i want to make sure everyone understands that you know you need to return the cheapest flight from source to destination that has at most k stops right so if k is equal to zero that means that you're looking for direct flights right if k is equal to one you're looking for flights with at most one stop at most right you can still return a direct flight if that's cheaper but you're allowed to make a move to one stop so um the first thing that comes to mind is uh using a keep um it's probably dijkstra's algorithm because uh you want to sort it by the cheapest points um and then obviously if you go down a path that goes over your uh or your number of stops or um yeah if you go over yeah the number of stops then uh i guess you just have to like return uh if you didn't hit your destination um and then uh you just keep on popping off the heap until uh the first destination that uh or the first node that reaches the destination okay so first of all you know when you're during the interview we're describing the do not mention the data structure okay before you talk about so you should talk about the algorithm before you talk about the data structure because data structure is about implementation right now if you first so you mentioned dijkstra's algorithm so you can mention that extras algorithm without mentioning a heap right everyone knows that you can use a heap too you can't extract algorithm but that's implementation detail right so that you first need to um you know uh make sure that the algorithm is correct or um so when you're doing the express algorithm the typical algorithm just finds the shortest the cheapest i think you know in this case the cheapest flight from source to destination right so how do you ensure that the cheapest flight you find has at most k stops so like if you do that for search or breadth research each iteration is going to count as one stop yeah so how do you make sure that the result you return of course when you're doing that extras of course um the result will be the cheapest right but how do you make sure that the cheapest flight does uh has less than or equal to k stops um well so you need to remember the number of stops in the code right yes distance only one distance which is the shortest in absolute many shortest distances remembering according to the number of legs that it has crossed already so okay so you're saying in the in this easy extras we just you know we have a um for every node we have the shortest distance to it yes right but you're saying in this case you actually want to for every node you want to remember the shortest distance for every number of stops okay if there's more than okay then we can put it yeah okay there's no point of continuity right so but you're saying i need to know um the shortest the cheapest slide to uh node two if i have one stop zero stop two stops three stop like for every stop up to k like you want to sort what's an action information array or dictionary up to of size k okay um daniel do you agree with this or is this the solution you have in mind wait sorry could you repeat that solution i'm thinking that in the shortest distance array instead of being an array of numbers it is an array of uh dictionaries and each of those dictionaries has the uh your values from 1 to k from or 0 to k minus 1 there's so many legs this is the shortest distance so at any given point in time we have so many like if we also remembering how many legs we have crossed to get to this shortest distance so if we get another shortest distance for a different number of legs that does not supersede the one for a different number of so when we are comparing our normal algorithm was that we just compare it with the number and if we get a shorter distance from a different route we used to supersede it now we will remember both that by one leg we got this distance but by two legs we got this distance so every time we get a new one we know how many legs there are because we there is one more than whatever it was for parent and uh now in that we update for accordingly okay so um i want to illustrate the intuition right why we want to keep the shortest distance to a node for every number of stops right so let's say that um you have three ways to reach uh a given node n some node n from source okay so the first way is uh cost is one thousand stops is equal to two the other one is cost is equal to two thousand stops is equal to one the other one is cost is equal to 1 500 and stops is equal to one now among the three we what kind of information is needed like do we want to remember do we care about the third way or do we care about the second way if we have the third way we do not want to remember the second way right because if you're able to reach stand using and using one stops um then why you know with a cost of 1500 why do you want to go there with 2 000 right it doesn't make sense okay now how about uh the first way online 25 the first way we have to remember because the first one is the cheapest way right it uses more stops but it is the cheapest way so we still want to remember right so it seems like for every number of stops we want to remember what is the cheapest way to reach this node in this number of stops right so basically okay how do we reach and if we uh about one stop how do we reach n if we allow zero stop or do we reach end if we allow two stops et cetera but for a given number of stocks if we're like okay i you know let's fix a number let's say three so for three if i allow three stops there should i should only remember one number right it does not make sense to remember more than one number for a given number of stops right so if i yeah so just like in this case if the number is one i just need to remember 1500 i do not need to remember 2 000. right so for a given number of stops i just want to remember what is the cheapest um what is the lowest cost to reach end in that number of stocks right so that's why sanders proposed that we should use an array so this distance is right remember we usually use this distances um array to remember the shortest distance from source to every node right but instead of an array of integers now we actually want to remember to do an array of dictionaries right so this dictionary will be like okay so if you allow zero stops then you know what is the cheapest maybe the cheapest is three thousand then if you allow one stop okay the cheapest is 1500 and if you allow two stops okay then the cheapest is 1000 right this is for some node and you will have another dictionary for another node et cetera so this is going to be a list of dictionaries uh so what would the second dictionary look like so well this is for the first node right this is the first dictionary is for the first node how do you like you know what's that what's the cost to reach the first node then the second dictionary would be what is the cost to reach the second node et cetera so three thousand wait so three thousand is from one thousand plus two thousand but why are you writing no so okay let me complete it right so three ways to reach n and let's say n is zero from store source is something other than zero right so if you have forwards to reach zero from source then you would have this dictionary for zero right like starting from zero or two zero from source so which one is your source oh so your source is each one of these like one two no source is something given by is in the input yeah well i'm wondering how are you getting these numbers so to zero you're getting three thousand um added that index is for wait is it one two three four are those nodes or is that um one two three four these are let me call them abcd so there's no well there's no ordering right these are just ways different ways to reach zero from the source okay so with zero stops is three thousand one stop is fifteen okay yeah so i'm saying this is the amount of information you need right previously in the sort of dexterous algorithm we have seen um on wednesday the distance is what would the distances be the distance would just be one thousand for another zero because we're just remembering the cheapest value where the cheapest value is one thousand right but in this problem we need to also consider the number of stops we used right and how and so then the question is okay so do we just like what's the amount of information you need right do you obviously need both the stocks the number of stops and the cost right but uh do you need the like do you need to remember all of the possible pairs right but i'm arguing you don't need all of the possible pairs for example line 26 is not needed right if you can reach it if you have found the same number of stops but a cheaper cost then you don't need to and then that's the best one uh does that make sense yeah yep okay um so that i was thinking of uh something like that except i wasn't thinking of a dictionary i was just thinking so like i was thinking like a heap of uh tuples of the stops on the cost and they'll be ordered wait so you're saying this is a heap instead of a dictionary this is a heap so it's like a list of heaps or no like the heap is that it is the array and then um instead of the dictionary you have two points so okay so the reason why it cannot be a tuple is you need to quickly you need to be able to quickly update that right so if i found a cheaper way to reach some node you know in two stops i need to so if somehow i discovered that okay you can reach um this zero with a cost of 500 with stops equal to two then i need to be able to quickly update change this 1000 to 500. but why would you need to update it if you just keep push it to the heap it should already take priority over the original one and then if that when it hits the destination you just return so you never even finish the rest of the heap so like if you push it like let's say you have this 502 and if you push in 502 then that will go in before the other um 1500 into or 1002. yeah but then wouldn't you be too large oh i see so okay um because the heap actually contains a lot of unnecessary information and the only one there's no way to bring it out right so yeah but no so i think so daniel's point is that you don't need the odd one the old ones to be uh removed because you're not going to get to the old ones right so then you were saying that you can the heap can contain both two um 500 and to 1000 that's okay because 2 500 is going to be processed earlier than to 1000. yeah but right now yeah but yeah so your function would you will not return the wrong answer that is true but the heap will grow uh very large i see how i feel yeah okay uh daniel do you want to implement this one just okay yeah i'm still uh so for the dictionary one um zero one two so like what could you do so we're still using it here we're still using uh we're still using a heap yeah but for the dictionary um so like the way i was thinking about it for the tuple was like two and five would be just together but then in the dictionary grouping zero one two and one dictionary and then zero one two again in the next dictionary is that right yeah so okay so in the so two five hundred right so if you say 2 500 is a tuple but that still that um you need to associate that with a particular node right that is the cheapest way to reach zero right that's not the cheapest way to reach one or something right how do you i think still you need to include that information in the tuple so i'm just wondering what the second dictionary looks like well the second dictionary is the cheapest way is to reach one remember you have n nodes oh okay um but then we wouldn't need to so we only need um so why are we keeping track of all of them like don't we only like we're giving the destination so we only need to keep track of one yeah but uh well in order for us to get to some node we need to we can get to that node from many previous nodes right so we need to remember the cheapest way to reach the previous nodes all right so this is like kind of our graph then our adjacency list um no so the graph is the graph um actually you know what maybe it's easier if you um try to implement using uh tuple if you already have that in mind then we can um you know we can work from there okay um uh so basically i want to create a heap with so okay let me just build my graph first uh okay and then we have i think it's from two and uh price so this is directly right this is directed or undirected this isn't directed okay so once we have our graph um so we have a heap of basically what we want to do is uh push in uh the source and then um for all of its neighbors we push in and uh and basically we only push them in if k plus one or if the so basically we start our heat with um uh source and the number of stops uh which is starts off at zero and then for each node that we're gonna push in we're gonna add one to it um and basically that if we add one to it and it's greater than uh is greater than k then uh we don't even push it to the v but if it is less than k and that means we're allowed to um and then from there like we're basically going to keep on popping uh we're going to pop the as well as cosplayers and if it's equal if the node is equal to uh the destination then we just return the price so we're going to start off at uh so we're going to push the price to so we're going to start off at zero price as well um uh and we're going to pop so it's going to be we'll call this stage um and then half the middle is going to be the price and then the right one is going to be k um basically we can check this c is equal to destination which is um and then i don't think we need to keep track of like a visitor because it's uh i'm assuming this is a cyclic actually can i see that you cannot assume that but as we have seen before you don't need to visit it with this oh because i forgot why um like what's the benefit of having it visited to prevent cycles right so but a node will be visited um multiple times right that's why we need to update because we do need to update our shortest distance actually also you know i remember you explained this but when i sat down to doing the some problems i was i realized that otherwise what if a in this so there are nodes for which we've processed all the children now we do not want to go to those nodes even if routes exist right so uh if it's if there are cycles in the graph then in this one they aren't but uh if there are cycles in the graph then uh we do want to avoid them right well you won't avoid them no matter what because you only push to the heap if you're going to shorten the distance right but if for those that have already been processed you're not going to shorten their distance you will not shorten the distance but you'll still traverse you'll still continue the traversal which will take your resources no so you will um you'll come to that if where you're finding the max between the what the short assistance correctly is and the last orders distance plus last leg so that you will choose what it was so you won't touch anything i agree but then but the node will again get placed on the e plate and you know the old which node will again get then you are facing well you're placing a neighbor on the heap only if the neighbor is only if the only of the neighbor's distance can be has been shortened right so then you're saying that shortest distance array also doubles up as a visited yeah exactly okay so basically i'm keeping um you might keep up i'm popping the price stops and city if the city is in the station i'm going to return the price um and that basically stops is less than k then if stops is less than k then i know i can like uh continue adding to the heap but what if it's equal to k oh well if it's equal to k we don't want to represent um well so if k is zero that means you allow direct flights okay so right so okay sure yep right so if k is one start at negative one then we can one stop um i would just he said i would yeah maybe online 10 just saying let's go 2k okay but the thing is i'm starting at zero and then if i add one then the next time i can add another neighborhood right don't make it that'll make it too old right like if it stops at zero and then um k is one then i'm gonna keep push another stop so zero and then it's gonna check if one is less than or equal to one right uh and it is and then it's gonna keep push two would you but that's but well that's okay you're allowed if you're allowed to make one oh start that means yeah right yeah because i'm not counting the second one exactly yeah so okay um yeah so this should be in order um yeah so if i do have stops left over then i can check my neighbors and push them to the heap and uh add uh the price um to my current price and then it order the stuff by price basically um okay so i thought the heap like the keep your store in couples right i thought the first one is the price the second one is the number of stops but online 12 you are p plus mp is the cost right but that's when you yeah then the next one should be stops plus one then the last one should be nc uh oh yeah there you are right here so yeah so this is a neighbor on oh neighbor city uh and then yeah so it will be ordered by price um and then if at the stop as long as it falls under the stop so once we hit our destination it's uh it should give us the right answer um okay yeah we're always assuming oh no so if uh you're gonna yes so yeah if you cannot reach it then return minus one so yeah this is fine um i think it's going to complain uh yeah c double equals and uh also heap pop does leak or no keep up do you need to import yeah no you don't have to okay you push expected to yeah online 13. you need to give it the heat okay i think it's going to time limit exceeded yeah yeah so that's why we have to go through yeah so okay so let's think about what you know why it's slow so you're putting all possible um you're essentially you're not being selected in the in what you're adding to the heat right you're adding everything to the heap as long as they don't see the number of stops allowed right okay so in the okay so think about it in wednesday's class when we were doing those actress um algorithm problems we usually have a step like we say okay if the new um cost is smaller than the old cost only then do we push too heavy right but you don't have this step here you don't have this thing here right so here on line 13 you're always you know for every neighbor as long as they don't exceed the number of stops you're just going to add to the key right so we can keep that uh the distances array um yeah it has like the cheapest price and then for every um basically we only want to push it in if uh if it's less than the price in our distance area but how about the number of stops the first stop so what if you what if the current way is actually is no cheaper it's more expensive than the old way but you the current weight uses fewer stops but then well like so fewer stops like we don't care about the number of stops as long as it's under k right so well yeah but if there are if in the end you want to reach n but you know there's a easier one there's a you know there are two ways to reach uh you know like ann's parent one uses exactly k stops the other one uses k minus one stops you actually care about the one that uses n k minus one stops right because if you've already used k minus one stops to reach and the destination's parent then you need exactly p stops to reach and does that make sense so if k um if k if we can reach n uh with k stops versus n with k minus one stops you're saying n minus one is better no i'm not that's not saying i'm saying i don't know which one like in the end i only care about it right but let's say n is the destination i only care about the number the cheapest flight to the destination right but i but you know i don't know that right i don't know and so you like what is so in order to figure that out you need to know what is the cheapest flight to that destination's parent right now so how many stops to uh the destination's parent what if you've already okay what if what is the cheapest way okay how about this what is the cheapest way okay let's say k is three oh okay let's say k is zero so you only you're only allowing direct fights okay so somehow there is a very okay let's say k is one um yeah let's say kk is one okay so there are two ways to reach the destination's parents one uses already uses one style okay but it's very cheap right the other way um the other way uses it is a direct flight to destination parent but it's very expensive right so which information is needed and let's assume there's no direct flight from the source to the destination the only way to go to that energy is through that parent right now at this point in this case you actually the only way is to go to the more expensive direct flight right because you're only on one stop and the cheaper way to reach the destination parent already uses one stop right so you cannot go further from that parent to the destination right so what i'm saying is just because you know it's it is possible to reach a place cheaper does not mean that's the best way right so i so of course i want to know what is the best way what is the cheapest way to reach every node um for every stock for every number of stocks right that's why in the beginning i said it should be a list of dictionaries not just listed integers so i started uploading this list of in list of which and these things but the problem is that when we are putting they will still have only one heap right so now in that heap what comes for c in the conventional dix algorithm we traverse the nodes in from lowest to highest among the unvisible nodes yeah uh now the concept of lowest to highest i am writing the comparator for that and the problem is that i have two things in my hand one is the stops and the other is the prices yeah so still you should prioritize the price and ignore the stops so no if there's a tie of course you would yeah the smaller number of stops works then smaller is better as you explain yeah wouldn't i have exactly the opposite way also that i should prioritize i should say stops and then why would i not say that so the difference is if you prioritize on the number of stops then when the moment you pop destination the moment you're currently visiting destination you cannot stop at that point because there may be a cheaper way to reach the destination with that uses more stops makes sense right but if you're prioritizing on the total cost then the moment you see the destination you know that's the cheapest one um with an array of stops like and like just having the minimum uh the minimum for each stop uh sure yeah that's fine too so like if we keep it like this way then and then stops array um for each stop right so okay so but the thing is how do you differentiate each node so like how do i know the you know the cheapest way to reach uh like node a in three stops how is that represented how can that be represented by this stops array uh so node a and three stops uh okay yeah i mean you can't i think this can be done but there's you need a two-dimensional way need a two-dimensional way need a two-dimensional way okay and the reason why we need um okay i think that's here so we're keeping track of every single one like every uh every note every node at every stop yes um okay and that will help us save space basically is uh basically if we're at stop one um and we're hitting node b and we see that node b is already in our dictionary then we know uh we know not to push it in because or if the cost is or larger than the one in the dictionary yeah then you don't need to push through the heap that makes sense yeah okay um okay so we have this array um basically we want to update uh for each k right so um okay so this is an array of dictionaries in dictionaries but you have k such dictionaries yeah so in each dictionary it is what will the key and the values be so the key value will be um the node uh actually uh yeah the node yeah i think if the origin like this and yeah the node will be the key and then the cost will be the value yeah sure yeah we can do that yeah so uh we're still going to check if the stop is less than yeah if it is then uh then we're going to compare it or see if it exists in ourselves um so i think that will come after line 4 13 right because this is different for each neighbor for each city if s is already in first circuit as a margin stops at s minus one or two yes we're starting at zero so i think so current so s is the number of stops to c right but now you're talking about nc so you actually need to increment s to plus okay yes so let's increment s outside of the for loop because you need to increment as in all cases for every neighbor zero index right so we're um okay so this should be k plus one right range k plus one because we wanna go up to k right like if it's one stop and one stop yeah and then we have to ignore index zero not like nothing should go yeah okay so yeah that makes sense so if that's one um so if it's not in our stops then basically we want to add it in so stops of online 13 stops of s plus one this is a dictionary yeah so stops of x plus one is a dictionary so online 13 shouldn't you be doing if nc is not in oh you got an s yeah sorry this is a 2d so yeah nc is not in um okay so s plus one always exists so yeah if nc is not in this dictionary okay then you're going to uh is it mp or it should be p plus mp right okay yeah if it's already there then you need to um set it equal to the minimum set it yeah equal to the minimum and then you yeah then you need to be yeah then there need to be a condition you know when do you push to the heap so yeah um right so you only push it in if uh if it's not there you know if it's not there or if it's smaller than this yeah yes i'll get rid of them yeah uh so if it's yeah if p plus np is less than that or yeah it's greater well if it's equal okay let's think about if it's equal then you don't want to update right updating is fine because it doesn't change anything but the question is if it's equal do you push to the heap well okay uh if it's equal um if it's equal why do you want to then nothing happened right because if it's equal that means it's the same number of stops in the same cost so it's so there's no point of yeah i don't think you should yeah this is equal to n plus and also i think after line 15 you need to push after line 14. right so line 14 if it's currently not existing you still need to push to the heap okay yeah this makes sense so if s is equal to k then oh maybe it should be range of k plus two let's try that yeah or i could just do um good okay um so during the interview right i expect um you should it's you know you get to uh you are able to get a working solution right of course it um it was not the most efficient one but uh it was correct so um i will still give you like a pass but um not be not going to be like a uh so it's going to be on the fence right now how do you of course during the interview you definitely the goal is to um impress the interviewer right but not we cannot do that in all cases right maybe the problem is really difficult or maybe the interviewer is not happy today or something like you may not be able to impress every wrong but still there's like a few small things you can do to you know make the odds in your work towards your favor so you can provide more test cases or you can um you know propose ways to uh to like so first the most important thing is you need to recognize why it's exceeding the time limit of course in each of you there's no one's going to ask you to run the code so but i still need to understand where the inefficiency is right so you know in a real interview setting it's actually more difficult because just because you don't you cannot run all of the test cases so you do not know if your solution is optimal or not right so you need to in this case you need to understand that okay um we're not we're pushing every possible um every possible tuple into the heap right so that's actually not that extra because extra assumes that you're being selective right but you're not so you at least you should be able to recognize that this is probably where we can further improve as to can you improve it that's a different story right but i expect a good candidate to understand that you know this is probably where the inefficiency is right and um is it okay like if i go like i'll finish the proofers first and then the interviewer tells me like can you improve it and then i get the solution yeah that's totally fine but i think would be better if so it's totally fine if the first draft is not the optimal i think some in some cases even if you know the optimal solution you can still implement a less than optimal solution as long as you know that the less than optional solution will lead you to the optimal solution like if you know that this problem can be solved using like a bfs but somehow you decide to you know like do a blue force or something then that would be stupid right because um you would have to erase everything you've written and rewrite everything right but in this case the optimization really builds up on the brute force and not the like on your um you know your first approach right so this is definitely a good starting point um but the thing is you should be the one who realizes that this is not optimal right um so if you can yeah so do not so yeah like after you finish this you can say yeah i think this is working but um may not be the most optimal right now let's see how we can further um optimize this right and now you cannot so then the only way to understand how we can optimize on an existing code is to understand where the inefficiencies are which is what are we doing duplicate work right so in this case we're doing duplicate work because the heap is taking in a lot of unnecessary levels right and the heat pop operation is log n where n is the size of the heat so if your heat grows very fast then your heat pump is going to be pretty slow right this is different if we were not popping instead if we were just looking at the smallest value like if we're just picking the smallest value then this will be okay because you know peaking is over what no matter how large or your heap is installed one always but if you're popping it then let's log in
|
Cheapest Flights Within K Stops
|
sliding-puzzle
|
There are `n` cities connected by some number of flights. You are given an array `flights` where `flights[i] = [fromi, toi, pricei]` indicates that there is a flight from city `fromi` to city `toi` with cost `pricei`.
You are also given three integers `src`, `dst`, and `k`, return _**the cheapest price** from_ `src` _to_ `dst` _with at most_ `k` _stops._ If there is no such route, return `-1`.
**Example 1:**
**Input:** n = 4, flights = \[\[0,1,100\],\[1,2,100\],\[2,0,100\],\[1,3,600\],\[2,3,200\]\], src = 0, dst = 3, k = 1
**Output:** 700
**Explanation:**
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.
Note that the path through cities \[0,1,2,3\] is cheaper but is invalid because it uses 2 stops.
**Example 2:**
**Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 1
**Output:** 200
**Explanation:**
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.
**Example 3:**
**Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 0
**Output:** 500
**Explanation:**
The graph is shown above.
The optimal path with no stops from city 0 to 2 is marked in red and has cost 500.
**Constraints:**
* `1 <= n <= 100`
* `0 <= flights.length <= (n * (n - 1) / 2)`
* `flights[i].length == 3`
* `0 <= fromi, toi < n`
* `fromi != toi`
* `1 <= pricei <= 104`
* There will not be any multiple flights between two cities.
* `0 <= src, dst, k < n`
* `src != dst`
|
Perform a breadth-first-search, where the nodes are the puzzle boards and edges are if two puzzle boards can be transformed into one another with one move.
|
Array,Breadth-First Search,Matrix
|
Hard
| null |
354 |
Same simple bollywood style number pregnancy 40 list subscribe and subscribe the channel loot subscribe to and jyoti grover satish question is what is the number of you can do but mostly subscribe to tomorrow college rotation is Not lost you can not be seen its problematic play list lutab school subscribe now to receive ki sadak par jha lalit electronic what is subscribe button dab school intermediate hai the increasing ki vegetables subscribe this video plz subscribe channel subscribe 49 350 subscribe secretary and subscribe The fort yes bhai saif youth 4579 13151 more force youtube subscribe and subscribe the channel subscribe video subscribe jo vyakti samay jab school dubo aandhiri do you do subscribe my channel ko subscribe to ki dynamic programming approach hai here approach which you will meet all your This problem in president Anil Vij 909 subscribe to that dynamic programming light and tears a lot statistical data this liquid solves the problems of subscribe and subscribe the video then subscribe to subscribe our that we hold to convert what is the call the biggest thing is able to convert In Two Decades Ago That Into One Day In Life Is Log In And Record Is 10th We Consolidate With Loot Flash Lights And Enemy Positive Seconds Not Only But Understand Trees Now Loot Of This Problem And Unique Lee Loot Come Up With Anil Gautam Right now the Buddha victims can eventually Guddu sometime subscribe and subscribe the video then subscribe to subscribe our channel subscribe finally hard match of Udayveer video subscribe v2 ki de number laga dijiye a real ment by dars on flash lights Navami Shot Element Weather Report Will Have Punished Adheen Famous Vinod Dhawan Subscribe Page And Hai Noobs And What They Want Oo Also Understand What Did Not Conducted What Is Subscribe And Subscribe The Video Then Subscribe To The Page Quote So Lets And Dual 5.23 Like Quote So Lets And Dual 5.23 Like Quote So Lets And Dual 5.23 Like Subscribe and 6 more where is the phone and here is the increase in the liquid Subscribe To that look at six and sit in Dubai This 5-wicket win match Like This is the thing will 5-wicket win match Like This is the thing will 5-wicket win match Like This is the thing will not Like Share Subscribe That Iraq Mr. 1008 Liquid Diet Absolutely Reduce Will Know How To The Same 2009 Subscribe Now To And Subscribe To The Channel And Send A Message The Incorrect My Favorite Song 2014 Elements In Ascending Order Which Ended The Element Subscribe To Set Alarm Feature Suggestion Singh Will Provide Custom Short short information with now screamed amazon subscribe to that and where lok and avoid and avoid and avoid falling on loot meaning of is next and heard minute posted start 30 subscribe this video please subscribe and subscribe the channel please subscribe and subscribe the that electrolyte such Things Related To Handle The Starting Point To Avoid Quite Well Into Light On Setting Show Me The Best I Will Lead To Start Sandhi The Start Sandhi The Start Sandhi The Car And After Unveiled Open Spelling Divya Problem Daughter And Or Se Nav Did Not Issue Neetu Person Subscribe kare subscribe and subscribe the ke lachhe gusal factor of intent on ki naav the voice of tribes commission maximum subscribe to subscribe and share dip is this is the best wishes subscribe now to receive one day and ki lakundi towels aur yuva samsam this is Equal To Subscribe And In Detail It Was To Now That Das And You Want To Return To Avoid A Me Aa Yash Chopra Distic And The Beast Ameer And Subscribe Now To Receive I Just A Single Child Extremely Specter Vector In Witch College Life Subscribe 208 And good very simple to quit subscribe that if Gautam a ab half lakh ab element that in this prayer in love uh that in animal sacrifice of na element that element of one middle subscribe to that without written in the Plural of plz subscribe channel e will write dysfunction length sexual orientation function veer ko tight and complexity after am shopping subscribe and subscribe the that today date against the constitution told that on thursday that problem in log in this problem these people subscribe to New Delhi Lens Do That Ek Chocolate To First Gas Is Function In Which Is The Mistakes In Neither A Vector Of Indian Law Of Prophet Ko Ek Handa Please Share And You Know You Notification More Subscribe To Ali Subscribe Hello Viewers Common Element Electronic a is here nandish schedule is honorable and v 5 seconds and this obscene pea two a view of time ribbon adam returns 583 that nine 's report 's report 's report 112 place and state Lucknow appointed on sexual intercourse that this returned shahrukh jhal i also quickly element zinc subscribe To loot lo ko turn problem hai deputy mayor and deputy mayor appointed will see what is subscribe and subscirbe subscribe to a written without neither money nor element of like share and subscribe the video then subscribe to the page if you liked the video then subscribe to subscribe our channel subscribe and subscribe queens baton difficult few pilots among the earth twitter the amazing subscribe to torch light 989 3583 love with a beginner reverse foreign secretary david 512 subscribe button subscribe to that trick height ten length appointed 2358 999 subscribe video subscribe and subscribe the channel subscribe loot lo kyun nahi ho me bank of baroda security number na element wich element ko subscribe jaroo subscribe kar lu subscribe 189 difficult subscribe 9 are you saying that you have also adding 12345 no thanked website my voice with abhinav hafte ke Andar live without oo ho r element well in this inter remedy subscribe video to get more lecturers on after this position he guys to all ur interested in snakes leave this problem once again but looking at this logic not mean that they are loot that now subscribe for loot pit that understand What is Pimple Report Subscribe to Loot Chop Wadhawan Jhoot Bhi Election Tension Limit Vihar Subscribe Increase at Thursday subscribe and subscribe the channel please subscribe and subscribe the channel subscribe me interest level also level Thursday subscribe and subscribe the channel please subscribe this video plz hai 200 lak hi reduce program doo Benefits se i plus newly appointed subscribe and subscribe the channel subscribe and subscribe kare pimple design to aap this question in evolving amazing spider-man president evolving amazing spider-man president evolving amazing spider-man president district element come where is the place for elements please subscribe this video plz subscribe kare ki problem nahi hoti hai lovely Daughter in law tarzan sid subscribe to ki electric jan id 2nd p.no a would-be of there heart pushed back to withdraw a would-be of there heart pushed back to withdraw a would-be of there heart pushed back to withdraw support and difficult create something subscribe to entertain subscribe hua jaise roadways back 9th subscribe video subscribe and subscribe the channel please subscribe our Ek Se Ek Andhra Hai To Definitely Restrictions On Oct Loot You Can Hardly Life Is Obscene Vid Loot Tak Chautari Memory Complexities Created 16 Sons From President Who Dies At Stupid subscribe this video subscribe video like and subscribe video
|
Russian Doll Envelopes
|
russian-doll-envelopes
|
You are given a 2D array of integers `envelopes` where `envelopes[i] = [wi, hi]` represents the width and the height of an envelope.
One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.
Return _the maximum number of envelopes you can Russian doll (i.e., put one inside the other)_.
**Note:** You cannot rotate an envelope.
**Example 1:**
**Input:** envelopes = \[\[5,4\],\[6,4\],\[6,7\],\[2,3\]\]
**Output:** 3
**Explanation:** The maximum number of envelopes you can Russian doll is `3` (\[2,3\] => \[5,4\] => \[6,7\]).
**Example 2:**
**Input:** envelopes = \[\[1,1\],\[1,1\],\[1,1\]\]
**Output:** 1
**Constraints:**
* `1 <= envelopes.length <= 105`
* `envelopes[i].length == 2`
* `1 <= wi, hi <= 105`
| null |
Array,Binary Search,Dynamic Programming,Sorting
|
Hard
|
300,2123
|
1,969 |
hey everybody this is larry this is me going with q3 of the weekly contest 254 minimum non-zero product of the 254 minimum non-zero product of the 254 minimum non-zero product of the array elements hit the like button hit the subscribe button join me on discord especially if you like contest problems and you like to kind of discuss it with people right afterwards and just kind of go over it and get gow or nerd out just with me uh you know yeah uh join the discord it's in the description anyway for this problem the first thing i did was remember the mod because i forget the mod a lot and actually i have a bug that i'll point out later that i actually modded too often uh because i wasn't paying attention too much but uh and it's good that they have the note though it's a little bit awkward in general but yeah so the idea here is that um i actually end up taking about nine minutes so you can watch the video of me solving this live um but i actually did uh and i sometimes i get questions about pencil and paper and i have i actually wrote down all the small p so i try to write out the piece and then kind of match them uh see if i can match them in a way or uh so i did it for p goes to four or the binary numbers so 16 of them you can't really see it but yeah and if you're on an interview you know use the white board and kind of work it out it's fine um but i think the so this problem is about minimizing product um so one thing that i know about products and i didn't really think about it initial immediately is that for product to maximize the product you want to let's say you have x times y it goes to some number and you want to maximize this where x plus y is equal to you know x plus y is constant right um so you want to keep that the same and you want to do that in that case what you actually want to do is um you want x and y to be as close to each other as possible to maximize it and you can kind of draw the graph where you know x times y graph and then you know you can do the maximum or whatever you can take the derivative if you like or something like that but yeah um but con on the opposite side to get the minimum number you would want to have them as far as possible and in this case i think example three kind of gives away a lot if you know what to look for which is that yeah if one of the numbers one and the other one is as big as possible that's going to minimize number um and here it's a little bit tricky to see but oops but i actually did this for four and i did this on paper so you could kind of see it but the thing is that you have one this yeah oops besides typing this out uh yeah almost there you go right so the first thing i notice is that okay so you're not gonna get rid of the last number because in theory you would match that with the zero but then that's not a thing so let's just skip this and then the next thing you ask i asked myself and i was trying to do it on paper is whether i can get is it true that i can get all these numbers to be one and all these numbers to be in this case um 14 right and the answer is yes because i could switch this one um well that um so this one we're looking for what are we looking for right we're looking for do um because the sum of these is going to be or the bitwise total is going to be one which means that you can break this up to this and one right so this is fourteen and one so that means that for every one you can get the output to complement um yeah and i actually took a long time to see this uh relatively speaking uh and i didn't have this queer as a visualization but that's the idea and then now the question is okay how do i generalize it right um well in this case uh so yeah so this is 2 to the p minus 1 and then this is 2 to the p minus 2 and then you times that by 2 to the p over 2 right um because that's the number of pairs oh wait it's over 2 minus 1 i think yeah because that's the number of pairs you have and you could just really count these to be you know i could prove this but you can just count this that's what i did um i generalized this and then yeah so there oh whoops i think i made the same mistake and explanations that i did so each one is this and they appear in uh and there are this many pairs right so that's basically the solution once you have that it's just about modular math uh and yeah so i have i call these the top number is just this thing so it's two to the p minus one uh the middle is what i call this thing because i just matched them up in the middle like i said i this is during a contest so i wasn't thinking about the variable names too much um so this is just this uh this thing minus one which is i have here and then mid count is just this thing uh which i put here and you know divided by two is equal to p minus one so that i have here and then at the end um i did the power of mid to the mid count so yeah so this to the power of this with respect to the modular math times the top and then we mod it again um so that's basically the solution uh so i did get a wrong answer from this if you click the one button i did get a wrong solution here if you didn't notice um and what i did was that i was a little bit sloppy and that i did this with the mod so what happened was that for p is equal to 30 i'll say 31 or something like that um this is just the wrong answer because you can imagine that two to the dirty one is uh mod you know this thing is not the same as uh let's just say some number any number right it's not the same as uh this for example because that's just not how mod works i'm not gonna you know uh go over too much and then once i realized that i fixed it for a nice five minute penalty but that's basically the solution i have here and because p is 60. um you could say this is constant time or you could say this is o p for one for each digit um both of them are probably okay uh that's all i have for this one uh even though i guess you could say multiplication is p squared i don't know and but it's going to be relatively or very fast it um is it's my point anyway uh that's all i have for this one um i don't know that yeah uh like i said this is more of an exploration problem and it took me a while even though you know some top people did it very quickly um yeah well actually some people also did it kind of took their time as well so i don't know but yeah let me know what you think hit the like button hit the subscribe button join me on discord oh yeah you can watch me sub it live next first now before you say oh my okay i don't even know what the question's really asking for i'm hmm what is the greedy so we wanted to greedy maybe i think i see the pattern but i'm not sure sometimes this is so hard to test okay put these two birds this skill per se match this one you match this one it's the middle number there's no middle number on that but i feel like i get it but it's such a weird problem just refreshing to see how many people garnet so far hmm oh wait how does this work these two groups together so okay so this should be let's see two to the p so this is this minus one now is this number minus one is equal to top say and middle is equal to top minus one and then middle and how many of this mid count is equal to this n over two which is uh two to the two p minus one mod so then this is just with count times mid times top okay maybe oh this is mid whoops typo okay that's not right 223 is eight all right this auto thing is killing me okay now mid is so we can fix that one but what's two i got it wrong the middle is six and there's four of them is that isn't that right there's three of them okay oh yeah minus one so that's this minus one but six times three oh no it's not six times three this is i see okay i don't know what the four is but also the biggest number is 60 so let's test that but i have no idea what the right answer is so we'll have to see that's weird though and that i don't know what to maybe there's an off by one but i don't know if the four is right or whatever see more details can tell us what test case this is it doesn't tell us what test case this is okay um oh this is not right or whether we don't mod this that's why uh what is 31 okay that is a silly mistake i was too aggressive and modding okay let's go what a silly mistake uh yeah thanks for watching hit the like button hit the subscribe button join me on discord especially if you like these contest problems we talk about problems all the time uh of the contest type but you know come swing by uh let me know what you think i'll see you later to a good weekend to good you know mental health and i'll see you later bye
|
Minimum Non-Zero Product of the Array Elements
|
maximum-number-of-accepted-invitations
|
You are given a positive integer `p`. Consider an array `nums` (**1-indexed**) that consists of the integers in the **inclusive** range `[1, 2p - 1]` in their binary representations. You are allowed to do the following operation **any** number of times:
* Choose two elements `x` and `y` from `nums`.
* Choose a bit in `x` and swap it with its corresponding bit in `y`. Corresponding bit refers to the bit that is in the **same position** in the other integer.
For example, if `x = 1101` and `y = 0011`, after swapping the `2nd` bit from the right, we have `x = 1111` and `y = 0001`.
Find the **minimum non-zero** product of `nums` after performing the above operation **any** number of times. Return _this product_ _**modulo**_ `109 + 7`.
**Note:** The answer should be the minimum product **before** the modulo operation is done.
**Example 1:**
**Input:** p = 1
**Output:** 1
**Explanation:** nums = \[1\].
There is only one element, so the product equals that element.
**Example 2:**
**Input:** p = 2
**Output:** 6
**Explanation:** nums = \[01, 10, 11\].
Any swap would either make the product 0 or stay the same.
Thus, the array product of 1 \* 2 \* 3 = 6 is already minimized.
**Example 3:**
**Input:** p = 3
**Output:** 1512
**Explanation:** nums = \[001, 010, 011, 100, 101, 110, 111\]
- In the first operation we can swap the leftmost bit of the second and fifth elements.
- The resulting array is \[001, 110, 011, 100, 001, 110, 111\].
- In the second operation we can swap the middle bit of the third and fourth elements.
- The resulting array is \[001, 110, 001, 110, 001, 110, 111\].
The array product is 1 \* 6 \* 1 \* 6 \* 1 \* 6 \* 7 = 1512, which is the minimum possible product.
**Constraints:**
* `1 <= p <= 60`
|
We can see that the problem can be represented as a directed graph with an edge from each boy to the girl he invited. We need to choose a set of edges such that no to source points in the graph (i.e., boys) have an edge with the same endpoint (i.e., the same girl). The problem is maximum bipartite matching in the graph.
|
Array,Backtracking,Matrix
|
Medium
| null |
110 |
hello everyone and welcome to another video today we're doing a little easy question about trees and this time we have to determine if a tree is height balanced so as for the definition a tree is defined as height balance with the left and right subtrees of every node differ in height by no more than one so let's take a look at the examples given so for example one let's just say that at the base level the height will be one okay so for fifteen and seven here they have a height of one sorry so for fifteen and seven here they have a height of one so for the height of twenty it will be the maximum between the height between the left and the right subtree and since both of them are one piece will be two and then for nine in this case you have a height of one since the leaf and finally the height of three is the maximum between the left and the right so be 2 plus 1 which is 3. so as you can see right here the output return is true because each of the nodes in the left and right because for the node the left and right subtrees only differ in height by no more than one take a look at taking a look at example two you see that the fours here have a height of one which means this tree has a height of two and the right number three here has a height of one and this means that the left number two has a height of three because two plus one and we take a look at the right side you see that the two has a height of one and lastly for the root note right here the one it has a height of four so as you can see right here you see that this example two right here the three is unbalanced due to these values right here because the left and right sub three of the node at one differ in height by more than one which is two so as such the output is false and for a trigger case we are given an empty node we will return true okay so hopefully you have understood the question right here okay so the way i see this is that firstly the output they want me to return is a 3d or is either true or false however in order to check the heights given to see if there are height balance or not i have to look at integers because they are heights so this can bring me the idea of creating a helper function okay so maybe i'll have a global variable code balanced and then inside the inside list i'll have a helper function and what this helper function will do is to help me check if i make any height balance i made any imbalance in the height so initially i'll set balance to be true and inside this function right here if i meet imbalance then what this does is it will simply make this balance right here to become false enemy and imbalance so that'll be how the general algorithm will work so what this function does what it will do is that it will simply be a or make making into a recursive function and it will just at every point help me check if it's left and right subtrees are balanced so this will be how the helper function will work okay so you're taking a note so basically for the direct very trivial case whereby i don't ever i don't have any node so if my node is none it's none i'll simply just return 0 because an empty node will not have any height but else what i will do is that i will have to recurse down the left and right subtrees in order to get the height so the left height will be hyper function caught on the left of the node okay now the right one the right height is the helper function as well but this line code on the right of the node okay so what this does is that using by recursion this will give me the left height of the current node that i'm looking at the subtree well this will give me the right height of the counter i'm looking at the right subtree so finally what i have to do is just simply compare if the absolute difference between the left and the right is greater than one so the absolute difference is more than one what it simply does is to like what i said just now we'll change this right here to become false okay else if not what i need to do is that i try to return the updated height so that when the value comes back you can continue to check the higher levels of the tree so first i need to take note so as what i mentioned just now when you take a look at the nodes for example the height will be the maximum of the left and the right subtree one plus one may cause me to add one to the next level or the height so what this will be just will be a maximum of the left and right subtree's height added to one name so that would be the height so this will be how the general algorithm will run so in this case right here since i've originally set my balance to be true which means that if this condition is never met and i never set my balance to become false then that would mean that my balance was to be true so at the end of this all i need to do is just run the helper function on the root node and after that return balance because if it is in the imbalance you have been set to false at this point in time to return me the answer so let's just run this algorithm as on maybe example 2 i can take a look so let's refer to example 2 so at this rule note right here our run helper function on this okay on the note one so you will check if it's none it returns zero what else you are because on the left and the right so recurs and it's still not none so you're continuing so what you'll do is look at the left side one first and you'll recurse and because and still looking at the left you're going to recurse definitely it will be at four then it still continues to recurse because you need to check because at this stage four the falls here are still not none so at this point in time finally i made the non values right here all right so what this will do is that you return me zero as expected so just use another color so be zero and zero then now i can take a look at four so it's the absolute between these two more than one it's not right because zero minus zero is just zero so i'll just return max of alpha plus 1 so my 4 right here will have a value of 1 and then we can take a look at the right side now so same thing this 4 also has a 1 because it's the same case as the left one here then finally your continue to recurse up so it's one minus one greater than one it's not right so three will have a height of the maximum between the left and right sub trees which are both one so be one plus one which is two and then now i continue to look up at three so this is right here also one because of it's a leaf node right here which has a similar base case this which has a similar analysis of the node four right here so again i'll just check is two minus one greater than one it's not then i'll go to the else so my for this two right here you'll be you have a height of two plus one which is three because two is a higher value of these two sub trees respectively and finally i'll take look at two so likewise he has a height of one and then i'll check three is three minus one greater than one he is right because it's more than two and as such balance will be set to false then it continues to look up whereby one will not have a height of four so in this case i will have set my value to become false and now finally i'll return it and get output force so this will be how the general algorithm will run so now let's move on to the coding part of the solution okay so now let's move on to the coding part of the solution so what as always i stored it on pseudocode first so we have a boolean variable of whether the tree is balanced and next up i need a helper function to help me check for imbalance finally i'll run the helper function and return the variable okay so let's now have a global variable initialize okay so for this part i'm going to assign it to an array actually because i don't know how to actually uh because i don't know how to actually refer to this right here inside the helper function because it will treat this you know because if you use it inside have a function just as a primitive variable you will take it as we haven't defined anything yet so this is my uh in essence my band-aid method is my uh in essence my band-aid method is my uh in essence my band-aid method to fix it now you can also use non-local to fix it now you can also use non-local to fix it now you can also use non-local but for some reason it's not working and in general this is actually kind of bad code practice but i don't really have a resolution for this set so this is what i'm just gonna use for now so now let's define the helper function we should take in a node so likewise check this now if none return 0 else i have to recurse on the left and right to get the height check the difference in height and if more than one set balance to false after that i'll return the maximum height between left and right and add one to it to increase the height so this will be how my hyper function will run so if node is none i simply return 0 else i will request on the left the right as well all right oops this should be height after that i'll calculate the difference to say it's more than one at least right here we can just use the absolute imbued function right here to help us to get the positive value then we can check so that if the difference is more than one now set balance to be false in any case i'm referring to the zero index right here in order to reach this part of the code and after that i'll simply return the maximum fit to the left and the right height and add one to it so this will be how the algorithm will run so as for the pseudo code i need to run the helper function and finally i can just return balance the zero index because it's where you hold my boolean value so this is how the code should run so for the time space complexity i believe that the runtime is going to be o of n but n is the size of the three because we have to traverse and look at every node actually so this is for the run time and for the space complexity if you look at the recursion stack depth it's going to be a on sl because you have to recurse to almost every i mean we have to request to every part of the tree so yeah i think the solution should work and this is how i will code it out solution does work and yeah if you have any questions then feel free to leave it in the comments down below or else if not then thanks for watching and see you guys next time all soon i guess
|
Balanced Binary Tree
|
balanced-binary-tree
|
Given a binary tree, determine if it is **height-balanced**.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** true
**Example 2:**
**Input:** root = \[1,2,2,3,3,null,null,4,4\]
**Output:** false
**Example 3:**
**Input:** root = \[\]
**Output:** true
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5000]`.
* `-104 <= Node.val <= 104`
| null |
Tree,Depth-First Search,Binary Tree
|
Easy
|
104
|
1,636 |
welcome back for another video we are going to do another legal question the question is 1 6 3 6 sort away by increasing frequency given a array of integers nonce sort the away in increasing order based on the frequency of the values if multiple values have the same frequency sort them in decreasing order return the sorted away example 1 nonce is 1 2 3 the output is 3 1 2 explanation three has a frequency of one has a frequency of two and two has a frequency of three example two nuns is two three one three two the output is one three two explanation two and three both have a frequency of two so they are sorted in decreasing order example 3 nonce is negative 1 negative 6 4 5 negative 6 one four one the output is five negative one four negative six one let's work through the code we initialized a hash map to recall the frequencies of numbers phony array the numbers are keys and the frequencies are values we then initialized a list with map keys we saw the keys in decreasing order if they have the same frequency else we saw the keys in increasing order based on the frequency we then initialized a new array with the length of array nouns we place numbers in the array based on the order in the list and frequency time complexity is o n log n space complexity is o n and the solution works thank you if this video is helpful please like this video and subscribe to the channel thanks for watching
|
Sort Array by Increasing Frequency
|
number-of-substrings-with-only-1s
|
Given an array of integers `nums`, sort the array in **increasing** order based on the frequency of the values. If multiple values have the same frequency, sort them in **decreasing** order.
Return the _sorted array_.
**Example 1:**
**Input:** nums = \[1,1,2,2,2,3\]
**Output:** \[3,1,1,2,2,2\]
**Explanation:** '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3.
**Example 2:**
**Input:** nums = \[2,3,1,3,2\]
**Output:** \[1,3,3,2,2\]
**Explanation:** '2' and '3' both have a frequency of 2, so they are sorted in decreasing order.
**Example 3:**
**Input:** nums = \[-1,1,-6,4,5,-6,1,4,1\]
**Output:** \[5,-1,4,4,-6,-6,1,1,1\]
**Constraints:**
* `1 <= nums.length <= 100`
* `-100 <= nums[i] <= 100`
|
Count number of 1s in each consecutive-1 group. For a group with n consecutive 1s, the total contribution of it to the final answer is (n + 1) * n // 2.
|
Math,String
|
Medium
|
1885,2186
|
64 |
hello guys so let's understand today question that we have this is expert Panda and you're watching on YouTube for the sum and we have given uh what we've given M cross and grid we have given and it is filled with non-negative numbers it is filled with non-negative numbers it is filled with non-negative numbers Now find a path from top left to bottom right top left is what let's suppose this one right this is uh this array right so from here to here okay this is top left and this is bottom right okay so from here to here what we have to do we have to find a path uh okay and which minimize the sum right of all numbers along its path like this there can be two path either right away or either you can say done way and for the from the down you can see there can be a left way or up way okay so uh to find the minimum sum right what we have to do we have to sum out of all those numbers right and we will uh or we need to find what uh write a step or you can say downward step to minimize the sum so for finding the sum what we have to do we have to say let's suppose this our cost right it will take what two thing I and J okay why because C if we'll take I and J we have to find the cost we'll take grid at what Grid at I and then we put our grid of J correct gate of I and gate of J then we'll find What minimum of what the cost of I plus 1 right and J right this one first of all we pass this one and we'll pass comma right and then we will pass what this is a minimum cost I plus J right this one I should take note take it like this one I hit this one right and then other will pass what cost of ah I and J Plus 1. I think understood right so first of all we will take Grid at inj and then we will take the cost of I plus 1 and J plus 1 right this grid will contain what two thing first it will take uh you can say ah let's suppose I and another will take dot j right so this is the you can say implemented and this is the you can say definition right so what I will take ah I will take from here right so now I will put I J and this grid right like this we will call and we will Define that one letter okay now I'll put here and make with body and it will return what integer correct coming back to here grid we know what is I and J right so initially I and J I will take 0 means we are at origin right at the down right from there we will start I plus 1 J plus 1 will do that later okay so first of all now what we will do let me increase little font so first of all what we will do here we will take if condition and we'll say if uh this I is equal to what will take grid dot length okay so if I equal to grid dot length or J is at what Grid at 0 Dot length right so if it is uh I is equal to gate dot length means we are at last index and J is at last index of the particular row right means we will do nothing we will return you can say integer will take a value integer Dot Max value like this we will do once this is done now what we will do once this is done let me close this one okay so uh we'll have if we are x equal to the last index we will do what integer of max value now if it is not let me write this one I will do copy from here to here let's suppose if this is at last index minus 1. if we are exactly we are not exceeding the last index and J length minus 1 okay now we will return what we will return grid at I J right now it is the time to do we will do the calculation right so to do the calculation we already know that first of all Grid at I and Grid at J will do right so if we have to find the cost we'll do plus and this is nothing but upper you can say cost equal to cost of I and J equals is equal to this but we are not going to take a variable right like this we will just return what this one return Grid at i j plus we know that we have a math function from the math dot we'll do mean and we'll take a calci function it will take what the grid will take we will pass our I plus you can say sorry I Plus One will pass and then J will pass similarly I will take this calci and will take comma and this time it is I and this is plus 1 J plus 1 okay now we are going to return so this is what I am talking about right so what we are going to do first of all we'll take a grid 0 right and uh we'll start from 0 Index right now what we will do this calci function will take uh int I and J so we'll check its boundaries if it exceeds the boundary then it will return max value if it is uh ah some value we have right so what we will do we are at last index we will return date I n j okay if we are not exceeding the index right then what we'll do grid I plus J plus math dot mean and I plus 1 and J plus 1 between that we will find the cost right cost of grid I plus 1 and J and cost of grid I and J plus 1 that we talk about already so will return I think you understood right so let me do what I will compile this one what we have given this one right so we are doing uh some costing right so uh always put in mind that if we have to find some cost thing right what you will do we have given uh I we have given then we have J we have given okay wait one minute okay I'm sorry so coming back to here right we have some call if you want to find the cost right what we have to do to find the cost we have to find the what we have at grid I and J right that we have already talked right then what we will do right we will find the minimum which one is minimum right these two thing either there will be a cost right and this sorry this cost of what I plus 1 and J right there will be value another will be what we have I and J plus 1 right that we have only talk about if the value at this is a position right so we will find in the next position and another we will find in the downward position right here so if we are finding the cost at this position right so this is the value we have let's suppose it's 12 we have the nearby it's is 2 we have a nearby it's what we have 5 we have right so what we have to do so we will go this path or this path right so who will decide this line of code right so we will find the minimum so if you will find this is minimum we will go this one so these 12 and plus 2. so this is our 12 and here we will find about 2 right so this path we will choose so that we have to do this one right so let's suppose ah this is the minimum thing right so let me clean this one okay so this thing ah we have it will take uh it will give two it will give uh let's suppose five right so we'll choose this one because we are doing math with math dot mean 2 and comma 5 lit so that we will find we will calculate will get the cost and this is cost is nothing but this is also you can say cost we have and cost of uh I plus 1 you can say and J and this is cost of what uh J sorry I and J plus 1 right so which one is minimum let's show if this is minimum we will consider this one and there will be some value and that we will return right so this is because equal and it's it will take ah all the time to calcul all the time to calculate the you can say uh cost and so that it is going to be a net recursive call right so now if we'll talk about the time complexity right so time complexity for every move right uh we have at most two operations right first what we are doing we are calculating either ah with either we are going to this operation right we are going moving and we are talking about ah we are doing for every move we are taking a minimum thing and then we are doing plus right so two thing we are doing okay so in this case let's suppose ah for every everything right we have we are going M and N right we have what MB again and N we have even so it will become for every move right 4M we are going to the power n right and we are doing what uh another DC for M right row and uh similarly we're going to do what n okay if you do this sum it will become what o 2 to the power M plus n right and this is your time complexity okay this here this is your TC you can say that right this is your TC now if we'll talk about the space complexity right so we are storing each time the value right we are calculating we are also doing recursive call right so M we have given and N we have given right so total element we will find so for M we are going uh let's suppose uh M operation for the uh you can say row operation we are going o of M right and for the column we are also going o of n okay so in this case it will become M plus n so this here is space complexity right see each time we are going I also going J also going right that's why we have to take both right I think we understood time complexity and space complexity okay now further what we will do we will try to understand uh another approach sorry this is a dynamic programming approach that we are that we can say 2D approach right so in this approach uh we will use an extra Matrix DP right of the same size that we have in the original Matrix we are taking right so let's suppose ah this is the Matrix right we have original Matrix we have and we will uh do what ah will create one DP right of the same size right then uh the DP at I DPL is suppose we'll talk about DP of I and J right so DPF I and J this will represent the minimum sum of path right from the index I to J right I J index i j so uh you can say bottom right element right so for Le any element let's suppose we are talking about the first element we what we have is at I uh this position what we have three we have so DB will remain here 3 okay but if you going to any other position let's suppose we are coming to here so these two will get added into the previous one this one right so now it will come 3 and plus 2 it will be convert 5 right so this 5 will we go so that we can say DP of I and J so it will represent what the minimum sum of the path from the index I and J right and to the bottom right element so we will start by initializing the bottom right most element of the DP as the latest or you can say last element of the Matrix right so therefore now for every starting or you can say every element right which is starting from you can say bottom right and we will Traverse backward and we'll fill the Matrix with the required minimum sum like this will go and will go right so then each element will start from what ah bottom right and we will Traverse backward and will fill the Matrix with the required minimum sum and now we need to note that for every element we can move either right word or the downward right so therefore what we will do will first what we will do will fill the DP right and therefore finally we will reach to the DB here okay so we will complete our DP right so once our DP is ready right filling now we will do what we will either move ah you can say right word or downward right and we will find the PATH right so therefore to for filling the minimum sum right we will what we will use two thing what we have given DP at I and J let's suppose depend ing is what we will take grid of I and J this one and we'll do plus we'll take a minimum right minimum of DP and it will be about I plus 1 that we have already seen and J and comma will take DP at what I and J Plus 1. this is ah this year I think understory so this is uh you can say write what and this is your downward okay this formula remains same right so in this way you will find the you have to calculate the path and then you will return right so taking care of the boundary condition right we have to see this one right as you can see so let's go to the browser and we'll do this implementation how what I am trying a few moments later and we are trying to implement this one okay now first of all what we have to do we have to take the same size of the DP right as we unders understood right so we'll take a and let me Zoom little bit so I'll take what uh you can say dynamic programming right DP and this is uh this is DPA the new programming away okay and we'll take what the same size as we have as a grid right so I'll take int and row will become what we have grid and grid length is a row and its column will become what Grid at what 0 dot length you can find the m and you can pass here okay the same size we have added now what we should do we will Traverse uh the grid right from the last element okay so I'll take uh what we can say int uh let's suppose this is nothing but of your I and I we will going to start what grid Dot length and -1 so this is the last Index right and -1 so this is the last Index right and -1 so this is the last Index right and I is at the last uh last row from we are going to start with our last row so from the last row I'll come to what greater than equal to 0 first row and what I minus I think understood okay now coming back to uh column back column what we will do uh for and will password J and J should start from what where Grid at uh 0 means the last row of the last column last row of last column right this is grid 0 and we'll do minus 1 so we will get our last row last column okay so we are at the last column and we'll uh each time we'll go to uh the First Column and for that we have to do like this and G minus so each time we will as from we will come to the last row last column to last row you can say First Column and from the last Row 2 will come to the first row so this is done like moving things we have done now what we will do we'll check the condition that we have already talked about that is if we have uh I and if I is at what uh gray dot length right uh so I'll take like this grid dot length and if I is equal to grid dot length minus 1 right let's suppose minus 1 then what we will do uh we should take one more condition so for uh J should not equal to you can say Grid at 0 Dot n so we should take both thing so Grid at we are at last Index right and another what we have this one okay so if we are at last Index right gate dot length minus 1 means last row and J is at you can say last row both thing then we will do the calculation how we'll do the calculation we will take DP of what I and J and we'll take what uh there is a grid write we have Grid at some value will be there I and J and we'll do the Plus DP at I and plus J plus 1 right DB and I J plus DP of you can say DP of i j and DPF I and J plus 1 is nothing but DPF I and J next uh we'll check if else if J is uh let's suppose J is equal to what Grid at zero and we'll do length this one minus 1 and we'll say and operator right and will pass but if I not equal to grid Dot length and minus 1. so in this case what we should do we will use let's suppose I'll copy this one this line of code and I will paste here okay so first of all I and J will have right so now this case grid of I and J is what I plus 1 it will become I plus 1 but J will remain like this so we have what I plus I and J plus 1 here what we have like this now in else if okay now what we have J is not equal to Grid at 0 Dot length right if J is not equal to Grid at 0 dot length right will do minus 1. and we'll do and I is not equal to grid dot length and we can do minus 1 the last index I think understood okay now this is done will make the body will pass the same thing but in this case we will find the minimum right low math dot mean and will pass this I and J plus 1 but before that okay sorry we have mean and I will take like this and this is this time this is nothing but I plus 1 J and I and J plus one like this is done now we'll do else in the else we'll take DP at I J is what Grid at I and J right and once these are done here we will return what DP at 0 and 0. minimum path okay so understand here what I am doing here for a few moments later okay it is coming like this yeah let me submit this one yeah this working so let's go back here understand uh what we have done till now right so we have this approach grid approach to in the dynamic program approach right today in which we are talk we were talking about like how we will calculate the uh you can say uh minimum sum right so to find the minimum sum this is the place we are actually finding the minimum sum right so we'll take what uh grid value right Grid at i j and then what we will find math dot mean will do and I plus 1 will do means we'll check the let's if this is the element right so we will check the uh you can say this one I plus 1 right at this element and another will check that downward the right uh right most element will check and the down most element will check okay so like this we are checking okay so this is a rightmost this right move and this is down move okay we'll check and this is the exact element from where we are checking inj this one so in this way we are finding so now you can see that what we are checking if I is equal to 3 dot length minus 1 means uh we have uh L Elementary M right so I should not go to exactly equal to m is rho and N is column right okay so here similarly we'll check for J should not be equal to what uh n in this column if this is not the case then what we will do DP of I and J will do the sum and we'll move how we are moving see here we were here starting right so first initially what we have this element we have right so this element will check at we are at the last Index right this is the last row see we are talking about this one this in this row right we are talking about this line of code right for this line of code we are at what last index sorry we are at where we are at last index here means I is at the last I is here in this one we are start coming from here we will go back to here again and J is also here right I and J both are here so we will not do anything we'll do I and J will do the sum and we'll come back to here right we'll do come back to here okay so ing is the last one so we'll do grid of I plus 1 I grid of i j and we'll do grid of I and J plus 1 right we'll do and we'll initialize this one another will take what uh the next element will check if J is at the last index and I is not at the last right in that case what we will do we'll do I plus J and we'll move actually we will move to the uh you can say uh right most we will move okay and similarly we will find the cost each time and we'll move each time if these three are not the cases means we are at origin we'll do exactly well value will update so as you can see the first element we are doing first element is exactly coming same the next time we are doing what we will checking with this will go either this way or we are going to this way right we will find and we'll update each time okay so this is the thing we have right let's understand now uh if we will talk about the complexity right so to understand the complexity you see that uh these are the row and these are the column right row and column we have so time complexity right it will become if row and column is there right so I'll say o of M and N why because uh B Traverse the entire Matrix right we are traversing entire 2D Matrix right and this is the dynamic program so we are moving M cross n right so I'll take o of M and N similarly we are storing all the values right so the space complexity will also remain of M into n right so both will remain same now coming back to next approach that is we have is a dynamic Dyno programming approach with 1D array okay we are seeing the 2D array but this is ah 1D array so in this ah approach or you can say in the previous approach what we have seen uh we were using 2T but instead of using 2D Matrix we will use uh 1D array for the DP right and what we can do ah do that the same work uh we can use a DP array of row size right and since for making the current entry all we need is uh the DP entry for the bottom and the right element will do right so thus we will start initializing only the last element of the array as the last element of the Matrix right and we'll do what last entry of the bottom right or bottom right most element you can say in the given Matrix we will ah we actually we will initialize right and uh we start moving toward the U.N select we start moving toward the U.N select we start moving toward the U.N select and we'll update our deep entries okay so what we have did in the last right in the 2D we will go to go with uh 1D array Okay so instead of using you can say 2D Matrix for the DP we can do the same work by using a DP array of the row size and since we are since making the current entry we all need is DP into for the bottom and the right element so thus we'll start by initializing only the last element of the array as the last element of the given Matrix the last entry of the bottom is rightmost element of given Matrix that's all we have and so what we will do uh to find the you can say DP at some uh J suppose how will calculate its value so it will become let's suppose we have grid we have given right so grid we have I and J so that will take and then we'll take What minimum and in the minimum we'll take DP and which DP of either we'll check J or we'll go to DP at J Plus 1. understood either will go with this one ah sorry DP of J Will how will calculate we'll take grid of I in that particular index data and the minimum DPF J and J plus 1 what we have that bill but why we are taking because see we are not taking DP in the 2D Matrix we are taking single Matrix and this will start from J will start point zero two n minus 1 right as you understood so what we will do let's understand the what we have uh number okay we have taken what 2D area but now we are not going to take 2D array we will take 1D array so to get the 1D array what will take I will remove this one and from I'll take remove this one now this will become like this now what we have in we are going with grid length minus one and uh you can say last row we are going and similarly we will go with the grid last row and last column this is done now uh we'll check if we are uh for the first we'll check if I is equal to grid uh you can say last column last row last column right so what will say if I is dot length minus 1 means last row and we are not at the last column okay so in this case what we will do grid I plus uh grid of i j and we'll do grid of J plus 1 only we'll do will not do anything else right like this one okay and this is nothing but our J now correct now coming back to here we will check J position J should not be at the last column right and in that case what we will do we will say DP at DP of J is this one and here we will take what DP of G only because this is uh 1D array now similarly for this one if J is not equal to gray dot last element right last row that's the last column then DP at J equal to it will become what gate of i j and we have math and here what we'll take one in DP of J and J plus sorry DPF J and J Plus 1. like this right and once this is done we will update our DPF J we have to remove from here okay now what we will do we'll uh this 1D array so we'll pass one day let me compile this one this is working let me submit this is also working okay so let me take this slow time right so first of all we will take what uh we'll take a DP at uh 1D array right and I will for this condition for Loop this is the last row last column right and for each row we are we will start from the last column to last will come to the First Column and then we'll check if I is at not the last column last row and J is at not last column then what we will do we'll find our DP of J is uh the grid value and then G plus 1 will take then similarly we'll take if J is not last column and uh is at last column actually you can say and uh row is not at the last row then in this case what we will do get a git value and then DP of J Will store onto the DP similarly we'll check if J is not at the last uh row and you can say column you're also known or the last row in that case we will update this one will do minus uh we'll take the minimum of DP J and dpj plus 1 which only will come will add the element value and will store onto the DP if these are not the case we'll just take DB of J we'll store the element and then we'll finally we'll return DP of 0. I think you understand right so in this case if you see we have a m is a row and N is a column right so the time for the time complexity right TC we will we are moving M into n where actually we are tracing all the element right for the temperature but for the space complexity thing we have reduced the into the 2D to 1D array and in that case it will become only for the column things we are going for oh sorry or only we are taking the rooting right and that's why uh sorry column thing and so that we are streaming what uh o of n Only right so another way we are what are we doing going we are using row size that have been used that will take only okay now coming back to uh Next Step that we have is Dino programming uh dynamic programming without extra space right so this is the same approach as the approach two we have talked about right so with the slightly difference what we have is uh instead of using another DP Matrix we can store the minimum sum in the original Matrix itself and since we need not retain the original Matrix here so in that case uh what we will do our ah how will calculate this one so let's understand this one okay so for Grid at I and J what we will do we have some value at grid I and J right and we'll take another value what will take a minimum and this minimum will store what grid of you can say I plus 1 will take and another will take J and another will take what will do comma and another will take what I and J Plus 1. okay so which one will come minimum that will come on to the element because we are replacing the original value we have just replaced the original value right in the original Matrix itself and uh we'll do the calculations right so what time we will start with the last row last column and then build the first condition will check if I is equal to the grid minus 1 and J is not equal to grid of uh you can say means we are not I we are not at the last row and no last column right so in that case what we will do we'll update our value I will update our value so we are not storing at the DP now so I'll take this one actually okay so we will store at The Grid at i j git add eyes is nothing but grid of or you can say i j itself value and another value will be a what you understood J plus 1 will do only right similarly uh for this condition when ah not last column and not we are at the last row last column and not the last row that gets what we'll do we'll add the DB of I say I'll take this one and here you know that will take like this right we'll take what uh Grid at what uh i j is GitHub i j and in this case what we'll do we'll update our plus this one previously J plus one now this is I plus one just after the last one right coming back to this position what we have to do we have to update when uh we are not the last column and not the last row so at that time what we will do we will check the math dot mean and first we'll take DPO in place of DPF I will say DP of I plus Grid at grid plus grid of I plus 1 and increase of J plus I and J plus 1 you can say so here we'll add this one okay so I think you understood right and coming back to here we have to update this one also just like this okay or either we can leave this is not required actually okay we can leave this so because this is the same right this is the same now coming back to this one what we should do will remove 0 and it will become zero let us submit this one this is also fine let's submit so what we have understand previously that in the dynamic program we are not going to take any Extra Spaces right and so that we will how we'll calculate this one gate of uh this one I will take the element and the minimum I plus 1 and J plus 1 will check right each time so coming back to here what I am trying to do here is uh we will start from where we are not taking any extra expresses so directly we will go to the loop we'll check in the last row last column and if our uh we are not we are at the last column last row and not the last column in that kit what we will do grid of I will take i j is invest just will do great of i j the current position plus J plus 1 right J plus 1 means downward you see for the downward okay and then grid of uh when grid When J is last column and not the last row in that case I plus 1 means uh right most right and if J is not equal to grid length means not last row last column and not last row in that case we will find what which one is coming minimum right from uh you can say from the right to most it is coming or downward it is coming which one is minimum right that will take into the current position and will store I will do the sum and we'll store onto here right so actually we are updating replacing the value and finally we'll return this one so I think this is the best approach and in this approach what will happen time complexity will come ah we are reversing all the elements so TC will remain o of M into n rho into column right we'll do row into column but for the space complexity we are not any we are not taking extra expressive yet using the constant space right no extra space we have used so for that will come over okay so this is the best approach and we should always use this one otherwise ah what will happen you know that so always use the best complexity so this is why I think we have created very good videos so if you really like this video please hit subscribe this channel is for uh more videos and if you're not subscribed please subscribe so that it will motivate us and I'll uh also like this video if you like which part of the video please comment into the uh in the comment box and let me know which approach you like thank you so much guys
|
Minimum Path Sum
|
minimum-path-sum
|
Given a `m x n` `grid` filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
**Note:** You can only move either down or right at any point in time.
**Example 1:**
**Input:** grid = \[\[1,3,1\],\[1,5,1\],\[4,2,1\]\]
**Output:** 7
**Explanation:** Because the path 1 -> 3 -> 1 -> 1 -> 1 minimizes the sum.
**Example 2:**
**Input:** grid = \[\[1,2,3\],\[4,5,6\]\]
**Output:** 12
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 200`
* `0 <= grid[i][j] <= 100`
| null |
Array,Dynamic Programming,Matrix
|
Medium
|
62,174,741,2067,2192
|
1,977 |
hey what's up guys uh this is chung here so this time bit code number 1977 number of ways to separate numbers okay so this one it's a it's another very hard problem okay but idea of the problem is not that hard you know the difficulty for this problem is how to improve the performance or how to reduce the time complexity okay so the description is also not that long okay so you have like positive integers in the stream mode in the string format right but uh and you want to separate it you want to separate those uh the strings right into several different numbers uh while those separated numbers are not decreasing in non-decreasing are not decreasing in non-decreasing are not decreasing in non-decreasing order okay and no integer had the leading zeros right and you need to return the number of possible lists of integers that you can split right from this number and since the answer may be large return module returned by the modular right so i think you know every time when you say this kind of i'll do a modular by this one you know the total weights will be huge right that's why you need to do a modular here right in that case you will always need to do use the dynamic programming basically you cannot do a brutal force search right because the number will be too big right and if you do a brutal force search it will definitely tle that's why every time you see this one you know it's always a signal to ask you to use dynamic programming right and for example we have two three seven right so this one uh we only have two answers because there are only two ways to split it right so either like uh split it to here right simulate it to here where we have three and 27 right or we can just split uh here right basically split it here where we have uh three to seven we cannot split it here like this right this is wrong because this will give us like a decreasing sequence okay and example two here right there is like zero nine four in this case uh in this case you know what we have zero and the reason being is that you know something someone said okay can we do like nine and i'm sorry zero and 94 right so this could be a valid answer right but there's another like uh constraints here so all the numbers right has to be positive so which means 0 is not an option right so basically whenever we see a zero to start you know we know it's not a valid answer in this scenario right so obviously this one is also a zero right and then here we have this one zero one okay and the constraint is like this so basically three thousand five hundred right uh to solve this problem you know um let's start with the very basic right and then we can improve our algorithm one uh step by step so that we can pass all the test cases okay so first the idea of doing this in dynamic programming shouldn't be that hard because i think this one is kind of similar to uh to another basic dynamic programming it's called decode ways right so basically in decode ways we just simply based on current one we get the based on the current state we can get the current state from the previous state right in this case what is the current state right so let's say we have this kind of let me do this in the blackboard here okay right so in this case let's say we have this number right and this is i right so let's say ending which is i right so it's this uh string here right so uh a common state is that is we the first state will be i right i means that okay so we record the state the current string ending at is i right and then what's the uh what's the second one right because we know the current state ending with i and we want to know all the uh we want to know all the possible ways that we can get and get to the current uh possible ways that we can or we can get right uh by ending with the current state but by ending with the i here right but then we need the what we need the second uh state here which is will be the length okay so that basically the length is telling us the uh the state that you know we're ending with i and the last number has length of this l for example let's say we have this is l right so l in this case is four right so it means that okay so here that's the last number right that's the last a number we are we're currently look we're currently looking at okay and if we define this the dp in this way right so in the end so what's going to be the final answer if we define it in this way basically it's going to be uh going to be a sum right going to be the sum of dp right dp what dp n minus 1 right n minus 1 means that okay we're ending with the last one and this is going to be at the length of k right so where k is equal to from 1 2 to n right because you know since we're getting all the ways that we can we want to get all the ways that we can decode or decode right this current string the length could be from could be the last like that the last integer could be either this one or this one that's why we have to accumulate every all the length right from this dp so that's going to be the initial dps definition right and if we have this dpi and l right so how can we uh get the state transition function right um so assuming we have this l equals to four right and how can we get this uh the ways from for this state and naturally we will just simply look at the previous letters right so the ways we can get to the current state is that you know the previous number is smaller than the current one right so in this case you know if so the previous number has to be has to ending has to end here because we're remember we're splitting this array right so there's couldn't be any skip here right scap here that's why you know obviously you know we have l equals to four and this number is okay because the length is smaller than the current one and it's obviously smaller than current one right and this two this one is also okay right and the three is also okay because all these three numbers they are that they'll be definitely they're definitely smaller than the current than this one right but here right this one we have to uh we have to check it's not uh it's not guaranteed this one will be greater i will be smarter than this one we have to check these two numbers basically to compare them right so that's why you know we have this what we have this one gonna be a sum of dp uh let's say we have i and let's say there uh based on this l we can easily get the j here right so j is the start of this j the start of this uh the last number and i is the end of this last number right so that's why we have this one it's going to be what's going to be a dp of uh j minus 1 right j minus 1 and then the k right where k is equal from 1 to l right or l minus 1. right so that's the state transition function because so this dpj minus one because dpj minus one means that you know we're getting the total weights that ending with ending here right ending here that's the uh that's the previous numbers last digits right and then the length how about the length like i said with the length we need to loop through from one to three for sure and basically to one to l minus one but for l we have to check if this l we need this l right we have we need to check if these two numbers if this previous number is smaller than this one that's why i put like uh option sign here right so that's basically the first version of it right so we simply do this and since we have two dp state it's going to be a nested for loop right so basically the outer for loop will be looping through each uh the ending point right and the inner loop will be looping through all the lengths okay so let's try to implement the first version right and then we can improve on top of it how about that and let's do it let me see we have yeah so what do we have we need n here obviously right it's going to be a length of num right and then we have dp right so dp is going to be uh i'll do this unplus one because uh for this in range of n plus one so the reason i do n plus one is because um actually the first one n will be enough because we're only looping through from zero to n minus 1 right but for the inner one since the inner one you know so it's going to be let me try dp i and l right because the total waste to split the string right the string with last number at i and the last ending okay and the length of last number is l right so that's the uh that's the definition of our dp right and since that's what so for the inner loop right sorry for the inner dp since we are talking about the length right so that's why you know the last one going to be n right the total length is going to be n that's why i do a n plus one here okay and then for the dp right so for outer loop it's going to be a uh enough in right oh by the way we're using a bottom up uh dp approach in for this time i think what the top down will also work but i think bottom up for this one is a cleaner okay so the outer loop is we simply just uh loop through the ending point one by one right and the inner loop will be like this l is going to be in the range of one to i plus two okay i know this one is a little bit weird because you know for the inner loop i need to loop through the length right from the current state let's say uh until the from one to the whole length you know since i is zero base but the length is one base right that's why i have to do a i plus one to make sure uh the length can reach i plus one i can reach i plus one because let's say we are at like here right so the i is like zero one two three four so when i is equal to four the biggest length is what is five right because it's because i zero base of l is length is one base that's why i have to do a 1 2 i plus 2 to make sure we have the last one is i plus 1 right okay and then okay so we have this i we have l right and then so the next thing is that let's get j right j is going to be a l minus l plus one so j equal to the start of the last number okay so when j is equal to three right uh we have i and then we have the j is pointing to here right i'm simply using this j for the future use assign create this create straight and then let's implement that state transition function here first and then we'll handle this at zero no leading zero case so uh let's see i'm going to define like a max l2 in this case right so x so this max l2 is the biggest that we can uh look through for the previous lab previously like previous ladder right for example we have i here and l is equal to four right in this case it's going to be a this is l right so the previous slider depending on basically depending on how many what is the biggest length of the of that we have left for the previous string and if and also if this one is smaller than this one the max l2 will be different right because we simply cannot use l minus one as a base because let's say when the l is here see we only have two numbers left right for us to iterate that's why we cannot simply use l minus one as a base so you know there are a bunch of ways i'll let's let me just do this um and this max l2 will be the uh basically be the nut the times the number of loops the checks we need to do for the previous numbers right depending on those kind of factors so if the j is smaller than l right so what is the j here just so j is here this one right and what's the value of j and even okay so first it's start off the last number and it's also like what's the length of the remaining strings here right so let's say this is two here right so the basic the remaining string is the length of remaining strings also too that's why you know when i check so first i check if the remaining string is smaller than the current one right then obviously we don't need to check there's no need for us to check that compare strings because all the possible string the previous strings will be us shorter than this one right then uh the max l2 which is equal to j right because that's the most we can loop for the previous number right else if right out if and then we need to check right we need to check these two numbers so let's come back to here so let's say we have j is equal uh this is i this is j right so in this case when uh when the previous string has enough letters then we need to check if this one is smaller than this one right we need to check these two then let's write the simple version here so what is the value for this one it's going to be the num of what j minus l to j right so this is j and this is what this is j minus l right if this one is smaller than the number from j to i plus one right and this one is j two i plus one if this one is smaller then the max l two will become two l right it means that okay we can uh check all the length from one to l so remember there's we don't need to go over to l because whenever this one has like length greater than the current one you know it'll definitely be greater than this one right else if this can if this check failed okay sorry i need a light source recall it's going to be a max l2 equals l minus one right okay cool so that's that now we have the max length we need to check for the previous letter so all we need to do is that we have l2 in the range of max l2 plus 1 right so that's why we have to loop through everything from 1 to this and then we have dp of i l accumulate this one to dp of j minus one right and then l2 right and then in the end uh return what returns sum of the dp of n minus one right so that's our first version i think oh sorry uh that's the dp part but we haven't uh handled this uh no leading zero case right where uh how can we do that and yeah let's see i guess we can just do this right basically whenever the num of j is equal to zero right so you basically if the every time when the current when the start of the card number start with zero uh we just do a dp of it should be dpi uh l is gonna be equal to zero right well actually you know we already initiate everything to zero but you know i'm just trying explicitly uh write it down here right and that's that and oh i think we forgot the base case right so we have handled everything right except for the base case because now everything's zero right and zero plus zero will always be zero so where would that one come from right we need a one right where one is the base case so what is the one so one is the basically a one is when we use the card everything as the card number right so no matter how many numbers we have right let's say we have i here you know if we use all the numbers as a last number right then that's where we get one because this will always one way of doing that right so and so to do that let me see uh we can do this right house if right as if j equals to zero right so basically if j is equal to zero it means that okay we so the last number will be the whole string right if that's the case right so what do we have dpi and l equals to one right and then we i'll have our else here right so i'll just do this okay and so this is the base case right the base case okay cool i think that's the first version and let's try to run it i think this should at least pass oh did i they're like okay let's run it this one will definitely tle let's try it yeah because the reason being is that you know yeah it's time out right because the time complexity is what we have an acid photo here right and then we have another photo here so which means which makes this one is a like n cube time complexity and with the constraints 3 500 this one with tle so which means in order to pass all the test case we need to somehow bring this one down to n square right and how can we do that right so obviously this is the this is a place where this is the for loop where we want to uh remove right because these two are kind of necessary right but this one yeah you know so how can we remove this one so as you guys can see right so basically this one is always from one to this max length right so what does it mean it means that it's accumulation right it's accumulation for dpj uh minus one uh for dbj minus one for all the length from one to this max l2 right so this is going to be a it's gonna actually it's gonna be a prefix uh a pre-sum right prefix uh a pre-sum right prefix uh a pre-sum right not prefix so if we can somehow convert this one into a pre-sum uh convert this one into a pre-sum uh convert this one into a pre-sum uh equation then we can basically remove this one right and how can we let's try to do it right so let's say we don't have this one and uh dp i and l you know let's try to define like another pre-sum right pre-sum dp pre-sum right pre-sum dp pre-sum right pre-sum dp okay um for this one it's going to be the same right n plus one so this pre-sum dp right n plus one so this pre-sum dp right n plus one so this pre-sum dp right uh it's almost the same except uh except for what except the total weight the split at ending i and the length of the last is what is from one to l uh from one to two l right so basically this one is the only the ways for this specific l but the presump is the ways from everything from one to l and that's exactly what we can use for this one because that's the exact like i said that's the definition of this presump right so if we can somehow get this pre-sum so if we can somehow get this pre-sum so if we can somehow get this pre-sum right and then here inside the for loop we can just do i l equals to the what a pre-sum equals to the what a pre-sum equals to the what a pre-sum of j minus 1 and what minus one and uh oh yeah and the max l2 right so if we can do that then this that would be perfect right uh yeah but this one you know uh but where did where does this one come from right how can we calculate this one here um it means that we need to do what we need to somehow update this one right so how can we update we need another state transition function for this presump to be able to also accumulate this one right and what's going to be what's going to that be so it's going to be pre sum of in l right so how so what is the state transition function for the presump uh i and l right it's going to be a pre-sum and l right it's going to be a pre-sum and l right it's going to be a pre-sum of i l minus 1 plus this dp in l right so remember the definition of the sum of the presump right i and l means that the odd is that's the total anyway with i uh and the length from one to l okay and then what does this one mean it means that all other ways from i to l uh from one to l minus one and what we are getting here we're getting the total ways that ending with i and the length is specifically l and that's exactly what is missing between from this one to this one right because the proof this one the i might the presump i o minus one plus this dpil will be exactly equal to this one right that's how we basically that's how we convert right from this one from the dp version to the presumed version right so keep in mind that you know this one has to be uh outside of the e-files right because we need this the e-files right because we need this the e-files right because we need this one to do that right and i think that's okay i think i forgot one more thing so we have to do a module right mod equals to the end okay right so that's the uh that's the change and now as you guys can see actually we don't need this dp uh array anymore right because it will so this dpi and l will always be like intermediate uh variable because in the end it because all it does it will just simply use it to update this presump oh and right over here and we don't need this presump uh we don't need to do a sum here because we already have the pre-sum it's going to already have the pre-sum it's going to already have the pre-sum it's going to be a pre-sum be a pre-sum be a pre-sum of what the last one is going to be n minus 1 right so ending with this one and the length is n so right so this that's the uh the definition of this presump and that's exactly what we need so go back to here so we can see we can just remove this dp right for now because we'll be using this presump all the way right and we can define it or we can just remove this one uh it doesn't really matter i mean i can call this one let's call it like a current right kind of going to be zero right we can just do this current and then current right so right yeah so that's the second version of this problem and you know but still you know even though this one we have already removed this one right but we have this part see you know this slice i think the worst case scenario it also gonna also be a of n time complexity right even though we have already removed this photo but we have a slice here so the last version will be we'll get rid of this part but let's try to run this one first let's try it if this one works and give us some better results what wow i didn't expect this one would i mean would pass uh fine yeah because in my i thought this one would give us like another off and so this one theoretically speaking this one is still like an cube time complexity but for some reason this one passed um but okay let's try to uh improve this one okay so what we're doing here is we're trying to compare like two strings right two strings where that you know each one uh who is smaller okay basically it could be start from and from anywhere right so this one starts from here so let's say if we compare this sorry it has to be the same length right it's going to be this one let's say the first one start from here second one start from here right so we want to compare this two numbers so the comparison is fairly straightforward so we check uh strings one by one if the first one is the same then we move to the second one and then we move the third one and then to the last one right and so the moment we see a different uh ladder that's when we can tell which one is smaller and which one is bigger right so and how can we uh improve this one we can do some pre uh processing such that you know given like this i given like this two starting point if we can immediately know uh which character we need to compare right so for example if this one is like uh let's a b and c right sorry this okay never mind i'm using like english letters but it did the concepts are let's say is same so it's a d e right so if we know uh we if we know the third letter is the first one that is that we need is the ladder that we need to compare then we can we don't have to uh scan from the beginning to here every time right and then what can we do about it so we can do some pre-processing and we so we can do some pre-processing and we so we can do some pre-processing and we can simply just for each of the pair two pairs of string right if we can get the longest common string for these two pairs in this case it's going to be what so this is i and j so basically the longest common string of inj or equal to two right and if we know this one if for any given pairs if we know the longest common string then we know the next letter will be the one we need to compare right obviously if the length is the same as the string uh we're trying to compare right and then the y is greater than they are they're equal to each other right so that's why all we need to do is we just need to uh preview this along this common string uh dp array to get rid of this and how can we do that you know it's easy right we simply just use uh two pointer and to loop through all the uh the strings right and then we compare so this kind of two it's a kind of common technique for dp for like two pointer dp problem so whenever the num number the i the num i is equal to the num of j right so if it's the same then this d lsi equals to what lcs inj equals the 1 plus lc s of i plus 1 and j plus one right otherwise it'll simply be zero okay so let's uh do that uh so now we need a third dp array okay and this one is what it's the longest common string the length okay the length of the longest common string right that starts from i and j right so for i in range of what we have n minus 2 minus one and the minus one okay because so the reason i start from n minus two is because uh it's because those two strings cannot be overlapping to each other right that's why i start from this one so that we have then the j will always have like position right and then for j in the range of what i plus one and n okay and oh and now the reason i do it from the end is that you know in that way i will be on the left and j will be on the right so that's aligned with our definition otherwise we have to put j on the top and then i uh below it looks a little bit weird but you can also do it right and then if number of i is equal to the num of j right and then the lcs uh lcs of i and j is going to be 1 plus lcs of i plus 1 and j plus 1 right so basically if i and j are pointing to here right sorry this is i and this is j right so if this these two are the same then we know okay we can simply compare the numbers uh the string starting from here to here right and yeah and else lcs of i and j is going to be zero right so i think this one could be there could be a very uh you know this one could be more than what we need because you know let's say for example right i mean we have this one right let's see the eyes here and the j is here right so in our case like actually in our like below what we need is that we just need to know if but basically we're trying to compare these two right if these two are the same okay right but for this one you know if everything is same let's see this is l a right if they're all the same right if this is all a then the lcs of iron j will equals to what or equals to uh one two three four five well equals to five instead of two right but five is also fine because when we use this number we simply just check if this number is either equal or greater than the length we're trying to compare right if there if it's greater or equal either equal or greater then we know this at least these two numbers these two like strings will be the same okay right so it's fine this one is bigger than what we need okay and there we have that and finally we can try to get rid of this part right and let me try to come out this part so what we have is like this so we have else right uh so i'm going to like this common length i call it cl uh common length right common length of the lcs from what so from we have two start the first one is j minus l the second one is it's j right so that's the number that's the value we pre-processed that's the value we pre-processed that's the value we pre-processed and what do we compare so if the cl it's either equal greater than l so this one means that okay the strings the two strings are the same right or the num of if okay so if the cl if when the cl is smaller than l then it means that okay so these two strings right so we have because we know that the length we're comparing is like it's l right so this is the i and this is j so when this one fails right so when this one fails it means that uh these two strings are not equal then the number we're trying to compare is what so let's say that the cl is equal to two right that means that this isn't these two numbers are the numbers we're trying to compare right or the number of what it's going to be a j minus l plus cl okay right so because that's a start right that's the this is i and i plus cl will be this one and if this one is smaller than the num of the other one is j right j plus cl right so we can simply just uh navigate to the numbers we're trying to compare directly without looping through that's the benefit of pre-process that's the benefit of pre-process that's the benefit of pre-process processing this lcs right and if these are the two reason then we do the same right we do this then we know okay we can use it we can use this uh this length otherwise same thing right otherwise max this one same for this one okay i think that's all we need to do here right so let's try to run this one last time memory what memory limit exceeded wow i'm not expecting that uh is it because we i did this okay let me see oh interesting okay seems like you know we cannot even pre-allocate too pre-allocate too pre-allocate too many spaces either but for some reason this uh the last version didn't improve our run time for some reason i think it's because the online chart is not that accurate but for sure as you guys can see the last version oh yeah so this time it's faster right but as you guys can see for sure this for the last version this one is n square right and here we have a we also have n square right time complexity because everything here is like o of one right this is o of one and this is also o of one so the last version is definitely n square time complexity and that's it right i think that's everything for this problem okay so i mean the idea at least for the first version shouldn't be that hard to come up with right so the let's make what makes this one a real hard one is how can we improve that especially for you know we have two challenge here this is the first one is that how can we get rid of this photo pier right so what we did was the uh instead of uh using the deep the first version of dp we convert it into a presump right where i think this is a common technique whenever you see like this accumulation from one to this one you know i think we can most likely get rid of this for loop by uh introducing another like pre-sum uh introducing another like pre-sum uh introducing another like pre-sum uh pre-sum uh pre-sum uh pre-sum dp array right and then the second one is this one so this one's a little bit tricky i would say that so how can we get rid of this one so we have to then we just simply pre process all the common longest common strings for each of the pairs right and yeah there you go i hope you guys like this one and thank you for watching this video guys and stay tuned see you guys soon bye
|
Number of Ways to Separate Numbers
|
minimum-interval-to-include-each-query
|
You wrote down many **positive** integers in a string called `num`. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was **non-decreasing** and that **no** integer had leading zeros.
Return _the **number of possible lists of integers** that you could have written down to get the string_ `num`. Since the answer may be large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** num = "327 "
**Output:** 2
**Explanation:** You could have written down the numbers:
3, 27
327
**Example 2:**
**Input:** num = "094 "
**Output:** 0
**Explanation:** No numbers can have leading zeros and all numbers must be positive.
**Example 3:**
**Input:** num = "0 "
**Output:** 0
**Explanation:** No numbers can have leading zeros and all numbers must be positive.
**Constraints:**
* `1 <= num.length <= 3500`
* `num` consists of digits `'0'` through `'9'`.
|
Is there a way to order the intervals and queries such that it takes less time to query? Is there a way to add and remove intervals by going from the smallest query to the largest query to find the minimum size?
|
Array,Binary Search,Line Sweep,Sorting,Heap (Priority Queue)
|
Hard
| null |
347 |
video when you look at a league problem called top k frequent elements so given a integer array and an integer k return the k most frequent elements and the answer can be in any order so you can see here we have an example of this right so this integer array and then we can and we want to return the top two frequent elements so in this case we going to have one and two right in this case you can see one appears three times two appear two times and three appear one time so therefore we're just returning one and two or in this case we can return two and one right because those two are the top two frequent elements um and then you can see here um k is only one and then in this case the top one element is just one right so the constraints is that it is guaranteed that the answer is unique and um you can see here that the array is guaranteed to be not empty um so the goal for this question is we really want to solve this problem better than right better than n log in time complexity right where n is number of the uh the size of the array so in this case to solve this problem using a log n we know how to do that right we can basically first create this map right this table in this case um the key right will be will be the um basically each and every single element right so each and every single element and then the value is basically the um the number of times this element appears so in this case one up here three times to appear two times and three appear one time right and then what we're gonna do is that we're gonna basically um sort these arrays right sort these uh sort the keys right based on the value right so in this case we could have like an array like one two these are the unique elements and then we're gonna sort the array based on um their number of times uh their frequency right their number of frequency so in this case three uh one appears three times so one up here first right two appear two times so two appeared the second and three appear one time so three appear third right but worst case scenario um we could have each and every single element appear only one time so the time complexity will be just in log in right so unlock it so in this case what we can do even better is we can be able to use a heap right so in this case a heap um we can basically keep a size of k so let's say k is two right in this case we only have two elements in our heap so what we're gonna do is we're gonna have a min heap right and then what we're going to do is we're going to compare the top element with the nest element that we're going to add right so for example in our code basically what's going to happen is same thing we're just going to um keep track of each and every single element's appearance right a frequency in a table so the key is basically the element itself and then the value is basically going to be number of times or the frequency of that element and then what we're going to do is we're going to define a min heap right so we're going to define a min heap and then we're going to sort based on their frequency so we keep adding those elements that we have in our key onto our min heap once we exceed once the size of the heap exceed the k then we can basically take the top element out of the heap right and then again we basically just going to add the top k frequent elements or basically all the elements that we have in our heap onto the result array and then we're just going to return that right but this will give us a time complexity of big o of log n log k right so unlock k the reason why is a log k is because here you can see the size of the heap right in this case for insertion and deletion is basically going to be log k um so therefore um we're going to iterate each and every single elements that we have in our keys right and then we're going to perform a log k time complexity for insertion and deletion so therefore the time complexity overall of this algorithm is going to be in log k so how can we be able to even further improve the solution how can be able to improve time complexity well so to improve the time complexity what we can do is we can use something called bucket sword so bucket sort basically what we're going to do is that we're going to have uh we're going to do the same thing right first we're going to keep track of their number of times it appears right so in this case same thing so one appears three times two appears two times three appear one time right so we're gonna do is that we're gonna basically use bucket sort and we're trying to improve the time complexity down to a linear by utilizing another table right so once we know how many times each and every single element uh well basically each every single element's frequency what we're going to do then is we're going to convert this table into another table and this another table has a key that is the frequency right so the key is basically now the frequency and then the value right so in this case the value let's draw this way so key is basically the frequency and then the value is basically the list of elements right so in this case what we're gonna do is that we know that um uh one up here three times so in this case we're gonna what we're gonna do is we're gonna have so basically this is the list of elements right list of elements okay so in this case we're gonna have like one here right and then two so for frequency two in this case we're gonna have only two for frequency one we're gonna only have one element right in this case basically three and let's say we also have like another element in this case four right so what we're gonna do is we're just gonna append it onto this list right so it's like this so let's say in this case k is two so what we're going to do is we're gonna we know that the maximum uh frequency is gonna be the size of the array right so one two three four five six seven right so in this case what we're gonna do is that we're gonna go from seven right iterate from seven uh integer value seven to in this case one right um and then what we're gonna do is that uh we're gonna check to see if we have that frequency we have that value in the table in this case let's say seven does not have it in our table and all the way going down to three so three does happen in our table right so we're gonna do is we're gonna add that element onto our list onto our result list so we have one and then what we're going to do is the next element is 2 right so in this case 2 we actually have a value which is 2 so we add 2 onto it and then once we have a size of 2 right size of k then we can basically return this array right so this is basically how we're going to utilize this bucket sort we're basically using two tables one is we basically one table is uh one bucket is to keep track of all the elements appearance right all the elements frequency and then we use that bucket use that table to create another table that the key is going to be the number of frequency and then the value is going to be the list of elements that has the same frequency so you can see here in our code we doing something similar right first we're going to uh basically save each and every single element's frequency in a table right this is our first bucket now the second bucket is we basically store each element's frequency as the key so you can see here uh for each and every single elements right for each and every single key in bucket one uh we're just going to get their frequency and then we check to see if bucket 2 has that frequency if it doesn't we're going to create a list and then we're going to add this current element onto this current frequency right so then what we're going to do is that we're going to get the top k elements right what we're going to do is we're going to create a result array with size k and then we're going to go from n right to uh to basically one right we're not going to go down to zero because we want to make sure right for if there is an element then their uh minimum frequency is just one right so in this case we check to see if bucket two contains that element um in this case if it does then we're just going to um get the list and then we iterate the list right remember we want to iterate basically k number of times right we basically want to get top k elements not all the elements so if k in this case is equal to zero right you can see that um because the order doesn't matter so in this case result k minus right we basically get the current the last index is equal to integer right and then if k is equal to 0 then we just return the result and because in this case we want to return something at the end right let's say let's just say that if we have a situation where um where in this case k is actually bigger than number of elements that we have in our array then we at the end we can just return the list right so you can see that this will basically help to bring the time complexity down to a big of n where n is number of elements that we have in the array so there you have it and thank you for watch
|
Top K Frequent Elements
|
top-k-frequent-elements
|
Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequent elements_. You may return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,1,1,2,2,3\], k = 2
**Output:** \[1,2\]
**Example 2:**
**Input:** nums = \[1\], k = 1
**Output:** \[1\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
* `k` is in the range `[1, the number of unique elements in the array]`.
* It is **guaranteed** that the answer is **unique**.
**Follow up:** Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size.
| null |
Array,Hash Table,Divide and Conquer,Sorting,Heap (Priority Queue),Bucket Sort,Counting,Quickselect
|
Medium
|
192,215,451,659,692,1014,1919
|
951 |
951 flip equivalent binary trees for binary treaty we can define a flip operation as follows choose any note swap the left and right subtrees a binary tree X is equivalent to a binary y tree if Y and to binary Y if and only if we can make X you go to Y add to some numbers of some number of operation where the function that determines whether two binary trees are equivalent issues are given by we know it's one end would - oh God hmm I mean I think the would - oh God hmm I mean I think the would - oh God hmm I mean I think the first thought that comes to my mind about this problem is well this is a there's only a subset flip okay just want to make sure I think that was the first thought I want to come came to my mind was that like do you have to flip a and then the other thing that comes into my mind I worry a little bit because I think sometimes the test case is a little weak we could then you expect because for a tree of a hundred nodes how many I guess there's only six step actually that's not so bad because so my dog process now or was that like you know for a full tree with 100 no Tom what is the depth of that way and the depth of that is I don't know to the was it to the eighth so the diamond is 128 wait no that's 256 the tutor 7 is 128 that means you're Deb is at most 7 so I think that will maybe is good enough course that mean I mean the mathematical analysis are no tricky people didn't try to figure out how what's the possible thing but I think there's a lot of cell filtering that allow it to having the analysis the complex is a little tricky but yeah we could just do this recursively anyway and yeah and we could even use this because something I think that's kind of and we could just actually use the definition poorly called Coast excuse me which is and there's a dot Val type thing okay so first of all we have to do with one that wow it's not returned for us and I'm oh I just oh because I've been using pythons I haven't needed to cause places I'm used to causing my own voices still but this is returned for so this is the no obvious base case let's say okay so what are the cases right so let's say if a lot of weirdness I don't know if this acquit why I'm not usually could add I don't know just a cleaner way to kind of separate out this case again separate all these cases so I you should just enumerate them especially I can test well sweep it up whoops actually I want off forward to be true right okay I mean you could get funky of the logic but I'm just going to write them out for now I think there's also like a more trivial case where if one is just not know then I do I think if tastes like a children maybe that's how it'll be simpler but it is money in it dan returned for us otherwise they would tuned it no actually I think we could simplify this a little bit okay so that's just add another one if one is you know or and I guess this is true if it's not you go to put two / - no Dan we turn for us I just put two / - no Dan we turn for us I just put two / - no Dan we turn for us I just picked this could come ahead for us hey uh yeah I mean I think to be honest a lot of it is just practice I think now and I actually was like one of my mentees ish if you want to call him dad what I have a mentee of whom I still work with and he actually recently got into programming these problems and fool him I actually find out what because I so kind of disclaimer is that I've been doing on and off so not it's not a like that but yeah I was gonna say that I've been doing these four years on and off so not like straight but as a we sell no disallowed stuff that did I take for granted that like he has to be like Larry people don't you know this is not typical I'm like oh I did not realize this but uh but yeah so like so I think just a lot of practice and you kind of see patterns in both problem-solving and coding I would get problem-solving and coding I would get problem-solving and coding I would get into that I'll answer your question fully after this problem because so I don't want to get stuck in the middle but a little bit but yeah I will answer your question no worries but there are a lot of online boats and youtubes and stuff I think it yeah give me a minute okay so now I don't have to worry about it - no cases don't have to worry about it - no cases don't have to worry about it - no cases here I could just return the equivalent of one love with $2 and so both this has to be true or the operation of this right maybe that's good enough let's see my studies try on the test case whoops - too much - on the test case whoops - too much - on the test case whoops - too much - sorry no semicolons okay that's the only thing I may be worried about his time limit or if I missed one case just possible Wow Java is really fast maybe I should do Li colognian Java I mean look at this he'll milliseconds huh decided that or they don't have a good time and they just put so much I gave everybody which would be hilarious oh yeah that's uh yeah I don't understand like how the time timing works to be honest also nice to see you Oh DX that's yeah I don't know how this is so fast but might as well give me negative a second it gave me a true before I submitted it no but uh yeah I mean I think this is a very big definitely recommend this question for an interview and that it is uh it tests a couple of key concepts one is trees which maybe in real life you could unless you can to like MLE decision tree stuff trees why don't come and deploy that much in your life but it's still fun to know and people and interviews interviewers love trees so you have to know chewy so defi I like that part this problem for that reason and - is recursion which obviously also and - is recursion which obviously also and - is recursion which obviously also interviewers love in general so definitely I mean I think it's not my type of question to ask if I mean as an individual but uh but it's generally like a very reasonable question I could see asking I am I think the thing with trees is kind of doing it in a way that it's very clear and so yeah and this is complexities a little tricky to know the branching I think so despite where lots and only branches twice at each it's not even deb-deb is not the each it's not even deb-deb is not the each it's not even deb-deb is not the right word it's like two to the demos or something like that in the worst case right but you know there's a lot of self feel to it and I don't know if you could construct and also because of other values that unique actually doesn't really branch right so maybe it's linear actually now that I think about it because it doesn't really yeah because it's unique these both cannot be true at the same time so only one of them will have a vertical recursion and therefore there are the one time is o of n which is linear because you look at each node at most two or three times and so forth yeah actually I think you can do this I mean so the question is how I could do this iteratively I mean with well first search yeah you can you just have to keep a list of all the stuff you have to process and then when you process it you only insert one new item to the queue and then you come that way you could prove that so event very trivially but wait yeah so you have you know you started inserting good one and with twisting knows to compare and then every time you process it you put one left and then with two left and so forth and then put down and processing in a tree in the queue side and then just keep on doing and that's how you're doing it was definitely I think that's possible and actually I'm using a queue or irritably you would also very obviously doing it in a level first thing so some like instead of I wouldn't say it's pre-order oh I guess yeah instead so pre-order oh I guess yeah instead so pre-order oh I guess yeah instead so it's like difference between doing it in pre-order and pose order no that's pre-order and pose order no that's pre-order and pose order no that's not why I don't know that will first versus okay maybe I'm just trying too hard to use those vocabulary maybe it doesn't really fit what it how you're doing in this one but yeah that's kind of how you were doing can you make just two lists addition of one compare them but there could be two delay and possibility on each level though if you're not careful right depends on how you do it I think you could definitely probably do it I think the way that you're talking about there's almost like a dynamic programming thing on each level in that there are only two suffix to each note and then you use that to build on your next level so I mean Ennis which I think you could do definitely because I think that's one of the core concepts in dynamic programming and how you save space and it comes up a lot actually so it comes up off and maybe you don't need it is fully code it's not necessary I haven't found that usually to be necessary but uh but yeah I think that's the same concept where you're almost like look at you top of it again obviously all those things are way overkill this is ten nine to code or so maybe a little bit messy but I also actually I'm happy that I'm able to do this a little bit cleaner than I initiate was because you saw me try to do this whole thing with a lot of other cases but this really simplifies the case more and once I mom to check the nodes the root notes for now yeah that's pretty cool maybe I'll do one more farming job or something but no I guess maybe there's also uh kena Nagato and that's such a fancy okay actually no that's ten make sense it's a very fancy vocabulary but it just means normalizing both poetry so dad like you could like that's it and the way they voted which actually make sense even my own to ban is like you can have both trees to a binary search tree and if they're the same then they should be the same right otherwise they're not the same tree and I think that someone like that is fine yeah I think that's a pretty cool idea like I don't know if I would have liked that's a lot of work so I don't know if I would do it well it came out of it without another forcing function or someone like that but that's a key way of doing it for sure yeah
|
Flip Equivalent Binary Trees
|
partition-array-into-disjoint-intervals
|
For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees.
A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** after some number of flip operations.
Given the roots of two binary trees `root1` and `root2`, return `true` if the two trees are flip equivalent or `false` otherwise.
**Example 1:**
**Input:** root1 = \[1,2,3,4,5,6,null,null,null,7,8\], root2 = \[1,3,2,null,6,4,5,null,null,null,null,8,7\]
**Output:** true
**Explanation:** We flipped at nodes with values 1, 3, and 5.
**Example 2:**
**Input:** root1 = \[\], root2 = \[\]
**Output:** true
**Example 3:**
**Input:** root1 = \[\], root2 = \[1\]
**Output:** false
**Constraints:**
* The number of nodes in each tree is in the range `[0, 100]`.
* Each tree will have **unique node values** in the range `[0, 99]`.
| null |
Array
|
Medium
|
2138
|
36 |
Hello friends, welcome to the new video, question number 36 loot code is a valid sudoku medium level question, the question is Singh's question, you guys will get internet, it has been asked in Google amazon, let's start by voting for a nine to noida sudo. If there are some cells in it, your body is frill, then tell us which cells are there or whether you have failed correctly or not. Only the field cells need to be validated and according to the following rules. Some rules for folding a valid beginning. You can use number 1098 in every day without repetition, you can use line number from seven in every day but cannot be duplicated and you can use number from every column without repetition, no number should be repeated again and Your all boxes are of 323 size, in that too you can use descendant number. Do all these boxes without hesitation. We will see further that the input given to us is today's grade and if you see in this grade, all your sales are not filled. The number of selfies is there and the number of your MTS number is given there, we have to validate all the selfies that you have taken. For example, if I look in the first column, I am seeing the number 8 and in the first column. Below I am again seeing number eight, so this is my repetition. Number eight is being repeated, so it will return its own false. This selfie has not been done in a valid manner. Spread it among as many celebs, we just have to check it, so its true. We will return false. In this example, let's understand it in a little detail. What is it? Well, it is Daku Valid. We have some conditions for Chotu. Beach Romance Content Digit 129 without repetitions. No number should be repeated in your row and the number should be of Vansh. This can be Columbus content digit 1298 without petition. There should be a number in your column and in the same way 323 sub box is mask content digit 129 without addition. No number should be duplicated in your sub boxes of 323 and should not be repeated. And you can use numbers between one to 9, so let's consider this as a little example. We have a Sudoku, this is our nine to noida's great. In this, if our first row is spread like this, then any number in it. If it is not repeated then it is Velvet Joe and if I look at the column, there are 179 numbers used in it, then this column of mine is also valid, but if I pick a number in the crops and repeat it, if it is used here, then we They will say that our problem is not valid and this Sudoku is not filled in the velvet way and in the same way quickly pick a number in the column and repeat the number then we can say that if the number for is being repeated in the column then it is not a velvet column and This is not velvet sudoku in the same way we have sub boxers from cream to three and in these boxes numbers can be used between one to 9 and no number should be repeated and total you have nine boxers in the whole you will see in the beginning If you have nine boxes then do the income numbering and this numbering starts from managers and ends at eight. Why is this because your stop index starts from zero and ends at one. In the same way our column. The index also starts from zero and ends at one, so we numbered our boxes in such a way that it starts from zero and ends at our box8, so how will we solve it? What is the intuition? So what can we do Stress Solution That tweet 283 times over the board to ensure that it is not too late May be no problem video subscribe to like So we can ride three times First we will check all the diseases and then all the problems We will check and we can write a loop for this we will check all our boxes but what could be better than this actually all this cold be done in just one of the nation so we can check all the diseases in one single hydration You can check, you can also check the balance of the columns and you can check on the box of your 323, then let us discuss the one direction approach, we have a great one from Nine to Noida which is a Sudoku, so first let us see this. How do you rate? First of all, first stop, check and first romance, see all the columns, after that we come to control, then we come to ₹3, then in some then we come to ₹3, then in some then we come to ₹3, then in some ways, we nitrate the whole in our grade, we have One number is 9, so we have to find out whether the number nine is in your romantic playlist, whether your column is a duplicate, whether it is a duplicate in your box and your note, this will be the vibration approach, so you will visit each number once. We are not going to visit this number nine again, so first of all we have to find out in single digit, what is its column index, what is its row index and what is its box index, so if you see that it is on four throws then its roll will be death. This is on the fourth column, so our column index will be three, so let's take the number and write the column. If we see what is its box index, then we will number the box and this box index will be for, so how will we calculate? For this box number, we will have to use a formula for this, we can write Robot Reel, we will multiply it and make it plus the length three, then you will know from which box the number belongs, so our Will go to four and in the same way if I am another example, my number is seven, then its number is my phone, its column is my favorite column in text and if you calculate drops using this formula, then that will be your box. That will be your box number five. Now we have to see whether this number 7 is repeated in its row, whether it is repeated in its column, whether it is repeated in its box, then for this we will use the data structure asset and Handset has a property that it does not store duplicates, when you add a duplicate in it rejects it, so how will we start it and how will we check it, for that we will have to create a string and how will we create a string like your number. Seven is, first of all we calculated that on row index for, then you will write roll, keep roka index and save your number in it, add it and make a string in it, we have made the combination stunning, now we have added this drink in the set. This means that the number seven has not been kept on the row and row. Okay, now you have calculated its length. Your column is indicated, so you wrote the column and set the plus index, set the number seven in it and you put it in the set. This means that the number six has been made on column eight. In the same way, the number six has been made on the box pipe. If you add two, then what did you do. You made a single visit to each number. In a single visit, we found out that it prevents the column from being intact. What is the box index and in that same visit, we created this trick and added all three settings to our handset, it was fine, what do you do if a duplicate number comes again and I take a number, agreed, first of all, let's see Its row index is this index for and its column index is our change which is 6 and its box index is our five so if we make limiting of this number then my row and prem number is seven and if I call it hair style Either I will put it in the set or it will reject me because it has got the same setting again and in the same way if I make the acting of number seven coming on column six and put it in the set then here I am not facing any problem because This is seven on column six and the previous seventh was column eight and in the same way if I look at my box number five back and I add to this and I will put it in my handset then it will be rejected on this also so it means that Number 7 is repeating in the box and is repeating in the row, so in a single visit in a single hydration, we can calculate the index of the box of the stopped column and the same visit name is there and store it in the set and check that it is If it is a duplicate or not, then if a duplicate comes then now you can say at the same time that this to-do of yours is invalid and in this way we this to-do of yours is invalid and in this way we this to-do of yours is invalid and in this way we can check what will be its complexity. If we analyze the complexity a little and then all video. here in this one hydration and votes we have only one hydration Kareena and total you had nine to 9 great Meena yours were 771 cells if you zoom in that the options are 281 then your time complexity could be of a fool and you had used a headset And if you have stored every number in the set as a string, then turn off your space complexity bag. If you laugh, then this is our complexity. Now let's see how we can code it. Let's start coding. Retentive has given us pills if If any number is duplicate then you will fold the return and if no duplicate is found in the last then you can go through the returns here and in a single hydration we have to check, we will make a single visit to each number and we have to see that Is that number repeating or not and what is the size of our great one, the size of 1929, this plus of Ajay Jano is fine, so we will make a single visit here, in this single visit, you have to see the Roy index, you have to see the column intact box. Have to keep an index and in that single visit you have to store it in the headset and check whether the track is duplicate or not. We also create a set and name it seal. A new hair will be set. If this is fine then we will directly set it. And how to enter village, then we can enter something like this F, which is yours, if you have made stuffing in it and we have inserted it, then if I directly make assistant, row plus row index of probe plus number, then your number is If it is something like this, then you will check that if this repeat is coming, it is not added in this handset, if it is not added then you will fold the return here, okay and we can add a little more to this condition. We can copy the same for the column also, so how will our column be? For the column, we will write column here, village, okay, and here we will do this, okay, and we will write this condition for the box as well. There is one more condition below, but otherwise the line will become long, then how will we write against the box? What was our index for the box? We calculated the index for the box and got for. I divided by thriller multiplying wealth. There were and plus z divide three so in this way we were taking out the box so this is our boxer index friend we will check if there is a repeat in the box and it is not added in this handset then we will file a return and it came This will work but all our cells are not there again. You saw that now the worry was a dot in some years, so you have to check the voice mail from us. In the cell in which the number is in your actual, then in the rest of the cells I was your dot. So if in your spell. If there is a dot then there should not be a dot in your cell, there should be a number then you will check this and we put this condition inside it is okay if there is no dot then you have to check the health, if there is a number then you will check and you are added to the set. We will do this and check that if these return forms are not there then the last knot will become pregnant or we will compile it once and check that our ad is getting compiled, once we submit it and see that our ad code is being submitted and If you go to the latest suggestions, you will see that here Jhamkudi is maintained using the hash map, so if we test this cord as well, I think its performance can be slightly improved with the hash map. Let's check if Ajay is active then you will see that this is a small code part, so you can either implement hash maps or you can improve it directly. You can support me and my channel. You can do so with a small donation so that I can continue making videos for you guys. You can find the donation link in the What's But section of my channel or in the first comment of every video. You can go to the About section of my channel and access this Google Shadow. You can see in shape which video of interview date questions I have made, which list question see video, you can make category voice search, channel related news, which video is coming next, you will get all the updates by watching this video. Thank you very much for this please rob Ajay mp3
|
Valid Sudoku
|
valid-sudoku
|
Determine if a `9 x 9` Sudoku board is valid. Only the filled cells need to be validated **according to the following rules**:
1. Each row must contain the digits `1-9` without repetition.
2. Each column must contain the digits `1-9` without repetition.
3. Each of the nine `3 x 3` sub-boxes of the grid must contain the digits `1-9` without repetition.
**Note:**
* A Sudoku board (partially filled) could be valid but is not necessarily solvable.
* Only the filled cells need to be validated according to the mentioned rules.
**Example 1:**
**Input:** board =
\[\[ "5 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\]
,\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\]
,\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\]
,\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\]
,\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\]
,\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\]
,\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\]
,\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\]
,\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\]
**Output:** true
**Example 2:**
**Input:** board =
\[\[ "8 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\]
,\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\]
,\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\]
,\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\]
,\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\]
,\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\]
,\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\]
,\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\]
,\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\]
**Output:** false
**Explanation:** Same as Example 1, except with the **5** in the top left corner being modified to **8**. Since there are two 8's in the top left 3x3 sub-box, it is invalid.
**Constraints:**
* `board.length == 9`
* `board[i].length == 9`
* `board[i][j]` is a digit `1-9` or `'.'`.
| null |
Array,Hash Table,Matrix
|
Medium
|
37,2254
|
521 |
okay so this problem is about longest and common subsequence right so um it is trying to let us find out what is how long is the longest uh uncommon subsequence between two strings so for example like uh string a is a b and a and string b a c d c all right so the longest uncommon subsequence so is of the length of three why ABA is a subsequence of a but it is not a subsequence of string B so that's why like ABA is the longest and common subsequence with length of three all right so by first looking at this problem it seems to be like relatively hard because it like seems we have to get the subsequence of two strings and do some comparison and then find the longest Etc but when thinking through this problem is actually kind of uh simple because if A and B are have the different lines right so the longer string for example like this the longer string will always be a subsequence of itself but the shorter screen won't be ha won't be a subsequent won't have a subsequence of the longer string so that's why that's where we know that the longer screen is going to be the result that will return quite similarly like uh for if they have the equal lines right so for example like this and all we have to do is to compare these two strings whether they're equal or not so if a is equals to B then um we returns negative one because there is no uncommon subsequence between these two but if a is not equals to B then uh like for example this case has one character difference then we know that string a is a subsequence of itself but string B won't have a subsequence of string a because there is one character difference so the length of the string a or the length of the string B since they are equal lines will be the result we're going to return right so by knowing that so this is the code so basically we're going to compare uh A and B if that equals number to negative one if they have different lines then we return the longer screen the lens of the longer screen and then where else they have the same lens but not each equals to each other we're gonna return the um either length of a over length of B
|
Longest Uncommon Subsequence I
|
longest-uncommon-subsequence-i
|
Given two strings `a` and `b`, return _the length of the **longest uncommon subsequence** between_ `a` _and_ `b`. If the longest uncommon subsequence does not exist, return `-1`.
An **uncommon subsequence** between two strings is a string that is a **subsequence of one but not the other**.
A **subsequence** of a string `s` is a string that can be obtained after deleting any number of characters from `s`.
* For example, `"abc "` is a subsequence of `"aebdc "` because you can delete the underlined characters in `"aebdc "` to get `"abc "`. Other subsequences of `"aebdc "` include `"aebdc "`, `"aeb "`, and `" "` (empty string).
**Example 1:**
**Input:** a = "aba ", b = "cdc "
**Output:** 3
**Explanation:** One longest uncommon subsequence is "aba " because "aba " is a subsequence of "aba " but not "cdc ".
Note that "cdc " is also a longest uncommon subsequence.
**Example 2:**
**Input:** a = "aaa ", b = "bbb "
**Output:** 3
**Explanation:** The longest uncommon subsequences are "aaa " and "bbb ".
**Example 3:**
**Input:** a = "aaa ", b = "aaa "
**Output:** -1
**Explanation:** Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.
**Constraints:**
* `1 <= a.length, b.length <= 100`
* `a` and `b` consist of lower-case English letters.
| null |
String
|
Easy
|
522
|
112 |
hey guys in this video i'll be showing you how to solve late code question 112 path sum um so for this question we're given a binary tree and a target sum and all we have to do is return true if there is a path from the root to leaf where all of the numbers add up to our target sum and a leaf is considered a node with no children so in this example you can see the target sum is 22 and if you took this path from 5 to 4 to 11 to 2 adding all of these numbers would give you 22. so then say like our target sum was 20 this path would not be valid because or the path from 5 to 4 to 11 would still not be valid because 11 is not a leaf so it has to end on a leaf node and so the best approach i think for this problem or at least the simplest is going to be to use depth first search because that way we can just make it a recursive call and we won't need to store um any like extra sums that we need to do further calculations on you can just kind of know the current value that you're on so if you start at 5 we could say subtract 5 off of 22 and then just move on to here subtract 4 off of 22 move on to 11 and so on and you don't have to store what the sum would be here and then what the sum would be here um if you tried to do it and say like a breath for search method so to do this recursively i think the best way to think about it is to just pretend like all you have to deal with is the root so to start if the root value or if our root node was null that would be a reason to return false so if root is equal to null pointer we'll return false um and then in the situation where the root has the value equal to our target sum that's when we would return true and again we're just not worrying about any like children nodes yet so um if our root value is equal to target sum then we would return true uh but we're actually going to have to again check to make sure that if this is the case um it's also a leaf node so we'll have to do and root left is null pointer and same thing on the right side so if this is a leaf node and we've reached our target sum then we can return true and if neither of those are the case that means there are children nodes that need to be checked um and they need to be checked for the target sum but minus the current value that we're on so we can declare a new variable i'll call it new target and it's just going to be the target sum minus our current value at root okay so then with this new variable we can call this function recursively um so we're just going to call has haspathsome on root left and with new target so this is going to check now the child node so say we started at 5 it would go down to 4 and check the same conditions for 4 with our new target which is the target sum with the first value subtracted off of it and then we're also going to want to check the other side the right side it'll just be the same exact thing and we're using an or here because if either side has this condition to be true then we'll return true and that should be it for this function so i'll submit this to make sure it works and it does so for the complexity of this algorithm for time we could be checking up to every node in the tree so we can just say that this is o of n where um n would be the number of nodes in the tree that we're given and then for space complexity um it's also gonna be actually we'll say this is o m or how about o h um because even though we are not storing any complicated data structures we still have to store the call stack since we're calling this function from within itself and that call stack is going to be like it could be up to the height of the tree so the height will note as h for the space complexity and that should be it so thank you guys for watching and i hope this was helpful
|
Path Sum
|
path-sum
|
Given the `root` of a binary tree and an integer `targetSum`, return `true` if the tree has a **root-to-leaf** path such that adding up all the values along the path equals `targetSum`.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,null,1\], targetSum = 22
**Output:** true
**Explanation:** The root-to-leaf path with the target sum is shown.
**Example 2:**
**Input:** root = \[1,2,3\], targetSum = 5
**Output:** false
**Explanation:** There two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.
**Example 3:**
**Input:** root = \[\], targetSum = 0
**Output:** false
**Explanation:** Since the tree is empty, there are no root-to-leaf paths.
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5000]`.
* `-1000 <= Node.val <= 1000`
* `-1000 <= targetSum <= 1000`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
113,124,129,437,666
|
1,663 |
hey guys what's up this is steve today let's go through legal problem 1663 smallest string with the given numeric value let's take a look the numeric value of a lowercase character is defined as this position one indexed so it's starting from one instead of zero in the alphabet which makes sense because it's in the alphabet so one up to 26 all of the 26 lowercase english letters so the numeric value of a is one the numeric value of b is two of 3 fc is 3 and so on right the numeric value of the string consisting of lower case characters is defined as the sum of its character's numeric values for example the numeric value of the string abe is equal to one is two one is a right two is b five is e a b c d e is five right so one plus two plus five is eight so that is why the numeric value of this string abe is eight it's just a sum of all of its characters corresponding values add up right so you are given two integers n and k return the lexical graphically smallest string with length equal to n and numeric value equal to k it's kind of confusing you understand let's take a look at the example n equals to 3 k equals to k and the output is a y this is unique it's guaranteed there is only one unique distinctive value answer to the given problem the numeric value of the string is 1 plus 25 is 26 27 that is matches k is 27 that is what k denotes for and it's the smallest stream with such a value and length equal to three so this is what the n stands for the length of the output right it's three it has three characters in this given output all right this is what it means it cannot be anything like abc will abc working no abc adds up to what one plus two plus three that adds up to six so k is 26 in this case that means abc is not a valid answer although it's lexical graphically lexicographic is smaller than aay but it's not a no abc is not lexical graphically smaller but aaa is lexicographic smarter but aaa the numeric value of the string a is only three right a plus um one plus one is only three but the k here is 27 so a is not correct only a y is correct that is because the numeric value adds up to 27 which is k that is what the problem is asking us for let's take a look at the second and the second example which is 5 and 73. so the lexicographic smallest string with the length of 5 is aasz it is this one okay i hope it makes sense it has a total length of 5 and all of these characters the add up to 73 and this is the smallest lexical graphic the smallest why well just to put the smallest letters first so lexicography smaller here is a kind of small um quick definition of explanation know that a string x is lexical graphically smaller than string y if x comes before y in dictionary order that is that means a comes before b comes before c right so a is lexical graph is smaller than b that's what it means that is either x is a prefix of y or if i is in the first position such that x i not equal to y i then x i comes before y i in alphabetical order okay so you see here we got all of these five characters and it's sorted it's solid right because this is guaranteed to give us the lexicographically small smallest what if you put zz as a if you put zzz first a in the last that's going to give us a much less graphically larger string right so you can see every single character in this given string is sorted alphabetically that's going to guarantee to give us the smallest lexical graphically so back to this problem we know n is the length of the stream so let's talk about now let's talk about how we can approach this problem so n we know is going to be the length of the entire string of course we're going to use a stream builder to map to find all of the proper characters that we can piece together and find the lexicographic the smallest string to return but how do we get there the way that things the way the idea that occurred to me is pretty natural which is that we can just think of one extreme case which is kind of econo case which is n equals to 10 and k equals 10 to 10 as well that means we need to find well that's kind of not a super straightforward example of see n equals 2 5 and k equals to 5 as well so let's think one extreme case which is this is going to the smaller lexical graphic the smallest or possibly the unique only answer is a this is the lexical graphic smallest right so what if the n is still 5 but k becomes 6. what is let's just in induce one step at a time so then it becomes easier to understand if k changes from five to six right in this case what's the lexicographic the smallest string if k is five we know this one is the lexicographic the smallest right so if k is increa incremented by one what would this be it would be a b right and we would put b in the last we are not going to put b in here or we are not going to put b in here this neither of these two last strings are not the lexicographic smallest right because we need to solve every single character in the given string alphabetically that's going to give us the lexicographic smartest so back to this extreme example we know if k is six in this case then this one is the lexical roughly smallest okay let's just increase this one to seven then this one becomes c if this one is eight this one becomes d right so what if this k is larger than 26 or 30 something that means this one the last one is guaranteed to be z and then this one might be changed into b or f or something else right if this one is greater than say 26 or 30 right so this is the kind of the gotcha moment right how we can approach this problem is basically we can first we want to find if this k is greater than n if it is smaller than if it is if it equals to n right k equals to n and then we'll just append every single character as a into the string and just return that's it if it's greater if this k is greater than n we'll just find the possible or just as well we'll try to form as many z as many later as many larger characters as possible and then we append them to the end right of course we um while we do this we'll just append everything in the beginning and in the end we'll just do a stringbuilder.reverse.2stream that's it stringbuilder.reverse.2stream that's it stringbuilder.reverse.2stream that's it so what tried the idea is to try to form as many larger characters as possible if it's necessary and then we just keep appending and then in the end we do a reverse that's it that's the idea i hope it makes sense now let's put the idea into the actual code first we'll have a stream builder stream oops next i'll have a balance which is the one that we care about because we'll start from the end which is going to be the beginning in the code right so while balance is greater than zero that means we need to we still need to for form new characters we're trying to find new characters to match up to add up to this total k right so as long as balance remember a equals to one right so in the numeric value of the lowercase english letters is a equals to one so we want to make sure that as long as balance is greater than 25 why 25 because we reserve one for the lowercase letter a right as long as if balance is greater than 25 which is to keep appending we know one plus 25 is 26 mapped to the letter z so that we can safely append z to the string builder right so we'll decrement this balance by 25 and then append a z to this and also we'll decrement n because n is just a number that means we have formed one character right we append one z to the stream builder and n is the total length of the target stream that we're trying to form that means we have formula one else that means balance is already lower less than 25 that means we cannot form we don't need to form a z and we cannot form a z anymore we can find any characters that is less than z because this is the last character that is not going to be an a if there is any right for the rest it's all going to be a else will just form a string char a plus balance so this is the way to do it in java so we can use a character plus an integer and then do a chart conversion to convert it into a chart and then we'll just append this is remember this is a chart and we are appending and a string so i'll just attach an empty screen to this so that it can this function this api own through a compile error and then we're also n minus one and so at this point we have found all of the letters that are none a so while at this point we can do if n is greater than zero all that we can do is well all that we need to do is we need to keep appending a to this yeah it can attach characters so i don't think this is needed and then we'll just keep decrementing n so in after this one loop is finished remember we need to break up because at this point we don't need to check balance anymore right and then in the end we'll just return string reverse to string all right this is the entire idea now let me hit run code to see if there's any compile error hopefully not all right there's none now let me hit submit yeah accept it looks cool seven and seventy eight percent not super impressive let's give it one more shot seven one no seven time complexity isn't very impressive let's see ah not super impressive yeah anyway but this is the idea of this problem as soon as we figure out that we need to form as many larger characters as possible and as necessary then we'll just attach it after that we'll just find all of the oil just to attach we'll just append all of the a's lowercase a's to this and then do a reverse dot to stream that's it hopefully this video helps people understand this problem if it does please do me a favor and hit the like button that's going to help me a lot i really appreciate it and don't forget to subscribe to my channel as i have accumulated quite a lot of different videos to talk about data structures algorithm bfs dfs you name it all cloud computing amazon web servers is how you can prepare and pass aws certification exams videos like that feel free to check them out hopefully i'll just see you guys in a few short seconds in my other videos thank you very much for watching i'll see you guys in the next one
|
Smallest String With A Given Numeric Value
|
detect-cycles-in-2d-grid
|
The **numeric value** of a **lowercase character** is defined as its position `(1-indexed)` in the alphabet, so the numeric value of `a` is `1`, the numeric value of `b` is `2`, the numeric value of `c` is `3`, and so on.
The **numeric value** of a **string** consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string `"abe "` is equal to `1 + 2 + 5 = 8`.
You are given two integers `n` and `k`. Return _the **lexicographically smallest string** with **length** equal to `n` and **numeric value** equal to `k`._
Note that a string `x` is lexicographically smaller than string `y` if `x` comes before `y` in dictionary order, that is, either `x` is a prefix of `y`, or if `i` is the first position such that `x[i] != y[i]`, then `x[i]` comes before `y[i]` in alphabetic order.
**Example 1:**
**Input:** n = 3, k = 27
**Output:** "aay "
**Explanation:** The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3.
**Example 2:**
**Input:** n = 5, k = 73
**Output:** "aaszz "
**Constraints:**
* `1 <= n <= 105`
* `n <= k <= 26 * n`
|
Keep track of the parent (previous position) to avoid considering an invalid path. Use DFS or BFS and keep track of visited cells to see if there is a cycle.
|
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
|
Medium
| null |
1,187 |
hey everybody this is larry this is try two for trying to get a problem we haven't done before uh earlier we did get an sql problem and i did solve it but you know obviously it's a little bit awkward oh okay so let's look at this one 1187 make away strictly increasing hit the like button hit the subscriber and join me on discord let me know what you think about this problem so let's see so given two arrays i haven't done this one right yeah i don't think so but it feels like it's reads like something i should have done before but or could have done before but i don't remember anyway okay so yeah to erase return the minimum number of operations needed to what's an operation you could choose i and j so basically you could steal an i and a j can we do a swap or is this oh no okay so it's not a swap it is just uh that you can do it okay um okay they're both end is 2000 i mean this my first intuition is just going to be dp just because these things uh with decisions maybe we can figure out a way to be um you know maybe we could figure out a way to just yeah um maybe you know maybe we could figure a way to uh be exhaustive search right so that's why i was thinking about dynamic programming um and you go use the 2000 kind of confirms that for me a little bit or at least as a possibility not that it is dynamic programming we have to kind of see the second thing is that all the elements are attend to the nine meaning that well you know you can't do anything funky like linear search or something like this um that said you it doesn't stop you from a linear sorting sorry i don't know if i said linear search i don't remember but that said because n is the only he goes to 2000 it doesn't stop you from uh doing um you know re-indexing or re-normalization you know re-indexing or re-normalization you know re-indexing or re-normalization uh basically a coordinate compression type thing uh to kind of get like the relatively ranked and stuff one thing i would say is that the order of r2 doesn't actually matter right because you don't have to give response or anything like this um so the first thing i'm going to do is sort r2 and why do i want to sort it is because now yeah now it allows me to maybe do either it just like it's just um it gives me a better structure to work with right because now i can sort uh or already sorted i could binary search on it i can you know do a walk walking up uh there's more greedy race and so forth um and because now um you can almost think about it as an implicit thing i don't know if it's needed for this problem but you can say that you know um because it's sorted you can also instead of keeping track of which element was is used individually you can now say all the elements smaller than x is used right so now you can represent order used things with one index roughly speaking i mean i don't know if i explained that right okay uh beyond that let's see right so then here i'm trying to think um i'm uh so i think i have an idea on how to do it but i'm also just trying to think whether it makes sense it's like yeah this is definitely one just to be clear you know you're watching this live uh i don't know the answer off my head so uh so in those cases i'm not in explanation mode quite yet but i'm still trying i'm in the working out mode for now so the thing that i'm thinking about in my head is that um the thing that i'm thinking in my head is just that it is n squared or not n squared i guess it's just let's say this is n and this is m there's n times m times two or something like that and i was just trying to think whether you know like i can do a top down or bottoms up or whatever so um i'm gonna try to do this top down and then we will see if it's fast enough to be honest i do have i'm a little bit skeptical that it is going to be too slow i mean i think the n square complexity will be fast enough but especially in python there are a lot of um there's just a lot of overhead with recursion and function cores and stuff like this was always gonna say sorry it's later in the damn a little bit tired so my apologies if uh oh i also hope that you watch it on like maybe a little bit faster like 1.5 x or maybe a little bit faster like 1.5 x or maybe a little bit faster like 1.5 x or something like that um okay so basically there's going to be two things right that we can do um how do i say this in a good way let me think about this right so what are my states i mean i'm trying to think about the cleanest way to write the states um so the naive state is just you know index one index two where index one is the um trying to find a number to put in r one right uh index one so that part if we do it in a naive way it's gonna add another o of n so that's why i'm trying to think about not but maybe i don't know how to do this because i guess there are two scenarios that i was thinking about uh oh and index two is just you know uh all numbers up to index two is used or something um and the idea is that the only two cases one is that the last number or the r sub or one of index is used from a uh a1 or it is used from a2 right meaning that um let's say we have something like yeah we have someone like this um and we're on index site two um then we wanna see you know um and all one is just say i don't doesn't really matter but um that we replace it with this number instead right or something like that um yeah uh then you know we replace with that then the next number and stuff like that we have to check with that number i think that's the problem okay and i think i have an idea let's kind of play around with this uh by exploring the code i might be way wrong on this though so definitely watch it on a faster speed if you're kind of you know uh i don't know but let's think about this so i'm going to have you know a couple functions but let's just say make increase so this is index one index two so um this is just a base case of what we had here actually right um okay the problem is also okay i mean i'll just set up infinity real quick okay the last number used is r1 of index one minus one so that's what this assumption is for this function um i know that's not order assumptions but we'll go over that for now right so yeah okay if index one is equal to n then we can return zero so we said n is equal to length of r1 m is equal to length r2 let's just call it l1 l2 actually just to keep it consistent or not consistent but you know easier to remember which ones which okay otherwise best is equal to infinity and it will return best so now the last number is uh so we let's get the previous number if index one is equal to zero then previous number is equal to negative infinity else um or maybe like write something like this instead it's greater than minus one is greater than zero then this is equal to r one of index one minus one okay so then now we have a choice right we if r1 of index one is greater than previous then we're already okay i mean we may not make this move but it is a possible move that we make right which is that we just go to the next number right um and then here we can the other move that we can do is let's consider oops the other one um so this is basically saying um let's use another number from r1 right and then we go to the next index here what this is saying is we don't want to use r2 of index 2 but we want to consider a bigger number right so the idea here and i don't think i made this explicit yet is um i kind of hinted at it but i don't ever made it express it is that for this r2 if you use a number and all the numbers it is and smaller cannot be used in the future because now you're getting bigger right so that's why we're able to do this move we're going to come to a bigger number um so yeah so this is basically it's that if we want to get use a bigger number i don't know if this is necessary but it is exhaustive ish but it also it just causes all one so why not right and now we want to use um uh r2 of index 2 if r2 of index 2 is greater than previous then we can use it as well right but this is a different one right y we'll see we'll show you my thingy is a little bit terrible but uh wait oh um previous two index two is used okay uh and this is let me also add some if statement here to make sure we don't go out of bounds typing index two plus uh if index is less than l2 then we could do this otherwise there's no more number to consider anyway um i guess i can move this into that if segment but it's fine right um yeah and now i have uh maybe this is uh using max increase from r from two i don't know naming is tough but with me for a second so what is this function that i'm trying to do here right is that this is the same idea but for index one and index two but the last number you used is r sub 2 of index 2 minus 1. yeah so that's basically why we do it plus 1 because we used this number and then that would give us the answer okay so then now this is index one index two oh and this is this plus one that's the move that i forgot or one just in general just forgot because now this costs one move right uh yeah um okay so then if index one is equal to l1 we return to zero uh do we do anything about index two no i think we're okay so this is the same ish idea that we had before and then now yeah if index 2 now this should be this should always exist just by definition i think yeah so previous should be r2 of index 2 minus one as we talked about if r1 of index one is greater than previous then we can you know just yeah same as before we use it from another one so let's just do no comment increase in text one plus one index two uh if and i know that you don't need to separate out into two function but i just wanted to make it clear for learning purposes uh yeah so out too then actually i guess that's really it i think in the sense that i think we can actually copy and paste this because i think this is the same uh so maybe we can reduce this a little bit uh and maybe we'll talk about how to reduce this in a little bit but yeah and then at the end we just return make increase oh this at this point may not be right there is this one maybe that's right maybe that's fine actually no this one's not fine because now it changes the assumption even though that's the last number and we haven't replaced that number i think we can be i think the only part yeah i think we can do this instead okay uh from two um index one but then now this is a little bit awkward because it assumes that we replaced it with a bigger number but this is always going to be true so i think that's okay but i don't know that this is necessary but let me just comment it out for now so maybe it didn't have to say but uh okay so zero all right let's run it real quick i know that i don't i haven't memorized it yet i might not do the memorization explanation today but i mean this that seems right then right because i forgot to handle the infinity case but uh yeah all right i'm not gonna lie today i am very tired as you can see from my voice i am just going to do the lazy caching um this is fun tools dot cash it basically allowed me to do memorization uh way yeah based on this um let me just give it a submit to see if this works uh just as a yolo um i'm only worried about the timing so that's why i'm well maybe other stuff as well so let's give a quick submit to see this is just me being lazy on the submit so this could be wrong and it could be time limit exceeded but if it time limited it's more on the pi final lead code because if it time limits that means that the algorithm is right which i'm happy about but you know okay that's not the case though so we'll have to kind of look at the debugging here um this is going to be an annoying one to debug though dentist eight huh what if i do use this okay so i guess we oh i was thinking about this but i didn't have a case to test it the reason why um the reason why i needed something like this though i wasn't sure that like i thought maybe there's another way i could do it but the reason why i was thinking about it which is so one i know that sometimes when you watch these videos i'm always like oh i thought about this and you know and maybe everyone who you know pretends to be smart or whatever uh they're like oh i knew it all along of course i knew it all along right uh and you may think that about me and that's fine um but the reason why i am able to debug it so quickly is because i did think about it but i'm just i think to be honest i'm a little bit older than i used to be and i just i thought about it and then i forgot about it immediately but that's also why when i get the wrong answer and i'm you know i'm able to identify why that's the case and also uh i know the test case for which this is wrong you know i mean this is a case where it's wrong but the reason why this is wrong is also because in this input um they're duplicate numbers right so the so all r2 could be um let's say in an extreme case like one two three four five six seven um if we used one of the ones we get stuck is why um because then and we want to use the two next say for whatever reason let's say we have you know a hundred or one thousand uh nine and then like i don't know three four five six seven right um in this case you wanna change one and a two i think the answer is obvious but because of um because of the way that this is constructed you know i was stuck at the second one because the second one would never be bigger than the first one so that's why i got this wrong answer and also as soon as i uncommented it i it bugged it but i was i thought that just the way that i did it is a little bit inefficient and a little bit sketched that's why i didn't that's why i commented out but i kind of forgot about it as yolo submitted so whoops uh but i did think about it and that's at least i thought about i need i knew that i needed to take care of this case but then i just forgot about taking care of this case which is why i was sad i was like i should have known better because that's what i you know i was thinking about it okay so at least now we know that we're right except for that you know um let's take a look 20 of 21 okay um so we know that we're right or at least i mean technically anyway i mean i guess technically you could also be wrong in a later case but like a regular wa for a later case but at least we know that we're functioning right and we can you know do some optimizations here and you know to be honest this is n square uh you know we want to do the analysis this is going to be n squared time and square space uh and really should be fast enough but python is just or lead code python is always a little bit yucky and to be honest i'm a little bit um you know this isn't the most things um i also find that cash for multiple parameters is a little bit expensive so let's first of all let me maybe i shouldn't have been lazy but i just wanted to check the correctness more than that i want to check the timing um you know if i need to do it but so let's say we have uh yeah i was just looking at this and i think i could combine both of these functions into one function it's very similar but i think for learning purposes for your learning purposes so maybe i need to learn a little bit too uh i'm just gonna do it this way and i know that it's very tempting to put in a dictionary um but one is if you have a tle the dictionary is just on a tuple or something like this it's just slow um on tuples in general um it is what it is after a certain point so you actually want a two-dimensional so you actually want a two-dimensional so you actually want a two-dimensional array for that reason so yeah because this can be l2 so okay and you know if you've been a watcher of this channel and if you're not you should hit the subscribe button um you know this is a standard way that i write this for you know it's pretty straightforward it has cash up to inputs then we return the cash right otherwise you know we do the actual work and then we cache it if this is still too slow i would just write it tops down i think that should be good i mean you know like what we would say i don't know i mean right now we're optimizing uh right now we're optimizing um oh there's a typo here mostly because we have two of these uh yeah we're optimizing some constant uh constants so like you know um yeah we'll see if this is that much faster i guess i could actually let's see yeah so like this is still going to be n squared and it doesn't really change it makes it faster for sure but how much faster i you don't know so yeah uh like it may be one or two x faster or something right and you know is that fast enough to submit well at least now we have a test case and it takes seven seconds to run um but there are other inputs right so that's why this is you know a little bit sad um i don't know how maybe i should have had uh oh i forgot to take out the cache so that's why it is you know now it's doing both those things so at least in that one let's run it again real quick see if that's faster it should be faster well maybe it should be slightly faster but um i don't know if it's just fast enough all right let's give it yolo i if i wasn't lazy i would have did a comparison to see how much faster we are from the cash version um but i'm okay with just like eating a tru you know it's not really that serious uh okay still tre okay that's very sad but uh okay so then now we can write it bottoms up right yeah uh i think the tricky thing about the way that we i did bottoms up is that i kind of did this one in a funky way but otherwise i think this is fine um yeah i think we just have to do a bottoms up so uh that's kind of and we could i know that i could combine them with again one function but i'm still gonna let's just do two of these so that it's a little bit fun to do the dynamic programming all right i just yeah uh um well let's go dp because i'm lazy and let's just say this is zero right oh no we want this to be infinity and then we want the base case is you can write the base case in a little bit different cases for now for me i actually do struggle i mean because now we have to think either think backwards or whatever um in this case the problem is symmetric but you know for if you want to translate tops down to bottoms up um you know i want to keep it as fateful as possible so yeah so then now for index one in range of um from l1 yeah from is it from l1 yeah from well o and minus one two zero two in range uh i'm just double check um what i'm doing now is i'm looking at these to make sure that i you know i'm doing this in the right order i'm actually not quite certain which um actually not quite certain which oh i guess the other optimization i could do is get rid of the mints i forgot about that but i don't know if this is gonna be fast enough so i might as well get a little bit more practice on bottoms up um i'm also just thinking making sure that this is actually you know good enough um but of course you sharp eye people might notice that i actually need two of these and you're right okay the naming is terrible but it's terrible in a standard way so that makes it a little bit better maybe not but uh and one thing that we have to do is set up the base case and my base case here is actually l1 right so um uh index one is equal to l1 so dynamic set for index two in range of l2 minus one uh dp of l1 index two is equal to zero and dp2 of this as well okay and then now we just have to kind of copy this code really um we go and away we go um oh i guess previous is you go to array one of index one minus one uh and uh okay fine i have to do this like logic okay so best now is dp of index 1 index 2. i might have to get rid of those min statements too but uh we'll cross that butch when we get there i'm keeping it sorry friends if this is a little quiet i mean right now i'm just literally copying line for line and from this code so that's basically what i'm doing dp2 okay that's basically this code and then we also might as well just put in uh so this is for dp1 so we almost was doing some i think we have to do simultaneously actually otherwise the thing is not filled correctly so um yeah now doing the other one so previous two is going next to minus one right and then this is where uh f r two oops let's see and this is just all about being careful really and not making a typo but you can see that it's very easy to if you're not careful and for prom i know how it's uh you know figured out there's a lot of it's a lot of work to get it right okay if i could win this another way okay and then now it should be just tp000 i don't know that this is uh transcribed right and the algorithm at least the original one should be right but you know whether this is right is another story it's because it's easy to make mistakes i hope i don't and i hope that this is fast enough but huh okay so i got most of i mean it looks okay what am i missing right i'm getting a negative one on here so maybe i do have a typo because i am getting the big wow this is actually slow too so it's not even that much faster really wow huh it's still a faster way maybe it's just the min functions yeah this is actually slower than before to be honest and more incorrect i suppose but that part we can fix uh let's see i think this part is now this part's right yeah this part should be right let's see did i miss the case uh i mean the code should be the same i deleted it let's see and all these depend on the previous one this one's a little bit dubious actually now we do them in the right order so this should be okay unless i'm oh i see maybe oh yeah this should be out too that's why because we don't update it i mean that's one of the examples i don't know if this is the only thing and also we're still running into speed issues is it because of the six minutes okay well that's huh that was definitely an issue i mean and obviously you're gonna be slower because you have one more loop but now i think you have to set this one as well to set the base case when set the base case here so that's gonna be a little bit yikes there's the thing you can do is with um you could do space optimization stuff as well or is it wrong though let's try again maybe i think we're close but i mean i'm worried about the correctness more than the time that i'm gonna exceed it that's why i uh i guess i could remove someone into smaller cases okay so now we fixed it okay i just want because i thought most of the because i was looking at my conditionals and that looks okay but that's a little yikes man because the thing is if i did this in another language i'm relatively confident about it we have to get rid of the mints but a what the dubious thing to get rid of uh that's what i mean by lead code is sometimes you know not great and that we got i should keep it consistent uh no fine i didn't i did it this way earlier because we kind of you know i kind of do want to just explain the problem but i think i've explained it okay by coding it but you know right now we've spent about 20 minutes just optimizing um optimizing what we already know right so that's a little crappy or like you know it's not that interesting right uh i don't i'm not learning you're bored i don't even know what to say other than being sad about it i know that i didn't do the other half i just want to see if it makes a measurable difference um some of it is because mine is a function called python overhead and we're doing four million of them uh you know in a problem it's a lot it is faster but not so fast so i mean okay i guess it is what it is um i'm gonna submit this just so i have it on my submission i know that this is going to time out but uh and the reason why is i'm just going to do it in c plus just to get it done but yeah okay thanks i'm just thinking about it for a second but yeah i mean oh that's some weird windows up uh yeah i mean i think i'm just gonna come over to sleep plus there's no uh not trying to do anything so this is just so silly getting 10 dollars is actually good because you're you can only do 4 000 anyway or 2 000 i mean okay making sure my syntax mostly because i'm just it's been a while for python and stuff like for c plus and stuff i sometimes will we'll double check um i will double check that my you know that i got it correctly anymore roasting okay i mean sorry friends if you're watching this if you are watching me saying these exact words right now uh what am i doing uh yeah let me know what you think about the show westworld uh i actually just finished watching this season finale uh it's very intense let me know what you think and i'll give you some props in my head or something i don't know because this is like 40 minutes into a random problem so um okay i guess it just has to be negative one really so that's fine if this time so i'm gonna be very sad though by the way so i really hope it doesn't i think this part is copy and paste mostly kind of um yeah obviously not actually but just save me some typing i'm gonna get this wall that's fine i guess i should just copy this instead of going down okay um to okay i think this is okay i mean it's not okay yeah but i just want to make sure i don't have any typos or anything weird and see if this is fast enough 198 that's actually i mean look at this for this i mean i know they have to do more work but look at this that is so fast come on come uh on come on friends but yeah whenever you see hear me complain about you know just to give you a little bit of a comparison that went for eight seconds on uh that went for eight seconds on python so anytime you hear me complain about c plus well not c plus but like that i should have done in c plus this is why um actually this one but um what oh yeah this is kind of annoying because i don't know when i started it but oh geez i'm very lazy to look at this point that's right uh because this was about half an hour ago so i got oh no not this one but still this one i got it mostly right half an hour ago and i'm just oh my god larry i'm just gonna but yeah half an hour just trying to get the constants right so that's a little bit sad okay we do get one into some issues though so maybe i am wrong unsigned offset do they not tell you where it is do we overflow we shouldn't overflow we don't really do anything right i can't tell this is like a like do we look at the wrong thing and also how does this not like have an issue in python five that's the one thing about python that's a little bit scary is that i sometimes still get one uh i guess that makes sense because i do have index plus one here that's why the index plus two where am i going out of bounds is it just here all right let's see i don't think i over folded like one character so there's something weird typo about just then index one plus one right why is that an awkward thing or maybe it's this one oh well this is definitely why wasn't that an issue earlier oh because in the recursive function yeah it's a little bit different because in the recursive function you cannot get to the recursive function uh unless so yes okay so maybe i just do this i think that's fine because you can dp 2 may not have any right answers for index 2 is equal to 0 because we assume that index 2 minus 1 is a thing and also i forget what language i'm in but only in a weird way okay so it still takes quite a bit of time but we'll see let's see but 10 times faster than the python version and also some ac on the first go i don't know if i could have done it recursively maybe i still need to make this optimization but as you can see it is just ridiculous right it took me 10 minutes to convert the code um maybe that's a little bit slow but nonetheless this is also this one the way that i did it has a lot of typing i guess uh and just typing index one and two is a little bad um yeah so the complexity as you can see here um let me scroll down a little bit so you can see all my code um is just that yeah the space and the time should be pretty straightforward right we just have all of one operations on youtube in everything inside and on the outside it's l1 times l2 or n times m same here um there's a sorting of course so technically that the time is going to be o of n times m plus m like m for so you have a small n or something and space is going to be o of n times m so yeah uh that's pretty much all i have for this one let me know what you think it's very tiring because you know i basically lost literally half an hour um you know just optimizing it because lead code is a little bit silly um so yeah um that's what i have uh stay good stay healthy to good mental health i'll see y'all later and take care bye i'm really tired i don't know uh if you do have any questions i know that i cut this a little bit short but if you do have questions come to the discord leave a comment on the channel uh yeah you are seeing this live so but come hang out we'll ask questions uh i hope you did it today this one was annoying s f so i'll see you later uh anyway like i was saying um i don't even know anymore to good health to good mental health i'll see you later and take care bye
|
Make Array Strictly Increasing
|
print-foobar-alternately
|
Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing.
In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`.
If there is no way to make `arr1` strictly increasing, return `-1`.
**Example 1:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,3,2,4\]
**Output:** 1
**Explanation:** Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`.
**Example 2:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[4,3,1\]
**Output:** 2
**Explanation:** Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`.
**Example 3:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,6,3,3\]
**Output:** -1
**Explanation:** You can't make `arr1` strictly increasing.
**Constraints:**
* `1 <= arr1.length, arr2.length <= 2000`
* `0 <= arr1[i], arr2[i] <= 10^9`
| null |
Concurrency
|
Medium
|
1203,1216
|
1,376 |
Hello Hi Friends Welcome Back To Yaar Go Into Solitude Problem 3176 Time Needed To Inform All Employees Were Willing To Android Discuss Problem And Solution Details Of Joint Commissioner My Channel Is Focus To Aa People Were Preparing For Coding Interviews And Job Interviews And All My Channel Late and Over 200 Should Examples and Skin Big Companies Lite Amazon Apple Google Facebook Microsoft Yahoo and Manya Rate Companies and Misdeeds Consist of Different Varieties of Problems Dating and Dynamic Programming Languages Related Dynamic Programming Languages Related Dynamic Programming Languages Related Problems Related Interview Questions Graph Problems of Binary Search Tree Joinery Search Related Problems and Logical 20 Problems Sophia Preparing For Job Interviews And Code Interview Dhan Please subscribe The Channel This Channel Can Definitely Help You In Your Job Interview Preparation For Please Subscribe Sholay Problem Statement For The Time Needed To Inform All Employees A Company Has Given Employees With Unique ID For each employee from zero to minus one the head of the company is the one with head ID inch employee is the dream direct manager given in the manager and manager I is the direct manager of the employer manager head is equal to minus one also this gallant What Subordination Relationships Have to Restructure The head of the company wants to inform all the company employees about any urgent piece of news only he will inform him as directed by the subordinates and will inform their subordinates and take off until all the employees know about urgent news Responsibilities Employee Needs in form time or minutes to inform all of his direct subordinates after inform time minutes all of his direct subordinates can stop spreading news the return the number of minutes needed to inform all of the information about the urgent need urgent news so this is the problem specifically for Example If you look at this example to here days have given that so common toot is the head of all temple is right and left his subordinates for example 0 4 5 4 on subordinates of to and the informed time the toot axis one hair rates developed 0.01 And to shirdi say the 0.01 And to shirdi say the 0.01 And to shirdi say the in funtime details required for employee to basically write that paid news tweet subordinates to as you can see all to all his subordinates say time required will be one minute rights have 2.1 here right because one minute rights have 2.1 here right because one minute rights have 2.1 here right because all the subordinate employees where 0134 5,000 Oil subordinate employees where 0134 5,000 Oil subordinate employees where 0134 5,000 Oil Subordinates Off To And Protects One Minute To Spread News His Subordinates Work Have Written One Shot Common Aspects Certificate Example The Tiger Create A Career For Your Past So It Can Explain New Arm Easily About You Know Water Problem And How To Solve The Problem So Are You Can See I Don't Tree Actually So This Is Manager And Inform Time Is Given To During Total Seventeen Employers Air Tight T-Shirt Total Seventeen Swadeshi Tight T-Shirt Total Seventeen Swadeshi Tight T-Shirt Total Seventeen Swadeshi Starting With Zero West Indies And 1000 Jawans This Is To End Destroys 6.the Jawans This Is To End Destroys 6.the Jawans This Is To End Destroys 6.the Largest 116 Basically And inform time is the time taken to inform 2all the subordinates by time progresses protects one time din one takes one time to take one time like this physically and agro solvent sesame 16-8-2016 so aa hai to agro solvent sesame 16-8-2016 so aa hai to agro solvent sesame 16-8-2016 so aa hai to this is the name of Input is given to was right member input so is due attri so you can see from the tree for example if you want to know how much time it will take to reader news2 employee seven rates for example you want to reduce to employee 7 the news bean Started Spreading from 10 Top 10 380 IND 2181 Minutes Day Will Inform and Subordinate Time It Will Take To Visit In The Employers In The Company Will Know About The News Red Suit Which Means That You Have To Find To Maximum Fine Basic Candidate Will Be Required To 9 Spread News Raat Soi Hui 18 Dec 10 A Height Software Let's See A File If You Look At This Point Zero To Strengthen 126 203 241 Is One More Swedish 3 And 4265 More Workshop Three Plus Five Wishes For This The Longest Time Date When Required For New Stories 258 Temple Witch Is Eight Minute Slide Show This Is The Answer Of this problem is basically sixty minutes is the answer side how we are going to solve this problem but some places of this creator graph from this manager and inform times for this is a graph data will create right graph using his map and this time will have All activities are listed for example 1007 Ordinance one and two so you can see Dr. has subordinates least one and two right similar issues Six has subordinate 3148 So you can see year 6 Subordinate list thirteen fourteen and routine has subordinate list 15618 For B.Ed 1516 Subordinate Is A 15618 For B.Ed 1516 Subordinate Is A 15618 For B.Ed 1516 Subordinate Is A First Will Create A Graph Using His Map By Using This Manager And Inform Time In Food Additive 212 Has Raised And In What We Will Do By Clear Graphics Created Swinuse Edifice Right To Understand What Is The Maximum Time Will Be Required To Spread The News White Vinegar Dad Starting From Root And Will Give Person Track Of Maximum One Variable Titles Remaining Time Needed And Something Like It Say Time Is The Very Bright And What This Is The Maximum Times For Example Plate Started From FS14 And Defense Works Is It Will The Recessive Gold Call Girls Like This Rights Of Cost Vansh 2380 Store Se Ki And In 087 Tax One Minute Right Tourists And Tenth Like Required Total Criminal Tribes University 3 Minutes Will Be Required By Seven Toe Is The News Liability Tax Secretary Dr. Harisingh Gaur Like This Right Will Go To 8 And Went From 8 To Welcome Back To Like A 40 Like This Is Gold Basically 830 Powder Equation Works So Aam Ultimately Hui Will Find Maximum Time Which Is Required To Reach Is Not 1516 Special Minute Side APN Overall Other This Lymph Nodes Like Share 80 11-12-13 Night For All Off This Mode Time 11-12-13 Night For All Off This Mode Time 11-12-13 Night For All Off This Mode Time Will Be Recorded 3 Minutes As You Can See It In 500 Index Remains Closed For Example 0235 211 Ki In One Mins Total 10 Minutes Required But For Fifteen It's Like Ka 1238 Plus 528 Minutes Pretends 15068 Minutes Will Be Written Exam Maximum Time Date Will Be Required Shoulder Is The Cockroach Soft Lips Mujassam Rice B4 Wear Look At The Solution Courts Will Create Graph Using Manager And Inform Time Soe Graph Will Contain Every Life Every manager and intimate subordinates as you can see ride start zero and immediate subordinates one and two so you can see 012 fennel one image and subordinates from this 31405 visit subordinates three and 400 SIM like this dhokar office create and after that you will call deficit end Will keep track of the maximum time required to speed the news to important 9828 You think will keep track of them during and implementation Solid Unicode name is first is creator time not Doria but because this is how you want to trap track the maximum time in The deep fried autonomous creative variable in this award function reddy 120 penis given total number of employees in the dried is the guide me fruit basically try to you can start the graph and manager and inform time as given so first is created for graft variable share and At the same time the point is an amazing to see in teacher right explain in this example 100 entries where is the employee ID and disease list is subordinates images and subordinate set so work will read through all the employees share0 to and you will check will create dagra Flight So While Creating Na Graph Manager Is I Request To Minus One Rise In This Room Service Continue You Will Not Proceed Pickup The Quid Must If Wife Will Just Park Your Life In Ready Is The Manager Of Already Is When Link Please Write Gifts Not Having Only a small kid will create a brand new liquid only earliest years and villages and till current like the employee ID employee as you can see into the subordinate list and will just user graph dot right so this is the manager right end List Will Have a Subordinate Staff and Manager and It's Already You've Created 40 Days Hui Winters Get from the Map and Uses and the Current Employers Current Subordinate Clear Web 100 Will Fight Back into the Graph The Leaves Basically Healthy Baby ₹15 Creating This Basically Healthy Baby ₹15 Creating This Basically Healthy Baby ₹15 Creating This Graph Thursday 100g E Agri Employability ID And Its Demerits Award In It's All The Employee ID And Subordinate You Can See Air Tight Edition Industry Hair Soft 2012 345 600 2345 600 All Will Have Subordinates This Original Note Service Note Comment Graphics Did Not Have Any Ordinary Friend For Example 600 will not come into the graphic Co divine does not have any subordinate leaves basically a Deepak Verma Manager Shopping Employees basically so lets what you have done in this for you and you have to calculate time this is the recursive function to perform their differences over graph With Father He Died In Which Is The Root And Intellectual Graph Dedicated The Inform Time And Zero Point Is A Superhero Is The Time Header Starting 1200 Its Volunteers And Has Its Difficult Times Recessive Function 100 December Bech Ke So Whenever Hui Hai V id Is Equal To Zero Day You Will Return Ride So Thisawar Record Shiv's Is And Other Wise Wilfred Our Current Time Plus The Informer Led So Let Me Explain This What They Are Doing Share 100 Is Just Yaaron Free Mode Scholars Like And Use This Pressure Is August So What They Are Doing Clear Is It Se fir Clear Right Wear Earrings Differences And Were Trying To Calculate The Benefit Means Is Will Have Already Needed This Time Like Khar Tutu Min Side 100 Grams Fennel From Its Name From 327 They Are Going Right Some Will Add This One Plus To basically so let's move to yr do in basic rights or vikas tourist on this not be tolerated to minutes and fare from 327 add one more night riders one plus two is totally free minute subscribe to restore 730 what is like you have implemented in doing so Yeh Tweet Actor Karan Time Which To Write To In This Case Two Is That Current Time And Press The Time It Required To Reach Two From Three To Which One Is That Is It Is One Plus Two Equal To Three Quote This Logic 10 End In Hui First Will Get The This Is The Never Sleeps At Night From Graph Hui The Giver Hai LTD And You Will Get The Missions Least Two Equal For Example For 0.125 Least Two Equal For Example For 0.125 Least Two Equal For Example For 0.125 With Three Four Pride And Would Give Weird Look Leo Andhero Din You Will Have To Check For one to write words were looking at one day you will have to check for free full battle for the defense website for every month you will have to check and subordinate to right and you have to calculate time dependent on the spot where you are doing so will get All his subordinates will calculate the size of how much salary for death are now you will read through all his subordinates list right and you will treat you differently Shivli kaun to calculate time gear wife my for the subordinates you can see time date I miss you Man Passing A Subordinate Clear Again And Again Graph Inform 522 A View Of Passing Team For Example When U Were Passing It For 752 Hair Oil Ready To The Function And Two Plus One Will Calculate 12427 Basically It Today This What They Are Doing And Whenever You Will Find the time taking and taken by the current mode switch more than and find will keep modified time date fixed when you want you can capture the maximum time date is required right today news basically it's always you can see you have to find number of need to inform All Employees Means Maximum Time Required By Name Apply To Receive New Basically So Let's Move To Yar Do In Shares Sour This Time Different Function Dance Right Sophisticated Graph Vyapar Singh Ne Fear And Widening Deficits Vitake The Current Time The Are Doing Near Tried Every Scientist Crush Ki Who Calculate Time Passed The Current Time Years It And You Will Update The Current Notes Time Basically Craft For Example When You Hear That Calling The Common Receipt Function To Calculate Time Required For 7 Days They Already Know The Time Required Tourist Places To Subjects For Two Wheeler to will send into this function light years are you met and you will and disciple 152 plus one because one request from three to 7 swift welcome two plus one edit 1238 is equal to two three for that is what they are doing a global updated from different So Ahead Inventory Control Goldberg And Want To Calculate For 80 Gyan Hui Hai That Two Plus One Will Begin R Will go 215 hair right tidy plus five dried sector-22 b id admission this supreme plus sector-22 b id admission this supreme plus sector-22 b id admission this supreme plus five physical work to get hair right and similarly from 4216 again three plus five is eight correct for both a text minutes shoulder this what we do the year and will Keep track of Vinod this year's rights will always keep track of the maximum time What is needed by anyone Don't know dear right 100 grams and the face will just untimely death Vikas World Cup shirt Maximum time required to reach the newspaper In this it is basically clear so One more time will just go through the summary so I create and craft which is the employment and its immediate subordinates basically solvent proof and 1000 populated our graph written by using the given manager and inform time so manager and tonk sorry for the population right choice Manager winters who is the i who rented images and subordinate white and where spotted graph year and after that is call our recursive calculate time function fasting drought of the graph will ask 2012 poison hair pack and faster fall created and inform time here and in initially 150 Difficult Swar Time Will Start From Zero Minute And In The Villages Basically Different From The Root Show Like This 110 3080 Grown From Awal But It Is Instant 90 Difficult For This Is The Function Of You Have Implemented Difficult Will Give The Opposite Word From Graph And Subscribe To can withdraw all the adjustment in this year and they will request you all equal calculate time function for each employee here right and now you will calculate the maximum time which is required and will return and answer so is created life but example date with justice K steering 2017 employers and 0is avatar turning point right and decision of the team to junior manager and inform them while passing the answer sheet come S8 so let's go ahead in this code format can see you are cutting correct answer and share white to common and Code Working Fine Services Take All The Examples And You Have Given This Rs 10,000 On The Example Given This Rs 10,000 On The Example Given This Rs 10,000 On The Example And Have One's Will Run Away Abroad 5004 Second It Is Made 1600 Correct Servi Contestants Shyam Subscribe Saugata Its Only Cigarette Submit And Code 200 Gr Cold Not Accepted By List 22% better than ideal in performance and 22% better than ideal in performance and 22% better than ideal in performance and 2017 memory usage show which is the pretty good show this is question solve time needed to inform all in this problem with the help of diagram of Hui career graph using his life and you used this face please like Kar Shivling Andar Graph With Starting From The Roop 31217 Doing Please The Maximum Time Required To Reach The News To In Employment News In One Variable Tight If You Have Already Check My Play List On My Channel For Lips Code And Solutions Please Check 9 Meter 120 Solved Problems Door of Mining Companies Like Amazon Apple Microsoft Google Facebook Yahoo and Manya Dar Companies Friends Problems Consist of Variety of Problems and Dynamic Programming Gram Problems Binary Search Tree Problems in Streaming Links Related Interview Questions Suthara The Will Give You Will Be Good To New Recording Interview Preparation And For Your Telephonic Interview Preparation There Is Another Place Called As Of Java Interview Dry And Gokhru Years Of Law To Frequently As Californian Interview Questions For Java And How To Answer Questions Explained Here If You Like This Video And If You Find You Solution Helpful Please Like And Subscribe And Your Subscription Is Really Important Yasmin Ko That's The Video Can Reach To More People Who Are Preparing For Coding Interviews And Java Interview Cold-Cough Voice Videos And Interview Cold-Cough Voice Videos And Interview Cold-Cough Voice Videos And Problems And You Can Get Her During Your Job Interview Preparation Show Aam Please Subscribe To My Channel And Thanks For Watching The Video.
|
Time Needed to Inform All Employees
|
time-needed-to-inform-all-employees
|
A company has `n` employees with a unique ID for each employee from `0` to `n - 1`. The head of the company is the one with `headID`.
Each employee has one direct manager given in the `manager` array where `manager[i]` is the direct manager of the `i-th` employee, `manager[headID] = -1`. Also, it is guaranteed that the subordination relationships have a tree structure.
The head of the company wants to inform all the company employees of an urgent piece of news. He will inform his direct subordinates, and they will inform their subordinates, and so on until all employees know about the urgent news.
The `i-th` employee needs `informTime[i]` minutes to inform all of his direct subordinates (i.e., After informTime\[i\] minutes, all his direct subordinates can start spreading the news).
Return _the number of minutes_ needed to inform all the employees about the urgent news.
**Example 1:**
**Input:** n = 1, headID = 0, manager = \[-1\], informTime = \[0\]
**Output:** 0
**Explanation:** The head of the company is the only employee in the company.
**Example 2:**
**Input:** n = 6, headID = 2, manager = \[2,2,-1,2,2,2\], informTime = \[0,0,1,0,0,0\]
**Output:** 1
**Explanation:** The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all.
The tree structure of the employees in the company is shown.
**Constraints:**
* `1 <= n <= 105`
* `0 <= headID < n`
* `manager.length == n`
* `0 <= manager[i] < n`
* `manager[headID] == -1`
* `informTime.length == n`
* `0 <= informTime[i] <= 1000`
* `informTime[i] == 0` if employee `i` has no subordinates.
* It is **guaranteed** that all the employees can be informed.
| null | null |
Medium
| null |
1,799 |
welcome to Pomodoro Joe for Sunday May 14 2023. today we're looking at the code problem 1799 maximize score after n operations this is a hard problem so you are given nums an array of positive integers of size 2 times n you must perform n operations on this array in the ith operation one indexed you will choose two elements X and Y receive a score of I times the gcd of X and Y remove X and Y from nums return the maximum score you can receive after performing an operations the function gcd X comma Y is the greatest common divisor of X and Y okay so we have some examples there's nums one and two well the gcd of one and two is one so your output 1. all right that's pretty straightforward next we have three four six eight and we have output of 11. how does that work so looks like we have three and six where the gcd will be three and four and eight where the gcd will be four so we choose 4 first because we want that to be oh sorry we choose three first we want to use the higher multiplier later so we choose 3 first so 3 times 1 and then four times two so that's three plus eight is going to give us 11. all right let's look at our constraints the constraints are pretty good here n is between one and seven so we have up to 14 numbers which makes this a very small set which is very convenient the numbers themselves though it can be quite large so we have to be careful with that all right with that we'll put 25 minutes on the Pomodoro Timer and we will get started so I think we will just follow the recipe they lay out right here we'll choose two elements we'll do this calculation with the I times our gcd then we'll remove those elements from our nums and we'll recurse so this is a recursive solution all right so let's start out with an internal function def Max score recurse now what will we take here in this one we'll be taking our remaining numbers and our remaining operations because we need to keep track of how many operations we've performed so far so I'll have some remaining numbers and I don't know I'll call it remaining Ops so that'll be just the count of how many operations we still have left all right so internal we will have our base case what's our base case here well if we don't have any numbers or if we don't have any remaining operations then we're done and we can return zero so if not our remaining nums or not remaining Ops then we're done and we return zero all right so that's just saying if we don't have any numbers or we don't have any operations left be returned zero what's next well according to our recipe here we choose two elements X and Y so for this we'll want to choose essentially every combination of our elements left so we'll just go through every i j or X Y in our remaining numbers all right so for every I in well let's calculate our length out here so we don't have to do it more than once okay so for every index in the range of our remaining numbers then we will grab that index and we need to find the gcd with some other index so then for every J in range and this will be I plus 1 because we don't want to use the same number twice so we have to go to the next index I plus 1 but we still go through the length of numbers and I was silly I created a variable for this so I don't need to do this same thing up here all right so this will give me my two elements that I'm going to pick out of our array find the gcd for these elements and then we'll add that to our current result so let's see we'll need some value here so our current value will be I times well not I our remaining Ops times so this is going to be how many Ops we have left so this will be our what they call I over here this is our ith operation so the remaining Ops times our gcd of our number at I and J index so this is going to be remaining nums okay so this is our remaining number of operations times the gcd of our nums at I and J now this gcd we could Define it on our own this is the greatest common divisor there are some fairly simple algorithms for this but since this is python we have libraries so I'm just going to say from math import gcd now if you're not using the latest version of python if you're on a python 2 this may not be there I'd have to go back and double check if it's not there you can still write your own gcd function it's actually not that hard I'll try to leave some links in the description so you can check it out all right so this is the value for this particular op we're saying this I times our gcdxy and now we need to remove X and Y from our nums so we're going to have some new nums here okay our new remaining numbers I'm just going to call it new nums because it's kind of getting along the names getting a bit too long okay so our new nums are just going to be well so in this case because python passes by reference meaning we're sharing this same remaining nums if we were to pass it on or make changes to it I really don't want to make any changes to this remaining nums itself so I need to make a copy of this if I want to do anything to it so I'll say remainingnums.copy so I'll say remainingnums.copy so I'll say remainingnums.copy and now I can pop out these values at index J and I so new nums dot pop and we're going to remove J first because we know J is further down in the list because if we popped I first that would actually shift all of our indices and our J would be in the wrong place so we're going to pop J first and then our new gnomes will pop I and now we can recurse so we've created our value we've created our new set of nums here and now we'll do our recursive call so that just means our value will be increased by the recursive call on what's remaining of our numbers so this is going to be our new nums and we do need to decrement our remaining Ops because we performed one operation here we have to rotate one away from our remaining Ops and now we need to choose where we need to decide if this is the best result so far so we will need some results I'll put the result up here let's see I'll put it right here so our result will start at zero once we go through and we choose some values we do their gcds find their I guess resulting value out of this multiplication then we'll decide whether or not this gives us the best answer out of all the possible answers so this is kind of like a subset and we're choosing the best subset so in this case our result will just be the max of our result or this new value now at the very end outside this for Loop we will return our result okay and that should be it so we're going through all the possible pairings of values in our remaining numbers we're going to grab each one of those find the gcd calculate this special value out of this operation here then we're going to create a new set of numbers we're removing these X and Y that we've popped out of here we'll remove those numbers and then we will recurse we will just perform the same operation again at the very end we'll find out whether or not that gives us the best answer and we'll store the best answer in our result returning our result when we're done now the last part of this is we have to start this whole thing off with at least one initial call to this function so down here we'll start this whole thing off by calling we'll do a return on this Max score recurse and we'll just pass in the original nums and let's see what are our remaining Ops well it tells us here that we have integers where we have an array of size 2 times n and we're supposed to perform n operations so it's going to be the length of our nums divided by 2. so that's going to be length of nums and we'll do an integer divide by 2 just in case although it should be an even number all right and that should be it let's see if this works and it works so let's submit this but I can guarantee it's not going to pass all the runtime tests or it won't do it in the right amount of time this is a very slow algorithm even though there are only seven I guess seven by seven even though there are only up to 14 numbers here this is still a lot of calculation going on and a lot of branching going on with every recursive call so it's not going to be fast enough we'll use this test case and we'll see if we can speed up our algorithm here all right so what are some things that we can do I think the biggest thing to me right now is this copy we are copying this array and popping values out maybe there's a better way we can do this copy the other thing that's standing out is this recursive function I would really like to either have some dynamic programming to Cache the values or use the func tools cache method to cash out the values now I'll show you what happens if we try to just use the cache method right here so from Funk tools actually I'm going to put this above the math just because I like keeping things alphabetical we'll import cache and what cache does is cache is a function decorator so we put it just for a function with at cache and what this will do is the first time you run a function with a set of inputs it will run the function then it will cash out the return value remembering what the return value is for this set of inputs if you ever call this function again with the same set of inputs it will just return the cached values instead of having to run the entire function again now this won't work in the current way we have this set up because cash requires your inputs these arguments to be hashable and these remaining numbers are lists and lists are not hashable this is just an INT that is hashable but this list is going to be a problem so if I try to run this now it'll probably throw an error and it does runtime error unhashable type list yeah so this isn't going to work for us so this list not hashable we can't actually do this caching but what does work for us is a tuple tuples are hashable tuples are not mutable so they are hashable I guess that's not the only reason why they're hatchable but let's remove this caching for now we'll come back to that because we're going to be changing this remaining gnomes into a tuple so we can keep the rest of this pretty much the same we can still use this not nums we can still go through our nums we can still get the length of nums all these things are still valid for tuples but this part we're going to change we want to get rid of this copy so we're not going to do copy and then pop out I N J we're going to turn this into well since it's already a tuple we're just going to take this Tuple and reconstruct it without the I and the J valued without the index I or J valued numbers so how do we do that well we use slicing so we take our remaining nums let's just grab this here so we take our remaining atoms and we go up to index I now the way that this slicing works is it goes up to but does not include index I so that's going to give us everything except index I or everything from the beginning to index I not including index I itself then we'll take everything from index I plus 1 so we're skipping over index I and we'll go to J all right and then we will append everything from index J plus one so we're skipping over index J and we'll go all the way to the end of our Tuple so this is taking our input Tuple it's going to grab just the beginning of that input Tuple up to index I skip over index I grab everything between index I plus 1 to J but not including J then we'll skip over index J and go from index J plus 1 to the end so this is effectively removing the elements I and J from our Tuple all right and then we can still just pass it in like we were normally so not much else changes here now the other big thing that does change is because we've converted this into a tuple our input value here this is a list we need to convert this into a tuple and that's really easy to do you just say Tuple so you basically construct a tuple from the list okay let's see if this still works I'm not expecting this to pass all the runtime checks in terms of speed but this should pass everything in terms of I guess just function all right timeline is exceeded not too surprised by that but now we can go back and use this caching because we've converted these lists into tuples we've made this function a cachable function so let's just add our at cache here and try again and that works so let's see how we do oh we get a wrong answer so we're going to use this test case and see what we can do about this one all right so we're going through let's see what we're missing here you've seen me make a lot of dumb mistakes on this channel but this is probably the dumbest I was typing too fast and I had a typo and I typed I when I meant to type one and eyes and ones look a lot alike uh eyes and ones look too similar J plus one to the end not J plus I to the end I'm surprised it passed the other tests all right now that I fixed that let's try this again and we pass and we do okay we get 87 for run time and let's see only about eight percent for memory so we don't do great on the memory but we do all right with the runtime so there are things that we can do to this basic function we can go in and clean out some of these variable names maybe make these a little bit shorter um I don't know if it's worth spending much time on that though I'll leave that up to you can check that out try to take this and make it faster see if you can get a 90 or better all right okay well hope you enjoyed this hope you had fun hope you learned something hope you can go out and write better code
|
Maximize Score After N Operations
|
minimum-incompatibility
|
You are given `nums`, an array of positive integers of size `2 * n`. You must perform `n` operations on this array.
In the `ith` operation **(1-indexed)**, you will:
* Choose two elements, `x` and `y`.
* Receive a score of `i * gcd(x, y)`.
* Remove `x` and `y` from `nums`.
Return _the maximum score you can receive after performing_ `n` _operations._
The function `gcd(x, y)` is the greatest common divisor of `x` and `y`.
**Example 1:**
**Input:** nums = \[1,2\]
**Output:** 1
**Explanation:** The optimal choice of operations is:
(1 \* gcd(1, 2)) = 1
**Example 2:**
**Input:** nums = \[3,4,6,8\]
**Output:** 11
**Explanation:** The optimal choice of operations is:
(1 \* gcd(3, 6)) + (2 \* gcd(4, 8)) = 3 + 8 = 11
**Example 3:**
**Input:** nums = \[1,2,3,4,5,6\]
**Output:** 14
**Explanation:** The optimal choice of operations is:
(1 \* gcd(1, 5)) + (2 \* gcd(2, 4)) + (3 \* gcd(3, 6)) = 1 + 4 + 9 = 14
**Constraints:**
* `1 <= n <= 7`
* `nums.length == 2 * n`
* `1 <= nums[i] <= 106`
|
The constraints are small enough for a backtrack solution but not any backtrack solution If we use a naive n^k don't you think it can be optimized
|
Array,Dynamic Programming,Bit Manipulation,Bitmask
|
Hard
| null |
1,897 |
hello and welcome to another video in this video we're going to be working on redistribute characters to make all strings equal and in the problem you're given an array of strings and in one operation you can pick two distinct indices I and J where words I is in on empty string and move any character from words I to any position in words J return true if you can make every string equal using any number of operations so in this first example we have ABC and BC so what we can basically do is we can take this a over here and put it right over here so we'll get rid of this a and this will now be a BC and in second example we have a and a so we can't really do this because there's only one B that's kind of the key to this problem it's a pretty straightforward one basically we don't really care like what operations we do but there is something that we have to follow right like let's say we have three words first word is ABC the second word is like ABC BC C and then the third word is a something like this the order of the characters doesn't matter because you can take any character from any location and put it into any other location but you can actually think about it another way where you can basically just count up all of your characters right so in this case we have A3 B3 and C3 so if we have these characters then we can redistribute these characters equally so because you can move all these characters around you can treat all these characters as like a character bank and then your goal is basically saying you know given some number of wordss with some characters can I make that number of words in this case three with my characters and what do you need for your characters to be to make that number of words right like if I have some characters like a with a value of x b with a value of x or whatever right C with a value of x let's then they could all be different and I want to make y words what do I need for all of these X's to be I need basically to be able to distribute them equally right so I need X mod Y to b0 right so whatever however many characters I have like let's say Y is three in this case I need to have a multiple of three for all of these otherwise I can't distribute them equally and that's basically what the problem is saying given some number of words count up your number of characters and figure out can you distribute them equally and distribute them equally just means can I divide it by the number of words and not have a remainder that means I can distribute them equally and so that's pretty much all you have to do for this problem you just have to go through every single word count up all of the characters total and then for every single value we can just go through the values the characters don't even matter and because there's only 26 characters this is going to be like a very small um amount of space right this is basically all one space because it's only 26 characters no matter how long the word is so we just go through the values we don't even care about the keys and if our values are like let's say 3 then obviously all of these um divided by three or mod 3 is zero let's say our values was like 1285 then like this character would be able to be uh distributed equally right because we can distribute it into uh like four44 but then this one wouldn't right like we can't distribute eight characters into three piles evenly and that's kind of essentially what you can think about you're distributing some kind of characters into some piles and can I do that evenly also for this character you can't distribute it evenly either right so that's pretty much all you have to do you just count up all the characters and then for every single one just mod it by the length of the word or the number of words like the buckets you have and the that remainder has to be zero and if any one of them is non zero that means you can't distribute that character equally and like I said you can treat this as a bucket because basically in any operation you can move any character anywhere you want so that's basically like your characters are interchangeable they can be anywhere you want we don't really care how many operations so you can get any word to look like whatever you want because you have infinite operations and so now we can code it up so basically we just have a counter and we can just make it a default dict of in you could also use an array like index array and just use the uh asky value of the character would also be fine like a would be like zero B would be one and so on but I'm just going to use this instead um and then we just say for word in words and for a character in word we basically just increment the character so counter character plus equal one now if we now we basically just have like a dictionary of all the characters combined and all their counts now we simply have to figure out if the count of each character is evenly divisible by the number of words so we can say w equals length words and we just have to go through all of the values so we can say for uh for key in you could take the values array but I think that does take up some space actually it doesn't even matter right it doesn't even matter because we already have this dictionary that takes up some space but like I said this is basically one because you have uh only 26 characters like if it words a billion characters this would still only be 26 keys so it's one okay so essentially now we just go through all the values we could say four Val in counter. values we just go through all the values we don't even care about the character we just want to make sure that for every character it's its count is evenly divisible by the number of wordss so if Val mod w uh is nonzero or you can just do this will be like uh if this will be um true if this is non zero right so this and uh this is exactly the same because this is basically like truthy so Python and like JavaScript and stuff has like truthy right so if it's non zero this will be true so if this is true then just return false otherwise return true try that and there we go uh yeah so I am not sure about the run times I think I raise a little bit faster but I think you do have to have counts so and I do think everyone has like roughly the same solution we can take a look so use a set Jo word set one okay so they use to count like a native method let's take look some others yeah it's still kind of the same thing it's like a set of words Set uh yeah and the other thing I noticed that you can do actually that I didn't know so before I didn't know you could check the memory so you can actually look at Solutions about memory too you click on this little memory tab you can click on like this for example so they use a default dict here and so on right so everything use some kind of cache or set or so if the best solution doesn't have like a uh over one time or over one space then you know like your solution is pretty good so you can just check like what are the best memory Solutions what are the best time Solutions and is mine kind of close to that and this one is like I said um yeah basically you can see like all the run times are kind of right next to each other so there isn't like something super good same thing with all the memories are kind of like in this little range there aren like two piles so this is fine okay and now let's go through the time so the time is um o of so I guess we can just say like o of C where C is like every character and every word combined so we can think about it that way or if you want C to be like the number of characters in a word then it would be like oh of C * n or something would be like oh of C * n or something would be like oh of C * n or something right we have to go through every single word and for every single word we have to go through every single character so something like this kind of get the picture you just go through every single character um and then this part will obviously uh I'm going to argue this is of one because like I said there's only 26 characters so that's negligible so actually for the space I am going to say it's of one so like I said if this constraint was huge uh this would this counter would still only have 26 characters so anything alphabetic I think is pretty reasonable to say is of one unless they say like it can be any ask you value possible or something but when you get this kind of thing um in theory and in practice you can use a bunch of dictionaries or whatever you want with this because this is basically all one so yeah that's going to be all for this one hopefully you liked it and if you did please like the video and subscribe to your channel and I'll see you in the next one thanks for watching
|
Redistribute Characters to Make All Strings Equal
|
maximize-palindrome-length-from-subsequences
|
You are given an array of strings `words` (**0-indexed**).
In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`.
Return `true` _if you can make **every** string in_ `words` _**equal** using **any** number of operations_, _and_ `false` _otherwise_.
**Example 1:**
**Input:** words = \[ "abc ", "aabc ", "bc "\]
**Output:** true
**Explanation:** Move the first 'a' in `words[1] to the front of words[2], to make` `words[1]` = "abc " and words\[2\] = "abc ".
All the strings are now equal to "abc ", so return `true`.
**Example 2:**
**Input:** words = \[ "ab ", "a "\]
**Output:** false
**Explanation:** It is impossible to make all the strings equal using the operation.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consists of lowercase English letters.
|
Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subsequences are non-empty.
|
String,Dynamic Programming
|
Hard
|
516
|
858 |
hello everyone welcome to coding decoded my name is sanchez i'm working as technical architect at adobe and here i present the fourth of august sleek code challenge the problem that we have in today's mirror reflection this problem is a medium level question on late code and is based on the concept of geometry and geometries are rarely as in interviews so in case you want to skip this question it's all right for those who are still interested here i present the solution even before jumping onto the presentation where i'll talk about the algorithm let's try and understand the question first here in this question we are given a square room so remember it's a square room given to us with all mirrors on all the four walls there are three receptors given in the equation numbered from zero one and two so if you have a look at this figure then you will see that this is a square given to a square room given to us and all the walls have mirrors on it there are three receptors stated at zeroth position first position and second position a beam is thrown from this particular end and we are given the distance from the zeroth index to which the beam first lands upon so this is the distance q and we are also given the side value of the square that we have which is represented by p what we need to do we need to identify on to which deceptor the beam will finally land upon will it be zero will it be one or will it be due so this is the ask of the question and without further ado let's quickly jump on to the presentation where i'll be talking about the algorithm and how to identify the approach mirror reflection link code 858 it's a medium level question and we will be using the concept of physics from 11 to 12 standard and in case if you're not aware of those don't worry i'm there for you also if you have any doubt understanding this question or if you want to ask anything from me in general please feel free to drop a message on the telegram group or the discord server of coding decoded both the links are stated below now let's get back to understanding the algorithm here i have taken a slightly different example to what was satisfied in the question and let me just explain the question first and then we will converge on to the algorithm so here we are given a square the side of the square happens to be of three units we have three light receptors located at three corners of the square the first one is over is here the next one is over here that means if a ray of light enters these receptors it's going to be absorbed and rest of the area that is being highlighted all the four walls of the square are filled with reflectors that means whenever light falls on them laws of reflection will come into picture what we are also told we are told that a light source is located at this particular corner and a light is intended onto this particular wall the wall that i am just highlighting right on this one and where will this light fall in the first place it will fall at q distance from the zeroth coordinate which is this one so in this case light is falling at over this position that i am just highlighting which is at two units from the zeroth coordinate what we need to do we need to identify the receptor id at which this ray of light finally converge and let's apply the laws of reflection on to this particular point and let's name this point as r1 we know that the angle of incidence happens to be equal to the angle of reflection so light would be traveling somewhat in this direction once reflected from r1 point and for the sake of better visualization let's assume that the a parallel square is placed somewhat like this light is getting reflected at r1 what do we need to identify the location at which this particular reflected light would finally land and this position let's call it r2 will be at same distance from r1 as r1 is from the source so r1 is at 2 units from the source two vertical units from the source as a result of which we can say that the distance between r2 and r1 will be again be two vertical units so this is two and this is again two by virtue of laws of reflection now it's time to again apply laws of reflection on to point r2 and what's going to happen again light is gonna reflect it and what would be the angle of reflection it again would be equal to angle of incidence and light would travel somewhat in this direction so if you carefully observe then you can see that light would be absorbed at this particular receptor id what would be the id of this receptor it would be equal to zero so this will find it this finally converges at the zeroth receptor if you carefully observe then you will realize that whenever the final terminal value of q happens to be even and final terminal value of p happens to be odd then we can say that the convergence point or the receptor at which the ray of light would finally converge would be equal to zero so you can draw few more cases you can take the value of q as four the value of p r six and you can draw few more permutations as well with respect to the terminal value i'll explain it in the coding section so don't worry so this is first test case that we can think of the other test case would be equal to where the final terminal value of q is odd and final terminal value of p is even so what is going to happen in this case let's assume q as 1 ps2 so the light would be reflected about this particular location and it will converge at the second receptor id somewhat like this so the answer in all such case would be equal to two let's talk about the third case where the final terminal value is odd of p and that of q is again odd so let's assume uh q to be one and p to be one as you can see the light will directly land at the receptor id1 and it will be absorbed over here when shooted from the source so in all such cases the answer would be equal to one in order to conclude it up let's quickly walk through the coding section so if you carefully analyze from line number seven to line number 17 you will see that these are the same three statements that i talked in the presentation these are the three test cases if q happens to be even and p happens to be odd answer would be zero if q happens to be odd and p happens to be even the answer is two if q and or both are odd the answer is one and before that what we have i have done i have removed the common factors of 2 from both p and q till the time both p and q are even in nature as soon as either p turns out to be even odd or q turns out to be odd we abort this process and those values of p and q would be the terminal value so you can draw a few test cases and you will yourself visualize that why are we doing this so let's submit this up accepted with this we have successfully completed the fourth of august sleep good challenge i hope you enjoyed it if you did then please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more updates on coding decoded i'll see you tomorrow with another fresh question till then good bye
|
Mirror Reflection
|
masking-personal-information
|
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0`, `1`, and `2`.
The square room has walls of length `p` and a laser ray from the southwest corner first meets the east wall at a distance `q` from the `0th` receptor.
Given the two integers `p` and `q`, return _the number of the receptor that the ray meets first_.
The test cases are guaranteed so that the ray will meet a receptor eventually.
**Example 1:**
**Input:** p = 2, q = 1
**Output:** 2
**Explanation:** The ray meets receptor 2 the first time it gets reflected back to the left wall.
**Example 2:**
**Input:** p = 3, q = 1
**Output:** 1
**Constraints:**
* `1 <= q <= p <= 1000`
| null |
String
|
Medium
| null |
673 |
in this video we're going to take a look at a legal problem called number of longest increasing subsequence so this question is very similar to the bitco 300 longest increasing subsequence so highly recommend to check out that video that i did longest increasing subsequence before this video so in the longest increasing subsequence video i talk about how we can be able to solve this problem using dynamic programming top-down approach bottom-up approach as top-down approach bottom-up approach as top-down approach bottom-up approach as well as how we can be able to use binary search to improve the time complexity down to and log in but in this question in this video i'm going to focus on a question that's related to that's similar to longest increasing sub sequence which is called number of longest increasing subsequence so the question is we're given an integer array nums return the number of longest increasing subsequences so notice that the subsequence has to be strictly increasing so first let's answer what is a subsequence so a subsequence basically a sub array of the original array where each and every single elements that we have in the sub array is the same order as we have in the original array so let's say this is our list right this is our array and uh in this case a subsequence will be four or in this case there could be many situation right we could have one five seven could be a sub sequence right or three five four that could also be a subsequence right we can also have one seven or one 4 right so those are all valid subsequence but let's say we have a situation where we have three and one that's not a subsequence right because you can see the order is not the same so in this case what we want to do is we want to find the increasing subsequence if i want to find the increasing subsequence basically means that elements right let's say we have a array like this right in this case you can see there are two longest in this case two increase well there are many increasing subsequence right three and five that's increasing because the l the next element which is five which is bigger than three right or i can just have one element itself that also can be an increasing subsequence if i have four uh seven that's also a increasing subsequence right however though if i have let's say for this example if i have two and two in this case you can see this is not increasing right they're not increasing so therefore this is not a increasing subsequence so in this case you can see here we want to find the longest increasing subsequence basically we're trying to do is we're trying to find the longest increasing subsequence right in this case you can see here for this array there are many increasing subsequence right i can have three five i can have three four i can have three seven one seven there's so many but the longest increasing subsequence is four right so the maximum or the longest increasing subsequence in this array is basically four right i can the max the longest in this case is one three four seven or long or the other one is one three five seven right so in this case these two subsequence will give us a size of four so therefore um there are two longest increasing subsequence in total right and that's what we're trying to return at the end and you can see here we also have another example right here's our example two and if it's not increasing at all then in this case the longest increasing subsequence in this array which is just one right so total in total how many longest increasing subsequence do we have we know that the longest increasing subsequence for this array the longest is one and there are five of those subsequences that has a longest increasing subsequence of one so therefore in total there are five of them right so length of longest increasing subsequence is one and there are five subsequence length is one so the output is five so you can see here this is the output and let's take a look at the constraints here so the constraints you can see here uh we could have negative values and the array is not sorted and you can see here the length of the array is between one to two thousand so in this case how can we resolve this problem so originally when we're trying to find the longest increasing subsequence right in this case you can see here we can basically using dp or dyname programming right basically here's our recurrent tree we're starting from the first element and then in this case you can see we're basically iterating through the remaining elements that we have right so in this case you can see we're going down the five right element five branch in this case you can see we starting at the bottom right and it you can see here five this four right here is actually uh smaller than five so in this case there's no way that we can be able to connect this right so in this case we cannot have uh four added on to our uh subsequence right because they're not increasing so in this case we if we choose this path we know that seven is one right in this case seven has a increasing subsequence of one and then in this case we get to five in this case we know that seven is one so therefore the longest increasing subsequence at this position is two so then we will choose this path right here right or let's say we go to four so we know that four in this case we have a longest increasing subsequence seven is already one so we will basically save this in a cache right so that we don't have to compute that before uh again and then we know the four is uh two because you can see here we four is smaller than seven so therefore the longest increasing subsequence at this position at this point is two right and then seven is basically one we already cached that and then you can see once we uh backtrack we're going down this path we have three five is already being cached is already computed before is two four is also being computed which is also two seven is one so in this case the longest is basically either those path right so you can see here this is two and this is also two right so therefore we're basically have this at this position the longest increasing subsequence of which is three right so we have three five seven or three four seven and then once we are back to here the root we know that the maximum out of those path is three so here is going to be four right so basically you can see here we're basically this is our recursion tree and we can use caching to solve this problem um it doesn't matter how you're gonna do it you're gonna do a bottom up approach or a top down approach but this is how we solve the problem right to find the longest increasing subsequence but in this case how can people define the total number of increasing or longest increasing subsequence so in this case to find out the total number of longest increasing subsequence that we have in the input array right of course we have to go through to find the longest increasing subsequence right what's the longest increasing subsequence that we have in the array and then what we have to do is that we have to figure out how many subsequents are in nums that has the size of lis right once we figure out once we figure that out we basically have our answer right we can just return our answer and basically you can see here this is our cache longest increasing subsequence array and then for each and every single element we're basically trying to find the longest increasing subsequence for each and every single position just like the leeco 300 but in this case we're just going to have another uh cache array that stores the frequency right for each and every single uh positions and its remaining elements frequency right so for each and every single position we want to know how many subsequences right has the same size of our current longest increasing subsequence so let me walk you through an example for example this one right here right so we're starting from the back to the front so initially the longest increasing subsequence for seven right the last element is just going to be one and then for this position right in this case the longest increasing subsequence that we have seen so far is just one right and then for a cache frequency right in this case how many subsequences has the same size of our current longest increasing subsequence in this case it's basically just one right because you can see here there's nothing on the right so in this case the frequency is basically our current subsequence which we only have one element right so then what we're going to do is we're going to continue so in this case we have four okay so in this case in our four uh we basically iterate the remaining elements right we're trying to figure out the longest increasing subsequence at the current position which is gonna be two right because you can see here four and seven right and then in this case the longest increasing subsequence that we have seen so far is two so then once we get to here you can see here um in this case it's basically just gonna be one as well right because in this case so far we only have one subsequence right we only have one subsequence um and which has the size of longest increasing subsequence right so then we move one to the left we have five so in this case the longest increasing subsequence at this current position right in this case it's basically just going to be five and seven which is two right four is not bigger than five so therefore we have two here the longest increasing subsequence at this position is five and seven right so at this position in this case you can see we still have one sub sequence right which is five and seven so in this case we put one here right so once we get to here you can see start the time start change you can see here um or sorry things start to change you can see here for three right we can go down to the five path which we have three five seven or we can go down to four pathway which we have three four seven right so how do we figure that out in this case you can see here the longest increasing subsequence at this position right in this case you can see is uh basically going to be three right you can see we have three five seven or three four seven so therefore the lis here is or the maximum ls right that the where the longest increasing subsequence is three so here you can see here we have five right so five in this case you can go down this path which we have five and seven right so that's one path right and we know that at this path the uh the total number of subsequences right is basically just one and i can also go down to the four path which i have four or seven in this case the longest increasing or the total number of subsequences is also one so one plus one which is basically two so there are two subsequences that has the same longest increasing subsequences as the current position right so in this case they all have the size of two for their subsequence right and they're the longest increasing subsequence that we have seen so far so and then we move our pointer one to the left again and then you can see here at this position um the longest increasing subsequence is going to be four right because you can see here we can go down to three path and then five and four oh sorry one three five seven or one three four seven right and then in this case the longest increasing subsequence that we have seen so far is four and then cache frequency at this position right here you can see it's basically just gonna be one right and then you can see sorry not one i mean like you can iterate through which is uh five you can go down to the five or three path right in this case three has a long has two subsequences right has two sub sequences um that you can go down to either three five seven or three four seven right and that's also that's so far in this case it is the longest right that we have seen that's the at this position is the longest increasing subsequence right which has a size of three plus the one which is going to be four so therefore if this and this element is basically the longest right or in this case at that position is the longest increasing subsequence and there are two subsequences which is either three four seven or three five seven so therefore it's gonna be two so in this case after this is done we know that the longest increasing subsequence is four so what we do what we have to do now is we basically have to iterate through the array right the array and then try to find elements that has the that has a longest increasing subsequence of four in this case there's only one element that has the longest increasing subsequence of four and that element has a frequency of two and then let's say let's just say that there's another one right let's just say that there is another one and then this is also four and then the frequency is also two here right so at this position you can see we can go down to one three five seven or one three four seven right so in this case the frequency is also two because you can see we can go down two path and then the longest increasing subsequence here is one two three four right so it's basically four so in this case you can see here the res the output is not going to be two anymore it's going to be 4 because you can see we basically iterating through the array try to find uh elements that has a longest increasing subsequence of 4 which in this case there are two of them and their index in the frequency cache has a two right so you can see we have two uh subsequences right either one right one three five seven one three four seven or here one three five seven or one three four seven so there are four of them so the output is basically the sum of those two right so in this case you can see the output is four so now let's take a look at the code uh so the code you can see what i did here is i basically um first check the base case if n is equal to one we just return one and then what we do is we're basically have two cache array with size of n and then the last element we're gonna set it to one the longest increasing subsequence we're going to set initially to one and then we iterate through the array so we're starting from the second last element so working our way to the first element and then in this case for each and every iteration we basically iterate the remaining elements and then we're basically check to see if the remaining elements the current remaining elements is bigger than the current element right then we're basically just going to do our conditionings right so in this case you can see here cache at longest increasing subsequence at the current position if it's smaller than this element then we're just going to uh sign this element to here right this is the longest increasing subsequence and then at the end we basically just increase by one because we're including the current element right and then here you can see here we're basically also have to assign the cache well sorry the frequency for this element to here because we know that this element right here is the max right is kind of like the biggest that we have seen so far right and then let's say if there's a situation where cash uh longest increasing subsequence at i is equal to cash along this increasing subsequence at j then we just basically uh you know increase the current frequency right uh by the current element because we see another uh another element that has the same uh longest increasing subsequence uh that we can go down to and we're gonna get its frequency right and we increase that for the current element and then we continue through and at the end we like i said again we just increased the longest increasing subsequence for the current element right uh because we have to include the current element and then we also have to make sure we update the current frequency or a cache frequency element right let's say if there's two bunch of twos right um and then in this case we can't just set the current element zero instead we have to make sure if the current cache at the or the cache frequency at current position if it's equal to zero then we want to make sure we set it to one if it's not then we're just going to continue right and then we also have our longest increasing or max lis in this case we basically want to make sure we update the max lis every iteration right and then you can see we also have our total uh total is equal to zero and we basically iterate through try to find a long a position that has the longest increasing subsequence that's equal to the max longest increasing subsequence then we're going to get their frequency right how many subsequences uh does this position has in this case if it's two we're going to increase the total by two right and at the end we're just returning total so you can see that this is basically how we solve the problem
|
Number of Longest Increasing Subsequence
|
number-of-longest-increasing-subsequence
|
Given an integer array `nums`, return _the number of longest increasing subsequences._
**Notice** that the sequence has to be **strictly** increasing.
**Example 1:**
**Input:** nums = \[1,3,5,4,7\]
**Output:** 2
**Explanation:** The two longest increasing subsequences are \[1, 3, 4, 7\] and \[1, 3, 5, 7\].
**Example 2:**
**Input:** nums = \[2,2,2,2,2\]
**Output:** 5
**Explanation:** The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.
**Constraints:**
* `1 <= nums.length <= 2000`
* `-106 <= nums[i] <= 106`
| null |
Array,Dynamic Programming,Binary Indexed Tree,Segment Tree
|
Medium
|
300,674
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.