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 |
---|---|---|---|---|---|---|---|---|
371 |
today we're gonna working on net code question number 371 uh sum of two integers uh you have been given two integers a and b return the sum of two integers without using the uh operators uh plus or negative sign so we just have to sum two numbers and we're gonna run the result so we're gonna be using uh doing the bit manipulation for that uh so just for the like the edge cases where a is basically equal to zero again something adding to the zero it's gonna be we're gonna be returning the other number similarly the b is equal to zero we're gonna be returning a okay so the logic goes like this one like while we have this uh b not equal to zero now we're going to update the b the way b gets updated is we're going to calculate a thing called carry and then that carry is going to be left shifted every single time right so basically b and that carry is actually the end of a and b like so if you do the bitwise and uh of a and b uh that would be the carry and then the carry gets shifted to left shifted to the uh once every single time and e gets updated by doing the x a x or b so once you come out of this slope you can return a and that would be the answer there is a way of addition uh like addition of two integers uh without using that plus or negative sign of course looking good and it works
|
Sum of Two Integers
|
sum-of-two-integers
|
Given two integers `a` and `b`, return _the sum of the two integers without using the operators_ `+` _and_ `-`.
**Example 1:**
**Input:** a = 1, b = 2
**Output:** 3
**Example 2:**
**Input:** a = 2, b = 3
**Output:** 5
**Constraints:**
* `-1000 <= a, b <= 1000`
| null |
Math,Bit Manipulation
|
Medium
|
2
|
494 |
hey what's up guys john here again and today let's take a look at another lead called problem here uh number 494 target some another medium problem okay so let's see what's the problem is asking us to do here you're given like a list of negative integers right it's either zero or positive integers and the target as now you have two symbols plus or minors and for each symbols you can do you can choose from you can either do a plus or do a minors and if you need to find out how many ways to assign basically how many combinations right you can make and so that the total is the final sum is the s in this case it's 1 right there are like five ways that i can make uh to the final three here okay and uh yeah so basically this is like a very like typical dp problems and uh i'm gonna talk about two ways you can solve this problem with dp and uh the first one is the traditional like recursive is like memorization which basically we uh we start from the first one and every time basically we have two options right we either have we can either do a plastic card number or do a miners with subtracted card numbers and we keep tracking of the current that of the current positions and also the current sum and by the time we reach the last one we check if the current sum is equal to s if it is then we return s right otherwise we just return 0. so yeah and that's the first one and the second one it's a it's more elegant it's a very brilliant way of thinking this problem it's like we can convert this problem into a knapsack into a zero one knapsack problem okay so let's okay let's try this let's try to solve okay let's solve this problem in a traditional way first okay so in that case we're gonna have a dp here uh dp i and current sum okay i'm going to write some of the uh the dp the variables here like the numbers right and then the uh of course we need the memorizations right that's the standard template for all the top down dp problem right and then you know actually we can uh anyway i'll try to finish out right of the first one here the return dp yeah basically we just return dp 0. zero right at the beginning the current sum is zero and then here we just do uh first we check right if the i and the current sum is in the memorization if it is we simply return the memorization right very standard top down template okay and then like i said so by the time when the i reached the end reached the last it's the last place right which is the end in this case because we are going to add one then we check if the current sum is equal to s if it is we simply return one else house return zero right so this is like easy to understand and then we're gonna have an answer right so the answer here we just have two options basically every time we do i plus one and then the first one is going to be we're gonna plot we're gonna sum plus the card number plus nums i right and then the second option is the uh still i plus one and then current sum we subtract card number right and then other than that just some once we have the answer we just assign this one to the i dot sign we just memorize the current answer right for the state and we simply return the answer okay so yeah so i think this should just work let's run the code here yeah okay so the test case passed let's try to submit it yeah see okay so this one works pretty straightforward like top down dp right basically we just start from zero which is the first one and every at each step we have two options we either like uh plus the card number or what we uh subtract the current numbers and every time we will remember the current state okay a current state plus the current i here because that's the basically that's the two to the state we're gonna use to remember our current state because with the current with the curve is the i and the current sum if this state has been that basically these two variables can uniquely identify the current state and if this one has been calculated before we simply return it otherwise we'll just do the calculation right straightforward and easy right okay so that's that and is there a better way we can do dp here the answer is yes and let's think about this problem this example here let's say we have a the numbers we have is one two three four and five and that's the uh that's the answer that's the numbers we have and the s is equal to three okay and then so one of the examples is going to be a 1 minus 2 plus 3 minus 4 and plus 5. is equal to three okay right so that's one of the uh basically that's one of the ways you can come up with the three answer here three targets target three and the tricky part here is that if you move right if you move all the uh the negative numbers to the right side of this equation so what do we have we'll have 1 plus 3 plus 5 equals to 1 equals 2 3 plus 2 plus 4 right and basically so what's the total what's the so as you can see here so here the total sum between from the left side and right side is what is the sum of the numbers plus s right so that's the left side plus the right side because now we are all we're converting the other numbers to the positive numbers right so that the total sum for in this equation will be the sum of number that's one two three four five and the plus s and then if we do a divided by two since each side basically they're equal and then if we divide it by two that's the numbers on the left side okay basically that's going to be our target on the left side right so now the question will become as you can see now the uh the capacity right so now it's a backpack problem because the capacity or is this right the target that's the capacity and the items are all the numbers and basically now we either choose we just need to find out how many ways we can get to the exact capacity right get to this exact capacity by either choosing one item or not because in this case as you can see you can only use the one the number only once right so now the capacity will become the sum of this divided by two and uh the sex or the item so it's the other items and the problem converts to uh how many ways we can use those items and the one item can only be used at most once right so that we can get the exact this capacity that's a very typical dp sorry the knapsack zero one knapsack problem right okay so let's try to code these things up oh and one more thing here since we're going to do like a target here right the target like the uh we're assuming this target is correct right so we have to do some pre-check sanity check for this pre-check sanity check for this pre-check sanity check for this like uh a total basically the total sum basically if this total sum cannot be uh divided by two and then we simply return zero which means there's no way we can uh find this target because right basically there isn't there's zero ways we can come with the target here okay cool so let's try to code these things up here and uh yeah like i said we're gonna have a total my total is the sums equals the uh the numbers right sum of numbers and then the uh okay basically if like i said if the total plus the target right and divide it by mod by two if it's there's still some remainders we simply return zero right which means there's no way we can come up with that function right else to target right else the target equals to what's going to be the like i said it's going to be the total plus s and divided by 2 okay and now we can simply define the r1d when the uh knapsack problem are right here so going to be at zero uh divided by also not divided the size is the target plus one okay and again so the first one is always one right which means to get to the zero to get to s zeroes and we simply just don't do anything we don't use any of the numbers hmm yeah basically this dp0 means to uh to get to the zeros and with the target zero and we have zero numbers there's uh the base case is one there's always one way basically we don't use anything to get to the to this state right that's why we initialize this one dp0 to one and other than that it's just a regular dp uh knapsack problem here and so notice here we are we have already uh compressed the space comply complexity from 2d to 1d and numbers in nums okay for and j in range target right to a number uh minus one basically dpj will be caught we're gonna accumulate that right um dpr j minors num okay here we simply return the dp dpr target so uh for those who still don't know uh how can we uh compress this compressed 2d problem 2d space into 1d space and you can check my previously uh i think i briefly talked about that in my chained corn chain coin like videos you can you guys can like take a look at that video to understand how can we uh how why we're doing this how we can improve this thing into 1d and while we are traversing this inner loop from the biggest number to the smallest number so long story short basically since the current state you know for the 2d state right basically the 2d state is like this dp i and j okay so i means for the first ice numbers items in this case items to get to j capacity right capacity t how many weights okay so that's the definition of our like original 2d problem but to the uh to the array here and since the current dpi and j only relies on the uh only relies on the dp uh i my i minus one basically i minus one and j because uh we can only use the dp that use this number once that's why we have to solely i mean solely depending on the i minus one state okay and since we are only depending on the previously state we don't have to remember all the first dimensions here we can simply remove the first dimension basically this is something like the basic dp i j right equals to dp i minus 1 j so this means like the uh the first scenario for the third card number we can either choose we don't pick it that's the state right that's the first choice which means we don't pick the card number and then the second one would be like okay so now we're picking the second number we're sorry we're picking the card number which means if we're picking the second numbers now the dpi and j will become the uh the previous previously state right and then but the capacity will go back we'll go back to the j minus when since we have decided to pick this number that's why to get the current j the previously stated hub previously capacity has to be a j minor j minus a number and since like i said this i only depends on the i minus one we can simply remove this remove the first state right so that's why we can just uh simply convert this one to uh to this one and the reason we are doing this like from the biggest to small to smallest is because uh when we calculate the dpj right as you can see the dpj minus j minus num will be smaller than dpj right so which means if we doing the loop from the smallest to the biggest by the time when we calculate the dpj here the dpj minus n had already been calculated based on the current num right which that which is not what we want because we want when we calculate the dpj here we want the dbj uh minus num still uh is still storing the i minus one state uh data that's why if we do the loop from the biggest to the smallest but when we're doing the dp j here this dpj minus num has not been calculated for the current num right so but if this is like uh if this is like a complete knapsack problem then we have we just need to uh change this one to uh to a regular smallest to the biggest loop yeah other than so that's once it's finished we just need to return the dp target here um yeah i think this should just work let's try it oops oh yeah so um so other than check this if the total plus sum can be divided by two we also need to check another thing here as you can see here so if the s is super big right if it's too big that there's no way uh th this numbers can get to the sum right the total sum of these numbers it would cannot get to this to the total here the target which can simply return zero here that's uh basically the api's of s is greater than total right if that's the case we simply return zero because there's no way oh sorry and yeah oops sorry not and i think it's or yeah uh what am i doing here cool yeah as you guys can see this okay this new dp is super fast see because not only it's reduced okay sorry for the time and space complexity i think um yeah actually there the time complexity for this one is still the same that's the number of the uh that's the uh the number of the num number of num which is n and the s so as it's kind of like the uh the yeah so the num the second one is the uh target it's boundary to target then the target and the target is the uh um depends on the net total and s right so which means okay so i think now i have a i have something i want to talk about here um ah see basically the sum of the elements in the given array will not exceed one thousand and uh yeah and i'm assuming this s would also be two big yeah basically since we are even though the ass is too big we are will be stopped we'll be stopping our algorithm here we simply return zero so since the sum of the elements are given will not exceed 1000 i mean so that's which means the s will also be smaller than 1000 right and then our target will be bounded to uh basically also to one thousand here right so then okay and then the length of the given raise is positive and it will not exceed when exceed 20. so in this case uh the time complexity for this is going to be the n times the uh the sum right the target the total basically the total two times total yeah two times total here and yeah that's gonna be our time complexity for this knapsack problem and the space that's the time of that and the space is uh yes oh of the total right since we're doing the 1d yeah and how about this one here so in this case um yeah in this case the time complexity is the as you can see for each of the i here we have two options here right so the number of the sub problem is the 2 to the n right that's the time complexity because for each of the number and here we have two options and to loop through all the i's we'll do a 2 to the power of n yeah and the space complexity is also uh it's also 2 to the power of n maybe because for the memory so basically the space complexity yeah it's going to be the same yeah oh because the uh the dp we have a recursion here which is kind of slow right well actually so this one may be the um i mean since we have this memorizations here right so the total time complexity shouldn't be two the time of n so this time complexity is the time compressor if we just do a brutal force recursion without these memorizations with these memorizations i think i mean it's going to be close to uh of the n times basically the range of the sum right the range of sum and the space will be the same n times the range of sum because we are not always doing the dp here because for some time when whenever we have stored uh this numbers and plus the range the this sum will be directly returning from here so i mean basically i think for in that case this time complexity for these two solutions are kind of similar right but since we have this like the uh the recurs recursion overhead i mean where the uh the compiler where the operating systems have to store some like to store some the state of the recursive functions that's why the recursive function recursive solution is always slower than the uh than the eternity solution yeah cool i think that's pretty much it is i want to talk about for this problem and yeah it's very classic you can say dp yeah classic dp problem and there are two ways of solving this problem the first one is the traditional like top down recursive ways and this is more intuitive and but the reason i want to talk i want to discuss about this problem is i want to show you guys the uh the knapsack uh solution here right this is a very i kind of like it very elegant and the brilliant way of converting this problem into a zero one knapsack a knapsack problem cool i hope you guys enjoy watching the videos and thank you so much for watching my video and stay tuned see you guys soon bye
|
Target Sum
|
target-sum
|
You are given an integer array `nums` and an integer `target`.
You want to build an **expression** out of nums by adding one of the symbols `'+'` and `'-'` before each integer in nums and then concatenate all the integers.
* For example, if `nums = [2, 1]`, you can add a `'+'` before `2` and a `'-'` before `1` and concatenate them to build the expression `"+2-1 "`.
Return the number of different **expressions** that you can build, which evaluates to `target`.
**Example 1:**
**Input:** nums = \[1,1,1,1,1\], target = 3
**Output:** 5
**Explanation:** There are 5 ways to assign symbols to make the sum of nums be target 3.
-1 + 1 + 1 + 1 + 1 = 3
+1 - 1 + 1 + 1 + 1 = 3
+1 + 1 - 1 + 1 + 1 = 3
+1 + 1 + 1 - 1 + 1 = 3
+1 + 1 + 1 + 1 - 1 = 3
**Example 2:**
**Input:** nums = \[1\], target = 1
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 20`
* `0 <= nums[i] <= 1000`
* `0 <= sum(nums[i]) <= 1000`
* `-1000 <= target <= 1000`
| null |
Array,Dynamic Programming,Backtracking
|
Medium
|
282
|
797 |
Anatolia gram problem in this series and it was a great benefit like a boss I think she is a [ __ ] was a great benefit like a boss I think she is a [ __ ] was a great benefit like a boss I think she is a [ __ ] Talip Emre trust everywhere But this is the last grow to women liquid my first conscience rubber Studio with Horse leaf Yıldız mm there is BİM when did it become a province to BİM We made follow-up water Dear We made follow-up water Dear We made follow-up water Dear boss grobman expert ne neurose from the appropriate thoughts Idris blessed tul isagraf Zuhal Gül uyts Flexi listikvan yam Pulsar You are download you always turnover OEM Currently trixie or trivia this cools industry ghostun Things our cold milk repeats a fourier entry you eat starbase drama and Syria number full lot counting programmer to the water - rupee this Ford Muhammedi - rupee this Ford Muhammedi - rupee this Ford Muhammedi pieced Uf ruin skin continue partizon You are on holiday time this cookie's volcanopyre is fire from every egg Sanol that latest model Grande paste hdm1 rankings-top is zero rankings-top is zero rankings-top is zero this is worth it from me to you Viking also leave the water Again in the little skate Canon original Rojbaş good Things when Click knowing Turkish best dry water hobbykent harbi sol Extra English programm this tinit questions Start from Within a Given plus Sabrina Carpenter there is this final part with him boss Yurdu Ford brexin t******* Dragon and Fried Ford brexin t******* Dragon and Fried Ford brexin t******* Dragon and Fried Rice piece potato cold Once whitechapel proof diset Viaport ekolay724 Planet in Gültek may One by one's water ökse beans single Sad water dispelling Linet tripot We patent brand Keep the idea of water tripot We patent brand Keep the idea of water tripot We patent brand Keep the idea of water This Party news turnover The Wind prayer's subervi globe including the compound Party Stihl brand cultured Computer software Which form this Suavi dubspot Angry have Now this problem rex's very fighting on the boss Vur Biltekin had enviro director Turkan Sofuoglu boss cheap hit europid You big brother current turnover latest dryworld tek the spots award ten one to Force is being terminated hear me in the morning Tell me turnovers Ford is angry a certain turnover Plus tare Dragon Heroes this The To of free to for storing growing problemin to this Android was nice boss pick up andyroid turnover boss full en miles ce rohs King Edward greetings from Ukraine only Got to study too much pat SUV battery operated subject NEF chufu only one Never cold smile right now Grande this formula frill sleeve shirt No this will Özkan perweb There are pictures of Mount Everest etc. you would like tsuite Nuri does not like angullia indiskiye figure Mert Sokak 14 13 14 instantly let me join the Fun Club su2134 Ford depart from for novices Blue 3 watch whatever is good he was a child and part stop boss videos for suyla Pendik stopped 3C Digital Pendik population I love it again to for on the street Blue is invalid very cold found a partner 31 right hit this most her I swear I'm dead no opengroup tell a novel this for surprise me at from the Range from Friends Ford Transporter even sends before sports wall screen three four and develop and grow triforce sofali from this Power Rangers Wild Force free for and giving the foreign closeness the other also open process de protiv they are sorry download applied a cold idea face 10 Sofram turnover and your skin from somewhere for each other News energy seklik sorry no posts Were Going Back to adults with ease olives ant binlik athlete their troubles Central villa takir water in the series clixblue Simple Life Finish this opium Nur big arm 3 neverwet titles Party Woman jumping to the palsu particles of the train Veli in the camera Isparta turnover and A camera becomes pot and yours it somewhere Star Defender that before Kamer liquid pinscher kaf mountain Party Sude proof is holding it and there is water This Next Level partice skate 8 flirt know ki patronindir we give and partially provide for soup squeezes without us you so Let's write for Us This is just purple simplygon beatangers Roman triang Rotring subscribe to this water prurit is on duty at that moment Electro Point holder I will give it slowly no 1/1 Point holder I will give it slowly no 1/1 Point holder I will give it slowly no 1/1 Credit Card and pectoris Vector vector water you came in 4 form 304 this surec tofield arctander Fencing Championship follow works can you please take one from the place and urbanity more then freegrafiker illicit degree don't drive me crazy vitamin name problem photo suerden let's read from the middle of it grind my thing industry Nurs is right News of nur is that proper brosoft Norman from Migros Ordu Altınordu Creed in the prosperity of the country a al subzero League before the stylist video will be safe world or water This tree tooth your address list and achieving the pastry Ceren meksi Yurdu Party flag hard barbecue Global Blue Sunrise You will from me the past West pen pencil holder the most honest decent video on his face Now You Will Find breathe this water support surah graphic drawing the situation Vector of in safety rust mervant in the industry also will Power Balance Ener was a Fazıl Batu subscribe this and Adonis voxbox kolit you and abstract I think screen for tax and legal they are camping in the knee Target 16 biology is parked la sortex you know the winged is not digested proving it completed with python Pip insert into will stop that this else if facility took sports in March as the most part of Nevruz Do n't be in this weather Bonus Türüt I pat the sea is this Efendi ride this lemon on a tire and a factory place aviso a passive paragraph cold all brother boost Drop but if I say avipa it will explode fredji topa Twitter zironi pup the biggest head is a estudiantes U21 national benefit you made potatoes spilled machico Premium now Wordpress like Water and luxury games upload Yedikapı Yıldız skate passive straight exquisite When İTS Brand even and basket copy part1 731 basinc its Reference Guide for effective in water gulantep league match take away Syria pass Nikon's boss it you When for souvenirs valuable Anatolia fast while No is bosses a modified 2011/10 to full bosses a modified 2011/10 to full bosses a modified 2011/10 to full sucuklar penguard resentful interact water in Every screen defense colon ethernet our video popular street and nutri teaser 3 thousand Euros I Love You are having it show straight you singing vectorial Directorate police pathem Partner do you know the door opposing fronts mergal work Like every person the day is sultan subscribe this is both Sporx male Silk tulle flirt Samet subscribe you are asking now acceptor Enver Acer this is online for manufacturing to the school what happens in order Yours answer subscribe but Android game Club Little Play Store download subscribe this water 1 kilo I'm listening atnur I don't want this trouble is blessed velcro water quick ablution texture Open the door If Resul Eminem subscribe this is now mediapark tire I think it's Simon subscribe Enjoy watching subscribe Subscribe, subscribe, this is okay, it's a sin, I'm not wandering around, subscribe, this nox, delete the image, subscribe, come home, it's going somewhere, download it, sister, you give it early, the precious one is yours with myself, Tayyip, can you upload it, which move did I look at, the 10 elder brother, the building is yours, you're asking, Believe Radio, the problem is flexstyle Something free tablet case follow from the next video emergency service Another Thing No you won't let's talk about one Hi today AK Party glorify do 3 Knight while expressing dysgraphia you get it You read Android Phone 8.1 what is the read Android Phone 8.1 what is the read Android Phone 8.1 what is the difference to you subscribe this water is you seat subscribe leave this water at the bend make it normal and pastel found a note Agent Sude doesn't have it hop Yıldız most contents I'm sorry engineer Party smarting Tomorrow morning department Directorate f06 News subscribe this is the straightest sit and talk can I say arm both sometimes antipat and some Random please projects subscribe this will also play for the left 40
|
All Paths From Source to Target
|
rabbits-in-forest
|
Given a directed acyclic graph (**DAG**) of `n` nodes labeled from `0` to `n - 1`, find all possible paths from node `0` to node `n - 1` and return them in **any order**.
The graph is given as follows: `graph[i]` is a list of all nodes you can visit from node `i` (i.e., there is a directed edge from node `i` to node `graph[i][j]`).
**Example 1:**
**Input:** graph = \[\[1,2\],\[3\],\[3\],\[\]\]
**Output:** \[\[0,1,3\],\[0,2,3\]\]
**Explanation:** There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
**Example 2:**
**Input:** graph = \[\[4,3,1\],\[3,2,4\],\[3\],\[4\],\[\]\]
**Output:** \[\[0,4\],\[0,3,4\],\[0,1,3,4\],\[0,1,2,3,4\],\[0,1,4\]\]
**Constraints:**
* `n == graph.length`
* `2 <= n <= 15`
* `0 <= graph[i][j] < n`
* `graph[i][j] != i` (i.e., there will be no self-loops).
* All the elements of `graph[i]` are **unique**.
* The input graph is **guaranteed** to be a **DAG**.
| null |
Array,Hash Table,Math,Greedy
|
Medium
| null |
745 |
hi guys this is khushboo and welcome to algorithms made easy in this video we will see the question prefix and suffix search given a special dictionary which has some words and allow you to search the words in it by a prefix and a suffix implement the word filter class wherein the word filter constructor initializes the object with the words in the dictionary and you have a method f which takes in prefix and suffix and it returns the index of the word in the dictionary which has the prefix and the suffix that are the parameters passed in the method if there is more than one valid index return the largest of them if there is no such word in the dictionary return minus 1. so there is an example given over here and we'll see that example visually in the constraints you are given the constraints over the length and also that it would only contain lowercase english letters this is going to help us while writing the solution now let's see this example and then we'll see how we can solve this particular problem over here we are given the calls to word filter and then the function f and in the word filter we are going to have these words as a dictionary and the function has the two parameters that is prefix and the suffix so in this particular example we want to find the words that are starting with a that is the given prefix and ending with e that is the suffix given in this particular call and the dictionary that is given to us has three words apple applet and ape now we can see that these two words are satisfying the condition of starting with a and ending with e the index for these words are 0 and 2 and as we need to return the highest index we will be returning 2. if in case we wouldn't have found any word that would have satisfied our condition we would have returned -1 so that's about the understanding of -1 so that's about the understanding of -1 so that's about the understanding of how we are getting the output now let's see how we can solve this problem the highly used and recommended data structure for making a dictionary is a try because it is space efficient and time efficient and we'll see how that happens what is a try also known as prefix tree is a tree data structure that is used to efficiently store and retrieve the keys in a data set of strings we already have made a video on the question designing of prefix tree or a try you can find the link to that question in the top and also in the description and that would help you understand how we can create a dry data structure and what all methods are actually there in a try data structure and how it works in this question we are not going to see how a try is implemented but we will see the problem specific implementation of try the basic thing that a try has is a array of try and that array over here would be of length 26 as we are only going to have lowercase english letters which are 26 letters so we'll have this in our data structure that we'll be using and apart from that as we have to return the indexes we'll have to store them in our data structure so we'll also have an index and since you can have multiple indexes for a particular start and end we will be having list of integers now let's see the basic implementation of try so in general a try can be represented like this for these particular words wherein you will be storing apple which would be like a which is connected to a array of characters wherein you have the data for p then this p is getting connected to e which gives you a again this p is also connected to this p which is there in a p again this is connected to l then e and this gives you one of the words which is apple again when you connect a t to this e you get a word that is appellate so an end of word in a try is marked with a boolean that gives you an end of word this is a basic implementation of a try and you can see that it is saving a lot of space while storing your words and if you want to know what are the words that start from ap you can say that from ap you get words a p e you get words a p l e t so that's how you can easily search for words too now how would this trial look in our particular case in our case we are not having the end of word marker but we are having the indexes what are these indexes are the indexes wherein my word is appearing in my dictionary because we need to give the largest index amongst those so we start with this a and we have all the three words starting with a so we make a and then we connect it to the other letters in these words so if you take apple you will be connecting a p l e and that is apple and you will also be adding the index so that index would be like 0 will get appended in all the letters in the index now again for applet you will just do addition of t after this apple so that would give you the word applet which is appearing at index 1. what about a you will put e after this first occurrence of p and then you will say that this e is reflecting a word that is at index 2 in my dictionary so over here what i am getting is i am getting all the words that are starting with a and here are the indexes of those words and that is something that i'm needing right now so i'll be needing this particular list to find out my result now the second question is how do i find the indexes of the strings that ends with the letter e so the question here is can i use the same try or do i need to do some modifications in the try or in the input that is given to us so one of the logical things that we can say is if i am reversing this string instead of finding the string that ends with e i'll now have to find the strings that start with e in these reverse strings because now i have stored my input from the reverse side so if i wanted to find the word ending with e and i am storing the last letter in the first position i can simply check the first position whether it is starting from e or not and that's the logic behind this string reversal after reversing the strings this question becomes easy because now i need to find the indexes of strings that start with e for these reversed string if you create a try out of it you will be having a p l e a p e and applet over here but in the reverse manner so you get the last letters over here then you get the second last letters and so on so over here you can see that i can get all the words that are starting with e when i have stored my indexes with so all the words that were having e as the starting point in the reverse string are indexes 0 and 2. similarly for apple it was index 0 8 was index 2 and index applet was index 1 so this is how the indexes get separated over here now what i need is the indexes or the list of indexes for the words that are starting with e in this particular scenario and what are those indexes those are 0 and 2 and so now we have both our indexes 1 starting with a and 1 ending with e now there can be scenarios wherein you would not be having the same numbers in both the lists so as you want to find the indexes starting with a and ending with e you will have to find the indexes that are common in both of them and then out of that you need to return the highest index in this particular scenario the highest index is 2 and so that would be returned so that was all about how we are going to solve this question we are going to use a try and the try would consist of an array of try which would be of length 26 and a list of integers to store this particular list after we have the list we need to find out the highest common index from both the list and the most important thing is that for suffixes we need to use the starts with function but with the reverse string so these were the points that we need to follow now that we know this let's go ahead and code it out the first and the foremost thing we are going to need is a try so let's start implementing the try class so i'll be creating a class in this try class we'll have an area of try and the list of integers so this will be try and this will be the list of index now let's create our constructor that's our constructor wherein we are initializing the try with length 26 and the arraylist over here we are going to have two methods first is insert and second is starts with in the insert method we'll be inserting the words that are given to us and in the startswith method we will be finding all the words that are going to start with that particular string given to us that is either prefix or the suffix and with that we will be returning the list of indexes that have that particular prefix or suffix so let's first write the insert method which would be a void method and our insert method would take the string word that we are going to insert and at what position it was there in the dictionary because we need to add this index in our list of indexes and now we'll take our root which would be the current instance of the try after having this root instance with us we are going to iterate on each character that is there in the word in here if we have already seen this word or seen this letter somewhere then our root dot t would not be null for that particular character that we are searching for now if that is null then we need to create a new drive for this once we have our data structure in place we update our route to new root and with that we also need to put our indexes for this root so we will update the index by adding the ith pointer in this root and that's about the insert function the second thing that we are going to write is the startswith method the starts with method is going to return the list of integer of the indexes in my dictionary wherein the word starts with this particular word so for that we'll again take a root and now we'll start iterating for each character in this word now we'll check whether the word starts with this particular character or not so if root dot t of c minus e is null which means we have no words starting from this particular character or the set of characters till this character then we'll just return a blank list that is there wasn't any word otherwise we update the route to current character so that we can move downwards and finally after the loop ends we can return root dot index and that would return the list for this particular starts with word so that was about implementing the try that we wanted now we need to fill in the constructor word filter and this method f so over here we'll be taking two tries one would be storing the prefix and one would be storing the suffix over here will initialize and now we need to add all the words in our try data structure so we'll loop on the array of words that is given to us with this i am going to call the insert method on prefix and suffix in the prefix my word will go as it is but in suffix it is going to go in the reverse order so i'll take a string builder wherein i'll be putting word reversing that word and then that would go into my insert method as a reversed word and with that there goes my index so this is going to be word of i now we need to write down the implementation for this particular function so i'll just use another word because we already have prefix sense of x over here and now in this we are going to call the starts with function and get the list of integers or indexes with us so this would give me the list of indexes of the words in this particular string of words that are starting with the prefix and now i need same with the suffix so as we have done over here we'll still be taking the same thing that is we are going to search for the reverse and so i am taking this particular thing over here and i will be searching the reverse of my suffix that is given to me so this will give me the lists and now i need the highest common number in that list so i'll be starting from the end instead of starting from the start of the list so let's take two variables so this indexes would be the end indexes of the list and now i'll be iterating over those list while my indexes are greater than or equal to 0. and over here i need to do whether the content of the ith index and jth index in p list and s list are same then i just need to return that particular number because i am starting from the end it would always return the highest if not i need to decrement these indexes accordingly so since my list contains integer i'll have to use the equals method i cannot use double equals over here because it would give you a wrong answer so i am taking objects dot equals p list dot get of i and s list of get of j are equal then i need to simply return p list of i else if this particular number is higher than s list dot get of j i am going to do a i minus so that i am moving backwards in this p list so that i can come near to this s list and if that is not the case i am going to decrement j because in this case my this particular number was lower than p list so i need to go nearer to this lists number and if we are not getting anything from here then we need to return -1 so that's then we need to return -1 so that's then we need to return -1 so that's what we are going to return from here let's run this and it's giving a perfect result let's submit this and it got submitted now comes the part of time complexity so what we are doing over here is we are inserting all the words in this particular try so for that the time complexity that is going to be would be the one for this insert function so over here we are iterating for each and every character in the words that are given to us so the time complexity would be the number of words multiplied by the highest length word that is going to be there in my array the next thing that we are going to do is to have this particular function now the time complexity for this particular function would be the time complexity for starts with plus the time complexity for this loop so for the starts with the time complexity would be the maximum length of prefix or suffix which is let's say k plus the number of times this loop is going to execute so this loop can execute maximum of number of words length of time because at any given point the maximum list length can go up to the number of words that all the words were starting with some particular character or all the words were ending with some particular character so that's the maximum that this loop can run now the total time complexity over here would be n into k that is the complexity for this plus the complexity for this multiplied by the number of times this particular function is called suppose we have q number of queries so we'll be having q into k plus n calls for this function so that is the time complexity for the total problem that we are having now comes the space complexity for a try could go up to the number of words multiplied by the maximum length of word that there can be so that's it for this video guys i hope you liked it and i'll see you in another one so till then keep learning keep coding
|
Prefix and Suffix Search
|
find-smallest-letter-greater-than-target
|
Design a special dictionary that searches the words in it by a prefix and a suffix.
Implement the `WordFilter` class:
* `WordFilter(string[] words)` Initializes the object with the `words` in the dictionary.
* `f(string pref, string suff)` Returns _the index of the word in the dictionary,_ which has the prefix `pref` and the suffix `suff`. If there is more than one valid index, return **the largest** of them. If there is no such word in the dictionary, return `-1`.
**Example 1:**
**Input**
\[ "WordFilter ", "f "\]
\[\[\[ "apple "\]\], \[ "a ", "e "\]\]
**Output**
\[null, 0\]
**Explanation**
WordFilter wordFilter = new WordFilter(\[ "apple "\]);
wordFilter.f( "a ", "e "); // return 0, because the word at index 0 has prefix = "a " and suffix = "e ".
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= words[i].length <= 7`
* `1 <= pref.length, suff.length <= 7`
* `words[i]`, `pref` and `suff` consist of lowercase English letters only.
* At most `104` calls will be made to the function `f`.
|
Try to find whether each of 26 next letters are in the given string array.
|
Array,Binary Search
|
Easy
|
2269
|
717 |
all right so let's talk about one b and two big characters so we have this two spatial characters so the first character can be represented by one bit zero and the secondary one can be represented by two b one zero or one right so how do you actually solve it so this question is really tricky and you could be done but it doesn't matter so you don't have to i mean you can't ignore the last character this is because um the last character could be one or committee can be zero right so in this case uh this character can actually represent one zero and one right so i don't have to worry about like it is character one or zero right this is not uh this is not a case i have to worry about so the case i have to worry about is i have to starting from the second last and then i traverse the entire array um from back to front and then i have to check if this is one if there is one then basically i just increment the uh my counter and this is not one then i just click on the loop and i basically i just have to return if the counter is actually um mod two is actually equal to zero nine so basically if this is the even number of the ones then you return true but this is actually three bit of one so this is three so this is all number and then you return false so uh this is too much talking so i'm going to just call this or inch once that is so i normally have i normally minus one i'm so sorry for the last index but i want to ignore the loss in there so which is minus two and i put it equal to zero and also the b set i is actually equal to one and i minus right so if i should i implement my counter for once uh at the end i'll just have to return if one multi is actually equal to zero which is going to be even number so uh so in this case you break all the regular loop right away because the b psi is not equal to one and then and definitely the y is actually equal to zero so zero mod two is actually equal to zero so you don't have to come to the first bit of one and uh i don't know the exact uh the idea behind it but this is the way to solve it so uh i but i don't only know the last bit it doesn't matter because it could be zero it could be one and the rest of it should be uh the rest of it should be like just based on the counter right so this will be the solution let me run it so if you want to know the math larger behind you can basically um like this is the typo so using a full loop right so yes here we go so let me run it alright so this top talk about time and space complexity for time this is going to be all the fun plus space is constant and this will be the solution and we'll soon explain by
|
1-bit and 2-bit Characters
|
1-bit-and-2-bit-characters
|
We have two special characters:
* The first character can be represented by one bit `0`.
* The second character can be represented by two bits (`10` or `11`).
Given a binary array `bits` that ends with `0`, return `true` if the last character must be a one-bit character.
**Example 1:**
**Input:** bits = \[1,0,0\]
**Output:** true
**Explanation:** The only way to decode it is two-bit character and one-bit character.
So the last character is one-bit character.
**Example 2:**
**Input:** bits = \[1,1,1,0\]
**Output:** false
**Explanation:** The only way to decode it is two-bit character and two-bit character.
So the last character is not one-bit character.
**Constraints:**
* `1 <= bits.length <= 1000`
* `bits[i]` is either `0` or `1`.
|
Keep track of where the next character starts. At the end, you want to know if you started on the last bit.
|
Array
|
Easy
|
89
|
630 |
welcome to mazelico challenge today's problem is course schedule three there are n different online courses numbered from one to n you are given an array courses where courses i has two items duration last day this indicates that the ith course should be taken continuously for the duration of days first item and must be finished before or on the last day which is the second item now you'll start on the first day and you cannot take two or more courses simultaneously so it has to be consecutive now we want to return the maximum number of courses that you can take here with this example the answer is three and what we're going to do here is try to minimize the amount of end time the first thing we want to do is sort this by the second item the end time and that essentially allows us to maximize the number of courses that we can take by making sure that each time we add it see if we've gone over the end time here so i'll show you what i mean so say that we had some variable here keeping track of the max time right and we start with this item first just add whatever zero to 100 and we'll check to see is our max number of days so far is it less than the end time here and it is so we'll keep this one thing to note is we'll actually need to keep track of all the times that we've stored in some sort of day structure so we'll start at 100 like this now we'll move on to the next one uh now we want to add 1000 so that's 1100 is the less than 1250 it is so we move on and we also add 1000 here right now at the next one we add 200 we can add this so now it's 1300 and still 1300 so now we have what three right this was 200 uh but here if we add 2 000 we find that we've gone over uh it's gonna be 3300 here and we've gone over the end time right so we can't add that so what we'll do is um we're going to pop off the max one that we've added so far so here we added like 2 000 let's say um what we'll do is say well if it's over the end time uh we know that before was okay but we added this and now it's not okay so from this data structure take off the time that was the greatest here it's gonna be 2000 right so just pop that off and minus that from here so now it's still 1300 and if there were more courses like say i don't know 1 300 it's like that then we can go ahead and add that right and at the very end however many items we have in this data structure that's going to be the number of courses that we could maximally take okay so there's three things first we want to sort by the end time then we want to add to our heap and check our condition if it's less than the end time or greater than the end time that we have so far then we want to pop one off okay so first let's go ahead and sort this i'm going to use a lambda function and sort it by the second item which is going to be then time now we need a couple of couple items we need our heap and we need a max time here that starts with zero now for uh time and end time in courses first going to add to our heap we'll go heat push to our heap the time and we'll also add to our max time where this time is now if this max time turns out to be greater than the end time that we're on right now well then we want to pop one off uh what we'll do is uh pop one off of this heap and we want it to be a max heap right so to do that i'm just gonna make this a negative and we'll pop off one of the biggest time on this heap so just do a heat pop and we'll subtract this or add it since it's negative from the max time and this kind of guarantees that now we're going to be under that time here but we do lose one course but this kind of guarantees that our max time is going to be minimized each time we're moving like iterating down so at the very end basically we have all these items in our heap we just want to return the length of it because this is the number of courses that we could have and maximize or minimize the end time okay so let's see if this works okay it looks like it's working so let's submit that and accept it time complexity it's going to be n log n mostly because of this sort but also because of this heat so it ends up becoming n log n and in space wise i guess it's oven space oh well uh now there's certainly some other approaches that you can probably do um to do this but i think the greedy approach here is probably the optimal one it's a little bit unintuitive because usually with this course schedule problems that are like graph problems and stuff but once you realize it's this end time that we're trying to minimize then the approach becomes a little bit easier to go so all right thanks for watching my channel remember do not trust me i know nothing
|
Course Schedule III
|
course-schedule-iii
|
There are `n` different online courses numbered from `1` to `n`. You are given an array `courses` where `courses[i] = [durationi, lastDayi]` indicate that the `ith` course should be taken **continuously** for `durationi` days and must be finished before or on `lastDayi`.
You will start on the `1st` day and you cannot take two or more courses simultaneously.
Return _the maximum number of courses that you can take_.
**Example 1:**
**Input:** courses = \[\[100,200\],\[200,1300\],\[1000,1250\],\[2000,3200\]\]
**Output:** 3
Explanation:
There are totally 4 courses, but you can take 3 courses at most:
First, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day.
Second, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day.
Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day.
The 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date.
**Example 2:**
**Input:** courses = \[\[1,2\]\]
**Output:** 1
**Example 3:**
**Input:** courses = \[\[3,2\],\[4,3\]\]
**Output:** 0
**Constraints:**
* `1 <= courses.length <= 104`
* `1 <= durationi, lastDayi <= 104`
|
During iteration, say I want to add the current course, currentTotalTime being total time of all courses taken till now, but adding the current course might exceed my deadline or it doesn’t.
1. If it doesn’t, then I have added one new course. Increment the currentTotalTime with duration of current course. 2. If it exceeds deadline, I can swap current course with current courses that has biggest duration.
* No harm done and I might have just reduced the currentTotalTime, right?
* What preprocessing do I need to do on my course processing order so that this swap is always legal?
|
Array,Greedy,Heap (Priority Queue)
|
Hard
|
207,210,2176
|
257 |
okay so we have another one of the lead code problem so let's go ahead and uh check the question so it's our lead code 257. so it's a binary tree path uh so basically given the root of a binary tree uh return all route to leave path in any order alif is a node with no children so this is what we have so basically uh if you're given uh something like this a root is one two three no and then five you are supposed to return uh basically like one two five or and one three and then remember to put in the arrows as it appears in the output all right uh if it's one then you're just gonna return that I'll leave remember uh return all blue uh route to leave part in any order so you're basically returning this path to leave all right so let's go to implementation so this is what we have so we have a um a method here not very hands and stats and in the end we are supposed to be returning at least uh in a list of strings so uh so this is what we have the first thing we check is to see if the root is null and then if it's not then we're just gonna return an empty array list okay which is what we're returning and then um based on the question uh they need so basically uh we have to return integers in the form of strings so we call this integer to string method which will convert the into uh basically strings so we can so they can apply like this like one two industry you see this uh the max the string and so if you see here um here we are checking if the root dot leave if the root dot left it equals null and root dot right equals no then we're gonna add to the current part basically so it's uh so if both of them they are not we're just gonna add that and basically if we add that then we're just going to return all right I mean we're gonna return our end our list here in the end and then if left if root dot left is different from null uh so this part I will come back to it because we have to explain what this method does so if you come down here you will see that we have the DFS method uh so basically this method takes three parameters then uh three node the current part and the uh and the list okay so in our current path like we said here are we gonna create our string here which basically gonna add up the all the values that we get to the node are so it's adding this to the node basically so the error to the node and so that's what's going on here and then uh here we are going to check if they're not DOT left equals to null and not DOT uh right equals to no we're gonna do the same thing we're just gonna add that into our list like what we did here okay this is inside the um this is inside the uh this stuff method and as you can see here basically we are calling it we keep calling it calling this method and it calls itself in here so this basically conclude that this is like concussion that we're using here and um and here we you want to always check if uh the root dot node is different from null uh if it's different from now then you're just gonna keep on calling this method until it is uh we need at the end of the leaf there is no more leaves to cut through okay so that's how you end up calling it so just for brief captions so basically what we have here is that you have your current part here and you're adding it to it the arrows and you're adding those values and once you check that uh the left and the right nodes they are no then you're gonna add that once you go through everything you're gonna add the current path to your list so basically that's what's going on and then um yeah and then here you keep on checking if you actually don't have any Leaf left no more children and then once that is done and you come back here you're gonna return and then uh you come at this point so you check if the left don't know that route is uh so you call this method here and then basically it's gonna put into effect everything here okay and then if right uh if root dot right is different from null uh the same thing I'm just gonna call this method and then it's gonna put this into uh into execution um and then you're gonna end up returning uh the list in the end that has something that looks like this all right let's go ahead and run it and see what the results are all right uh so that's what we have let's see here as you can see it's accepted and uh basically it's returning what we expected it to return so I will see you guys in the next video uh with the next lead code question I'll see you guys later
|
Binary Tree Paths
|
binary-tree-paths
|
Given the `root` of a binary tree, return _all root-to-leaf paths in **any order**_.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3,null,5\]
**Output:** \[ "1->2->5 ", "1->3 "\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[ "1 "\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `-100 <= Node.val <= 100`
| null |
String,Backtracking,Tree,Depth-First Search,Binary Tree
|
Easy
|
113,1030,2217
|
215 |
hey what's up guys this is chung so this time number 215 k largest element in an array so this is one of the classic problem you know basically you're given you need to find the case largest element in the unsorted array so note that this is the case largest element in this sorted order not the case distinct number so for example this one right so after sorting we have one two three four five six and it asks us to find the case the second basically the second largest number which means that it's the second one from the end right so that's why we have five so here we have one two three four so in this case right so the fourth largest number is the fourth one from the end which is the four yep so i mean the description is pretty straightforward and so this one actually has a lot of not a lot of but some solutions you know i'm going to try i think today i'm going to try to talk about three solutions all right so let's get started so the first one obviously is that the most naive implementation is that we simply sort we sort everything and then we just look at the case numbers from the end okay so i mean that's we just need to sort right so num sort and then we simply return nums dot minus k right or you can use this right or you can just do this like n dot lambs or m and minus k so this is the same thing right basically the case one from the left so from the right equals to the n minus k one from left okay so if i run this one right so this one just yeah so it's worked right basically you know so the case largest from the right is equivalent to n minus one the smallest from left so in this case right so we have second largest which means that we it's the one two three four five it's the fifth smallest number okay so that's the first solution and obviously this is like unlock and right solutions and so obviously we want to find a better solution so another so the improvements we can make here the first one is what is the uh let's say the numbers is very it's huge and but the case is relatively small so how can we uh improve that so since we only need to get the case largest numbers right i think one of the so we can use priority queue so basically the product queue will store will always store the at the top k biggest number and so the way it's doing is like this so since the in python the product queue is a mini q right and we just do this so we just every time we have like numbers here right which are every time we just do a heap cue we will you push it right you hit push hit q dot push priority q to the uh for this number and if the length of the priority queue is greater than k so which means that we need to pop the top one okay and then in the end we simply return the priority queue dot zero so this one here right so every time we push it until we until the priority has reached the case limit so which means that we have more uh more numbers which means then we're gonna basically uh remove pop the smallest one since the pop will always pop the smallest one that's why you know basically we're pushing the uh we're always pushing the number into the priority queue here but since we're always popping the smallest number out and we're always maintaining the biggest case number uh all time so in the end the first one is the basically the smallest number among all the case largest number which is exactly our answer cool so this one will also work yep and that's the second one right and do we oh sorry so for the second one how about time complexity all right so for time complexity we have like right but and the second one is actually instead of log n we have log k in this case because we're always we at the mo at the most we are maintaining like case numbers in inside the priority queue that's why the uh the push and hop then the pop is lock k so when the case is relatively small so this is better than the unlock n solution all right let's see so now do we have even do we even have a better solution the answer is always yes right so and we can use the divide and conquer also similar like the basically also similar like as the quick sort so we can even reduce improve this time complexity to o of n and the question is how can we utilize the quicksort or divide and conquer to solve this problem so like i said you know the case uh largest element is equivalent to n minus case smallest number and if you guys still remember how do we do the quick sort and so we uh every time right we have a left and a right so and then we pick a pivot a random pivot right in the middle okay and then we move everything that's smaller than pivot to the left out of the pivot and then we move everything that was greater than period to the right of the pivot so that the next time you know uh all we need to consider is the left part of the pivot and the right part of the pivot basically we're trying to we're constantly uh splitting the um splitting the array into two parts because the pivot is already sorted right sorry the pivot is already fixed so we only need to sort the left part and the right part and how will this thing help us you know like i said since all we need to find is we just need to find n minus k smallest number and every time when we have a pivot right so if we have a period here then we know okay so let's say if this pivot equals to five so we know that i mean the uh we know that the uh um so we'll know that i mean the numbers of five numbers the number is five basically that's the fifth smallest number in the entire numbers right because you know this pivot it represents the final state which is the index after sorting all the numbers so which means that every time when we have a pivot we know that's gonna be the uh that number will be the that previous index uh smallest number so and let's say we have like period equals to five and let's say the k is equal to what let's say the k is equal to 3. so if the k is equal to 3 it means that okay so normally you know once we have like i said normally when we have like pivot we need to go to left or right to but in this case you know we don't even need to go to the right side because we know since the k is since 5 is greater than k it means that sorry uh actually let's say this n minus k is equal to 3 sorry so it's n minus k is equal to 3. since the 5 is greater than 3 then we know okay so we all we need to do is that we just need to find the numbers on the left side on this side because that's going to be our third or like smallest number and vice versa right so if this five is smaller than n minus k then we just need to we don't need to worry about the left part inside we just need to go to the uh the right part so you know for the quick sort you know since the average the time complexity will be a log n right but since we only need to consider uh one side which means that actually we're removing this log n part so the best case scenario which means that if we choose the pivot index uh wisely or randomly enough so we can reduce the time complexity for from unlocked and to often i mean the worst case scenario is it's still like o of n square but the best case scenario will be o of n cool so uh let's try to code the last solution which is the quick sort um so for a quick sort right i mean the first one is that i always need we need to have like uh a la a partition function where we will be given like a left and right and now we have a pivot right so i mean i'm just going to use like fixed uh pivot which means that i'm always using the last element as a pivot so and out of the rest is just like the uh the quick sort method right so we have four i in range of uh l dot right and to right and then we have a if numbers dot i smaller than the pivot right and then we move this number to the two to the j's location basically we swapped nums i num j and then we increase that to j sorry this j is not one sorry it's j from left plus one and then in the end see here we just need to uh swap the pivot right the pivot is the uh with this one okay yeah and then in the end we simply return the j right that's the quick sort partition method and then the next one is the quick sort right so the quick sort and recurs recursive function so we have like uh basically if the l is smaller than r right so and then we do this because if i always same as r there's no way to there's no need to just to start to partition anymore so and that we have a pivot right so the pivot equals to uh partition right so the partition of l and r right and then so for the quick sort template right so what we have is we're gonna have like the quick sort of uh l dot pivot minus one right and then we have a quick sort of pivot plus one dot r right so that's the uh that's the normal quickly uh quick sort template but in this case you know like i said so all we need to know is that we if the pivot right so if the pivot is same as n minus k then we simply return the numbers up the pivot uh you know let's call it pivot index right so this is a pivot index because we know since the n minus k the minus k smallest number is exactly the values where we're looking for here so that's why we can simply return that otherwise right so else if like i said the p if the pivot index is greater than n minus k which means that we need to go to the left part which means we're going to basically do a quick sort we're going to return right to return a quick sort of the l dot pivot minus 1. house also we return this side this way the other side um yep i think that's it right so now we can just uh run this quick sort uh recursive function it's going to be at this right return quick sort zero dot and minus one right so let's run the code oh okay yeah sorry yeah submit oh i see um i think this is a big this is why because we are actually if the l is smaller than r and we didn't consider the l equals to our case right that's the one case in that case we should just return one yeah so yeah i guess we don't need it we don't need this if statement if check here we can simply just always try to partition it okay i think let's try again yeah so at least it passed but so as you guys can see here right so this one is pretty slow and the reason being is that you know we didn't choose the uh the pivot in the uh the pivot index randomly instead we always we're always like the uh choose the last one right as the as a pivot that's why the uh time complex is not that good maybe it's even worse than the unlock and or unlock k because that's uh the worst case scenario for this one like i said it's a n square right i mean so i mean we can simply we can just easily improve that right so instead of always using the uh the right uh sorry the left and the right the last one as the index as the pivot index we can simply do uh do a random right so we can just do a uh pivot index right so equals to what to the uh we can just use the run int it run in from l to r right so that's we basically random we randomly pick a pivot index from l to r and then uh so now the uh let's see what can we do here um you can we can always uh basically we can always like uh move this pivot index to the end of the array and then so that we can just uh keep the same for loop here so we can still always do the p pivot index and then the nums are right equals to i'm going to copy here the nums are so here i'm moving this pivot numbers to the end and then the pivot value will be uh the numbers of r here so i can just keep everything else so that i don't need to modify it um yeah i think that's the only things we need to change here right and let's try again um it didn't help let's see i'm actually i'm hoping that we can get better cancer here let's see oh i didn't oh i see i didn't swap at all so i what am i doing here so yeah when you swap those two numbers cool so as you guys can see here right so this time it's much faster because we are we're using our like run into here so we're guaranteeing that we're always randomly pick a pivot so that's maybe it's closer to the o of n um uh time complexity it still is not guaranteed right it's based on the type the test case but anyway so that's basically all three solutions that i want to talk about today and yeah i think the last one is pretty uh tricky not tricky in the sense of in the logic wise but in the sense of utilizing the uh the quick sort uh id right actually you know i if i remember there are like some other problems that can also utilize the quick sort and you know so what i'm trying to say is that i mean quick sort is not uh basically it's very useful like technique so it's not only it basically combines the uh both the uh the divide and conquer and also the uh the pivoting thing right so um yeah and other than that i think that's pretty much i want to talk about for this problem and yeah thank you for watching this video guys stay tuned see you guys soon bye
|
Kth Largest Element in an Array
|
kth-largest-element-in-an-array
|
Given an integer array `nums` and an integer `k`, return _the_ `kth` _largest element in the array_.
Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element.
You must solve it in `O(n)` time complexity.
**Example 1:**
**Input:** nums = \[3,2,1,5,6,4\], k = 2
**Output:** 5
**Example 2:**
**Input:** nums = \[3,2,3,1,2,4,5,5,6\], k = 4
**Output:** 4
**Constraints:**
* `1 <= k <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
| null |
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect
|
Medium
|
324,347,414,789,1014,2113,2204,2250
|
515 |
hello everyone let's try to be a cheat code ninja today in this problem we are given a binary tree and we have to return the largest values in each row of this tree let's understand this with the help of an example in this binary tree we have three rows in the first row we have only one node and the maximum value is one for the second row we have two nodes and the maximum value will be three similarly for the last row we have three nodes and the maximum amongst them is nine hence the result array will be 1 3 and 9 please note that the result array should first contain the maximum value from the top row then the second row and so on let's look at multiple ways we can solve this problem the first thing that comes to our mind is that we have to do some kind of tree traversal hence we can either do BFS traversal or a DFS traversal since we have to find the maximum value rowwise it seems more intuitive to Traverse the tree rowwise hence it's easier to solve this problem using a BFS Travers cell this problem can also be solved using a DFS traversal and we'll also look at that solution as with all BFS traversals we'll require a queue where we'll store all the elements rowwise and for each row we'll keep track of the maximum value that we have seen so far using a variable we'll initialize this with minus infinity and after going through each row we'll store the maximum value for that Row in our result array we'll start with the root node and add it to our Q this will be the new maximum for this row hence we'll set one to be the new maximum it has two children so we'll now add them to the que now we have no more elements left in this row so this will be the maximum for this row now we'll repeat the same process for the second row we'll again initialize our maximum value to be minus infinity we'll start from the next value in the Q this will become our new maximum we'll now add it children to the queue now we'll move to the next node in the row its value is less than the maximum we have seen so far so we'll not update our maximum it has only one child and we'll add it to the Q so the maximum for this row will be three we'll repeat this process for the next row and reset our maximum to minus infinity our first value is five and this will be our new maximum it doesn't have any children so we'll not add anything to the queue our next node is three and this is not greater than the maximum that we have seen so far so we'll not update our maximum our next value 9 is greater than the maximum that we have seen so far so this will be the new maximum we have no more values left in the row so 9 will be the maximum for this row now there are no more elements left in this tree hence this will be our answer the time complexity of this would be o of n because we have to go through each element only once and for the space complexity we have to maintain a Q and that can take size up to O of n now let's take a look at the DFS solution and this also will keep a result list to store our output while we do our DFS we have to keep one thing in mind since we have to find the maximum for each level we'll keep track of these Levels by passing an extra parameter these levels will correspond to the indices in our result array let's take a look at a complete example we'll start with our root node and it will be at level zero since we don't have any value at index0 in our result array this means that this is the first value that we have seen for level zero hence we'll store its value in our result array now we'll call DFS on it children we'll first go to the left side and this will be at level one since this is the first value that we have seen for this level will store it in our result at index one we'll Now call DFS on its children similarly this value five will be at level two and this will be the maximum that we have seen so far for level two now we'll go to its right sibling since this value is lower than the value we have stored at index 2 we'll just ignore it now we'll go to the right child of our root element this is lower than the value stored at index one hence we'll ignore it and finally our last value for level two is greater than the value stored at index 2 hence we'll store it over there we are now done with our DFS and this is our answer the time complexity of this will also be o ofn because we are going through the elements only once and the space complexity would be o of n because of a recursive call stack let's Implement both our Solutions let's first Implement our BFS solution we'll initialize a Q and add the root element to it let's initialize our result list now we'll go through all the elements of the queue till it is nonempty we'll keep a variable to store the maximum value that we have seen so far for this row we'll go through all the elements in our current row using a for Loop all the El elements in the Q currently belong to the same row hence we are using the length of the Q our current node will be the left node in our que hence we'll pop it we'll have to check that it is not null this is because we'll not check well appending to the Q whether the left child or the right child is null or not if our current value is greater than the maximum value that we have seen so far we'll update it now we'll upend both the left and the right child of this node since we are already checking if our current node is not null we don't have to check if the child node exists or not we are now done with the BFS for our current row there's one corner case that we have to handle where our current row can be empty in that case the maximum value will still be minus infinity and we don't have to append that value in our result if it is not minus infinity We'll add this value to our result once we have no more elements left in the que we can return our result and now done with our BFS solution now let's Implement our DFS solution we'll initialize our output to be an empty list now we'll write our recursive DFS function where the first parameter will be our current node and the second parameter will be our current level our base condition for our recursive function will be that if our current node is null we'll just return from the function now we'll check if the index level is present in our array so if the length of the result array minus one is less than our current level that means we have to add this to our result list if our current level is already stored in the result list in that case we'll compare its value to our current value and maximize the value at that index now we'll call DFS on the left and the right child and the level for the children will be one more than our current level we are now done with our DFS function we'll call it on the root element and after that we'll return our result now we are also done with our DFS solution if you have any doubts or concerns regarding this Solution please mention in the comments if there's any other problem that you would like to see please mention in the comments if you thought this video helpful please leave a like And subscribe to the channel for more such content thanks for watching
|
Find Largest Value in Each Tree Row
|
find-largest-value-in-each-tree-row
|
Given the `root` of a binary tree, return _an array of the largest value in each row_ of the tree **(0-indexed)**.
**Example 1:**
**Input:** root = \[1,3,2,5,3,null,9\]
**Output:** \[1,3,9\]
**Example 2:**
**Input:** root = \[1,2,3\]
**Output:** \[1,3\]
**Constraints:**
* The number of nodes in the tree will be in the range `[0, 104]`.
* `-231 <= Node.val <= 231 - 1`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
295 |
hello everyone let's solve today's lead code question find median from data stream today's question is to implement a design problem the main feature to implement is to calculate the median value in an ordered integer list if you have an odd number of elements then we need to select the middle value in an ordered array but if we have an even number of the elements then we need to calculate the mean of the two middle values in an ordered array a point to be considered is we are not given the input array at once if the adenom method is called we are given a value num and we need to add it to our data structure if the find median method is called we need to calculate the median value of all elements that are stored in the data structure let me show you how this example is gonna work median finder is initializing the new object and we have an empty list add num N1 is adding 1 to the list add nomen 2 is adding 2 to the list find median is calculating the median value one and two it's one and a half add num and three is adding three to the list find the median is calculating the median value 1 2 and 3. each two if you want one more value one then the median value will be 1.5 then the median value will be 1.5 then the median value will be 1.5 because the list should be ordered lists like one two three it looks like we need memory for the array pick all of n and processing for sorting Big O of n Rogen but if we use two hips we can implement it for Big O log and time complexity we assume that we have two hips or row hip and a high hip the row hip is for storing smaller values that we've had and we set the row hip as Maxi hip the back zip keeps the first value as the biggest value for any operations like inserting a value or deleting a max value the other way the high Heap is for storing bigger numbers that we've had and we set the high Heap as the mean hip the bean hip keeps the first value as the smallest value if we are given these numbers so far one two three four five six the row hip has one two three it is a maxi hip so at the index 0 of the hip the number would be three the high hip has four five and six it is a mean hip so at the index of zero of the hip the number will be 4. we can calculate the average of values from each heaps three four divide by two if we have another number one then we add it to the row hip because one is smaller than the max value of the row hip size is one bigger than the high Heap so we can select the maximum value from the zero index of the row hip as the median value until now we saw the last size hips but we have to consider unbalanced cases the first one is the row hip is 2 bigger than the High hip like this it needs to pop the max value from it and push it to the high Heap then we can make these balanced the second exception case is the high Heap is one bigger than the row hip like this we need to pop the mean value from it to push it to the row hip then we can make these hips balanced okay let's cut it in the any method we defined row hip low and high Heap High for your information python provide only mean hip so if we want to use mean Heap as mix it then we have to negatize Value when we do hip push or hip pop the value unlike this one in the find median method we calculate the median value we assume that we are maintaining our two hips balanced so if we have one bigger size of the row hip than the high hip then we return the maximum value of the row Heap as the median value if we have the same size of the both hips then we return the average of values the first one is the maximum value of the row hip and the second one is the minimum value of the high heat in the ADD no method we do the task adding the given value num to the right hip if we have the non-empty high Heap and if we have the non-empty high Heap and if we have the non-empty high Heap and the given num is bigger than the minimum value of the high Heap then we push the norm to the high Heap if not we push the norm to the row hip we calculate balance value to check if we are on the exception case if two heaps are unbalanced because the row hip is 2 bigger than the high Heap then we pop the maximum value from the row hip and push it to the high hip if two hips are unbalanced because the high hip is bigger than the row hip then we pop the minimum value from the high Heap and push it to the row hip okay these Solutions time complexity is Big O of log n because when we do the hip operation such as hip push and Hip Hop it takes Rogan times and the space complexity is Big O of n because we stored all the edit number to the one of hips I hope you enjoyed this video and it was helpful and I will see you soon bye
|
Find Median from Data Stream
|
find-median-from-data-stream
|
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.
* For example, for `arr = [2,3,4]`, the median is `3`.
* For example, for `arr = [2,3]`, the median is `(2 + 3) / 2 = 2.5`.
Implement the MedianFinder class:
* `MedianFinder()` initializes the `MedianFinder` object.
* `void addNum(int num)` adds the integer `num` from the data stream to the data structure.
* `double findMedian()` returns the median of all elements so far. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input**
\[ "MedianFinder ", "addNum ", "addNum ", "findMedian ", "addNum ", "findMedian "\]
\[\[\], \[1\], \[2\], \[\], \[3\], \[\]\]
**Output**
\[null, null, null, 1.5, null, 2.0\]
**Explanation**
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1); // arr = \[1\]
medianFinder.addNum(2); // arr = \[1, 2\]
medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)
medianFinder.addNum(3); // arr\[1, 2, 3\]
medianFinder.findMedian(); // return 2.0
**Constraints:**
* `-105 <= num <= 105`
* There will be at least one element in the data structure before calling `findMedian`.
* At most `5 * 104` calls will be made to `addNum` and `findMedian`.
**Follow up:**
* If all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution?
* If `99%` of all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution?
| null |
Two Pointers,Design,Sorting,Heap (Priority Queue),Data Stream
|
Hard
|
480,1953,2207
|
100 |
hey and welcome today we are going to solve same tree interview question we will walk through both BFS and DFS solutions for this so let's get into it first example here we have two sub trees and every single node of them has the same value and placed in the same subt Tree location we have one as rot two in the left and three in the right so we return true for it second example we have one as a root we have two as left node in here but we have same two as right node in here this is the hint of this example even though nodes have the same value but they are not in the correct location in both sub trees so we return false for it and last example we have exactly the mirror version of the left sub tree in the right so since they are not following the rule of every node in the exact same location we are returning false for it let's see how we are going to solve it in order to solve this problem as a normal tree problem there are two ways to approach this either using BFS or DFS I have short videos for both if you are not familiar with them or you may need to refresh your mind on those topics so please check them out but I'll explain both Solutions here so that you can get a clear understanding of how to solve this problem in either way first of all the intuition for solving this problem is kind of easy the Baseline is that we need to iterate both sub trees at the same time and check for every note that is the only way that I can think of at least of course I would not be surp surpris if you come some innovative ideas to solve this but within this check process there are some cases that we need to keep an eye on so if both nodes from both sub trees have the same value we are fine we can proceed to the next iteration but if either of those are null or not matching in values you should stop in both of those conditions and return false that is or rule for checking and it will be translated to a Boolean in terms of code but the BFS and DFS Solutions are different in their core for bread first solution we are going to need a queue in order to process every breads of the subtree but again the whole trick of this problem is that we need to Traverse the both subt trees at the same time so no worries on that instead of one Q we need two cues to process this in each level after shifting a note from each Q to process we will take a look at or check rules the same rule of either of nodes or all or they don't match in values together which they are in this case and then as a regular BFS traversal we will push left and the right child of that node to the end of the que to be processed through next iteration in the same order that they've been added to the Q and finally we are clear with q and seems like all nodes are equal so we should return true in that case but before that I need to mention something small about the code implementation that I skipped to show in here what will happen when we are processing the last note and we are at the end of our last steps even if the values are going to be equal from both sub trees we will push null values of this node left and right child into the cube and same goes for this tree in here as well so in order to prevent nodes being null error while processing any node we need another check to see if a node is null and Skip them I'll show it in the code soon okay enough of detour for now let's get back to this state after processing trees what is left in the cues we'll Define if both subt trees are equal or not because if there are some nodes left in either of those cues let's consider this situation for example that would be a signal for us that there are some unprocessed nodes left sub trees are not equal and we should return false so if both of Q's were empty at the end that would be or guarantee that subt trees are equal but if we are going to process both trees then how on the face of Earth we could end up with on processed noes in E Q's that I'll show you in the code so let's jump right into it for BFS solution first we need to initiate our cues and manually put the root nodes as first element in the queue the reason that we always put first node in BFS required cues manually is that there has to be a way to trigger the next while loop we are going to create so we will check as long as both cues has some values within them then we are going to process the cues that is our key to process the both cues at the same time so here comes the usual BFS structure shift the node from q and process them then it comes the time for our valuable check of if either is null or if values are not matching then we might return false immediately now we need to add left and right children of both not into their relative cues remember that if we are at the last breads the left and right children would be null for leaf notes right so we could have pushed null values to the cues the same thing that we discussed in the slides so if both of them are null we might continue to finish processing cues here comes the time that I promised you to show in the code remember that if you are at the any notes from last breads of three the left and right children would be null for the leaf notes right so we could have pushed null values to the qes so before everything that we wrote from line 22 to 30 we need to check if both of the notes from cues that we shifted out are null then we need to continue to the next iteration finally as we discussed if all nodes in the cues were processed and until now that we are out of or V Loop and we did not return false based on our checks here the only thing that would be or guarantee that sub trees are same is the lengths of cues if either of them is still contains some unprocessed nodes then we might return false here right because look at the condition that we based or V Loop upon we always check if both cues has lengths of larger than zero so if either of cues rest out of nodes early the other one will is still contain some unprocessed nodes and that comes to our help in here to sure that we have processed them all so if both run out of nodes then it's okay to return true meaning subtes are same now if I run this tests are passing and if I submit we are in a good shape here now let's go back to the slides to cover the DFS solution for deps first solution you already have the whole picture and in DFS traversal we will use recursion so let's think about what could be your base cases one possible base case is both nodes in the recursion depths are empty if so we might return true because that would means we are at the last depths of a pass and if we come that far considering node values until that depths were equal which they are in this case then it is okay to have null values there because we are at the end of that pass the other Edge case would be again like BFS solution if either of the nodes were null or the values of them were not matching we might return false for this obvious situation okay what is left now in our recursive procedure just calling the function itself for both subop trees passing left nodes once and write nodes to another recursive call at the same time and if they both return true for each step that would mean that nodes are same and we should go to another deps and do the same check that's simple let's implement this solution now so we are back in lead code for DFS solution or job is simple here first we need to check if we are at the depth meaning if both p and Q are null and if so we might return true because what we are going to cook up next will guarantee that we are safe about this line next stop is checking if EOP nodes are null or their values are not matching which we will obviously return false for it and finally if we call the E same tree function recursively pass both left notes from subrace and we call it again passing both right notes this time and the result of that is true then we are good because we are going to pass both checks that we discussed about that means values on both left and right subop trees are same now if I run this test case are passing and if I submit we are in a good shape here now let's jump back into the slides to cover time and space complexity so the time complexity will be all of n for both Solutions n would represent the number of nodes in the tree since we would visit each node in each sub tree Once true or iteration and the space complexity also will be of and for both for iterative solution it's because of qes and for recursive solution because of colis Stack that was it for this video thanks for watching and please leave a like comment and subscribe to the channel I will put a few more links about different playlists in the description for you to check it out and finally hope you enjoyed this video and stay tuned for next one
|
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 |
896 |
here we go satellite radio what's up guys Nick white here I did talking stuff on twitching you to check the description for all my information join the discord everyone's in there talking about stuff we got referral sheets and all this crap and you guys I make all these videos doesn't seem like you like it so please like the videos because my channel will get bigger and then I'll make way more you know 896 monotonic array this is one of the easiest problems on the site that I've seen so I'm gonna explain this is if you're a very beginner to the site like this is gonna be for people that are just getting into algorithms here so an array is monotonic if it is either monotone increasing or monotone decreasing in arrays monotone increasing if every element is increasing or equal to or increasing so for every element the next element has to be greater than or equal to so you could have 3 4 5 6 as long as it's increasing and there's no decreasing like I can't go 3 4 5 4 that's not monotone increasing so that would be you know not good and monotone decreasing is you know 5 4 3 2 1 or 5 4 3 2 1 so if it's either a monotone increasing amount of tone decreasing it is monotonic so we return true so return true if and only if the array a is monotonic okay great so we're just going to be given an array and we want to return true if those cases are true so this one is monotonic increasing right and we return true because it's one of those right so it's going to be 1 2 to 3 that's fine because every element is greater than or equal to the one before it monotone decreasing this one's fine as well because 6 5 4 as long as the next element is less than or equal to 1 3 2 this is bad because it's increasing here then it's decreasing here can only be one or the other so false one two four five all increasing true that's good all the same that's all good it could be increasing or decreasing who knows but it's all good we're true so this one's really easy the fastest solution there's no trick here it's not binary search it's not anything there's no space trick here you're looping through the array one time and you can maybe this is something I'd recommend taking a second to think about because you could probably come up with the solution on your own so you could pause it here and try and we're back so if you didn't try that's fine but basically all you're gonna have to do is make some boolean values so we're just gonna say boolean increasing will be equal to true and boolean decreasing will be equal to true so right off the bat we'll just have two boolean such a true will loop through the array the best time complexity is linear in this case so it's just a linear loop we loop through two minus one array dot length minus one because we want to check two elements at the time the current element in the next element and we'd go out of bounds if we did that without we have to do minus one so we don't go out of bounds we go to the element right before because we're checking two elements at a time right so if a of I is greater than the element after it and I plus one a by plus one then that means that it is not increasing because the next element is going to be less than the current element so that means that increasing is gonna be set to false and we'll check the other case now if a of I is less than a of I plus one well that means that decreasing is going to be set to false because the next element is greater than the current element meaning there's an increase there so we just if we see either of these conditions we'll set them to false so we know when it's not you say anymore because it'll hit this condition right we're looping through all the elements two by one two at a time so if we see a decrease increasing will be set to false if we see an increase decreasing will be set to false and at the end I don't know if you guys have dealt with boolean conditions but it's just in Java it's just or and we just returned increasing or decreasing because if one of those is true still then that means that we found something that is monotone increasing or monotone decreasing or like in the last case it could be both so as long as one of those is true we want to return true and if one of the if they're both false then that means we found a case like 132 where it's not monotone increasing or decreasing both of these conditions hit eventually and then we just return false or false so this or condition just if they're both true it returns true if one of them is true it returns true which is fine because as long as it's either increasing or decreasing it's fine and if both of them are false it returns false that's just basic logic there I think this is one of the easier problems on the site so very simple here just to bully ins check and change them if you find there's a little trip up there and then just return you know as long as everything's good just return true and or false or you could make this even simpler if you don't understand you know you could be like if increasing return true if decreasing return true otherwise return false you know what I mean so you can do something like this as well so whatever you want to do that's pretty much it I think it doesn't get that much more simple than that there might be a few other ones that are just as simple but this one is you know if you're starting out this is a really good one to start out with you know you've got to know how to do this if you know programming right if you've taken a Python course or something you'd probably know how to do this so thank you guys for watching if you cannot do this and you cannot understand this after a while of trying to figure it out and then I think you need to go back and learn programming better before you pursue lee code because this one's pretty basic not to crush your spirit or anything but I really think that would be the best path is just going back studying then your programming a little bit better and getting comfortable because this shouldn't be something that you should really struggle with for you know maybe if you're taking a few minutes and trying to figure it out but if you cannot understand this solution after a long period of time you got to get go back to programming step one you know thank you for watching I appreciate you guys for watching join the discord like the video subscribe all that stuff and I'll see you in the next video
|
Monotonic Array
|
smallest-subtree-with-all-the-deepest-nodes
|
An array is **monotonic** if it is either monotone increasing or monotone decreasing.
An array `nums` is monotone increasing if for all `i <= j`, `nums[i] <= nums[j]`. An array `nums` is monotone decreasing if for all `i <= j`, `nums[i] >= nums[j]`.
Given an integer array `nums`, return `true` _if the given array is monotonic, or_ `false` _otherwise_.
**Example 1:**
**Input:** nums = \[1,2,2,3\]
**Output:** true
**Example 2:**
**Input:** nums = \[6,5,4,4\]
**Output:** true
**Example 3:**
**Input:** nums = \[1,3,2\]
**Output:** false
**Constraints:**
* `1 <= nums.length <= 105`
* `-105 <= nums[i] <= 105`
| null |
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
1 |
hey guys persistent programmer here and welcome back to my channel so in this channel we solve a lot of algorithms and go over legal questions so if you haven't subscribed already go ahead and hit the subscribe button smash that like button because that helps me create this content for you guys so without further ado let's go ahead and look at today's problem today we're looking at the problem twosome and this is one of the most popular questions that are asked so what i'm going to do is give both the brute force solution and then see how we can optimize the solution so first of all i will show the implementation from a brute force perspective so that in the question we're given a list of numbers and we're given a target and all we need to do is return the indexes where two numbers from this list add up to the target so in this case two and seven two plus seven equals nine so we return the index of zero um and one here so if we have a list like this um and we are using the brute force approach um and then the seven and two are at the end so what would happen is for each of the items in this list so we will find the sum of eleven plus fifteen eleven plus seven eleven plus two and then see if that's equal to the target or not um and then so for this case we can see that 26 18 and 13 are not equal to the target so then what we do is we move on to the next number so 15 and then for 15 we will do 15 plus 7 here and then 15 plus 2 which is also not equal to the target and then we move on to the next number here 7 and then we do 7 plus 2 and then we can finally arrive at the target so you can see that there are sort of excessive lookups happening here so for each number we're looking up um the possibility of this plus all the numbers that are um in the list and then the time complexity for this is n square because we are iterating through this list um by per number and then comparing it to each of the other numbers in the list so adding it to so in this case we're adding 11 plus 15 for example so this is not the most efficient way to solve the problem and i have the code over here to solve this although this may be the first way you can kind of come up with the solution um let's go over a optimization we can do to do a single pass solution for this case awesome so to solve this in a single pass solution we can um create a map here which records all the positions of the item so 2 is in position 0 11 is in position 1 15 and 7 but the question is how do we know that okay we need to return this position here this two and seven is what we're looking for so here the return would be um position zero and three um given the target is 9. so one way to look at this is okay we can look at it like this like 2 plus 7 equals 9 so this is the pair we're looking for but we can also think of it as looking for the complement of two so the complement of two seven actually gives us nine so we can check in this comp map each time to see if the complement exists or not awesome so i'm gonna start writing out the code and um hopefully it's going to get clear how to check if something is existing in the complement map or not so i will say i'll do this in a single pass so for i and we can say n for the number in enumerate nums okay so what we're going to do is get that complement so we can say comp equals so this is basically taking the difference from the target so here's what how we got it so comp is equal to target minus the current uh number here and then we're going to check if the complement exists in this map or not and if it doesn't we're going to place the current number and the position so i'll say if comp not in comp map okay so in the first case there is nothing here in the comp map so we are going to put in this two so we will say comp map at the index of the number which is currently two is equal to its position and we're storing the positions because we need to return um this position right so what's going to happen for this case is since the difference is at the end so two's complement is at the end here we're going to keep inserting here so first it will insert two in position zero eleven in position one fifteen in position two and then when it hits this case um here so in the last case what's going to happen is the difference is going to be two here nine minus seven is two right target minus n and then we can see that oh this two already exists so we know that what we're looking for which is what the return statement here is so return it's going to be returning um that position so the current position which is here three and the position where that complement was so um it will be the position of that complement so in the complement map the position of that complement right so we can see here this is two so we're looking for this index here right and we store the index here as zero so that's what we need to return okay so if comp not in comp map then map that to the index and then else it's going to return this the current index and the comp map index so in this case it will return 0 and 3. okay let's give this a run comp map is not defined oh i forgot to put this out here this was in the comments okay so run okay awesome accepted and then submit yay success
|
Two Sum
|
two-sum
|
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_.
You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice.
You can return the answer in any order.
**Example 1:**
**Input:** nums = \[2,7,11,15\], target = 9
**Output:** \[0,1\]
**Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\].
**Example 2:**
**Input:** nums = \[3,2,4\], target = 6
**Output:** \[1,2\]
**Example 3:**
**Input:** nums = \[3,3\], target = 6
**Output:** \[0,1\]
**Constraints:**
* `2 <= nums.length <= 104`
* `-109 <= nums[i] <= 109`
* `-109 <= target <= 109`
* **Only one valid answer exists.**
**Follow-up:** Can you come up with an algorithm that is less than `O(n2)` time complexity?
|
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
|
Array,Hash Table
|
Easy
|
15,18,167,170,560,653,1083,1798,1830,2116,2133,2320
|
539 |
hi guys this is Akshay and today we will be discussing an algorithm problem that was asked to me in one of the rounds at Google so here is the problem given a list of 24 hour clock time points in hhmm format return the minimum minutes difference between any two time points in the list the examples um are 2359 and 0. so you are given uh strings of time points and you need to find the minimum difference between any two of those strings so as you can imagine that we cannot simply find the difference between two strings we have to convert them into integer so that is first sub part of the problem that to read the integer to read the string and parse an integer value out of it and convert all of those values in two minutes because you need to return the minimum minutes difference here minutes is mentioned in bold so that's an important piece of information so these two values here 23 59 and 2 0 the difference is one because just before this one is 12 am and this one is just one minute before 12 am uh yeah and here in this case you have two time stamps two same timestamps so the minimum difference between those two is zero so what's the first idea that comes to your mind when you see this question let's assume let's forget for a second that you are given these values in strings rather you are given these values in its form only so you the first value is 23 into 60 plus 59. and the second value is zero and let's take this example because this one is bigger and the third value is also um yeah 0 so this can be translated to this so what's the first thing that comes to your mind when you see this sort of problem so how are you going to approach it in an efficient manner we can say that if a particular is a particular value has occurred two times we can you know find the minimum difference between those two and the answer in this case turns out to be zero but what if you had something like let's say 0 into 24 plus 5 instead of plus 0 yeah so here in this case again the answer would have been this value that is 5 minutes minus zero so answer would have been 5 minutes so don't you think our job would have been that much easier had we ensured that our input is in fact sorted so that comes and that brings us to the second intuition in this problem the first being let's just write the sub parts of this problem as to those so always try to um think of a problem at high levels first rather than going into implementational details that how am I going to implement let's just say you have some Genie this beside you who helps you to implement those functions your job is to think about the algorithmic structure how the codes flow is going to go so the first to do would be to parse the string files the integer minutes from given strings uh this is going to take an entire order of n items order of n time the time complexity would be order of n where n is the number of entries in your time points list okay the second part is to ensure that your time points on that your storing is sorted so to do again sort the time points and time points minutes no sorting the time points is going to take you n login time right and this is the idea that you should come up with as fast as possible in an interview because this is a Brute Force idea okay the sooner you express your brute force ideas in the interview the sooner your interview moves on and you might be able to get some hints from the interviewer if there is any particular intuition required in this problem in any problem the interviewer will guide you towards that intuition so yeah and finally once you have like the sorted input let's say this input was you know a bit more large um it was three minutes then 10 minutes with 50 minutes then 1 hour 50 minutes that is 110 minutes and so on and so forth so if had you been able to sort this thing so your array would have become 0 3 5 10 15. uh under 10 and finally this whatever value I mean this whatever large value this is that so this thing let's call it X so X yeah so then you could have simply traversed your array find out the difference between two consecutive elements and you know whichever the difference is minimum you are able to return that so just traversing the entire array would take you order of end time okay so order of end time yes uh but in the entire code your n login is the being the dominant Factor will dictate your time complexity of the code so now the interviewer might ask you that n login we can do actually better than that so how do we do better than that there's a key observation here to be made uh which is that your input times time points will vary between 0 to 23.59 to 23.59 to 23.59 they you cannot express any time in hhmm format outside of this range so you have a defined input space now which is the Sorting function because you have to sort this so which is the Sorting function that works very well when your input size is fixed the answer is none other than bucket sort yeah and that is the Crux of the problem this is a bucket sort problem are not commonly used algorithm sorting algorithm but you know you can sometimes get stunned by this in the interview so if you are able to store the information whether any time point between this range has occurred in your input or not if you're able to store that then the job becomes all that bit easier you know for example in this particular case 0 the time point zero has occurred once so you let's say create an array of yeah let's create an array of I you know of I indexes ranging from 0 1 2 3 4 5 6 and so on and so forth till 23 into 59 and you just Mark in this array whether this particular value has occurred in time points or not or in our case this particular input or not so 0 has occurred that is true one has occurred no that is not true 2 has occurred no that is not true three has occurred yes that has occurred and if it has occurred if the if 3 is not the first element then that means um some element has occurred before three and you find the difference between these two so okay the difference between 3 and 0 is 3 so right now your minimum difference is 3 in this case 4 has not occurred no four has not occurred yeah so ah 0 and 5 has again 5 has occurred so now the last item before five that had occurred is three and the difference between these two is two which is smaller than your minimum difference so yeah in this case the answer would be two let's proceed on it 6 has not occurred zero and so forth till you reach 10 which has occurred then again you reach 15 which has again occurred and finally your LA and the largest prime stand that has occurred again so this way once you Traverse this array you will find yeah you will find your minimum difference but yeah this sounds all fine and Randy but there's an edge case to be taken care of um here and as is always the case with Google interviews uh in Google interviews in particular you have to be very cautious about edge cases writing a code is not the most difficult part but coming up with all the edge cases yourself uh is the tricky part so you have to be very vigilant so what if let's say in this case none of these values had occurred you only had 23 59. yeah 22 59. yeah and all of these values would have been zero so in your case um the first value that would have occurred is zero and the final value the only other value is 259 in which case you try to find the difference and the difference turns out to be a huge number right and that is 0 and 23 59 minus zero so but the minimum time difference actually as you know is fun so what we need to do here is we need to think of this particular 0 as the next thing so the minimum difference is nothing but the difference between these two numbers and I mean is equal to minimum difference mean of Min dips so far and the other day that is you just add 20 24 hours into it and find the difference then if this is the latest element that has occurred so let it be called latest and this is the earliest element so if it would be called a realist so the difference between these two things will give you and the other time difference and you find the minimum between these two then your answer is like correct absolutely correct so let's just code this down so first part is I will be coding in Java you can choose the language of your comfort so here first we have to prepare an array now what would be the size of that array that would hold this information whether a time period has occurred or not in our case it would be nothing but the size of the total time window let's call it that is equal to 24 hours into 60 Minutes any time that we will get in this time points string is will be within this total time window and we call it um occurrence is equal to mu and total time window yeah and initially we initialize it with minus 1 so till now nothing no time has you know shown An Occurrence in this array now we try to populate this array so this would be the string time points and point in time points yeah in Java we have an ft function Nifty little function to split the string and we are going to use that so let me call it input is equal to time Point dot split yeah basically this will split the string into two halves the first half being this and the second half being this and how do we determine time from that so and P time is equal to the first value integer dot pulse and input 0 the first index number it can be zero or anything multiplied by 60 because one half maintaining 60 minutes yeah and integer dot parsing so input one yeah so now you have your time in minutes and you check if occurrence of time is already one so like in this case there are two elements of the same time value and first you go there you mark it one now when you again come here you see that okay oh this is already marked one you can simply return zero from here because that is the minimum difference your difference cannot be lower than zero otherwise you can mark it one yeah so the first part is done thanks to our Genie now we have an in fact improved upon this thing because our occurrence time is already sorted right because we have just constructed it that way we have intelligently constructed it that way so we do not have to sort this thing and this is how we save our time this is how we better the time complexity of our program now this is the order of anything which in which we will parse we will pass the occurrence to find the minimum difference yeah so let's just Implement that quickly for inpi is equal to zero I less than total time window I plus so this occurrence of I is not equal to 1 and for example these numbers so we don't bother about them there's nothing to be done here we just move on to the next one okay yeah before that we need to initialize some variables here very important int Min this which will be our this is nothing but the maximum value we can think of any number will be smaller than that no uh yeah the other thing is to know that which is the last index that we have visited which is the last time that we have seen so last time we can initialize it to be minus one because so far we have not seen any time whatsoever then uh we need to also store the information about latest and earliest which we'll use later so latest is equal to integer dot Min value yeah and the earliest is going to be in Digital Dot max volume because we want the areas to be the smallest possible value so we take it from one extreme and keep reducing like as we see more and more entries so yeah all the initializations are done uh we check if the last time is equal to minus 1 that means we have not yet you know seen any we are not even encountered our first time occurrence so in which case we will just initialize this the type so this is the time because if it is not one then we would have continued to the next time but because this statement has not triggered that means we have encountered An Occurrence so we just initialize it with that else what we do is first what we do is basically we are mend this so basically if our last time is not minus 1 that means we have already seen An Occurrence and we want to find the difference between the current reference and the last encounter one so that means index and um I minus so I is the on the latest one and last name yeah and we also need to each place last name of the time and we finally need to update our latest and the ear use the greatest man dot Max latest Nike and earliest is equal to mac.min Nike and earliest is equal to mac.min Nike and earliest is equal to mac.min earliest of my yeah because we are limiting we are making ideas to smaller or smaller and latest larger and larger from Min value earliest smaller and smaller from max value yeah now finally we return our answer the main difference is the lowest that is great otherwise what we check is what is the difference between your latest and earliest time periods you do not want to just I would be used yeah we do not want to be um dealing with that edge case yeah you do not want to be missing dealing with that edge case to be precise yeah and let's give it a run okay you know some array dot fill compilers have occurred we will just fix those erase dot fill igs.cil and cannot find symbol input fun igs.cil and cannot find symbol input fun igs.cil and cannot find symbol input fun so input of Aya not I but rather one and yeah our cases are pulse let's just submit and check voila yeah so this was the minimum time difference question I would suggest you go and practice yourself to internalize the concepts better and see you in the next class bye
|
Minimum Time Difference
|
minimum-time-difference
|
Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_.
**Example 1:**
**Input:** timePoints = \["23:59","00:00"\]
**Output:** 1
**Example 2:**
**Input:** timePoints = \["00:00","23:59","00:00"\]
**Output:** 0
**Constraints:**
* `2 <= timePoints.length <= 2 * 104`
* `timePoints[i]` is in the format **"HH:MM "**.
| null |
Array,Math,String,Sorting
|
Medium
|
2266
|
349 |
hello guys welcome back to my YouTube channel today I'm going to solve day 10 problem of this month on lead Cod before starting if you guys haven't subscribed my YouTube channel yet then please go ahead and subscribe it now let's read the problem statement so today uh we are going to solve problem number 349 that is intersection of two array in this problem we have given two integer array nums one and nums 2 and we have to return an array of their intersection okay so it simply means that we have to find the common elements uh between these two arrays and we have to return them but our result must be unique like here uh in this example you can see that two appears two time and in nums two is also there uh two times right but we don't need to return two times we have to just return the unique result okay so we can just return two here okay same way in nums array example two this is our nums array nums one array and this is our nums two array okay so what are the common elements between these two uh arrays one is four right four is there 9 is also there in both the arrays and yeah that's all so we can uh return the output as 94 or 49 okay so order doesn't matter here okay so here you may return the result in any order okay so since uh we are dealing with the unique result right we have to give just the unique result so let's use hash set for that so let's uh remove the duplicate elements in our uh nums array right we can do that so let's create one hash set of integers that we need to create okay hash set of integer set is equal to new hash set okay so this is done we have created our haset now after that uh let's store uh the result uh in one list so let's use one ARR list array list of integers list is equal to new ARR list okay this is done now after that uh let's uh add the unique elements in the set okay so let's uh go over our nums one array first for INT I = to 0 I is less than num 1 dot length I ++ set dot ++ set dot ++ set dot add nums one of I okay so this is how we are adding the elements unique elements in our set okay so this is done after that let's iterate over our second array so I'm going to write like this for in I isal to z i is less than nums 2 Dot length I ++ okay so now here I'm going length I ++ okay so now here I'm going length I ++ okay so now here I'm going to check if my set okay if my head set contains any element of nums 2 I okay so for that I'm going to write if set do contains nums 2 of I okay if my set contains any of this element of nums to my set which in which we have nums one element right so if my set contains this num two of I this number then in that case let's add this number in my list okay list do add nums two of I okay so here I have stored the common element which I find uh from nums one and nums two okay so I have added that element now after that I don't need that element for my future result like set dot remove nums two of I okay so from the set I have removed that element okay so this is done now after that uh I have to return done the result uh in an array right so for that let's create one array and let's give the siid of our list new int list do sides okay so this is done now let's run one Loop for in I is equal to z i is less than array do length i++ and inside that array of I is going i++ and inside that array of I is going i++ and inside that array of I is going to be equal to our list do get okay we are just adding the elements from the list into our array okay so this is done and in the end we are just going to over return the array that's it return array okay so now let's run the code okay so all the test cases has been accepted right now let's submit the code so our solution is accepted and uh run time is just 2 Mill second so I hope that you guys are able to understand today's problem if you guys still have any question then please feel free to ask in comment section till then keep coding and keep practicing meet you in the next video thank you bye-bye
|
Intersection of Two Arrays
|
intersection-of-two-arrays
|
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must be **unique** and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[9,4\]
**Explanation:** \[4,9\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000`
| null |
Array,Hash Table,Two Pointers,Binary Search,Sorting
|
Easy
|
350,1149,1392,2190,2282
|
134 |
Hello friends, today's question is gas station. This is a medium level question of eklith court. In this question, we will be given two expectations, first will be gas and second will be cost, so there will be a circular route inside which there will be gas station plants. We will be given any gas. We can start from the station and we have to complete the entire circuit. If we are not able to complete the circuit then we will return -1 in case then we will return -1 in case then we will return -1 in case if we complete then we will tell the starting point in it. If we see it through the example then In the first example we have, inside this we have first point van, second point you are three four and five, so I start from point number van, so at this time my initial was zero and at this point I came, how much gas will I get in the van. If I have to go to the second point in this, then the initial petrol that I have in the van, the fuel that I have in the van, I will do in it - whatever is its cost, I will do - if in the van, I will do in it - whatever is its cost, I will do - if in the van, I will do in it - whatever is its cost, I will do - if this is greater than 3 then it is equal to zero, like this is greater than equal to zero. So I will go to you, like me, I do it, I don't have mines, give a greater, like you, I see 2 - Its cost is like you, I see 2 - Its cost is like you, I see 2 - Its cost is four, even if it is not a greater dena, I ca n't do it, okay, I see three, 35, it's not even this So I ca n't even select it. Like, I do 4 - 1. n't even select it. Like, I do 4 - 1. n't even select it. Like, I do 4 - 1. This point is suitable for me. Like, I have got a grater in this, so I will start the point from here. Four is fine. How much does four cost? So I will pay here. What will I do, how much initial fuel do I have? If you have been gone for 4 months, you are on five. Okay, then what will I have? It is 4 - 1 then what will I have? It is 4 - 1 then what will I have? It is 4 - 1 and inside this I will add five, so in that case, how much will be my petrol? 8 Okay, it will be 8 - What will be my search for will be 8 - What will be my search for will be 8 - What will be my search for my pipe's castable - which will be my van's search, what will be its sam, its result will come to me, 66 and here 6 plus 4 plus 3, then it will go to you, how much is it here, its sam is Sam happens to me like how much time is 22 + 5 ok here it will go to five 22 + 5 ok here it will go to five 22 + 5 ok here it will go to five 5 - 5 + 4 so it min I have completed the whole circuit in this 5 - 5 + 4 so it min I have completed the whole circuit in this 5 - 5 + 4 so it min I have completed the whole circuit in this I had started from four and reached four in this case I Starting point, what is its index? So I will return that. Okay, this is our example. If we discuss its solution, then let's discuss the solution. Like the one which is my cost which is given to me, the one with the cost is the minimum inside it. What is the point, van, so I start from this van point, like four, I started from four, I will go to 5, near to go to 5, I had initial zero plus four, okay, 4 came 4, inside this, its four. How much is the effort to leave the van and this five is ok 4 - 15 = How much is this 8 What will I 4 - 15 = How much is this 8 What will I 4 - 15 = How much is this 8 What will I go to after coming to 8? It is ok near the van I will come to the van So here how much is the effort to leave 85 2 and 1 How much does it cost 7 Okay after Tu, who will I go to after the van? What is the cost after going to Tu Pe? How much does it cost to leave Seven Van? 3 + 2 = 6 Now who will I How much does it cost to leave Seven Van? 3 + 2 = 6 Now who will I How much does it cost to leave Seven Van? 3 + 2 = 6 Now who will I go to after this 3: I will go to 00 4 -1 If this is greater then you are equal to zero Then -1 If this is greater then you are equal to zero Then what is the cost of leaving me What is the cost to you When I mine, at which point will I go How much fuel will I carry in the van 53 Aa 5 + 8 - 6 - 2 6 Fuel is gone Ok now 53 Aa 5 + 8 - 6 - 2 6 Fuel is gone Ok now 53 Aa 5 + 8 - 6 - 2 6 Fuel is gone Ok now what will I do here I will plus I will give the van what is the cost of the van I have that 3 If this is greater give equal tu is zero then which position will I move on tu pe 77 - 77 - 77 - 7 - If it was 3 then it will be 44 + 2 - 4 If 7 - If it was 3 then it will be 44 + 2 - 4 If 7 - If it was 3 then it will be 44 + 2 - 4 If this is greater den equal tu hai then I will go to three pe kitna 2 4 Nikal aa tu nikalta hai tu ko leke main pe gaya three pe tu plus three minus five if greater den equal If you are zero, then which one will I go to? Like this, if I write it in the sense of formula, then my total cost is fine, what do I do in it, I make the gas plus and make the minus post, it is the lowest point. I started this point from that, if I start it from van, support, if I start it from 1 point, from the first point, I see that 1.6 is ok, the from the first point, I see that 1.6 is ok, the from the first point, I see that 1.6 is ok, the formula is right for me, I solved it on the basis of this formula, from 1 point I see, it's okay, how much is the initial course from the van, zero plus van, how much is the cost of the station, 3, so what will happen on this, I will go to you, I am okay, so what will happen here -2, okay, mines, nine plus six. Mines nine plus three If I go to the fourth point then what will happen here -6 + K4 The van of mines is ok 4 what will happen here -6 + K4 The van of mines is ok 4 what will happen here -6 + K4 The van of mines is ok 4 - How much will these three mines become Now I am - How much will these three mines become Now I am - How much will these three mines become Now I am going to the 5th point I went to the 5th so what is left here for me I brought in pass-3, what is left here for me I brought in pass-3, what is left here for me I brought in pass-3, plus was five, minus was 2 and what is this, zero mains, if we look, what is the total cost that we have got, this is zero, so can I do this, not what is my total? If the cost is greater then it is equal to zero, it means that I have completed the circuit because it is ok, what have I done to complete the circuit and if it is less than zero then I can calculate it in the case that no, I have not completed the circuit. My mines van will be the answer but what do we have to return in the question, this is the starting point, so we can return to this example by doing our total cost now and we can also do the root cost. If our route cost is less than this, then sorry, we will start from zero and our SP which will be the starting point, we will increase it from van. How much is it -2, our score in zero like, take a slightly different example. If you understand then ok ours was ours I write it back like we have starting point what is the van ok how much is this how much is our SP now how much is the route cost zero plus van minus three how much came -2 came to mines came three how much came -2 came to mines came three how much came -2 came to mines came So, what will happen in this case, what will I do with my starting point van, what will I do with it is okay on 2nd, it is okay on you, it is okay, now how much will we keep the route as zero, what will we do with the plus, the cost of 2nd -4, how much is this cost, we do with the plus, the cost of 2nd -4, how much is this cost, our answer is - 2 will come, okay, from this also we will jump forward, - 2 will come, okay, from this also we will jump forward, in this one, we will go back to A. 4. In the case of 4, we will go to the case of 4. In this case too, zero plus four minus one is equal to how much will you be. 3 will be plus in this case, so our starting point. What will be the four starting point, it will be ok and how much will be in the route. If we check on three five, then 3 + + + 3 + 5 - 2. In this case also we will check 3 + 5 - 2. In this case also we will check 3 + 5 - 2. In this case also we will check 3 + 5, how much will be 8 - 2 8 - 8 - 2 six. So what is our starting point? 4 If our root course is negative whenever it goes to zero, in this case what will we do to the root course? We will make it zero and to the SP we will take it to the current index running at that time. I will go and make its I + 1 I think you must have its I + 1 I think you must have its I + 1 I think you must have understood this solution a little, now let us look at it in the code, let us try to understand it a little better, then I will remove all the likes, turn this one off first. If we see then what are the variables that we need brick total cost which will be our total cost will be initial zero okay and what was the condition we saw when will we return what is our total cost give this less if In case it is zero, we will return to the mines van and vice versa. Ok, our gas dot till length and I plus ok, mines cost i route cost. If ours is negative then we will return to the mines, if not then we will return to the start point. We will increase the start point in which whatever current index we are running, we will make it plus one, okay and whatever sum of our root we will make it zero, okay, now we will check it by running it to check the intake error. So it is not there, I forgot to put it inside this code and here too I have not put the semi collar. Okay, it is not there anywhere else. Okay, both my tests have been run successfully. Now I will submit this code. Okay, this code of mine is successfully submitted. It's done, if we talk about the time complexity in this, then if we look at the time complexity that we have, like, here we have just done it from here to here, okay, it is taking our time to run it. On Okay, this will be our time complexity, that is, if we talk about space, then we have to do any extra special, all this is constant space, so our space complexity will be over, so time complexity will be on, and space complexity will be o one. So this was our solution to the gas station problem of the gas problem person. If you liked our solution and found it helpful then like the video, share it with your friends and tell them the solution too and if you have not yet subscribed to our channel. Go and subscribe the channel immediately, see you with another video, till then bye.
|
Gas Station
|
gas-station
|
There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`.
You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations.
Given two integer arrays `gas` and `cost`, return _the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return_ `-1`. If there exists a solution, it is **guaranteed** to be **unique**
**Example 1:**
**Input:** gas = \[1,2,3,4,5\], cost = \[3,4,5,1,2\]
**Output:** 3
**Explanation:**
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
**Example 2:**
**Input:** gas = \[2,3,4\], cost = \[3,4,3\]
**Output:** -1
**Explanation:**
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.
**Constraints:**
* `n == gas.length == cost.length`
* `1 <= n <= 105`
* `0 <= gas[i], cost[i] <= 104`
| null |
Array,Greedy
|
Medium
|
1346
|
209 |
you guys as we've been doing this is chaser in this video I'm going to try to solve 209 minimum size of ERISA we're given a rate of M positive leaders and a positive in GS find the minimum then minimum length of contiguous sub-array minimum length of contiguous sub-array minimum length of contiguous sub-array which the sum which some is figure and were equal to s if there is none which and 0 mm-hmm I see and 0 mm-hmm I see and 0 mm-hmm I see so the minimum right ok so like for example get 2 3 1 2 4 3 we need to get some them up to 7 well 0 does not matter does it not satisfy huh this not good this is six not enough that's 8 okay we find a wise solution but with these four so we don't need to actually we don't need to before in there's no for the starting next to this is already enough right so now we start three so we actually just remove this - and we got 3 actually just remove this - and we got 3 actually just remove this - and we got 3 1 2 which is it's 6 it's smaller so 4 3 if start starting at 3 we need to push for in and you gotta be 10 and out of 4 we so we were 4 3 there's nothing we there's no more need to do so we remove 3 and we got 1 2 streets 1 2 4 6 7 ok so for 1 this is already 1 2 4 is already enough 1 2 4 is enough so actually we need to there might be a smaller case like 1/4 if this is bigger than seven then there will be a limit like we get first we get two and two three five okay two three one this is six enough two three one two so this is eight in spirit at seven so for studying x2 there's no need to do anything right we just moved to next starting X which is 3 and 1/2 is it starting X which is 3 and 1/2 is it starting X which is 3 and 1/2 is it possible that 3 1 is already a possible combination if it is already begin at 7 then this should be already stopped right so it's not possible so the only chance is this because the 7 because this combination is possible because of the new added to so this is only possible chance or this is possible right about 4 3 this is a 6 and not enough we add 4 now where we are satisfied and the weak should we stop any more numbers for 3 right so we go to 1 2 4 this is already satisfied so for one it's just stopped this cannot be 7 because he's 7 this criteria is matched by adding 4 so this cannot be okay so we remove one we got 2 4 so from these we can know this is a typical like as fighting with a proper right sliding in the problem so let's get see the minimum right minimum so mainland goes infinity and Karan then left eye redness equals zero net current sum equals zero so let's see we need to the start and end right let's start equals zero let n equal zero if that's the case then we need okay where should we start from the previous one okay I say just start with previous 1 is minus 1 right and then yeah and then I would say start with minus 1 or think piece as the starting next start this and add he then got here start here in that here right so start zero and zero it's nothing I think it's better we say start from zero and nf0 then each one okay mm or if you start zero and end at zero then the current length would be one right and input might be empty so I need to fit it in value case as you see the main name okay karin-sama customs one let me then who's karin-sama customs one let me then who's karin-sama customs one let me then who's having some this figure that's up here that is then what not it's not infinitely if the first one is big enough then I think we should return by the way to infinity I should be your first if moms see you spin your coochie - now this is start interval and then we - now this is start interval and then we - now this is start interval and then we need to move them around a part in this what the lungs men's end while this is well this is it and maybe mistake Koreans start from this but we haven't processed yet I'm sorry zero the current sound yeah so we haven't processed yet and we are meeting a new number here it means we should act current men's force equals one South was right and then we checked if karin-sama is bigger than the checked if karin-sama is bigger than the checked if karin-sama is bigger than the S or equal to s then the minute you smack me net and subtract it we start that's what if we spit in it then we should what you should not only update the M in them but we move the next one it means start move to the next one but this still this will still my this still might be enough right he usually maybe we could move here to go further so I think we should use too wild to update it and start one and need updates this son also so some equal subtract it with start Wow Carson is bigger and equal to and we will continue wheels do this continue continuously yeah until that current sound is not enough like we did hear me okay and finally we will return do you mean if it's infinity zero not so let's review our code based on examples at first to start at zero and end this the end zero it's okay we update them into one update the Santa - and it's not okay so we got to Santa - and it's not okay so we got to Santa - and it's not okay so we got to we move into to another two now we get eight right so it's bigger than it and then we update the main length start move to three one two come inside we'll subtract with two I should yeah these are problem I should do subtraction first and three two one got seven six so we will stop here and then we go to next for next four with your son okay it's only after we move three and then we got this is karin-sama seven this again so go to get the current is seven so you're not updating each over three and now we got two for right to four and finally we will move to the next three it's bigger so we will is three so if I did it now we get for three and then still smooth a bigger and a or equal to seven so we updated these should be yeah it should have worked there seems to be a oh I know what happened I forgot to update the end oh I think it should work right no mm-hmm why think it should work right no mm-hmm why think it should work right no mm-hmm why we output 1 2 3 4 5 it's college increase this 1 4 0 3 4 1 K we got 15 which is last one so it's pretty honest we did it I'll do 2 1 you'll be taught and start 0-4 uh-huh you'll be taught and start 0-4 uh-huh you'll be taught and start 0-4 uh-huh and then 15 with one for you this is 15 okay this one for is 450 14 I mean what happened this should be ass God okay finally we get it right cool this is sliding window solution for the time every time actually we will move the end further or move the restart further back so they will have no stopping for the interval and start one step back and you need to next step so worst case I think will be to end with a in our time it's variance we don't we didn't use any extra space so it's constant so that's it I hope you helped some about the Ray when something when we meet something like contiguous then it's a we just think about just sliding window if it helps okay studying's continuous sliding movement that's helped see next time bye
|
Minimum Size Subarray Sum
|
minimum-size-subarray-sum
|
Given an array of positive integers `nums` and a positive integer `target`, return _the **minimal length** of a_ _subarray_ _whose sum is greater than or equal to_ `target`. If there is no such subarray, return `0` instead.
**Example 1:**
**Input:** target = 7, nums = \[2,3,1,2,4,3\]
**Output:** 2
**Explanation:** The subarray \[4,3\] has the minimal length under the problem constraint.
**Example 2:**
**Input:** target = 4, nums = \[1,4,4\]
**Output:** 1
**Example 3:**
**Input:** target = 11, nums = \[1,1,1,1,1,1,1,1\]
**Output:** 0
**Constraints:**
* `1 <= target <= 109`
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 104`
**Follow up:** If you have figured out the `O(n)` solution, try coding another solution of which the time complexity is `O(n log(n))`.
| null |
Array,Binary Search,Sliding Window,Prefix Sum
|
Medium
|
76,325,718,1776,2211,2329
|
63 |
Yes, hello, this is Gary Niel, a developer child. The problem we will solve today is number 63, Unique Pass Two. There is a robot in the upper left corner. The robot can only move down or to the right. This robot has a separate mark in the lower right corner. The goal is to reach the desired destination. It is a matter of calculating the number of all possible paths from here to here. It is the same as last time, but the difference is that there are obstacles in the middle. There are obstacles that cannot be passed. Considering these, it is unique. The problem is to find one path. In the actual problem, the two questions are marked as work, and the path that can be passed is marked in English, so in the case like the picture, there are two cases. So, this path is called Now, in the case of the second problem, there is only one mother-in-law. To is only one mother-in-law. To is only one mother-in-law. To conclude, I tried to solve it and failed. Yes, I also looked at the solution and solved it. Nowadays, they are kindly explaining it. As shown here, the robot can only move down or to the right. I said you can, so every cell in the first row can only be reached from the cell on the left, like this picture, and the first column is just above the cell. You can reach it from the cell on the left or above it. So, from the cell on Yom 2 3 1, you can reach it from above and look at it from the left. If there is an obstacle in that cell will no longer be included in the path. In fact, I have kindly provided the order of the algorithm and solved it like this. Let's solve it together by following it as is. If there is an obstacle in the upper left corner of this grid, you probably won't be able to go. In that case, exclude it like this and if it is Yes, since we know that there is no obstacle, we are going to mark this place as having now passed. And to indicate the rows and columns, we will give Jeonghwa King columns and rows 2 and declare our west side. Now set it to 1. It says move forward, but now we are exploring the first row and the first English. If there is an obstacle, we will change it to English. If there is no obstacle, we will change it to work. So it will be the opening. If we go to the first column first because we are parents, 5 This is the first one. The place we have arrived at now is 0 or Ayeong 9 5 This is not an obstacle, but a number on the path that passed above it. If not, we will declare it as 0. If this is a verse, the obstacle in the grid that we have just arrived at is 0. If there is or is not 0, it is unconditionally work, so there must be an obstacle. Or, since the 1 day above is not work, it is 0, so we are only considering the first 10, so 0 before means that there was an obstacle, so if it is used excessively, put 0. The same Logically, I 'll give the first row the same way. I've 'll give the first row the same way. I've made it come out only when the arrived row is 0 and the previous cell e is 1. Oh, then just wait. For example, the first column and first row are all depending on whether there is an obstacle or not. Now it's confirmed. From then on, you can just rotate like this from here. Of these, I use spring to rotate. Then, if the grid I've arrived at is 0 or a place I can pass through, I'll do something and the location I've arrived at will be more 0. Otherwise, because it is work, it means that it cannot be passed, so the distances reached are marked as 0 and cannot be passed. The value of the grid that has arrived now is 0, which means that it can be passed, so when you arrive here, the value above and the value on the immediate left are displayed. All you have to do is add up all the values. So, you can do this, the value right above it, and the value right next to it, like this. In the end, what you need to add in this function is the value here. The sum of all the possible paths is right here. Therefore, you can see that you passed the example and the problem as well. If you look at the solution card, it is actually this video. If you watch this, you will have a much better chance. I also failed problem number 2 and solved the solution. Today's video is That's it. I'll see you in the next video. Thank you.
|
Unique Paths II
|
unique-paths-ii
|
You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time.
An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle.
Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.
The testcases are generated so that the answer will be less than or equal to `2 * 109`.
**Example 1:**
**Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Output:** 2
**Explanation:** There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
**Example 2:**
**Input:** obstacleGrid = \[\[0,1\],\[0,0\]\]
**Output:** 1
**Constraints:**
* `m == obstacleGrid.length`
* `n == obstacleGrid[i].length`
* `1 <= m, n <= 100`
* `obstacleGrid[i][j]` is `0` or `1`.
|
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1]
else
obstacleGrid[i,j] = 0
You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem.
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j]
else
obstacleGrid[i,j] = 0
|
Array,Dynamic Programming,Matrix
|
Medium
|
62,1022
|
84 |
Hello friends welcome back today we are solving largest rectangle in histogram problem first we'll start with reading the problem statement and then we'll look at some examples next we'll discuss the Brute Force approach to solve this problem that has the runtime of ofn Cube and we'll optimize this Brute Force approach to make it an of N squared algorithm and we will optimize it even further to make it a linear time algorithm which is the most optimal solution and finally we'll write the python code for the linear time algorithm let's get started given an array of integers Heights representing the histograms bar height where width of each bar is one and we have to return the area of the largest rectangle in the histogram here is an example input array Heights where each element represents height of a bar in the histogram this input array represents for example five is height of the bar at index 2 in this histogram we have to find the area of the largest rectangle let's look at some of the rectangles that are present in this histogram here is one rectangle whose area is 2 * which is height of the area is 2 * which is height of the area is 2 * which is height of the rectangle and four is the width of the rectangle which is 8 here is another rectangle where height of the rectangle is 1 and width is six so the area is six here is another rectangle where height of the rectangle is five and width is two so the area is 10 which is the largest rectangle possible in the given histogram and that's the right answer let's look at the Brute Force approach to solve this problem here I have taken a different example and the largest rectangle in this histogram is this and the area of this rectangle is 2 which is the height of the rectangle and five which is the width of the rectangle so the area is 10 The Brute Force way of solving this problem is to look at all the index pairs for example 0 and one is one index pair 0 and two is another index pair and three is another index pair so on and so forth let's look at the pair 0 and two these indices act as the left Edge and the right edge of the rectangle next we go through Heights of all the bars within this range and we find the minimum height among them for example in this pair 0 and two the minimum height is three among 3 4 and five and that will be the height of the rectangle formed by the index 0 and 2 so we can calculate the area of the rectangle formed by these indices 0 and two as minimum height multiplied by the width where width is Right index minus left index + 1 because each bar has width of index + 1 because each bar has width of index + 1 because each bar has width of one so the area is minimum height in that range multiplied by the number of bars and we repeat the same for all the other index Pairs and finally return the maximum area so in total there are N squared such Pairs and for each pair we have to find the minimum height which takes off n time so the total runtime complexity of this approach is of n Cub we can optimize this Pro Force approach to make it an off and squared algorithm by making a simple observation which is each bar can act as a minimum height for some rectangle what does this really mean let's consider this bar of height three this bar is the minimum height of the rectangle formed by just the index zero it is also the minimum height for the rectangle formed by index 0 and 1 it is also the minimum height for the rectangle formed by the indices 0 and two similarly if we consider this bar of height four this bar is the minimum height for the rectangle formed by just the index one this is also minimum height for the rectangle formed by indexes 1 and two finally let's consider this bar of height two where this bar is the minimum height for the rectangle formed by just the index 3 this is also the minimum height for this rectangle it is also the minimum height for this rectangle and it is also the minimum height for this bigger rectangle so what we are seeing here is we can keep extending either to the left of the bar or to the right of the bar as long as height of its left bar or right bar is greater than or equal to the minimum height so the simple optimization we can do here is consider each bar as the minimum height and keep extending to its left and to the right until we find a bar whose height is less than the height of the minimum bar and that will be the largest rectangle that can be formed using this bar as the minimum height so the area will be minimum height which is the height of the current bar multiplied by r - L + 1 which gives the number of bars r - L + 1 which gives the number of bars r - L + 1 which gives the number of bars in the current rectangle so there are total n bars in the given input array and for each bar we extend to the left and to the right until we find a bar whose height is less so that takes off end time so the total run time complexity of this optimized approach is of n² next let's look at optimizing this further to make this a linear time algorithm in the previous approach for each bar as the minimum height it takes of end time to find the left Edge and the right edge of the maximum rectangle with this bar as the minimum height we have to reduce this from ofn to of One Time by that I mean for each bar as the minimum height we need to find the left Edge and the right edge of the maximum rectangle formed using this bar as the minimum height in of one time constant time the way to do that is using monotonic stack where we store the Heights in the increasing order let's look at how this works we start from index zero and the stack is empty for this index so we add this bar to the top of the stack so height of the bar is three and index is zero next we go to index one since the height of this bar is greater than height of the bar at the top of the stack which is three so we add this bar to the stack height is four and index is one next we move to index two similarly height is greater than height of the bar at the top of the stack so we add five to the stack five and two next we move to index three all we have done so far is we keep adding the bars to the stack as long as height of the bar is greater than the height of the bar at the top of the stack we do this because if we consider this bar at the top of the stack as the minimum height to find the left edge of the largest rectangle that's formed using this bar as the minimum height we just have to look at the previous bar in the stack because these bars are in the increasing order of heights so the previous bars height is definitely lower and that forms the left edge of the largest rectangle and we can do this in o one time coming back to the algorithm we are at index three and height of the bar is two is less than five which is top of the stack so this bar at index 3 will form the right edge of the rectangle formed using the bar at the top of the stack as the minimum height so the left edge of the rectangle formed using the bar at the top of the stack is the previous element in the stack and the right Edge is the current bar because its height is less so the bar at the top of the stack is five and its left Edge is the previous element in the stack which is this bar and Its Right Edge is the current bar which is this so the rectangle formed using five as the minimum height is just this so the area of the rectangle is five which is height of the bar at the top of the stack multiplied by right Edge which is a current bar whose index is three minus the left Edge which is the previous element in the stack and its index is one since we cannot include the current bar of height two in this rectangle we subtract one from the width so the total area is 5 * 1 which is five so we can area is 5 * 1 which is five so we can area is 5 * 1 which is five so we can remove this bar from the stack now so the new top of the stack is this bar four so the current bar has height two which is lower than the bar at the top of the stack so the current bar will be the right edge of the rectangle formed using the bar of height four and the left Edge is the previous element in the stack which is the bar or here and the rectangle formed using this bar of height four as the minimum height is this and the area of this rectangle is the minimum height which is 4 multiplied by right Edge which is 3 minus the left Edge which is 0 minus 1 because we cannot include the current bar in this rectangle which is equal to 4 * 2 is rectangle which is equal to 4 * 2 is rectangle which is equal to 4 * 2 is 8 now we can remove this bar from the stack now the bar at the top of the stack is three and the current Bar's height is lower so therefore the current bar will be the right Edge and the left Edge should be the previous element in the stack since the stack is empty we consider the previous element as minus1 so minus1 will be the left Edge and the rectangle formed is this so the area of this rectangle is minimum height which is three multiplied by the right Edge which is 3 minus the left Edge which is -1 and we subtract minus1 because we -1 and we subtract minus1 because we -1 and we subtract minus1 because we cannot include the current bar and the area is 3 * 3 which is 9 now we can area is 3 * 3 which is 9 now we can area is 3 * 3 which is 9 now we can remove this bar from the stack as you may have noticed already for the bar at the top of the stack as the minimum height we can find the left Edge and the right Edge in just constant time which is of one now that the stack is empty we can add the current bar to the stack whose height is two and index is three next we go to index four height of this bar is six which is greater than the height at the top of the stack so we add this bar to the stack height is six index is four next we go to index five height of this bar is 1 which is lower than the height of the bar at the top of the stack so this will be the right Edge to the rectangle formed using the bar at the top of the stack so top of the stack is this bar of height six and the right Edge will be the current index and the left Edge will be the previous element in the stack which is index 3 so the rectangle formed is this and the area of this rectangle is the minimum height which is six multiplied by the right Edge which is 5 minus the left Edge which is 3 - which is 3 - which is 3 - 1 and the area is six we remove this bar from top of the stack so the current top of the stack is this bar of height two again the current bar has height one and it forms the right Edge so the right edge of top of the stack is this and there is no previous element in the stack so the left Edge would be Min -1 and the rectangle formed here is this -1 and the rectangle formed here is this -1 and the rectangle formed here is this so the area of the rectangle is the minimum height which is 2 multiplied by the right Edge which is 5 minus the left Edge which is -1 and Edge which is -1 and Edge which is -1 and minus1 is equal to 2 * 5 = minus1 is equal to 2 * 5 = minus1 is equal to 2 * 5 = 10 and this is the largest rectangle now we can remove this bar from the stack since the stack is empty now we can add the current bar to the stack height is one and index is five since this is the only element left in the stack Its Right Edge would be n in this case six and left Edge would be minus1 so the area is minimum height which is 1 multipli by right Edge is six left Edge is min -1 and Min -1 and Min -1 and Min -1 which is equal to -1 which is equal to -1 which is equal to six and the rectangle formed is this and we remove this from top of the stack so that's our final algorithm the Run time of this algorithm is Big of N and the space time is also big of n because we are using a stack to simplify the edge cases instead of starting with an empty stack we add height of zero and index minus one to the stack so now we never have to worry about stack being empty and to find the left Edge we can just look at the previous element in the stack and to handle the edge case for the right Edge we just add another element to the input array Heights whose height will be zero so let's write the code for this algorithm as we discussed at the end of the last segment to handle the edge cases we add an extra bar of height zero to the input array so Heights a pend zero and in instead of starting with an empty stack we start with a stack that has a bar of height zero at index minus one to handle the edge cases again and we save the max area in this variable let's iterate through the given input array for I in range of length of heights we need to check if this forms the right Edge so the current height is height of I while current height is less than height at the top of the stack where stack minus one is the top of the stack and the first element is the height in this case the current bar at index I will be the right Edge the first we pop This Bar from top of the stack because we found its right Edge and the left Edge so stack. pop first element will be bar height and the second element will be bar index and the left Edge will be the previous element in the stack which is stack minus1 which is new top of the stack and the second element will be the index so the current area is equal to height of the current bar multiplied by right Edge which is a current index minus left Edge minus one and we update Max area equal to Max of Max area and current area once we have removed all the bars whose height is greater than the current bar we add the current bar to the stack current bars height and the index finally we return the max area let's try to run this code as you can tell this is the most optimized approach if you found this video to be helpful please support by liking the video and subscribing to the channel I will see you in the next video thank you
|
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
|
386 |
hey guys today we will be solving a problem called lexicographical numbers it says given an integer n return all the numbers in the range of one n inclusive sorted in let's say order is the same order that you guys see in a dictionary and for numbers it would be the smallest number comes first and uh if this first number is same go to the second number and zero is lesser than one similarly for one and two and uh for 13 all the two three four and five are at the end because you know they have one in the beginning so obviously uh so the easiest method that comes to my mind is that i can stringify all these numbers and solve them because string sort internally has uh the same lexicographical sorting but here there's a catch they want us to write an algorithm that runs in big of end time and uh sorting at the best efficiency would be n login and uh connections.sort in java also uses connections.sort in java also uses connections.sort in java also uses merge sort which is again n login so but you know i will still give it a try because to just show you what i am meaning to say here let's say i call this nums this is a new arrow list that i have created here i'll start from i'll start my things and i keep incrementing and here it should be inclusive what i'll do is what i do string dot value and i'll do num start add this is certainly going to take care of you know converting my string my integer string so once i've added this what the very simple thing that i need to do here is collections dot sort and i can supply nums the problem is i have to give it back in the list of integers so i would have to you know cast this as you know either i'll just map everything so let's say integer parts and collections connect connections uh that is tool list oh sorry it's collectors um yeah this should work let's just try to run i'm pretty sure it would fail for some of the cases since they explicitly want us to run in big of end time and use figure one yeah it passes the sample test case of course but let's submit i'm pretty sure we'll say timeline exceeded for a few oh wow it kind of uh worked but we are uh really bad on time because we are just faster than 18 of the submissions for java so let's just do one thing let's try to optimize this so uh if i go to so yeah it says surprising so uh let's just try to optimize this uh if i start printing all the numbers starting from one and okay here's a good catch so uh any number starts from one you'll have to multiply it by ten and maybe let's say the input here is uh 1000 to 234 what we'll do is this is the order and then we start incrementing one in the least uh important bit of the number and this goes all the way to 1009 and now what we have to do is we need to start incrementing the second digit okay yeah here's a pattern now we go all the way to nine now the previous digit was two uh one so now we need to make it two oh yeah here's a pattern here's a catch again all the way but the problem is once we reach this stage okay again just notice the pattern for this one as well once you figure out there's a nine and the previous digit is nine as well you go to one previous one so here there are a lot of numbers you print one zero and then you start the same what the logic that we sort of did here start with the lowest precedence uh number check if it's nine or not and uh just if it's nine just go to the previous one increment and make this one zero so this should work so let's you know sort it out uh so the best thing about this is this would require just one iteration so i start at 0 i don't know why i remove that for loop and we'll go to n so here i don't need to increment i don't need to start at one and end at n i can enter n minus one because i'll still be printing n digits here i'll also have to keep number two print i will start from one i'll just copy this because there's no autocomplete and uh so if number to complete the number to print is less than or equal to n we should print it or no let's just not print it because we need to return it in the list of integers let's just call it nums list and once we are done with this so what we'll do is we'll do a num start add and once you've added the number to our you know sort of the list that we are maintaining what we need to do is we need to increment it sort of this would run for every uh line of code and what we need to every follow payment uh now what we need to do is we need to check if the number okay this is number two number to add can be multiplied we multiply it by 10 yes this okay we need not check if it's less than equal to 10 because it doesn't be equal to n uh i think it'll be a problem let's just not add this condition here because we need to handle a lot of conditions here so let's say we added and multiplied by 10 less oops less than equal to m what we do is numbers to add easy or multiply equal to 10. so now we have sort of you know incremented the value by 10 and we of course it can also be uh you know less than uh less than that number that is anyway gonna get sorted because as we keep moving forward but in case it is not we also need to add that condition there for ones and twos and all of those numbers so sort of let's can we add another if you're you need to check for those numbers as well so if uh you know number two and so now we've already multiplied by 10 so the next for loop that it comes to uh so let's say if we are if we arrive to thousand we do not want to go to 10 000 but want to come at 1001 because 10 000 is out of what we have started with for reference this is n so we need to eliminate this so that elimination will already be done here we'll come to else loop we'll come to plus one and uh again this is less than n if yes uh i just don't need it here yep i'm good and in case oh one thing this uh this cannot be sort of uh this okay i do not need to add here because i'm adding generic you know for loop so what i can do is i can just do a plus and uh the thing that i need to do here is i need to check and if the digit is not nine because the moment i start adding a ninth digit i would need to have an explicit handling the same thing that i told you here we need to be shifting uh we need to be making it zero and we need to increment the previous one so what we need to do here is uh sort of if uh if number percent nine equal to nine if okay and else uh for this else block what we need to keep doing is i'll have to have a multi-line statement here so i multi-line statement here so i multi-line statement here so i just keep omitting that uh number to add i just keep dividing it by 10 until unless i reach a digit that is not 9 in itself i'll what i'll do is number to add divided by 10 uh and sort of take this i just get a remainder and uh if this is equal to 9 then so this is sort of complex so uh so while the number to add divided by 10 in this case uh it was 119 the last digit is nine we sort of have to uh drop nine and i need to have an explicit handling here because now we need to you know start moving the other way around so to move one bit what we do is we have number to add we which is divided by 10 that is a very easy operation there and now since we kept on removing one digit at a time now we just need to finally update the number which would be now the number itself divided by 10 uh and we since we were doing a increment here itself we are also going to do an increment we just divide and yeah this will get added all over again so now we just need to sort of figure out the return statement let's try to run this with at least a sample test case oh wonderful good let's see if we are better in the run time boom you see the difference n log n versus week of n our code which was 18 percent uh more efficient than the rest of the java submissions is now six almost 61 so quite happy with it so do let me know in case you face any problems and uh i'll definitely love to take it up in comments just uh drop in a comment how you like this video or if you want me to focus on smaller ones as i see that there is a lot of some bit of logic here just in case you feel you're stuck just to drop in a message on my instagram or my twitter i'm quite active there as well thank you so much guys for watching this
|
Lexicographical Numbers
|
lexicographical-numbers
|
Given an integer `n`, return all the numbers in the range `[1, n]` sorted in lexicographical order.
You must write an algorithm that runs in `O(n)` time and uses `O(1)` extra space.
**Example 1:**
**Input:** n = 13
**Output:** \[1,10,11,12,13,2,3,4,5,6,7,8,9\]
**Example 2:**
**Input:** n = 2
**Output:** \[1,2\]
**Constraints:**
* `1 <= n <= 5 * 104`
| null |
Depth-First Search,Trie
|
Medium
| null |
497 |
hey guys this is Dean uh I'll be covering all the questions from the earth 30 days challenge playlist and this questions uh this question consist of uh 100 to 90 questions of from top six companies like Google Microsoft Goldman Shacks Amazon and different companies uh so I'll be covering all these questions I'll be talking about the most Brute Force optimal and the most optimized solution so that I can uh provide the overall thinking and I will also share my Approach and intuition that will help you uh to think uh the question in every aspect so think about the question in every aspect so I will be starting with Microsoft because I think Microsoft does have uh more tricky questions than Goldman Shacks I haven't completed it yet there are some question which I have completed and yet to be uh marked as done but uh I haven't completed it test and there six to five questions are still left but I will be covering those also so I will start with this random point in non-overlapping random point in non-overlapping random point in non-overlapping rectangles why I'm starting from here because uh some certain questions required a bit of thinking I think certain questions required a better thinking or you can say it requires more of a dive into the in intuition game so what I will do I will start uh from I will pick four to five questions and put them in one video those questions are really easy and that doesn't require much of a thinking but if some question require much of like flip Matrix a maximum of two arrays or there was this maximum some BST these questions required a bit of uh more intuitions more intuition so I will cover them in a separate video and in those video I will talking about the brute optimal and the most optimized way of solving all these questions so stick around and uh let's start with it so I will be covering only this video because I'm starting this pis and I want to start on a good note like you can digest the questions also and also it will be really helpful uh I can say it is a very good uh way of starting this whole playlist because this question is not that difficult but it has some tricky points in it so I'll be starting this question yeah let's begin I'm hiding this because let's say I don't want to spoil this question for you I want you to think uh think about it and you can pause the video to think about it so here are given uh I will be talking in both Hindi and English so that majority of the audience can understand it so you given array of non overlapping axis line rectangles where re of I means a of I comma B of I comma X of I comma y of I indicates a i comma b i of the bottom left corner and of the I rectangle and x i comma y on the top right corner of the I rectangle basically this and this point so there is a which consist of non-overlapping non-overlapping non-overlapping rectangles those rectangles are not overlapping they're not overlapping but also they are axis aligned that means they are not rotated or shifted they are axis aligned okay so you can say that if the length of the rectangle is following the y- axis the width of the following the y- axis the width of the following the y- axis the width of the rectangle will definitely follow the x-axis that's I can say the rectangle is x-axis that's I can say the rectangle is x-axis that's I can say the rectangle is not like this they are not rotated okay the rectangle is not like this about the x-axis okay is not like this about the x-axis okay is not like this about the x-axis okay so we can say that is called axis aligned okay then design an algorithm to pick a random integer Point inside the space covered by one of the given rectangles a point on the perimeter of the of a rectangle is included in the space covered by the rectangle they are saying basically we have to design a random algorithm using the random function obviously okay there's one thing lit code hasn't mentioned that it has to be uniform okay they haven't mentioned that it has to be uniform I think this is why a lot of people fail in executing this problem because I will talk about it more but have to find you can see uh in so we have to find a we have to randomly print a point which is inside the space covered by this rectangle SP in the coordinates in the whole coordinate Universe I can say these rectangles are there and you have to pick out those points which are inside one of these rectangles any integer Point inside the space covered by one of the given rectangles should be equally likely to be returned okay note that an integer point is the point that has integer coordinates obviously we can't go for decimal point because they infinite points implement the solution class solution in this solution class basically create the rectangle this basically this will give us the rectangles all the rectangles not create all it will give us all the rectangles and int pick will the with the solution which will return the X and Y values you can see there is no mention of uniformly returning what does I mean by uniform returning let's say uh there are n rectangles okay no not talk let's uh break it down with let's say there are two rectangles this will be more visually appealing and this will be easier to understand the first one is A1 and the second one is A2 this rectangle is much more bigger than this one hence it will have more points and this one will have less points now you will be saying yeah obviously it is smaller but the question never said that we have to return a point which is uniformly in both of this rectangle rectangles that means let's say A1 and A2 let's say A1 is here and A2 is here they are covering certain areas right they're covering certain areas right the probability of picking between these two rectangles is 1x two obviously what I want to say that if I'm going to uniformly bring uh any of this so what there is no mention of uniformity so what an what uh a normal person will do he will think okay I can pick any of randomly I will pick any of uh these rectangles randomly picking between A1 and A2 but hey what is the probability of picking randomly A1 and A2 that is 1 by two right okay I'm picking 1 by two that's cool but as I said A1 consists of n particles or I can say l coordinates but I'm talking um let's uh consider each coordinate as particle n particle and A2 consist of M particles and we know n is greater than M because area of A1 is greater than area of A2 so what will be the probability of picking uh one particle from n particles one particle from n particle it would be obviously 1 by n similarly for 1 from m equal 1 by m right now if I'm am doing uh if I'm uh randomly selecting any of this rectangle then probability of picking one particle from n equal to 1x 2 into 1 by n isn't it like it would be 1x2 into 1 byn right makes sense yeah like first off we have a probability of picking s A1 as 1 by two and the probability of picking one en from n elements is uh 1 byn total probability will be 1x2 into 1 by n similarly for A2 it will be 1x2 into 1 by m so if a normal person will try to uh create this solution and by normal means person like me obviously so 1X 2 into 1 byn this is the mistake I genuinely did that's why I'm saying 1x2 into 1 by n and then 1X two into 1 by m ha this is the solution lead code wants this right because they never mentioned it they never mentioned that I have to pick it uniformly and what does I mean by uniformly means the probability of picking one element from n should be 1 by K which should be equal from 1 out of M how can we do that this is what uni family means and when I uh submitted this solution by making sure that I am picking at a uh constant probability each elements are at constant probability my solution got AC what I'm saying about is Let's uh it depend the probability depends on two factors size of uh rectang if the size are equal then it's okay because n will be equal to M and then 1X 2 into 1 by n = to 1x 2 into 1 then 1X 2 into 1 by n = to 1x 2 into 1 then 1X 2 into 1 by n = to 1x 2 into 1 by m that is okay that doesn't if the size of the rectangles are okay that's why it will give AC on certain cases but if the rectangles are of uh different sizes then we have to uh consider this solution and it is not mentioned in the lit code question and I don't know why they don't mentioned it but it is a pretty common maybe this is the reason uh this question is counted as a medium question unless it would be counted as a easy question okay the size of rectangles does matter the probability depends on the size of rectangle and also which one I'm choosing what I'm doing is that let's say there are K rectangles and I'm randomly choosing one of them that would give me a 1 byk probability and it will multiply to the 1 byn the light is the number of elements but instead of choosing randomly that 1 by K why don't I say you will understand this with better ex you will understand this better with examples let's say A1 has a area of 70 and A2 has a area of 30 why don't I make it that the bigger area get selected first get selected more like the probability of get selecting this uh A1 square is more sorry A1 rectangle is more compared to this A2 instead of randomly picking from the array of rectangles 1 by K that like k rectangles and randomly picking 1 by K what I'm saying is instead of randomly picking I am providing a different probability for different rectangle that is I'm giving a different probability to this rectangle and different to this one depending on their sizes this will come as a trade-off okay this will make sure that trade-off okay this will make sure that trade-off okay this will make sure that when I'm so what I'm doing the probability of choosing this rectangle will become 70 by 100 and the probability of choosing this rectangle will become 30 by 100 okay that makes sense right that makes sense that is 7 is to3 they are in the ratio okay so this will uh and the number of uh so what will there are total 100 particles let's say 70 will be from this one and 30 will be from this one obviously their area this is why I'm saying that examples help uh helps more by 7 uh 1X 70 there are 70 elements 1X 70 and breaking from 1 uh 30 element that would be 1X 30 this seems pretty easy to deduce right like w okay but that may that made the probability of picking any element equal constant and it can be done using so concl what the conclusion create an algorithm the better question should be create an algorithm so that we pick squares depending on their sizes and then return any coordinate this seems like pretty logical now like instead of going from 1X two into n or 1X 2 into M we are going 1 by K because we are not choosing 1 by two let's say here it is two because we have two elements it can be 1 by n or let's say different elements uh different name not n it can be uh Alpha okay 1 by Alpha not two alpha okay so if it is sorted I will suggest you uh to do it on pen and paper and try out some examples that will really help because it helped me so we did that okay now the solution should give AC the optimal approach is what I mentioned not the where not the one where we were picking randomly from the array of rectangles so that was it because the coding part is much easier so what we will do in yeah there is one more thing okay so how we will the algorithm okay the algorithm is easy but it may be difficult for some people because uh they may be struggling with deducing the probability Factor so it may be difficult for them but when you will see the algorithm I think most of your difficulty most of your problems will cease to exist okay the algorithm so instead of picking it like this each rectangle is like so why don't we pick why don't we create a slab of rectangles let's say the first array the first rectangle of 10 size the second rectangle of 20 size total array total size 30 third rectangle again of 10 five size okay fourth rectangle 30 fifth rectangle 30 again and then again of 10 size okay why will slap this slab will help us let's say we will create a prefix sum of this whole Vector so the slab will be like 10 this sign is like I'm merging both of them the slab will become 30 here merging 35 merging why am why I'm not doing it in a typical perix sum way because it will be much easier uh to visualize in this way now because it 35 and that will be wait sorry 65 another 30 95 another 10 105 so our uh our function our algorithm should uh give out the probability in this fashion like the biggest rectangle should have more probability to go out here the biggest rectangle is of 30 siid and there are two of them okay the probability should be 30 out of the sum of the rectangle okay the should be like this okay that does make sense all right so how can we do that we are what 30 out of the sum of all rectangulars so this way what we can do is why don't we just look into our slab hey let's say the sum is 105 hey let's randomly pick a number let's randomly uh random function is breaking a number and let's say it is 13 which number is just greater than 13 in this array just greater than 13 it started with 10 then it 30 this number is just greater than 13 right okay this number is just greater than 30 so if this number 13 that does mean the point which I'm looking for lies in this area right the point which I'm looking for lies in this area what does I mean let's say the random number is 61 the number just greater than 61 is 65 which means the number I'm looking for lies here somewhere around here okay the number I'm looking for lies here which means in this block if I will say uh please give me a number so I will create this in a better fashion so that it's not confusing 10 30 35 65 95 and 105 so let's say I will say 61 this mean it lies in here because from 35 to 65 there is one block this block has 30 elements in it so if you think about it this makes a lot of sense let's say the number comes out to be 91 it will lie here between 65 to 91 so which block is in the uh position of 65 to 91 the 30 size block again and it covers the maximum range right maximum range this definitely means like uh it if it's covering the maximum range this mean the probability of getting this number the number from 65 to 95 is higher right because it has 30 elements in it 30 because the hence the probability will be increased the probability from getting 65 to 95 is definitely more as compared to getting from 10 to 30 because there are 20 elements now we can see our algorithm does make sense oh we can just create a slab of uh rectangle areas and just pick any random value and depending on that ROM value will create because this is a prefix array and depending on this random value we can find the uh value just greater than the random number in login because it is a prefix array and we can use bind research on it okay that makes a that makes so much sense now like this is the oh this pen this is the array and it has areas in it this area like this area then this area the probability of finding a number in this area is Hell more than this and this so if I create a random function let's say R equals to Rand mod sum of total area so total area the probability of getting in this part is more than this oh sorry is more right that what I wanted to make algorithm such a manner that the bigger area get picked out most that it get picked out most of the time and it is uh picked out more than this and this hence we can just now the algorithm becomes like create a Prix array of rectangles prefix array of rectangles area and do a binary search on each random number which you just picked the just greater value can be calculated with upper Bound in login time and you will choose that rectangle to print the sum print the coordinates this is a question this question was not giving AC to a lot of people because what we were doing we were picking out areas in 1 by K that K is the number of rectangles this is wrong we have to pick area based on their sizes sorry we have to pick rectangle based on the sizes based on their area that's why what we did is we created slab of rectangles which is consisting of all the total sum of the areas in a manner that it is in a prefix sum so a rectangle which has bigger uh bigger Dimensions will be picked more as compared to the rectangle which is uh lesser which has lesser Dimension than it so the typical solution is like create a prefix some array and then do a Rand function on it and if once we get the rectangle it is pretty easy like we can create a Rand from this uh value of XX this value of x to this value of x and this value of y to this value of y we can just create a random we can get all the coordinates in this part and we can get all the coordinates inside this area that would be the easier part again what I'm basically doing is creating a temporary array temp array what it does it just stores some of areas it's like prefix sum let's say the areas of each rect is 5 4 6 8 so the first area came out to be five the sum was Zero the sum becomes five then the next area comes out to be four the sum becomes N9 the next area comes out to be six the sum becomes 15 and the next area comes out to be eight the sums become 23 and we'll be keep pushing those these areas inside the array the 5 9 15 23 now our next work is find creating a random variable on this 23 the Rand of mod 23 will give 10 values let's say it gave me 14 so it means that it lies in here the just greater than value let's say it gave me 14 which means it Li in this the third rectangle and its area is 15 so what I will do I will take that rectangle that is I will take the index so what and the index can be found using upper bound so idx equals to Upper bound from uh in the whole array area do begin you know what way we do this right area dot end and finding that Rand variable upper bound minus area do begin why we do minus because we need to because the upper bound will point it will provide the pointer to that value but we need a integer index so that's why we subtract it from dot begin because these are iterator terms and that why we and I need an integer term integer variable integer value sorry and that's why I do it with idx I ant idx equals to now I got the rectangle so in the rectangle array I have idx I got it and now I will print out X and Y this question is not that difficult the main question is like how are you going to uniformly pick out the rectangle picking out the rectangle is the main gist of this question and that's it now I will code it so okay uh let's code it so what were we doing we created a temporary area vector just a second my keyboard had some issues okay yeah so what were we doing we created we will create a temporary area Vector let's give it a name as area and we are also creating a vector of rectangle Vector for rectangle because we can't access uh this rectangle everywhere right we need to store it somewhere so what we will do we'll create a vector of vector int rectangles okay now rectangles the name is too big I don't prefer such name that's why I'm only giving it rect will be a perfect name okay the rect equals to rects we just copying the rectangle and for each rectangle for auto it correct what I'm doing is just oh we also need the total area sum right so total let's say In Sum equal Z so we'll create the cre we'll find the area so let's say I AR equals now finding the area is simple okay finding the area is simple we know in description AI is the first coordinates and XI is the second coordinate okay so we'll do abs of it of 2 minus it of 0 because 2 is our second x coordinate + because 2 is our second x coordinate + because 2 is our second x coordinate + one into abs of it of 3 minus it of 1 + 1 this will of it of 3 minus it of 1 + 1 this will of it of 3 minus it of 1 + 1 this will give us the area we will save this area in our area Vector area do push back AR we will keep uh pushing those areas and it will create the prefix some areay also okay we did that now let's come to the pick section in the pick section what we were doing is uh taking the last element that says in temp equals to area do back and creating a random fun random variable R&D finding the random variable R&D finding the random variable R&D finding the random variable equal to Rand of modulo temp we were also doing finding the ID index so idx equals to Upper bound area do begin comma area dot end minus area oh we also need to put our R&D because that is our variable R&D because that is our variable R&D because that is our variable right minus a area dot begin this will give us the index of that particular rectangle which has the area just greater than our random variable now if we get our uh so if we got the index we just need to find we just need to create uh Vector to for that particular rectangle Vector temp R equals to or let's say we haven't used R anywhere right so R equals to rect of idx that's why I created a temporary re uh rectangle variable that I can access it in both functions okay so Vector int R equals to re of idx that was it okay X and Y variable so ntx will be Sim L like uh this one I have to create a random in this total sum so I'll just copy it so it's like Rand of in this particular distance plus r of zero is it good task just return X comma y let's run it and oh I sorry how can I do this it would be R obviously this should give right answer okay let's submit it and it will get submitted the problem is not that hard I will say it is not that hard the just H okay the mistake was pretty evident I didn't summed it up and I need to push some right because AR is the current area not the total now this should work definitely you can see why it failed right because I'm pushing the current area and that will ALS that will create problem uh because the probability is now 1 by n total number of rectangles also the upper bound must be working wrong because it was not in sorted order but now this should definitely get submitted the question itself is not hard the approach is really great okay the approach is this approach is really great but if you do the uh 1 by n term it will stuck and that may be the reason why you're watching this video because it has stucked or maybe you wanted to uh know the approach behind it but yeah it will get stuck if you are using that uh the ideal solution like let's say we are picking any Rand picking any rectangle randomly that will provide errors I don't know why LOD didn't add the term or they could have used examples to show that you have to pick uniform answers it's okay so we'll see you in the next one uh the next question would be overlap circles and rectangle okay I will what I will do because this question is easy I will pick this one into who is the winner uh I don't remember yeah this question is very intuitive I will pick this one and uh IMS smoother is I don't think you I require a video on it because it's a pretty easy question so I will pick overlap Circle and rectangle along with uh minimum moves to equal a elements in one video and I'll be covering them next then we will go for envelop and dos and uh and then we will start and we will then first we will complete Microsoft then we'll go for bulls and cows and that in that order and then we will go for Goldman Shacks thank you for watching
|
Random Point in Non-overlapping Rectangles
|
random-point-in-non-overlapping-rectangles
|
You are given an array of non-overlapping axis-aligned rectangles `rects` where `rects[i] = [ai, bi, xi, yi]` indicates that `(ai, bi)` is the bottom-left corner point of the `ith` rectangle and `(xi, yi)` is the top-right corner point of the `ith` rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle.
Any integer point inside the space covered by one of the given rectangles should be equally likely to be returned.
**Note** that an integer point is a point that has integer coordinates.
Implement the `Solution` class:
* `Solution(int[][] rects)` Initializes the object with the given rectangles `rects`.
* `int[] pick()` Returns a random integer point `[u, v]` inside the space covered by one of the given rectangles.
**Example 1:**
**Input**
\[ "Solution ", "pick ", "pick ", "pick ", "pick ", "pick "\]
\[\[\[\[-2, -2, 1, 1\], \[2, 2, 4, 6\]\]\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, \[1, -2\], \[1, -1\], \[-1, -2\], \[-2, -2\], \[0, 0\]\]
**Explanation**
Solution solution = new Solution(\[\[-2, -2, 1, 1\], \[2, 2, 4, 6\]\]);
solution.pick(); // return \[1, -2\]
solution.pick(); // return \[1, -1\]
solution.pick(); // return \[-1, -2\]
solution.pick(); // return \[-2, -2\]
solution.pick(); // return \[0, 0\]
**Constraints:**
* `1 <= rects.length <= 100`
* `rects[i].length == 4`
* `-109 <= ai < xi <= 109`
* `-109 <= bi < yi <= 109`
* `xi - ai <= 2000`
* `yi - bi <= 2000`
* All the rectangles do not overlap.
* At most `104` calls will be made to `pick`.
| null | null |
Medium
| null |
109 |
hi everyone in this video we are going to solve a problem the problem name is convert sorted list to Binary and the pro number is 109 all right so guys first of all we are going to clearly understand what this problem says after that we are going to move to the logic part and after that we're going to implement our logic C plus Java and Python programming language fine now let's see what this problem is so this produce is given the head of a single link list so we are given the head of a single linked list here elements are sorted in the sending order that means our single linked list in a sorted order in a sending order right convert it to height balance minus St now this single link list we have to convert in a height balance binary system so we are given the first thing we know that we are given with head of a single link list like let's understand this to this statement uh with this example one right so let me explode it down so guys this is nothing but we are given with we are given the single nucleus fine and you can see that this is nothing what is that it now what we have to do we have to convert this single link list to high to variance by necessity right I have this making a sense right now what is height balance minus 60 if you know then well and good if you don't know then let me tell you height balance minus AC what is this so guys a bind it is essentially you know that left part should be the smaller right part should be the greater from the root right but height balance Ministry says that it made a binary and substantly right so it says that the uh left height of left subtree at Red height of left subtree minus height of fret subtree height of right sub tree should not be more than one and this is not only the we can say we have to take a more absolute value and it should not be more than one light so the height of left Supreme lead subtree should not be more than one if we can divide height left from left minus right a light minus left as well because we are taking absolute value so it's not like uh you can say right path should be always more than one in order to get a height velocity right so just simple statement height of left subtree and height of right subtree the difference between them should not be more than one it can be zero it can be one but not more than one it should not be two or three right so let's see whether our this answer is height balance by necessity or node so you can see if we talk about root then left height is nothing but two right head is also two so we can say the difference between them is nothing but zero right so this is a height balance minus St because it is not more than one if it over minus three then right left side we can see the one height right side is zero so one minus zero is nothing but one so still is it is a height values for SST because it is not more than one it is equal to one right so I hope this making a sense this is height balance minus St now guys we have seen the higher balance minus 60 we have to understood the problem what we have to do now let's see the logic part and let's see this example one that how they have achieved this particular thing right so let's move to the logic part and see how we can solve this particular problem how we can convert a single linked list to height balance minus St when we have single link list is sorted out okay so let me write a logic part now guys uh just forget about this single link list in your my don't forget uh don't think about this is uh we are given the link list assume that we are given that array then how you can solve this particular problem are you able to solve this thing because array in Array we have uh just pick up one of we can say insertion path so can you solve this using an array just think about little bit yes you can solve it why not see what you only need to do you need to just find the middle element from your array if it is your array nothing a nodaling place then you just find a middle element place it over a I have this making a sense then find the this uh on the left side always your left side because the left of this root is going to be on the left side of your middle element and right side of your we can say root is going to be the right side of this particular middle element I have this making a sense means whatever the right node is going to press it that should always be present in the right side of your middle index and whatever node you want to insert on the left side of this root is going to present on the left side of your middle element that is clearly right so can't we say that the left part assume that this is nothing but your this is an increased and right part assume that this is nothing but now this is your link is so we can say array right I'm just making a sense so now you have maintained a root part now it's time to get the left part so it's left what should be the left of this particular one so if you find the middle of these so always if the number are even if the nodes are even or we can see the elements are even inside your array or linked list you just need to take the next side of it like if it is two so you are going to take the first we can say phrase two let's say this is a node and this node so total number of nodes are two it is even we can't find a middle element right so what you have to do you have to say divide it by two so what you are getting the third one getting nothing but one's index have this making a sense so always you need to take this one right minus 3 so minus 3 is there now 4 minus 3 the right part is going to be nothing but we can say adminate this particular whatever the part after minus three right so there is nothing part so this is going to be no node on the right side but left part is there is somewhere no pressure on the minus three on the left side of minus three so that is going to come under the left part so minus 3 and there's only one part so it's going to be 10. I have this making a sense if it is not making then let me scroll it down and let me write here these things so that you can understand it clearly so we are having nothing but minus 10 and minus 3 and 0 and after that we are having nothing but 5 then we are having nine so this is the array which we added right now assuming that the first time we are we go to Middle this because they are old elements so we got 0 at middle so I created a root so this is nothing but with zero value the left side and the right side right so left side is going to be nothing but whatever the value present at there so I can say for left side my area is nothing minus 10 and minus 3 right for right side I have nothing five and nine so I have divided this right side for right node left side for right okay now we are going to find just nothing with the middle of minus 10 or minus 3 that is minus three fine and if it is we go to Middle then right side left side is going to be find out right so we have to find so that for minus 3 the left side is going to be minus 10 which there is one element present on the left side but right side there is no element present so we're going to say a null so it is going to return nothing so it's going to say null I hope this making a sense and here's only one node so I'm going to say middle is minus 10 only and there's no left side no let's say so null so I can say simply say null and here right also now I have this in making a sense right now in this sides you can see that the middle of five or nine is nothing but we can say 9. isn't it and nine right side is there is no element on the right side of line so we can say null and this one element on the left hand side so you're going to proceed with that particular one so we can say here is five present so the middle of five is nothing but five only so we're gonna Place five and left side is nothing right side is nothing so null and then I have this in making a sense now right so we have to build like this we have to just find the middle element and in Array it is easily to find we can see just say low plus high or we can say start index plus and index divided by two but we are going to do with using just a link list only right so in linked list also there is a we can suppose to find a middle element that in the reverse row at first point okay I hope you know this right so we're going to use a slow fast printer to find a middle element and then we are going to Simply put our height balance minus St right if you still have any other doubt you can access the comment section but now it's time to move to the implementation part where we are going to implement our low G in C plus language well let's now let's move to the implementation part so I'm here guys first of all I'm with the python so what I'm going to do first of all I'm gonna say okay I'm gonna say if there's no head if there is no node then you have to Simply return null I have this making a sense so if there is no node present in our link list and I have written is simply because and if note a head dot next you see base case right if there is no node present on the next node we can say like uh there's only one node present on our singular necklace then what we are going to say that is going to be the temperature root note right so we can say three node okay and here we can say head dot value so we have written that particular node right but if there are more than one node then we are going to use our uh logic we are going to find the mid value we are going to place the root there and left side of root is going to be the left side of mid and right side of mid is going to be right side of our load right so we're gonna say let's find a Mid Valley right Midway mid node so how we can find we can say slow is going to be nothing but uh head and fast is going to be nothing but our head and one more point up previous is nothing but is going to be let's say none right so why I am seeing it previous let me tell you uh just wait a second let me find the first form bit then let me tell you what is the use of previous so I'm going to say while fast and fasten known equal to null and passed out next not equal to none I can simply use dot next as well okay here in Python we don't have none we have none so fast is node equal to none and next and before doing that here we are going to use our previous that is going to be nothing but previous is going to be slow why I am keeping a maintain of a previous note of slow I'll let you know so once we come we can see we find out our slow we're gonna say if previous is not null if previous is not none then what you can say you can see previous to text now you guys look next and we have done this thing just because to break the chain I hope you are getting it so if I little scroll later so let me give it a space all right so here we have done this let me tell you here so guys assuming that here we go to this thing one two three four and five right so I found a middle three right so now what I have to break it like one and two on one side and four and five on Amazon so that I can pass one to uh we can say left row and fourth to the Lightroom right so I have to break it one two and four it so for breaking I need a previous note so that I can make them to null so if uh slot or well I got a middle root and this node dot left part is going to be nothing but we can say a head part right so I can say okay I can call it a self dot so did sorted list to BSC right so let me call this particular same function sorted let me here I use single T sorted list to BST and here I'm going to pass a headset right and I have to pass root dot right and here is going to be sent out sorted list to BST and here what I'm going to do I'm going to pass slow root next I have this making a sense right slow dot next is nothing but 4. okay and I can make it a slow dot external as well so OLED so this is going to be done and once we are done this thing we are going to return node right and let's run this currency whether it's working final node and you can see that both the tasks are passed right so let's try to submit this particular code and here we go guys right we have successfully submitted our code in Python programming language and I hope you understood the python code now let's move to the next programming language that is nothing but we can say C plus fine so first thing what we have to check it we have to check if head is null so we can say if head is null so we have to Simply return net node C in C plus we have to use a capital letter or nlptr so we can return null Media or we can simply written here I'm just making a sales right but if I had to next is uh we can say head dot next is exist right if it had to next is null PTM which there is only one node then what I can do I can say return new tree node and here I can pass head toward value fine so this was the base case so let me give it a Subspace here all right so this was a base case fine now what we are going to do we are going to say list node that's low which is nothing but we can say head and then one more thing which is going to be nothing but uh fast right which is going to be again head and last thing that he has good previous which is initially and all right so we made this particular thing now once we have done these things we are going to check user you can say metal element we are going to find a middle so we can say y first is not equal to none and we can say fast next is not equal to null PTR so you have to keep move you have to say so you got this 0. slow next and fast is going to be fast next and next I have to see making a sense right before doing a snow next I have to store in previous so previously gonna be Network slow and here I can see previous is equal to null PTR so what I can say I have don't have to do anything but if it is node if previous is not equal to null PTR then we can say previous next should be equal to null PTR and we have break the chain now we are going to pause sorted so we can say we are going to create first of all a node so I'm going to say uh list node my node is going to be nothing but we can say new to re node and here you're going to Slow Down slow of bell and once this is done we are going to say no dot left part node left side should gonna be same function sorted list to PSP and here I'm going to pass left side so I can pass head only same thing I'm going to copy and I'm going to do one right side but here I'm gonna pass by slow down next I have this in making a sense what I am doing I'm first of all checking whether base conditions after that I am finding the middle element that is Network element so I'm gonna make a note with the middle element that is going to be my loot node the left side is going to be nothing but noodle left side is going to be nothing but we can say that I'm going to pass the left link list that is pointing to head right side is I'm going to pass the road next which is pointing to light part of my middle element right so I'm going to run the code so here I got an error I can't written head so okay so it's saying that you can't written a head so you can write a signal PTR let's try to run this code so okay the one thing is node null in C plus one we don't have null we have null PTR and we also have null also so that is the last thing which we are having is nothing but node right so we're seeing that in list node okay cannot change is available the value of these things so fine so we are getting uh error over here it's saying that cannot initialize the variable of type list node with an r a value of type nodes all right so what else I can do I can see here I can say okay this is going to be new tree node slowed or well right so let's try to run this code again all right so let me see what else I could do okay so I am using a list node I am doing a tree node right so that was the issue isn't it so we just need to use a tree node here I am just making a sense that was a silly mistake isn't it all right so let's try to run this code now you can see that both the tasks are passed and let's try to submit this code hopefully I think don't think I should get any error so let's see and you can see that we have successfully submitted the C plus code as well isn't it so now let's move to the next programming language that is nothing with Java and this is a large programming language and I don't want to get any error in this programming language because it is a hard one so if head is equal to null we can simply return next is equal to null so we are going to Simply written a new uh we can say a three node of head and we can write a value right so once we have done this thing we have seen the base condition now it's time to find the middle element so what I can say I can install some variables so I can say list node is going to be uh slow which is going to be nothing but pointing to head one more is going to be not we don't have a pointerest Java so we can say slow this note 0 is going to be nothing would Point into our head and fast is also pointed to him and previous is pointing to none okay so we can write him right so once this is done what we are going to do we are going to say while fast is not equal to null and fast next not fast next is not equal to none then what we can do we can say keep moving and find the middle element so we can say uh solution will be equal to so let me dot next so what is this low dot next and fast is equal to fast dot next and have one more hair steps for because this first printers and here we are going to see previously is equal to slow so we are storing the slow element as well right so once decision we are going to say if first of all let's create a three node which is going to be nothing but we can say about Pointer so T node is going to be nothing but impossible root node and here we can see new tree node and here we can pass our slow load value right so slow dot pair once this is done we are going to make a previous dot next is null okay so we have break the chain so we can see previous dot next is this is also done so what we are going to do here let me scroll it down so what we are going to do we are going to say this node.left side is going to be nothing node.left side is going to be nothing node.left side is going to be nothing but let's call the same function sorted list to PST and here I'm going to pass head and this right side note on right side is going to be sorted list to DST and here I'm gonna pass my slow load next after that what I'm going to do I'm going to write a simply node so let's see whether we are getting any error nodes so let's try to run this code is not equal to null right if it is not equal to null then only you have to make it previous next is in there I have this making a sense right so again let's try to run this code all right so now let's say to submit this particular code and here we go guys right we have successfully submitted our code in Java as well and you can see that the beat hundred percent right so I hope guys you understood this particular logic part implementation parts and if you still have any kind of doubt you can ask in the comment section I'm always there to help you and if you learn something new in this video don't forget to hit the like button and subscribe my channel meet you in the next video
|
Convert Sorted List to Binary Search Tree
|
convert-sorted-list-to-binary-search-tree
|
Given the `head` of a singly linked list where elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_.
**Example 1:**
**Input:** head = \[-10,-3,0,5,9\]
**Output:** \[0,-3,9,-10,null,5\]
**Explanation:** One possible answer is \[0,-3,9,-10,null,5\], which represents the shown height balanced BST.
**Example 2:**
**Input:** head = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in `head` is in the range `[0, 2 * 104]`.
* `-105 <= Node.val <= 105`
| null |
Linked List,Divide and Conquer,Tree,Binary Search Tree,Binary Tree
|
Medium
|
108,2306
|
86 |
hello friends in this session we are going to discuss about another lead code problem partition list lead code labeled it as medium but this is pretty simple problem let's understand the problem statement you will be given a linked list as input and another input variable x we need to partition this linked list in such a way that all the node values which are less than x must appear before a node with value x here x value is 3 this is the node value with 3 now 1 2 or less than 3 they must appear before 3 there the result as shown here if you closely notice the problem statement it is never called out that we should move all the nodes which are greater than x value after the node with x value i mean it never called out that node value greater than 3 should move to after node 3. it is never called out so we don't need to worry about that these are going to be same so if you notice 4 is coming before 3 we are not changing this order this is the expected partitioning there is one more constraint you should preserve the original relative order of the nodes in each of the two partitions i mean you are not allowed to jumble the nodes you must maintain the relative order one should come before two should come before this node exact order exact relative order given in this list similarly even in this partition 4 should come before 3 should come before 5. we should maintain the order as given in the above linked list this is pretty simple problem to solve we will take two pointers two temporary nodes beforehand and after head now we will construct a list with all node values less than x and we will construct another list with rest of the nodes finally we will join both of the lists the first node value is 1 which is less than x less than 3 so it must be with beforehand the second node value is 4 which is greater than x so it must be with after head next node value is 3 which is equals to x value so it must be with after head node the next node value is 2 which is less than x less than 3 so it must be with beforehand the next node value is 5 which is greater than x value so it must be with after head the next node value is 2 which is less than x less than 3 so it must be with beforehand reference we are done with all the nodes now we will join these two linked lists together so this node next reference will be pointing to after head reference and this node next reference will be pointing to null this is the expected list partition as expected let's write code now i have already copied list node class and partition method signature from lead code directly let's declare couple of temporary head node references this node will be the head node for all the nodes with values less than x this node will be the head node for all the nodes with value greater than or equal to x we will declare two more temp variables initially before is pointing to lesser head node reference we will use this node for iteration purpose only similarly after a is pointing to greater head node reference initially we will copy head reference into another node for iteration purpose let's iterate over the list using while loop if node value is less than x then attach it with before list otherwise if node value is greater than or equal to x value then attach it with after list let's move to next note we are done with all iterations let's point after dot next reference to null now let's attach both linked lists together finally return back lesser head next node as head reference to newly created linked list we are done with coding let's test our code i have already written a utility function called print list which will print the linked list onto the console we will use this for testing purpose i have already written main method to save some time here is the linked list we have already constructed the object we are going to call partition function with head as a input reference the returned head reference will be passed to print list which will print the result onto the console let's run here is the result which is partition as expected hope you like it thanks for watching please do like the video and do subscribe to the channel thank you
|
Partition List
|
partition-list
|
Given the `head` of a linked list and a value `x`, partition it such that all nodes **less than** `x` come before nodes **greater than or equal** to `x`.
You should **preserve** the original relative order of the nodes in each of the two partitions.
**Example 1:**
**Input:** head = \[1,4,3,2,5,2\], x = 3
**Output:** \[1,2,2,4,3,5\]
**Example 2:**
**Input:** head = \[2,1\], x = 2
**Output:** \[1,2\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 200]`.
* `-100 <= Node.val <= 100`
* `-200 <= x <= 200`
| null |
Linked List,Two Pointers
|
Medium
|
2265
|
198 |
hey what's up guys John here again so this time I'd like to talk about this problem a least called the problem 198 house rubber and today what it's easy I think it's kind of easy between easy and medium because this we'll be using because we'll be using a dynamic programming idea here even though it's a 1d dynamic programming but it's still a DP problem so I think it should be like in between easy and then the medium anyway let's take a look okay you're given an array right so basically the it'll raise the house right each element in the array is a house the rubber needs can rub any of the house but only with only one with constrained only one constraints is that other the rubber cannot rub to house that trade that it's a adjacent to each other basically if he rubs number one then he can only Rob to right and then same thing if he Rob's two and then he can only Rob one and so the first in the most intuitive way will be using a drdp right so let's just do it shouldn't take too much time here let's do it and here right and I'll just do it a regular TP here so in this case the DP I means until the ice house from starting to I what is the maximum money we can get until that position right so that's DP I'm gonna initialize at the beginning we initialize everything to be zero right and the length will be I'll just put it in here so in the four I in range and right so what we do here so basically the idea here is that when we see a new house here we only have two options here reader rob that house or we don't right so let's say we Rob current so if we drop the current then at least we can get the current house money right Plus what Plus let's say if we robbed three then class whatever house we can get from starting from the from this I minus two right let's say here if we rob three right if we robbed three here then we need out we also need to add everything we can rub until the seven here right so that's going to be the D P right what I - ooh right but since we're only I - ooh right but since we're only I - ooh right but since we're only initialize this with n here we're gonna do it a range Shack right if I is greater than 1 right because we don't want to have a like a an active index right also what else we simply put 0 right and then the second option passed option will be not Rob right we don't Rob not we don't Rob the current all right then if we don't rub current then we can initialize we can get the I minus 1 right basically here same thing if we don't Rob 3 here right then we're assuming that 9 was robbed right so here we don't Rob 3 9 was robbed and then the next we can drop one but since we only well we're at the position 3 here if you're not robbing it then all the money we have robbed if by not robbing the current will be DPI minus 1 which benign right same team here I do if I square them than zero right same thing for the first range track right and then in the end we just do as input comparison right with to our max from those two right current a not drop court right that's and then we just return the DP and minus one right since we are it's a it's an unlit and a deep is that this list is the zero based right that should do it let's see what did we do wrong here oh yeah so if we have a house here no don't forget always use like parentheses otherwise it would like to something then to a weird calculation here because we want to Inc encapsulate this thing in the parentheses yeah okay sure yeah since we're returning this n minus one yeah we should I think it's but it's we should like initialize it with n plus one right in that case when we return this like an minus one we will be making sure we still have one element left in here right in case there's nothing here or we can just simply do a sanity check here I'll just do a sanity check here if not noms I'll just also I'll just return that zero here cool thing works right and yeah but and this as you can see the time complexity for this problem is o N and the space complexity is also o n right so since we only need to start to vitals from previous calculations here right instead of using a rate of store all the previous reads out we can just have like two variables every time we update those two variables and then we can just change the improve this code into a from old n times space complexity to all a one to a constant all right same here two seven nine three one right so for example same thing whoo-hoo so for example same thing whoo-hoo so for example same thing whoo-hoo so when we process three here right all we need is the like what we discussed we need the maximum three the maximum values from either from this position or from this disposition right because that's how we are to this will rob current if we rub current then we need to we needed the maximum value from seven if we don't rub three then we need the maximum value from nine right and then once three is finished right and then we have the current max value of three here right all right so we have three here so the current but once we calculate everything right we have the current max value of three right and then when we move to one right see all we need is three and nine right basically after we how can i how can we name this one right so that's the sum will rub the current one and this is the sum to not rub the current house right so then we can improve this thing to do not using a DP right instead we just use a howl name it max some Rob current right and Max some not Rob current okay so every time right so every time let me see a new number here since at this moment we don't need the index let's just use this one here so at this moment when we say this one writes what would we do we are the current the max Sam right Rob current right and what's the current right what's the maximum current we is the maximum of the of this maximum not Rob okay no Rob current class right plus the Nam right and the maximum sum not Rob current right and then here so once this is done right the and the value of this one will become the not Sun so not some current will become the Sun right because once we used it to previous two sums to calculate this one for the next values the current sum right that's the maximum of corn some the corn some will become the will be the not rob some for the previous one sorry so okay so at the moment so when we add two three right and we use the max the previous like we use the at the maximum sum Rob current plus that's not the number and also the not robbed some to calculate at our current result right and once we done that this will become two not robbed current for the next one right so that means we need to set this one to the Robin to this one and then for the current one right current one will be the L will be the value from here right so once this is done right the current one is gonna be from this value but since we already set this one we have to like have a temp sum here before using it before like assigning update this value so in the end which do this right and then so in the end here which to return this thing here like some current right something wrong here let's see sorry I think I should return this one not Rob current yeah so I know this is like a little bit confusing so basically okay let me try to go over this one more time with this oh one solution right so every time right let's say when we calculate three here right we use the previous like we use this one the one I call it Rob current maximum sum Rob current Plus this num right and then the maximum sum not Rob current to calculate a biggest number it's basically calculated the maximum number for this for the current position right and then once we calculate that we'll be using will be a sign instead of signing back to the current will be saying I signed back to this maximum sum not Rob current because that for the next value one this sum will become his not Rob current sum right and our current are our current nuts oh my god this not Rob current variable will become the current for one yeah maybe the name in here is that it'll be confusing but I'm trying to use a more intuitive firewalls here you know I think you guys get that what I'm trying to say right so once you calculate this wonder the meaning of this tool will be reversed right for the night for the next one that's why we're doing this kind of a swap thing and in the end we just return the knob not robbed current because that's our that's always the latest maximum sum for the current position right and okay I think that's it for this problem yeah thank you so much for watching yeah and I hope you guys enjoy it alright see ya
|
House Robber
|
house-robber
|
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and **it will automatically contact the police if two adjacent houses were broken into on the same night**.
Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_.
**Example 1:**
**Input:** nums = \[1,2,3,1\]
**Output:** 4
**Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
**Example 2:**
**Input:** nums = \[2,7,9,3,1\]
**Output:** 12
**Explanation:** Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 400`
| null |
Array,Dynamic Programming
|
Medium
|
152,213,256,276,337,600,656,740,2262
|
67 |
in this problem we have to perform binary addition we are given two strings and both are containing digits which are either 0 or 1 so this is not a simple string it represents a number in binary form so for example if you add 5 and 2 actually you are adding 1 0 1 its binary representation and the representation for 2 is 1 0 and the result is 7. similarly if you do addition in binary format then 0 1 is 1 0 is 1 and then here it's 0 1 is 1 so if you see this as this is the binary representation of 7 so this is what we have to do so first let's understand how do we perform binary addition given two numbers so this number is representing three this is one two one plus two three and this is one now let's perform the binary edition it's very similar to the decimal addition that we do what we do we add two numbers and if it goes beyond 9 we take a carry here also we have a number between 0 and 1 in decimal we have from 0 to 9 so 10 values are there in binary we have just two values so if the result is more than 1 there is a carry otherwise there is no carry similar to this decimal addition so initially carry 0 so we add 1 and 1 we get 2 which is more than 1 just like more than 9 in decimal so there is a carry of 1 and the result will be 0 so 1 and 1 if the result is two the result will be zero if the result is three result will be one it cannot be more than three in any case and if it's one then we will have result will be one so here 1 plus 1 0 and carry of 1 finally 1 plus 1 again 0 and carry of 1 and this one is written here so if you see what is this binary number it's 2 raised to the power 0 plus 2 raised to the power 1 0 times 2 raised to the power 1 plus 1 times 2 raised to the power 2 this is the decimal conversion so this is 0 this is 4 so this number is 4 and if you add in the decimal it's again 4. let's do one more operation to get some more practice so it's carry 0 initially we add 0 plus 1 no carry then 1 plus 1 2 so result will be 0 sum will be 0 but there will be a carry just like when we add 9 plus 1 we get result as 10 but we do a carry forward of 1. so now there is a carry of 1 and these 2 are 0 so it's 1 and there is no carry now 1 plus 1 2 which is 0 and carry of 1 and which is written here and if you convert it to decimal this will be 0 plus 2 plus 0 plus 8 that is 10 and what is this number it's more than that 1 more than that this is the only difference so 11 so it should be 21 and if you see this number it's 1 plus 2 is not there 4 8 is not there so 16 plus 4 plus 1 that is 21 so these are given to you this is s1 and it will be in string format this is s2 this is also in a string format you have to return this resulting s or resulting string again in the string format so how did we perform the sum here we started from the last characters of both the strings no matter whether they are of equal size or not and we continue till we reach the first character of the larger string and then we additionally check if there was any carry forward then we append it in the beginning so some so clearly we will start from this we will have two pointers so let's look here so we have the two strings s1 and s2 we start from the last character or both let's call it c1 let's call this as c2 and we when we reach the first character of the larger string then this is smaller would have already finished and then we check for carry and stop here so initially carry 0 we have not started yet and what will be some sum will be carry plus c1 plus c2 so we have to add all these three this c1 c2 and carry and what can be the maximum value of sum if all three are one then it can be three it can be two if two are one it can be one also it can be in zero also so what should be the result in all these cases if it's zero if it's one then we have to put one if it's two it will be zero again if it's three it will be one so you see that in odd cases it's one so it will be we will append here so we can have a result string which will be empty and we see that whether it's order even so in this case it's odd it's one so we append one here so this is the result now which will denote the last digit of result we have to finally reverse it since we start from right to left and here we are appending in the end since that is easy operation if we append in the beginning it will be costly operation we have to shift everything so it's 1 and carry will be carry is updated to if sum is more than 1 if sum is 0 or one that means only one of these three was one or none of them was one so carry will be zero but if it's more than one then carry will be one then one else zero so carry 0 here next sum will be carry plus c1 plus c2 c1 c2 r1 carry 0 so now sum becomes 2 so 2 is even so we append 0 here so 0 is appended and carry is 1 since it's more than 1 so this is the carry now add these 3 sum will be 1 carry will be 0. so append 1 here and carry 0 next add these three sum will be 2 so 2 means even so 0 and carry is 1 since it's more than 1 then carry we have reached the end or the beginning but there is a carry so we add in the end so this is the result in reverse order now we will reverse it to get 1 0 1 and you can verify that this is the answer so let's write the code for this so this is the result and will have two indices both pointing to the last character so this is denoting position we can get it using that square bracket and j is b dot length minus 1 and carry is initially zero so until we reach the beginning of the largest one the longer string we will continue so initially sum is carry or let's sum is initialized to carry whatever was the value of carry then we will add to it depending on if i is greater than equal to 0 then sum plus equal to a i and we can do minus here itself minus zero so this will be zero or one character but the sky value of that is not zero or one it's more than forty i guess so we subtract sky value of zero so if this was zero character the result will be zero if it's one result will be one similarly for b so and this will end when we have scanned both the strings and then we will check if carries there or not if care is there or we know that it's string so we can have one also or let's make it more generic it does not make a difference and it works for this case let's try this second example quickly and both the cases work let's submit and the solution is accepted next we will do the same thing in java and python 3. so here we will use the mutable string builder length is valid and this works so we will submit and the solution is accepted in java as well so we are right here beats hundred percent of runtime finally we will do it in python 3. is used to get the sky value of a character so this we cannot do in python and the python solution is also accepted
|
Add Binary
|
add-binary
|
Given two binary strings `a` and `b`, return _their sum as a binary string_.
**Example 1:**
**Input:** a = "11", b = "1"
**Output:** "100"
**Example 2:**
**Input:** a = "1010", b = "1011"
**Output:** "10101"
**Constraints:**
* `1 <= a.length, b.length <= 104`
* `a` and `b` consist only of `'0'` or `'1'` characters.
* Each string does not contain leading zeros except for the zero itself.
| null |
Math,String,Bit Manipulation,Simulation
|
Easy
|
2,43,66,1031
|
1,964 |
hey everybody this is Larry this is day seven of the medical day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's poem and why do they move afterwards also oh no that's tomorrow so tomorrow will be the weekly film and today's problem is 1964 find the longest rounded obstacle course at each position hit the like button hit the Subscribe button join me on Discord I hope everyone's doing all right weekends here uh in New York it is actually very uh very nice weather uh which is too nice to be honest for me because Peak allergy season drivers these a few times uh excuse me but uh but yeah um oh yeah and just have a good weekend in general and the contest is in about two hours so if you're doing that good luck to you um let's look at today's problem 1964 find the longest UPS valid obstacle course at each position okay um actually I've been kind of teasing this for a little bit let me set it up real quick um so uh let me might as well do that here where I hopefully this works I don't know if the sound comes out but I guess it doesn't really matter uh because basically those of you who have been following I've been saying since last Sunday that I did a did an obstacle course um the obstacle course was like this thing in New Jersey which is like about two hours away or something like this um it's three miles and just a lot of random obstacles uh obstacles um I did capture parts of it in video uh and those of you might know uh I actually did it in uh in a was it Patrick starfish that's me if I did Patrick starfish uh custom thing so let's uh let's take a look at it watch it together now apparently um and I'll try and go as fast as I can as you can see I was just like gunning for it let's see excuse the language it wasn't me but uh but and then basically that's pretty much it really I am very fast so to be honest I had to climb uphill after this and it gained like 20 pounds or whatever so this point I get stuck because apparently I chose a path that on the top people were just like yeah it's so heavy because I'm going to do it anyway but basically I'm stuck here now because there was a lady the camera doesn't change to it but there was a lady that was just like getting stuck up there so uh so I'm just like waiting Madness I don't know if you can hear it but basically I walk up two steps and then they would like you know can you give me a second I'm like I guess I'm just hanging out and then and you can see like the guy to my right just like raising food and then just climbed down and you can kind of see the lady still climbing so uh yeah and that's pretty much it really you could see me try to like not fall to my death which has happened a few times uh and this is me climbing down and you can also see that it is raining right now actually uh I don't know if you can see it on the screen that well but that's basically it oh but that's pretty much it's very nasty uh like that's pretty much it and everyone is giving high fives uh yeah anyway uh anyway that's it for that part of it uh let me turn it off did I turn it off I think I turned it off I don't know how to turn it off all right but yeah uh so that was the obstacle course and you know uh reading this poem I guess I had to do it okay fine anyway let's take a look at today's Vlog so you want to build some Optical cars you're given zero indexed integer way obstacles of length n where obstacles if I describe the height of the obstacle oh just like what I did forever I wearing that index I between zero and N minus one find the length of the longest obstacle course and obstacle such that you can choose any number of obstacles between 0 to I inclusive you must include I obstacle in the course you must put the chosen obstacle in the same order as they appear and every obstacles is except for the first is taller or taller than or the same height as tactical Optical media before return an array answer of length n to them misunderstood this foreign my misunderstanding this uh well I mean it's a variation of ois Lisi uh for those of you who might not be into the unnecessary lingo or acronym Lis is the longest increasing subsequence um and this one is it strictly increasing or the same height so it's monotonically increasing for this one um yeah I guess so right so then here I and I don't I haven't I don't know the answer to this I mean it is ois so I expect answers to be n log n and given that n is 10 to the fifth um that's probably the way to do it with Lis um the other tricky thing with this particular thing is um you know uh it's kind of getting the order right with the standard one use lis is not as necessary because you can go both Direction and it is symmetric in that longest increasing subsequence is equal to the I guess longest decreasing subsequence but going in the other direction right in this particular variation the order does matter and I think the way to kind of build upon knowing the answer instead of saying okay uh in the canonical version of Lis it's saying okay I'm at current step what is the longest path that ends in the step or this obstacle or whatever um in order for us to kind of enter it at the beginning which is what this ass right starting at I we have to answer it the other way which is going backwards which is the longest thing that ends in here right uh or begins on here but ends in here with your kind of do the backwards thing so I think that's pretty much the idea so we can do something like for x and obstacles um reversed right or maybe we could just do a reversed because then technically I think that's better space wise and you have answers right um and it may be a better way uh yeah and then X um and I'm not going to go over the longest increasing subsequence too much the analog and I think I've gone over in the past anyway and this is kind of very hard to kind of do with yourself um if you haven't done it if you haven't seen it before this is kind of hard to be frank because and it took me probably like five years before I really understood how this one worked um because back in the day the literature is just not as tight um I mean the end Square longest increasing subsequence of dynamic programming it's pretty like I learned it very quickly but the analog n version which is what we're going to implement now even though you look at it in code it's pretty straightforward and I think a lot of people kind of um just take it for granted because they've known it before um I don't know that they uh just because they've done it before I don't know that you know um I don't think it's a easy proof is my point um and there are some emerging properties that comes up which you would have to make observations as well which allows you to do a binary search thing which is kind of really not intuitive if you ask me so yeah okay but that being said so we do a five sec I don't know if I want to advice like well right I don't know if I want to buy stick left or right yet but I just want to do it here for now um but basically say we're saying okay and we might have to change it to negative or something funky um so this is the length of the longest thing that ends in here right is that right let me think for a second exactly um because then you have if index is greater than or you go to length of best then we want to do best DOT a pen um X L is best of index is equal to X right something like that and that answer dial pen index someone like that so that's the structure the idea is that we do a binary search on it and because we only when we update on a binary search it actually keeps an invariant that um the list is going to be monotonically decreasing in this case so we actually want to do something a little bit funkier with negative X instead I think um so then we can kind of do the monotonically decreasing file um the answer is wait is that true or am I mixing it up yeah because the idea is that you want to keep the property that um the smallest for a given length you almost greedily wanted want to replace it with the biggest number that is the last element of that length right so that's basically the idea here um yeah I knew that this has to be a plus one but that's fine but that's still wrong though because then now let's see so I'm thinking about in my head the same oh then I guess this is hmm okay so it started two okay two um and then let me maybe I did as well yeah whatever but basically here we start at two um that's the longest thing of length one and then we do a binary search on three is also going to replace one oh I see I am wait did I misunderstood this I think I misread this prompt to be honest I think I must misread this one oh man I mean the ideas I think I get the idea but I think I just read some of the things because of the zero to eye inclusive I think I did I've read this as starting from I for some reason thank you so okay so we don't need to reverse we're doing so yeah I think I set some stuff up yeah we don't need the reverse and I think I did then it is just very stereotypically uh Lis I think I miss read this when I thought I read starting from I but this is actually saying uh ending on why okay uh that's why I was wrong I suppose yeah I gotta do better about the reading I mean that was terrible reading on my part to be honest I just misread it uh because I don't I mean I it was embarrassing that I get to reading well um I mean both of them are the same problem really to be honest but I just because what I realized was that I was like wait why don't I because what I was going to do is reverse the answer back because we were processing and worst but I was like wait that doesn't seem to match the answer that would give even if I reversed it right from before and I had to reread it again and basically this is saying the prefix of it so that it's actually just uh yeah if you took up if you watch it again and you take everything I said except for you know changing the problem actually this is pretty straightforward um application of Lis um uh yeah sorry friends I just kind of misread it hopefully I got I get the misread out of the way here and not you know during the contest but uh but yeah also just I'm playing around my scars and I just kind of wipe it off a little bit but you can cut maybe you can't see it anymore because it's been a week but I have like I have a lot of scratches a lot of blood in random places uh from that obstacle course so yeah um that's all I have for this one um if you really have questions uh well first let me know but also maybe read up on longest increasing subsequence um this is actually turned out to be a pretty direct application of it uh um but it does really test your understanding of that algorithm um the N log N1 um because I mean it doesn't really test it in depth per se but it's still a good test of it so definitely recommend looking into it um cool that's all I have for this one let me know what you think yeah let me know what you think stay good stay healthy take your mental health I'll see y'all later and take care bye
|
Find the Longest Valid Obstacle Course at Each Position
|
find-interview-candidates
|
You want to build some obstacle courses. You are given a **0-indexed** integer array `obstacles` of length `n`, where `obstacles[i]` describes the height of the `ith` obstacle.
For every index `i` between `0` and `n - 1` (**inclusive**), find the length of the **longest obstacle course** in `obstacles` such that:
* You choose any number of obstacles between `0` and `i` **inclusive**.
* You must include the `ith` obstacle in the course.
* You must put the chosen obstacles in the **same order** as they appear in `obstacles`.
* Every obstacle (except the first) is **taller** than or the **same height** as the obstacle immediately before it.
Return _an array_ `ans` _of length_ `n`, _where_ `ans[i]` _is the length of the **longest obstacle course** for index_ `i` _as described above_.
**Example 1:**
**Input:** obstacles = \[1,2,3,2\]
**Output:** \[1,2,3,3\]
**Explanation:** The longest valid obstacle course at each position is:
- i = 0: \[1\], \[1\] has length 1.
- i = 1: \[1,2\], \[1,2\] has length 2.
- i = 2: \[1,2,3\], \[1,2,3\] has length 3.
- i = 3: \[1,2,3,2\], \[1,2,2\] has length 3.
**Example 2:**
**Input:** obstacles = \[2,2,1\]
**Output:** \[1,2,1\]
**Explanation:** The longest valid obstacle course at each position is:
- i = 0: \[2\], \[2\] has length 1.
- i = 1: \[2,2\], \[2,2\] has length 2.
- i = 2: \[2,2,1\], \[1\] has length 1.
**Example 3:**
**Input:** obstacles = \[3,1,5,6,4,2\]
**Output:** \[1,1,2,3,2,2\]
**Explanation:** The longest valid obstacle course at each position is:
- i = 0: \[3\], \[3\] has length 1.
- i = 1: \[3,1\], \[1\] has length 1.
- i = 2: \[3,1,5\], \[3,5\] has length 2. \[1,5\] is also valid.
- i = 3: \[3,1,5,6\], \[3,5,6\] has length 3. \[1,5,6\] is also valid.
- i = 4: \[3,1,5,6,4\], \[3,4\] has length 2. \[1,4\] is also valid.
- i = 5: \[3,1,5,6,4,2\], \[1,2\] has length 2.
**Constraints:**
* `n == obstacles.length`
* `1 <= n <= 105`
* `1 <= obstacles[i] <= 107`
| null |
Database
|
Medium
| null |
1,202 |
That hey guys welcome and welcome back to my channel english video we are going to solve smaller system with wax swiss problem mein kya hai ki aapke ek string gas de raha hai aur 1 and a half years of india is late akhar ok what should we do What we have to do is swap whatever elements we have given in this license and we can do this possibility any number of times and after sweeping what we have to do is to fine here the smallest laser. If you want to do minor molestation, then okay, then this is the problem of my statement which I have given, not only we do not have to see that among ourselves in India, we have to select not only this, those who will be connected to them, line is like A, if it is connected to poverty, then A is also there. So we will do this also, if the overseer is connected, then we will also do the AC. Okay, so this is the day here, but when you come to the solution, there is a note given here that look here and BA B.Sc. look here and BA B.Sc. look here and BA B.Sc. But if someone keeps laughing, then only Swapna is amazed, here you can whiten that too, so here now when you see this is why this direct indirect graph has been made, this connected graph has been made here, so look here, zero three give. Have kept zero three de hai 25250 ka two three author 238 sub character will be inducted so it will look like this white have kept one four de hai it will be different but have kept grind here see that zero and travel there is no love here But if you can select it, then only those which will be connected to each other, you are connected in this rice also, what can we do with this, we can swipe, so how will we solve this problem by using na de year. We will solve this problem, first of all, by using this bundle that India has given us as society, we will come to the end-directed customer connected group. come to the end-directed customer connected group. come to the end-directed customer connected group. Okay, after that, if we will solve this problem, then we will take our skin example of first example, after that we will take the example of first example. Then we will understand that whether we will do it in schools, first of all the challenge will be that whatever we have given to us, if we have given broken batter, then from the opposite side we can make a graph with gas, then you would not know it, nor can you read it. Yes, you can also watch the video from anywhere, there is a lot of information on the net about how you can make a graph of likes and shares, so here I am telling you what I have given you here, that I have given my introduction, okay whatever. If you have got a license, then what do you have to do? Here, if you want to make a graph using it, then it is connected to zero, then what will we do with it, we will reconnect the zero, there will be no direction, still strongly connected toe. This zero will be connected to the previous one then what is one and two connected Dhawan and how to do one is now tawa is connected to two Okay one two is connected to the inferior Pair zero is connected to two How is this current From two to a pad, here you see that all are connected to each other, are all connected to each other, then we can sweep anyone, here we can believe zero one, God Mahadev is not kept but we are together. We can do this because they are interconnected, so now what we have to do is to use this to find the smallest geography trusting. Okay, so how will we solve this problem? To solve this problem, we will use Davis. Okay, so using dates. What will we have to do to use it, first make this graph and what will you do with this graph, now you will store it there, what will you do, apart from this, people will leave a cut here in Uri sector, then how will you store that your zero is connected then This is fine, then what will happen to your zero cough syrup, zero cricketer is different from whom, we will also write like this, from additional organisms, how to connect to Dr. because it is an undirected graph, if it is a connected unwanted graph, then stay connected to Jyoti, previous quarter is fine, 023 collector. So be connected to 200. Here ₹1 is connected to ₹1. If you are connected to you ₹1 is connected to ₹1. If you are connected to you ₹1 is connected to ₹1. If you are connected to you then what is to be. If you are connected to one then this is our first duty time. Here I will make a graph and cut it so that this is our graph. It has been done that we will store the index in one note, OK, after that what will we do, if we use gas new updates, then what will we do to use the dates, see the graph here, whatever you see now, you have only one problem here. It may be necessary that no one is connected to each other, so here anyone can become a customer. Okay, so what I have to do with all this graph is Davis Ship and S. Okay, so now there is one here, so we have one. First of all, let's see what we will do here, what will we do here, we were giving a conclusion today, how much wind IS can be here, these license insistence, now the cashew nut size will be the same as that of the yoga screen, it will not be more than that of this tree. Can any of them become a user, can the feet be fixed, so what have we given here till now, it is four, here the length is its old photo, so now how many can be made in these digests, zero, then what will we do with the size, will we take Britain? Okay and Android Yoga, we will take mine here, this is our busy day, all the chords will be in the initial, okay, after that we will take one here, we will take one in these, we will take the shift in the store, we will take it completely western, which will come from India by adding one. That this is our index and will be done Anil Dhull one of our shoulders is the latest which is which letter is there among each other which is the latest which can be connected which can be subscribed keep this okay this one will be better your This will be its tractor type and what was above will be Midnight Intex's India, this is also like this, first we will see whatever is connected together, let us take all these likes here and as many tractors as we can in that connected. Take it here and then you can select them in whatever way you want, we will do it only like what is ours, whatever we will search here, if it comes under what is ours, then what will we do first here, what will we do for it one and a half We will do the first version to find out who is connected to each other. Okay, so what will we do here? We will take zero to four. Okay, if you set up Jio, you will love zero. Mark will visit. I will introduce you. Visit is not there, visit is this. We will also march and visit Tite, then what will we do, if we go to one side, then which one is his child, which is his child, there are three tubes here, now choose one of them, here we will use it, okay, we will use yours. Then if you use it then first of all we will mark it as visited but we will mark it and yes along with that what you have to do is not like you tweet it like this here, along with visiting the route you have to store it in the indexes. We have to take it in this life, we have to support it and if we have to solve whatever our character is on this page in this index, then what is the contact on this India, what will come on zero, you leave Guddi here. Do it, OK, then we will see which child is which and who is connected to it. Actually, to be connected is a free connection, both the marks can be used by anyone, so we can then take it, what about the first one? We will send the marks, we will set the marks, we will also joint the marks together, what will we do in this, we will also make a poster and whatever is on three, whatever is on here, we will leave out the character and 3p, what is B.ed side, then leave out the character and 3p, what is B.ed side, then leave out the character and 3p, what is B.ed side, then of course you are here. But you will store it and leave it, then what will you do? The appointment is a political one, hence no one is connected, otherwise you are real, will he come to Vegeta, then this has happened from live to zero, which visited child will go to two, not visited. First, it will be marked and digitized, then what should we say, here you will start here, you will use tow and on side 2.22, how is yours, then you on side 2.22, how is yours, then you on side 2.22, how is yours, then you start the same here, done, then what will we do, to 6 which one? Connected The zero is connected, it is related to it, so this something has already been visited, isn't it solid, so we will see one is our one, what to do with one, I will first digitize you that it is already a digit, then we will store it, so one What's your zero36 on one okay sorry minute up here it's solid up here and one piece is sorry product so this is done then what will you do then whatever you are connected to on this side whatever you were connected to on this side here Brother, I have left it, what should you do? First of all, both of you have to dry it. Both of them should start doing it. Will you shoot Adil? What will happen here, all the indexes are connected to each other, if you password them, then you have to go to 0120 and you will set it aside. So you have to become Egg Chief Afridi, this happened because you have got everything, so sometimes it can happen that two people become friends with each other, in that gym, this will not happen, okay here it has become 0123, you are wise. If you do this and send it, then ABC is done, now what will we do in this India, the extra inch on this, the value of this hair on the life line, the injection of the gallery on the life line, how will we do this element, then here it will be one of Or like this or what will happen that what will we do on the gallery that will be on 151 dialysis, we will leave the next one and also post it, we will start baking that the value that is there from this Indore, what will we do on it. Will do Agarwal element, if we do it the day after tomorrow, then if it is Bittu only, then two will be broken and what will happen on three, what is the good way, what is the value now, free life is domestic sale, in free life, if you follow it got deleted, this is what we wanted, right? ABCD You already got the meaning of this in the soft banner itself that we will see for a second, okay now let's see for a second, what will we do, first of all, what will we do with what is given here, My eyes? If we make act connected graph inside, then what will happen to zero, your free will be connected and from one, your two will be connected. On one side, when you see, these two have become separate groups, now they are not connected to each other, so let us check for a graph. If we have to do this, then to make a graph, we will check it will ask that if we create it here, then how much will be our widget, then our price will be equal to four, here it is okay, here we will see zero descent two three look do this Took that over here again what we will do is we will create one for a late index, first we will create another one for the index, for whom we will create one for the latest, A I Mukesh, first of all, you connect to this located here and if you call it, then zero. What will happen to it, what will happen after all, then what will you do with it, will you make it zero current, Vanshi, what will you do, connect it to two, and what will you do to connect it to two, okay, so this is done, then from here we will do rice, then we will come to zero, first then four from the districts. We will beat up zero, then what will we do here, we will store Jio and leave the age here, we will take it, there is D on zero, leave the to-do here, is D on zero, leave the to-do here, is D on zero, leave the to-do here, okay, then what is there after that? Which is connected is free will go after free will visit it's route and will store the ok here so it is done then which is on the degree is on the distance your b is ok after that it is here no here is the taste otherwise first So first settle this, first fold it, if you are sorry then there will be a shot in Jyoti, that is fine, also set this that there will be a shot in Coat D, there will be a shot in BOD, so what will we do now 041 India, we will depend on the value on this. If you give value, Jio has zero aspect on it, then we will also give pulse on zero index, so life one, what will we put here, look here, life line, we will put it, okay printer one India, whatever value is on this, the descendant of the index will be wasted. What will we do on three, we will put disco, then degree lead you, if there is only here, this index is the value on this, what do we have to do on this, we have to put a pin here, it was put earlier also and then this is over, then you will see that between If not then we will have to see separately what one day problem will be done, take a new latest and take guys, okay here we will take the latest and this is India, so first what will you do, you will insult one here, one fact which is of value. Will you search on it? Have you set the real school on one? Then what will you do? Arrest Vanshika. Use * If you do? Arrest Vanshika. Use * If you do? Arrest Vanshika. Use * If you digit Kumar, then what will you do? If you insult To, then after minifying Ko, you will insult the one who has value on Two. Which is the value on Two? Have done 159 then what was we will turn on both of them and do one two it will be like this Okay then we will put 0 this quarter inch extra value on it zoom inactive that we will put on one on we here on here and here But is it like this here Source Nadu 1212 If we want to laugh, then we are here Sister with cap, this is what we need flour in the answer, so this will be our approach, here we have to use deficit, first make a graph and then invest our channel. What will we do along with doing Star Plus, two people will use it, we will give one latest letter and one injection, okay, we can index. What will we do, when we do rice, the graph in which we will get the digest will be indexed by minutes and in the index. Jailu will be found, we will add it to the latest, then we will shift both of them, then what will we do according to the value, we will sign both of them, okay, so this is our approach, so what have I done here, I have already written that in the open. I am explaining to Ajay that first what will you do, one person will take and take a video, okay we have taken it, then what will we do, what will be the size of this Joe and Meera, the size of the sting could have been the same because it was more than Now the value of the injection in couples cannot be much, otherwise here we will end up taking the size of the lion's share of its size, then what should we customers do, we will resize it, here I am here, we have taken the size. It was signed, what will we do with it, we will disassemble it and add it, okay still patience is also needed, we have disassembled here, next9 side and what will be the calls in all the graduations, okay then whatever is here, we have done it. The data is here, we have to create a graph, here the connected and shared graph is increasing, what are we doing, then life tax goes on this and from here, whatever is this ballu, took this question. First of all, you will get whatever is on its zero, whatever is on three will be on one, whatever is on the life line or whatever is on that egg, its value has to be put it here, whatever is there on fever sites, what do we have to do on it, Jio net speed. That's it has to be inserted, okay, then follow it, then it will go ahead, then for this it will do SIM, it will do 1 to 2 cigarettes, it will connect to Pintu Kumar, then it will go to the next one, like to change zero to 2, if you saw the cigarette, then this is our part, this is his. After what we are doing, I am N size, followed here we will take the index, okay, took the injection and took the latest, we had said earlier also that we have to mix here, the person who gives one injection, take one latest. Okay, first we will start from I and look at all these indexes. We will look at all the lion's matches according to their size. So here we have folded from zero to end. Okay then. We will check on the eye index, if you have a quid, send you to jail, if not, then we will not be ahead. If there is no visit, soft waves will call. Okay, make these 10 calls. If you call on your health, then what will you do? First, will I ever mark him in the dark? True, this video is done. Okay, the video is done. After that, what will we do with the index? What will we do with the one who called on it? What will we do with the person who has to call on it? We will first ask here and take it in the index and then add the value which is there on the index. This team I will cut it to the latest here, okay, then what will we do from here, wash this index on this, whatever you have been called, you can connect with each other, here on 10, you will call, okay call on zero. Will you do it first Zero Kumar Dhakad Honge Whatever value is set at zero I liked it a lot in the last 10 matches, then what were you doing, watching whoever is connected to zero, watching the free one first, watching the tight film three. So we are again calling a discussion here, okay, first we will check that whoever is connected next, whoever is connected to this zero, whoever sees it, check that first, okay, check that first, hello. If there is no wicket, then I call the dress for him. What will the passenger of the call for the earth do with this road? Then he will have become a leader, then he will look back and will come to the districts, then what to do with him and It will be 212, then you will see alone, he is using follow here, okay, and then what will we do with him, let us use corruption, okay, then this is our problem, the solution is to call this, what will we do, we will do it on both sides. What we told you here is that what you have to do here is by leaving these two aside, it is here, so after folding it, what we are doing after softening it is that the index salary of our person. The value that is built on that value is of the latest draft in Prem, we will start with I, we will start with that and we will move ahead and we will also set the tehseem here, this one here, whatever you do here, make it Sindhi. Here this is what we will do finally, if we have to turn the gas then this is our solution. Actually I can write from the solution parlor that sometimes it happens, wedding season is going on here, he keeps saving the Sawan box. It's time to submit. Okay? Is it time tomorrow morning or not?
|
Smallest String With Swaps
|
palindrome-removal
|
You are given a string `s`, and an array of pairs of indices in the string `pairs` where `pairs[i] = [a, b]` indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given `pairs` **any number of times**.
Return the lexicographically smallest string that `s` can be changed to after using the swaps.
**Example 1:**
**Input:** s = "dcab ", pairs = \[\[0,3\],\[1,2\]\]
**Output:** "bacd "
**Explaination:**
Swap s\[0\] and s\[3\], s = "bcad "
Swap s\[1\] and s\[2\], s = "bacd "
**Example 2:**
**Input:** s = "dcab ", pairs = \[\[0,3\],\[1,2\],\[0,2\]\]
**Output:** "abcd "
**Explaination:**
Swap s\[0\] and s\[3\], s = "bcad "
Swap s\[0\] and s\[2\], s = "acbd "
Swap s\[1\] and s\[2\], s = "abcd "
**Example 3:**
**Input:** s = "cba ", pairs = \[\[0,1\],\[1,2\]\]
**Output:** "abc "
**Explaination:**
Swap s\[0\] and s\[1\], s = "bca "
Swap s\[1\] and s\[2\], s = "bac "
Swap s\[0\] and s\[1\], s = "abc "
**Constraints:**
* `1 <= s.length <= 10^5`
* `0 <= pairs.length <= 10^5`
* `0 <= pairs[i][0], pairs[i][1] < s.length`
* `s` only contains lower case English letters.
|
Use dynamic programming. Let dp[i][j] be the solution for the sub-array from index i to index j. Notice that if we have S[i] == S[j] one transition could be just dp(i + 1, j + 1) because in the last turn we would have a palindrome and we can extend this palindrome from both sides, the other transitions are not too difficult to deduce.
|
Array,Dynamic Programming
|
Hard
| null |
1,536 |
uh hey everybody this is larry this is me solving q3 of the recent contest minimum swaps to arrange a binary grid um so this is actually kind of a tricky problem for me to actually understand just reading the problem right but the key observation for this problem though is just knowing that uh the only thing that matters for a certain role um and all the rules are independent right so for a certain role you just have to keep track of the last one because that's the no good song right so then for me i just did uh a greedy of sorts insertion sort uh where for each so it's greedy um i don't have a good to be honest when i submitted this i wasn't super sure because it's greedy i don't i didn't have a good proof um but the idea was that okay for each row um find the earliest number that uh we can swap it up right so because and we want to prioritize the earlier thing that satisfies the current role um because that just allows fearless swap and then it pushes everything down um so i did it in a very clunky way to be honest in terms of implementation but the idea behind that is just that uh okay so for each row i keep track of the last place that um you know the last column that uh occurs on that row and then for each one i go okay if we haven't used this oh yeah we haven't used this row yet uh and that it is um and that this the last one satisfied the diagonal thing so that's what the i is i just keep track of the diagonal because the first diagonal is at zero then the second one is at one and so forth right so that's how it keeps track and we just take the first number in which this condition is true uh we add up the swaps we set it as being used and then we're done here um otherwise if this number is not used we and increment the number of swaps because that means that we're going to take one number lower and then that means that we have to move up at some point later on right and because the number of swaps let's say you take the fifth row uh the number of swaps to get from fifth to the zero would just be you know the number of rows you skipped um and also if none of the remaining rows are good then we just return with negative one because that means that we just couldn't create a thing and at the end we just sum it um yeah let me know what you think uh you could watch me stop this problem live right about now hmm so that we i don't know what's going outside it's really distracting though take this hmm okay this is two one zero can't do greedy so oh we move a 0 up okay yes um okay you hmm okay what come on you
|
Minimum Swaps to Arrange a Binary Grid
|
customers-who-bought-products-a-and-b-but-not-c
|
Given an `n x n` binary `grid`, in one step you can choose two **adjacent rows** of the grid and swap them.
A grid is said to be **valid** if all the cells above the main diagonal are **zeros**.
Return _the minimum number of steps_ needed to make the grid valid, or **\-1** if the grid cannot be valid.
The main diagonal of a grid is the diagonal that starts at cell `(1, 1)` and ends at cell `(n, n)`.
**Example 1:**
**Input:** grid = \[\[0,0,1\],\[1,1,0\],\[1,0,0\]\]
**Output:** 3
**Example 2:**
**Input:** grid = \[\[0,1,1,0\],\[0,1,1,0\],\[0,1,1,0\],\[0,1,1,0\]\]
**Output:** -1
**Explanation:** All rows are similar, swaps have no effect on the grid.
**Example 3:**
**Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,1\]\]
**Output:** 0
**Constraints:**
* `n == grid.length` `== grid[i].length`
* `1 <= n <= 200`
* `grid[i][j]` is either `0` or `1`
| null |
Database
|
Medium
| null |
209 |
hello and welcome to another CS tutor Center video today we're going to talk about the leak code problem minimum size subay sum so let's get started first what we'll do is we're going to read this description and we're going to look for keywords that tip us off as to what coding pattern we can use and then when we have that um tip then we're going to look at the constraints and see if there's anything in there that would tell us no don't use this pattern we're also going to think about the um Big O we want when we read this problem we're going to think about is there a uh you know is there a Big O that's not possible for me to go faster than okay and that the all these things will help us be able to figure out how to get started on this so let's read this it says given an array of positive integers nums and a positive integer Target return the minimal length of a subarray whose sum is greater than or equal to Target if there is no such subarray return zero instead okay so the key words that jump out to me is this right here minimal length of a subarray okay that's uh those keywords are what show up for um solving sliding window problems because with a sliding window um you are looking for one of them can be the minimal length of a subarray here let me show this list here's a list I produced of some keywords to look for in a problem that will tip you off to using the sliding window pattern Okay so if any if you know these are the types of problems that a sliding window can solve so here we are we're at the you know we're at the uh shortest sequence all right we so basically um I put a you know a sub bullet under that to say that um one such sort of sequence that they could be asking for is the minimum subray right and that's what they're asking that minimum the minimum length subarray and in here I say in the exact sequence as the original right so what that means is you know when we make a subarray like this here's our blue highlighted subray we're in the same sequence as the original the two is there then the three then the one we're not finding one where these numbers are flipped around okay um next I want to think about um I want to think about the Big O real quick because I know if I'm doing a sliding window then I'm going to be having a linear um in this particular sliding window problem where I'm just getting a subarray um from experience I know I can do that in later time and you build that up as you solve more sliding Windows problems um so linear right linear for the sliding window problem um let's take a look at if uh if it's even possible to solve this problem faster than linear and the answer is no let me explain why look at this um array they gave us right um in this array we need to find a minimum subarray so if you didn't know when we started out we don't know what's in this array so I'm just going to put question marks to signify that so we don't know what's in this array in order to know the minimum you know length subarray we have to at least look at each one of these we have to reveal at least each one of these and that means that the best we can do is linear because we have to look at least each one of these okay you know and that's because you know Big O of n at the minimum we're going to have to look at all of our all n at least once so we know we can't do any faster than uh linear so good we're still good with a uh sliding window problem perfect let's go down here the constraints oh I like this I like to see that the length of the array isn't ginormous uh because if this was like something like 10 to the 9 you know if this was like a massive length array then I wouldn't be trying to do a linear problem because it would just take way too long okay good so we're still we're doing sliding window we already know it has to be linear anyway we know it that checks out with our sanity check on the length of the array okay let's look at some other things with constraints like we know they passed in a Target that's an integer and um we know that um the value of Target can fit in an integer we know that the values of the numbers inside of the nums array can f fit in integers so quick question if I'm summing these like let's say I highlight this we know that's the answer right because it says it right here but we also know it's the answer because 4 + 3 equal 4 + 3 equal 4 + 3 equal 7 with and seven is the Target and um a length of two items is the smallest we can do to make up seven or greater so when I added that in my head you know I added that I added four and I added three when we go to write code we're going to need to store that addition somewhere and here's the question can we use a integer to store the sum of these numbers let's go look at the constraints and find out so the target um is 10 the 9 okay that can fit it in an integer um when we're doing our summing we're going to Loop over the nums and um each numb can be 10 the 4 so let's look at the extremes if I Sum 10^ let's look at the extremes if I Sum 10^ let's look at the extremes if I Sum 10^ 4 let's assume this whole thing each item inside of this array is 10^ each item inside of this array is 10^ each item inside of this array is 10^ the four and there's 10 the five of them so if I sum all that up is that going to fit in an integer yes it is so we can use a integer to store our sum okay um now let's get down to thinking about this problem okay so sliding window problem when we're sliding basically it's as it sounds as you have some window and it slides from left to right and this window can grow and it can shrink now whenever you do a sliding window problem you want to think to yourself do I need to shrink this window because that's not all you know that's not always the case some of the sliding window problems they grow and they slide but they don't shrink so you want to think do I need to shrink it well in our case we want to find the minimum subarray so in your notes to tip you off as to if you want to shrink if the windows is going to need to shrink or not know that in a problem where you need to find the minimum subarray that's a scenario where you're going to want the window to be shrinking okay let's see why all right so we're going to start out here first Loop we have two so we have a sum of two um that is not greater than are equal to seven so our Target is seven so we're going to um grow this so 2 + we're going to um grow this so 2 + we're going to um grow this so 2 + 3 which is five so that's still not seven so we grow this we're going to add one here so that's six still not seven so we grow this plus two so now we're at 8 so now a is greater than or equal to 7 so we're going to capture our minimum length so our minimum length um when we write the code we're going to do the index three which is the end of our window minus the start of our window which is zero plus one we just add you know add one um to because you get the difference between the start and the end and then plus one to it you know account for the length of it so that's for total okay so now um we have a potential minimum length solution here it is greater than the target so we're going to shrink the window notice that the two just left the window so what we're going to do here is when we um work on our sum second when we work on our sum we're going to subtract that two from it out of the window right um so sorry we had it like this so we subtracted the two out of the window and so that goes away and now we just have 2 + 3 + 1 which is + 3 + 1 which is + 3 + 1 which is 6 which is not greater than or equal 7 so we're not going to update the minimum length Okay growing the window so we grow it plus 4 so now we have 10 okay and this length is not smaller than the um our current minimum so we don't need to um update the minimum it's already four 10 is greater than or um greater than or equal to seven so we're going to remove we're going to shrink the window remove the three from it so remove the three from this window so now we got 1 + 2 + 4 so this window so now we got 1 + 2 + 4 so this window so now we got 1 + 2 + 4 so this is 7 and this is a this is three right so that's less so we're going to update this so there's our minimum length of three and then we're going to um increase the window so now we have a + three which is window so now we have a + three which is window so now we have a + three which is 10 that's greater than or equal to 7 so we shrink so take the one out so that's nine okay and then we shrink again take the two out and um now that's seven great it's greater than or equal seven it's also less length than the current minimum length so we're going to update this and then that's our solution two is our solution okay so now we got to write code for this so let's dive into that remember we started here so let's go write code starting there so we had the sum right I'm just going to call that current sum and then we had the minimum length I'll call that Min length and then we can do this and inte do max value right um to start it out like that and then when we find um one that is smaller than this maximum value we can update it or you know when we look at this these constraints here we see that um our nums do length um or not the constraint sorry when we just think about the problem let's just think about the problem for a second so we need to find a um a minimum length subarray Okay so let's look at this subarray here there's 1 2 3 4 five six right that is the smallest subarray or that's the largest subarray we can have is six so if we just start with a um seven nums do length plus one that's like an impossible State and the reason why we would initialize this with the impossible state is so that you know when we do find a solution then when we um check to see if that solution is greater than or sorry that solution is less than this minimum length that we updated on the first go and we can do that by just setting minimum length to be a length that is greater than any possible minimum length this solution can provide so let's start with the window end being zero window start being zero and then um wish this there we go and window n being less than nums do length and then window n++ okay that's because we are starting with um window end here so we got window end so window n's going to want to start right out at zero here and same with the um window start is going to want to start out at zero as well and what we're going to do let me create another text for this the start is going to represent the beginning of the window and the end is going to represent the end of the window so the beginning and the start and the end are at zero which forms this window here okay so we will say current sum plus equals nums of um window and so window end is at zero so we add what's at zero to our current sum so that's two and then um you can see each Loop you know next this will get bigger right because we're going to increase that window by one and we would add where the we would add that new number that entered the window and it would just continue to do that so remember we had that logic that like once we found a solution we updated the length and then we reduced the window see if we can find a better solution so let's add that um in there so first let me get up to a point where we have that scenario so in this scenario we have 2 + scenario so in this scenario we have 2 + scenario so in this scenario we have 2 + 3 + 1 + 2 which equals 5 6 7 8 so eight 3 + 1 + 2 which equals 5 6 7 8 so eight 3 + 1 + 2 which equals 5 6 7 8 so eight so we would update this minimum length and then we want to find a better solution now so we would shrink as long as we're going to shrink as long as the sum is greater than or equal 28 okay so let's update to have that so as long as the sum is greater than or equal to um Target I said eight sorry I meant seven in that um in our the target is seven in our scenario here so as long as the sum is greater than or equal to Target we will shrink the window okay so here's the part where we shrink the window so let's look at this we say this adds so here we go so we're so this adds and currently it's two so it's not greater than or equal to Target so it doesn't come inside of this um while loop and then it's going to Loop up and increase the window end so window end moves up here so that adds what entered the window now we got five not greater than or equal to the Target then we increase here let me just put what the let me uh have a note here for us that the target is seven okay so still not greater than or equal to the Target goes back up here increases the window size adds two in it is greater than or equal to Target updates minimum length so minimum length um remember we set minimum length to be um seven and we did that because there's six items in here so the smallest we could have is six so if we found that then we would want to update that so when we start out the minimum length we have to set it equal to something and we'll just set it to be a number bigger than we could possibly have so that when we do this math.min have so that when we do this math.min have so that when we do this math.min the one that we did find will overwrite it okay so in this case we have 3 - 0 + it okay so in this case we have 3 - 0 + it okay so in this case we have 3 - 0 + 1 which is 4 and then um we're going to shrink the window so we shrink this window so we subtract two out of this cuz that just left the window so now that's six that breaks the while loop because it's not greater than or equal to the Target go back up here and increase the window size so that adds four to this which makes that 10 and that is greater than or equal to the target comes in here at size four already reduces the window size so we just removed three from that window so now we have four five 6 7 and the window size here is three so that's smaller so we update that and then we shrink the window again because um the sum is greater than or equal to the Target so the sum is currently two the one left the window so the sum is two which is no longer greater than or equal to Target so we um the Y Loop breaks and we come over and increase the window size what comes into the window now is three so we add three so this is 789 and then um it's scare they equal to Target and so we shrink the window size here so two left the window so now we have a seven we update the length to two and then we try to shrink it again which is not equal to the Target so that breaks and then that increases and that window end is now no longer less than the length so here the minimum length is two now so um we return we can't just return minimum length because remember if we didn't find a solution it wants us to um we don't find a solution it wants us to return zero so we need to check to see if it's equal to this which means no solution so if minimum length equals that then return zero otherwise return minimum length okay so um maybe we would accidentally say two or something like that so instead of that what we can do is just say like Final in like um no result equals this signy is no result okay and then um and then we'll run it I'll run it here and it pass the test cases and then I'll submit it and then it passed the um it accepted it right okay so let me show the other way real quick so a lot of times you could just in if you're in Java I you could just do this it'll be faster and integer. max value that's um kind of standard here that's going to also be acceptable okay let's look at what it looks like in Python so in Python I wrote it over here already for us so you can take a look at that's what it looks like in Python all right well thanks everybody uh go ahead and like And subscribe let me know what you think in the comments I'm going to produce more of these and I'll talk to you later
|
Minimum Size Subarray Sum
|
minimum-size-subarray-sum
|
Given an array of positive integers `nums` and a positive integer `target`, return _the **minimal length** of a_ _subarray_ _whose sum is greater than or equal to_ `target`. If there is no such subarray, return `0` instead.
**Example 1:**
**Input:** target = 7, nums = \[2,3,1,2,4,3\]
**Output:** 2
**Explanation:** The subarray \[4,3\] has the minimal length under the problem constraint.
**Example 2:**
**Input:** target = 4, nums = \[1,4,4\]
**Output:** 1
**Example 3:**
**Input:** target = 11, nums = \[1,1,1,1,1,1,1,1\]
**Output:** 0
**Constraints:**
* `1 <= target <= 109`
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 104`
**Follow up:** If you have figured out the `O(n)` solution, try coding another solution of which the time complexity is `O(n log(n))`.
| null |
Array,Binary Search,Sliding Window,Prefix Sum
|
Medium
|
76,325,718,1776,2211,2329
|
149 |
imagine that you have a set of 2d points and you want to find the line that passes from the most points that's what the max points on a line problem about we have a list of 2d points and we want to find the maximum number of points that lie on the same line in the example below it's 5 because we have a line that passes from 5 points note that all points are unique how to solve this problem we can think of a brute force solution where we traverse all the existing lines while keeping track of the maximum number of points passed by one of them but it's just impossible because there is an infinite number of lines your solution would never stop the number of lines that passes from zero or one point is infinite but the number of lines that passes from two points or more is not we can have at most one per each couple of points in all the terms for each couple of points there exists only one line that passes from both of them and because we're searching for the line with the maximum number of points we can just ignore those with zero or one point okay but how to find lines we're interested by for that we just traverse each couple of points and see what unique line they have in common for example here for the couple a b we have this line for the couple ac we have this line for the couple ad we have this line for bc this one for bd this one and for cd this one we want to find the line that passes from the most points so we can think of a hash table where the key is a line and the value is a set of points that it passes by to fill it we do what we just did traverse couples of points for each one of them we found the common line and we add the two points to its set of points for example for the couple a b their common line is this one so we add a and b to its points in the hash table and for the couple ac their common line is this one so we add a and c to its points then for the couple ad their common line is the same as for the couple a b this is why a and d will be added to the same line this line now has three points it passes from a b and d which is true this line passes from three points and so on for remaining couples after doing so for all couples we just check the one with most points in the hash table its length represents the max number of points on a line ok but how to represent a line and how to find the common line of two points a 2d line can be represented with two elements its slope and its intercept the slope is a number that describes its direction and its steepness and the intercept is the value it passes from in the y axis second question how to find the slope and the intercept of the common line of two points we have coordinates of two points x zero y zero and x one y one the slope is how much the y value changed divided by how much the x value changed calculating that value tells us if we change x by 1 by how much y will change the formula is y 1 minus y 0 divided by x 1 minus x 0. for example with the points 4 5 and 6 9 we get 9 minus 5 divided by 6 minus 4 which gives 2 and for the intercept now that we have the slope we can subtract how much y changes multiplied by the distance from zero for example here the slope is two and at x equal to four we have y equal to five so at x equal to three we have y equal to three at x equal to two we have y one at x 1 we have y minus 1 and at x equal to 0 we have y equal to -3 so the to 0 we have y equal to -3 so the to 0 we have y equal to -3 so the intercept is minus 3. what we did is that we started from y 0 and we subtracted the slope x 0 times so the intercept is y zero minus slope multiplied by x zero we now know how to calculate the slope and the intercept but we have two edge cases one the line is horizontal and when the line is vertical the line is horizontal when y zero is equal to y1 in that case the y doesn't change so the slope is zero and the intercept is equal to y0 and y1 because the y doesn't change so the key is 0 y 0 and the line is vertical when x 0 is equal to x 1. in that case the slope is undefined because we're dividing by 0 and the intercept doesn't exist because it never crosses the y axis the only thing that makes it different from other vertical lines is the x so we take x 0 x 1 they're equal now if we want to make a function that returns let's say the id of a line it takes us parameters x0 y0 x1 and y1 if y0 is equal to y1 we know that the slope is 0 and the intercept is y0 we turn the tuple 0 y0 else if x0 is equal to x1 the line has an undefined slope because x1 minus x0 is 0 and we cannot divide by 0. and no intercept because it doesn't pass from the y axis the only characteristic is the x so we put x 0 x 1 they have the same value we can also add null as a second characteristic to keep the same return type else it means that we have a regular line the slope is y1 minus y0 divided by x1 minus x0 and the intercept is y0 minus slope multiplied by x0 we return both values note that we don't have the case where x0 is equal to x1 and y0 equal to y1 because the problem says that all points are unique okay now we're ready to solve the problem our function takes us parameter points an array of 2d points if it has only one point then the maximum points on a line is one it would likely return one that's an edge case now we create our hash table where the key is characteristics of a line and the value is a set that contains points it passes from a set to not have duplicates this is why we create a hash table where the default values are set we can start traversing couples for each index i starting from 0 for each index j starting from i plus 1 to avoid traversing the same couples we have the points pawns of i and pawns of j points of i holds x 0 and y 0 and points of j holds x 1 and y 1. next step we need to add both of them to their common line that we can find by using the function we just made we call it and in that key of the hash table we add both points we can add for example their indexes i and j after the loop line's hash table is now filled we just need to find the line with the most points and take its length for that we can put all the lengths in an array and take the maximum among them it represents the maximum number of points on the line and we solved our problem for the time complexity finding characteristics of a line requires simple calculations the cost is of one we also have nested loops to traverse couples and we have endpoints so the time complexity is of n squared note that this solution assumes that there is no floating point errors which is not always the case if you want to avoid them instead of calculating the slope and the intercept you can just let them as simplified fractions simplified by dividing by the gcd the greatest common divisor we've reached the end of this lecture i hope that you understood the solution to this problem if you want to support the channel you can like and subscribe or you can buy one of the courses in the description see you in the next one
|
Max Points on a Line
|
max-points-on-a-line
|
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_.
**Example 1:**
**Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\]
**Output:** 3
**Example 2:**
**Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\],\[2,3\],\[1,4\]\]
**Output:** 4
**Constraints:**
* `1 <= points.length <= 300`
* `points[i].length == 2`
* `-104 <= xi, yi <= 104`
* All the `points` are **unique**.
| null |
Array,Hash Table,Math,Geometry
|
Hard
|
356,2287
|
1,011 |
hello everyone so let's solve the problem capacity to ship packages within D days what is the problem saying a conveyor belt has packages that must be shipped from one port to another within days all right the ith package on the conveyor belt has a weight of this each day we load the ship with packages on the conveyor belt in the order given by weights we may not load more than the maximum weight capacity of the ship return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within the days Days so what are we given we are given an array of Weights weight of each package let's say this and a number of days let's say this now what is our task is to choose a capacity of ship let's say X choose in such a way that this x will be minimum and all these packages can be loaded into that ship one by one and they can be shipped all these packages can be shipped within this number of days okay there can be more than one ship okay so that is our task let's say we choose a capacity of 2 let's say so let's try to load our package we can load this one in this ship right but we can't load this one right so we need to increase our capacity let's say three we can load this but we can't load this one similarly if we choose 4 as our capacity we can be able to we will be able to load these three but not this one so we can see that our ship have to have a minimum capacity of the maximum weight present in out of all the packages that is six this one let's say we choose a capacity of six we will be able to load all of them isn't it so let's try to load our packages one by one this is our capacity six is our uh ship capacity can we load two yes we can load can we load three yes we can load what is the capacity five can we load four with that no five plus four is nine we exceed our capacity so this takes one ship fine okay now let's start a fresh let's load this one okay let's load this one no it exceeds we can load this one only in one ship okay how many ships did we take so far too now let's try to load this it's five can we load this one no we take one more ship then we take this one and we load it in another ship so how many ship did we require we required two plus one that is four ships and as per the question each of these ships will be shipped with in each day the first ship will be shipped in the first day the second one in second day the third one in third day the fourth one in fourth day but we have been given this that we need to finish our shipping within three days but we are taking four days right so this capacity is not possible we need to increase our capacity so that we can take in more weights into it we can load more weights isn't it let's say this is our weights array and let's say we have to ship all the packages in one day okay if this is the case we'll have to choose only one ship right we can choose only one chip and that ship will be sent in that very day right in a single day so for that what is the capacity that we are going to need we are suppo we are supposed to take a capacity that can accommodate all these weights all these packages right so what will be that capacity would be the sum of all these weights right what is the sum 5 9 14 20. we need a ship of capacity 20. not 21 because that Inc that because we are done with 20 only right no need to take more than that isn't it so what we can infer from this is that from this weights array in order to load in order to be able to load all the packages we need at least a capacity of six right and at most this is the minimum capacity that we need and at most we will we can have a capacity of 20. this will be able to accommodate every one of them one by one not all of them but at least one and this can accommodate all of them right so what are we getting from this is the lower bound of our capacity and this is the upper bound and our optimal capacity lies somewhere between 6 and 20. isn't it so what do we understand from that we need to increase this 6 as well as decrease this 20 our answer lies somewhere in between we have to reach from this from both sides so what do we understand from that this is nothing but binary search isn't it we have a lower bound we have upper bound what we are going to do definitely we are going to take a mid of 6 and 20 we are going to see let's say this mid let's assume this mid is our capacity okay we will try to accommodate all those every package into that chip of this mid capacity okay and we will see how many ships we are going to require let's say we have been given D days that is we need to ship our packages within D number of days and using this capacity of mid we have we are able to ship all the packages in X number of days okay X number of days or X number of ships because each ship will be shipped in each day right one ship is taking one day okay now if this number of days is greater than this given number of days that means it's taking more than we should right more than it should so what does that mean our mid is too small right that it's not able to accommodate more and more packages into it in that case we need to increase our capacity so that it can accommodate more and more packages right otherwise let's say we took X number of days or X number of ships and it is lesser than or equals to the given number of days okay that means we took if we are supposed to deliver within uh D days we took less than or equals to D days that means we are satisfying the condition right in that case what we can try we will see okay if we still decrease our capacity will we be able to deliver all our packages in time we can try that because our task is to minimize the capacity of each chip right so what if we can so we will try that okay so let's say this is the area of our weights these are the weights of our packages all right what is the minimum uh capacity that we should have it is 5 and what is the maximum that we should have it would be the upper bound would be the sum of all these what is that it is 15 let's say the number of days we are supposed to deliver them is three okay we are supposed to deliver all the packages within three days okay now let's try amid what is the mid of 15 and 5 it is what 10 okay let's try using this capacity one two three and four they can be loaded into one ship right the sum is 10 we can load it in and then we can load this one because if we take this five with them it will exceed right so how many ships did we require two ships that is two days that is less than three right okay we are able to deliver all our packages in time with this let's see if we decrease this can we still do it let's try that how are we going to do that we are going to decrease our high what is the what will be the high would be 9 that is mid minus 1 okay for now we will record this 9 in a variable rest result say okay that this one gives us an answer we will not try for a better capacity so the 9 is the high now 9 plus 5 is 14 by 2 is 7. so our new capacity is seven can we do can we ship all our packages in uh in seven capacity let's try one two and three we can do that recently we can load these three then if we take this one we can load it we can't take this one right it will exceed so we will take this one and take this one how many ships three ships and this one gives us a better answer right so we will consider this one that okay we have a better answer we can minimize our capacity and we can still deliver all our packages in time okay can we do better let's try that what will be the new high our new high will be six okay let's take six what is the middle six plus five is eleven the middle is five okay let's try with the capacity of five one two three no only one and two is possible okay one ship three four no we can't take four T is Possible only okay let's take four can you can we accommodate five no we exceed okay four and this remains as it is so how many ship did we take we took four ships means we took four days as well right so that is not possible we exceed our time isn't it in that case what we will do we will increase our low to what increase our low to mid Plus 1. that is 6. so our low becomes 6 5 plus 1 Let's what is the new MID 6 plus 6 is 12 by 2 is 6 only let's try with this new MID can we accommodate this one yes we can accommodate can we accomplish two yes three yes four no we exceed let's try to accommodate this can we yes can we no we stop here can we accommodate this one yes this one is the last one which remains how many ships did we take we took one two and three ships right and we haven't exceeded the given number of days now what is the capacity that we took this six capacity this new capacity right and it is better so this is our final okay we will still try to do better okay we'll start still try to minimize it now if we try to minimize our mid once again what we will do we will reduce high right High equals to Mid minus 1 that is 5 and our condition lower less than equals to high will be broken they would cross each other right they should not cross each other they should stop before Crossing each other so our condition breaks and we finally have our answer okay now that we have our idea that what we are supposed to do let's try to code this up what we are going to need a lower bound say low and an upper bound say hi let us initialize them with zero first now what is the lower bound going to be that is going to be the maximum weight okay that maximum weight is going to be the minimum capacity right so let's do that int W in weights low is going to be the maximum out of them hello W and what is going to be high or high uh upper bound is going to be the sum of all the weights right that it would be able to accommodate all of them right and we will take only one ship so high plus to w now we are going to need a result variable say address equals to what let's initially assume uh it the maximum capacity that is high okay now let's start our binary search while low is less than equals to high let's calculate our compute our mid that is the capacity current capacity I minus low divided by 2 what is this assuming say assuming mid as our capacity we will try this mid as our capacity and we will try to ship our packages with this capacity if say can be shipped what can we ship the packages let's say this one the weights the array and the mid that is our capacity less than equals to say days we will call this function and it will return the number of days that we took to deliver our packages if our capacity of a ship is mid okay if we can we will try for a better capacity a lower capacity so let's submit -1 -1 -1 okay and let's keep this capacity recorded right this can be a this can be our answer so let's keep it with ourselves if we find a better solution if we find a better capacity we will update result otherwise if we took more number of days that means our capacity is too low so in that case we will increase our lower bound that is mid plus one fine and at the end we will return our result now let's write our can be shift method the weights and the capacity that is our mid we are at least going to need one ship let's initialize it with one and let's have a current capacity equals to zero in this current capacity we will load each weight one by one okay all right for say int W in weights let's put it in our capacity current ship plus equals to W okay if our current capacity increases exceeds our capacity that we are supposed to have the maximum one like this is our capacity right this is our maximum capacity our ship can handle so we can't exceed that if we exceed what we are going to do we are going to need more ship right and in that new shape we will put this weight into that new ship all right because when we took the ship when we took this package our capacity exceeded right so we won't keep it in that previous ship we will put this in the new ship so we will reset this current capacity for our new ship okay at the end we will return the number of ships that we took that is nothing but the number of days isn't it let's try to run it so what is our time and space complexity initially we run a for Loop in weights to calculate our lower and upper bound that's the bigger of n right then we do binary search on our search space let's assume our search space is say m okay so that is going to take log of M now with each binary search with each iteration we call our can be shift method that takes a big O of n time right we uh in this we iterate over our weights array so that is into n right we can write this as n log m right so our time complexity is we go of n log M and what is the space it is constant we are not using any extra space right so yeah this is our solution I hope all of you understood I tried my best to make it clear all right so if you like this video hit the like button share this video to your friends and subscribe to my channel and I will see you in the next video bye
|
Capacity To Ship Packages Within D Days
|
flip-binary-tree-to-match-preorder-traversal
|
A conveyor belt has packages that must be shipped from one port to another within `days` days.
The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capacity of the ship.
Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within `days` days.
**Example 1:**
**Input:** weights = \[1,2,3,4,5,6,7,8,9,10\], days = 5
**Output:** 15
**Explanation:** A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10
Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.
**Example 2:**
**Input:** weights = \[3,2,2,4,1,4\], days = 3
**Output:** 6
**Explanation:** A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
1st day: 3, 2
2nd day: 2, 4
3rd day: 1, 4
**Example 3:**
**Input:** weights = \[1,2,3,1,1\], days = 4
**Output:** 3
**Explanation:**
1st day: 1
2nd day: 2
3rd day: 3
4th day: 1, 1
**Constraints:**
* `1 <= days <= weights.length <= 5 * 104`
* `1 <= weights[i] <= 500`
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
| null |
202 |
Hello hello friends in this section they want to discuss about this simple step is p number of the record interview will give you need to avoid happy number and unit replace subscribe and liquid in which results in subscribe next video subscribe are equal to 100 will Repeat Interactive Virval Two 9 Science Chapter Number Result one UP The Amazing Pimple The detention Video Last Wicket Ne Bigg Boss 60 More Numbers For Getting Into Cycle Ooo Will Never Get Number 9 P Number Ne Bittu's Drama Happy Number Logic Pretty Simple Way To Keep Track Of Members In Which Direction Problem Liquidation Subscribe Video Will Not Happy With Name Happy Functions Pay Click On Ne Bullion Is Happy Number 10-10-10 Bullion Is Happy Number 10-10-10 Bullion Is Happy Number 10-10-10 Positive Incident Returns The Amazing Track Number Inch Extra Mission E Will Used Oil Ukhd And Condition And Will Run Lutaaye The Language Setting Number Is Not Interest Alarm Set The Number Internet First That Declare A Local Variable To Keep Track Of Time Intense Penance She Deserve To Know Who Will Money Middle-aged Man Boys Note 203 Money Middle-aged Man Boys Note 203 Money Middle-aged Man Boys Note 203 Views A Pen Equals Two And By 10th Result Embroidery Number Interaction And Equal To Finally Bigg Boss Channel Subscribe Our Video Channel Subscribe To Ek Person Dalkar For North Number And North Listen To Avoid A Same Result This Point Like This Page Number 90 Thanks For Watching Please Subscribe Thank You
|
Happy Number
|
happy-number
|
Write an algorithm to determine if a number `n` is happy.
A **happy number** is a number defined by the following process:
* Starting with any positive integer, replace the number by the sum of the squares of its digits.
* Repeat the process until the number equals 1 (where it will stay), or it **loops endlessly in a cycle** which does not include 1.
* Those numbers for which this process **ends in 1** are happy.
Return `true` _if_ `n` _is a happy number, and_ `false` _if not_.
**Example 1:**
**Input:** n = 19
**Output:** true
**Explanation:**
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
**Example 2:**
**Input:** n = 2
**Output:** false
**Constraints:**
* `1 <= n <= 231 - 1`
| null |
Hash Table,Math,Two Pointers
|
Easy
|
141,258,263,2076
|
39 |
welcome to october's leeco challenge today's problem is combination sum given an array of distinct integers and a target integer return a list of all unique combinations where the chosen number sum chosen numbers sum to target you may return the combinations in any order the same number may be chosen from candidates on unlimited number of times two combinations are unique if the frequency of at least one of the chosen numbers is different so 223 is the same as 2 3 2 that makes sense i've solved this problem before so let's see if i could rehash and try to solve it from memory let's just look at our example here with two three six seven so say that we had candidates two three six seven and we have a target of seven now if we were to do this in the most straightforward fashion we'd probably do something recursively right we would start from the very beginning and try to do like that first search repeating as soon as we find that we are either the sum is equal to target or greater we will either add it to some output or revert back and then i guess do some sort of backtracking where we'll start from the next path to go on to the next number and now let's start like say it goes like two uh and then it goes two that's above seven so that doesn't work so now at two we'll try three then we'll try six so on and so forth but that's going to be exponential time complexity and on top of that we'll actually have to sort our candidates if we wanted to make sure that we don't get any duplicates so there's a dp solution where we could build up our candidate combinations by target numbers so what i mean by that is say that we had a target of seven what we'll do is create a dp array and try to build up these sub arrays to figure out what combinations we can make to get these numbers that precede seven so say with the candidate two we could see that while zero there's no combination at one there's no combination so the while the candidate is greater than our target we could just skip that but once we hit the target number for the same number we could add a combination here right so there you go but what about if it's less well obviously we can't make two like add two to make a three here but we could add two to a one to make three so why don't we check back to see all right one do we have any combinations well clearly we don't so we can't do anything here either what about a four well we can't do four but if we add it to two we could so we just go back and say all right what are the sub arrays for two well we see one of them is two so we'll just add that here we'll say two now five would be the same thing can't do anything at three and at six we would look back at four up to two we can add two to four so hey two what about seven nothing here now we move on to three and three um we'll be using the same line here and we'll say nope what about three yes we can so just say that we add three here what about four well we can add three to one and get four but there's nothing there so uh we'll just keep two and five oh right here we can see that um we can add three to two so hey right here two we just add three to two so great two to three and so on and so forth and we just build this up at the very end this last number here this last list here should have all the combinations so that's going to be our result all right so let's try to code that out and what this allows us to do actually is we don't actually need to sort our candidates at all so let's first create our gp array we're going to do is have a list of lists for blank in range of the target plus one because we want to make sure we get the zero for that uh okay so now four we're going to try each candidate each for c in candidates and for each let's say target in range of we only care about one here so we'll say one to the target plus one yeah so let's see if i recall correctly what we'll have to do is say if candidate if our candidate here is less than the target then we can just continue it's all right if our target candidate is oh okay that's the opposite if our candidate is greater than target we can just continue otherwise if candidate equals the target well then we're going to append to our dp array right here and what we'll do is append to the t we'll append a list of candid now otherwise we're going to go through our lists inside of the number that we could add to potentially in our dp array so dp of t minus c all these lists what we'll do is append to dt whatever list we have here plus the candidate now let's see if i did this right here and try to look at what the dp array looks like okay so i messed up some syntax here blank in range of target plus one targets and injurer oh okay forgot to make that equal sign now what's look like hey looks like it's working right so we just return this last index number of the dp array so let's try that submit that and accept it so i know this looks simple but this is not that simple but it's one that i would definitely say you need to know as far as time complexity goes it's o the target number i suppose as long as well as these lists inside this for loop so hmm i actually think it ends up being n squared times target might be n log n times target either way it gets accepted so that's the solution it's way faster than using a recursive that first search and that's it so thanks for watching my channel and remember do not trust me i know nothing
|
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
|
968 |
hello friends today list of binary tree cameras given binary windstorm cameras on the nodes of the tree each camera at a node can monitor its parent itself and its immediate children calculate the minimum number of cameras needed to monitor all nodes of the tree let's see these two examples in the first example we only need to put one camera here because it can monitor its children and its parent in this example in the two at least put the two cameras so how to solve this problem for a binary tree problem usually we can use a recursive algorithm but we needed to think about which order should we do the recursive or the dfs the pre-order owing order or the dfs the pre-order owing order or the dfs the pre-order owing order or pulse order in this example for this problem with the better use a post holder why because for example for this node whether we want to put a camera here is based on its children states for example if uh one of its children cannot be monitored we need to put a camera here or both of his children can be covered but does not have any more camera this state cannot be monitored so uh here's the thing the current state is based on its children's state so we need to do a post order so now let's think about the states carefully in general we have two states like we put a camera here or we don't put a camera here but for we do not put a camera here we actually have two detailed states that is even it does not have a camera that can be monitored or uh it has no camera and data cannot be monitored let's see in which state we need to put a camera that is uh any of its children cannot be monitored we need to put a camera here so we say we set we put a camera here to one and we set uh it cannot be monitored to zero right why do we need a number two because actually except these two states we have other states for example there is if the root uh the node is now if the node is now we set it to two and also uh if here is a camera this states uh for this node it does not have a camera but it can be monitored so this state is also true okay so now let's write the code then you can understand it better so the zero is that it cannot this node cannot be uh cannot be monitored if one we are sure that we must put a camera here uh what is tube um no camera but can be monitored and we set this part including it is an node okay we need a global variable we call the total that is total cameras we need so uh we must return the total but here is a help function we need to call a help function so and the return value is it this part is 3 node root so here the best case if the root is now we return 2 and then we do the post order traversal the left is helper and the router door left into right equal to helper route to the right so let's see uh as long as one of its children cannot be monitored so left equal to zero or right equal to zero we have to put a camera so turtle should increase by 1 and we return 1 and the what is we cannot be monitored that means if less left equal to 2 and the right equal to 2 because even all of its for example this part left and right all return to right because it's not this part should return zero because it cannot be monitored so return zero else will return two uh this part including it is unknown um this is in this function we should also think some base case or edge cases one is a node the root is not we just returned two so the total is not increment but the other thing that what if it only has one node so the lefter is two the right is two will return zero but actually we should at least put the one camera here so if the helper equal uh sorry helper route equal to zero we should increment the total by one okay it should work thank you for watching see you next time
|
Binary Tree Cameras
|
beautiful-array
|
You are given the `root` of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.
Return _the minimum number of cameras needed to monitor all nodes of the tree_.
**Example 1:**
**Input:** root = \[0,0,null,0,0\]
**Output:** 1
**Explanation:** One camera is enough to monitor all nodes if placed as shown.
**Example 2:**
**Input:** root = \[0,0,null,0,null,0,null,null,0\]
**Output:** 2
**Explanation:** At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `Node.val == 0`
| null |
Array,Math,Divide and Conquer
|
Medium
| null |
459 |
so today i'm going to show you an easy way to solve this problem it's called repeated substring pattern problem uh challenge number four five nine detectors so basically what we want to do is to be dividing the string by numbers so we are going to start from um r2 we are going to divide by two and then combine these two and check whether they are equal so basically when we divide by two we have h1 is equal to a b c a and x 2 is equal to b c a b c i'm going to check if x 1 plus x 2 is equal to s okay if it's not equal they're going to go ahead to divide again by three and in this case we're going to divide from here so we now have x1 is equal to a bc x2 is equal to a bc and s3 is equal to abc we are going to check if the three are combined h1 plus x2 plus s3 is equal to x and any time it's equal we simply return true and then stop so that's the approach we're going to use so the first instance we are going to divide the length of the string by two we are good we are going to get the length of the expected substring so in case of only divided by two and divided by two in this case we have uh when we divided by 2 we have the expected length of the substring to be this and we have the length of the number of repetitions should be two okay expected length is simply going to be length over two and the number of repetitions so number of substrings you're going to be getting will be uh will be this actually will be um one two okay so let's see how it actually plays out in code i think it's going to be clear up when we write the code and let's go ahead to write the code okay so the first one we want to do is to get the length of the original string so i'm going to say aims line is equal to as the length okay now we get the length of the string okay and we are going to start a folder that loops from because we are going to be dividing by two by three by four until we get to the length of the substring so we are going to actually say for end i is equal to 1 and i is less than length of the substring over 2 because we are going to first divide by 2 taking half and we are going to i plus actually i'm going to do it the other way around so i'm going to actually start from uh the bigger one to the smaller one so i'm going to say for i is equal to line over two so in our way it's going to return uh faster than when you start from the scratch so length over to and then we are going to r2 i is greater than zero we're gonna do i minus all right so this time we are now going to check if it was actually divisible okay because for us to be able to get chunks of the string that add up to the original string we are going to check if it was in the originally divisible so we are going to say uh we're going to say if is visible is so if the line over 2 the lane of 2 is equal to 0 it means it's divisible then we can continue the next operation all right so what knights do we do here we want to get number of substrings that we expect so number of substrings sub strings to expect here is going to be remember we say i is equal to length over two and in this case we had i becomes six so number of soft string we are going to be getting where we are dividing into six places is going to be is going to actually be the length over two so these are number of sub strings we expect to get the number of substrings we expect to get when we divide when we throw an i is equal to two is equal to 6 is actually 6 different substrings so it's going to be length divided by i okay and we are going to now create a string builder that we are going to use to concatenate all the strings so i'm going to say string builder sb zip alto neo string build up okay so now we have a new screen builder sb and we now want to iterate but before we iterate we are going to get this the particular substring that we want to concatenate so this is a number of substrings you want to concatenate and the number of the actual substrings i'm going to say uh string let me call it scr is if also is not going to be x going from s dot substring going from 0 to i okay so we are now going to concatenate uh all these substrings this substring here sr we are going to concatenate it number of times this number of times and once we concatenate it we are going to compare whether this concatenation this string we build is exactly the same as the original string and then we're going to return true so we're going to say for and i is equal to zero i is less than in this case is number of substrings so you can say num sub strings and say i plus and now i'm going to go down and we are now going to say sb that are paint that's going to paint this uh the particular substring so let's see so we're going to paint applying the soft of the substring to the string builder so the substring is str meanwhile i need to kind of uh put the declaration here so it's just going to be and this is going to be string okay finally we will if this completes uh this code completes and yeah so give me this yeah so we are going to check here if sb dots to string dot equals if this is equal to the original string then we return true however if he is not equal to there is no string until this loop exits we are going to simply return false okay sorry i may have mixed up a few things but this is exactly how it works you want to divide the strings into chunks uh right here get the number of substrings in question you want in question get the particular chunks here and then use a string builder to add a polygons and check if this equates the original string so i'm going to kind of reduce the size of my screen so i'll be able to see the wrong button so i'm going to run this code now let me just make some room here and we have error so we have if so this is java sometimes i think i'm writing with python uh sorry for that so let me run it again just to see if it works um so variable i is already defined in the scope so let's use j this time so j um use j and i'm going to run it again cannot find symbol uh second speed to string so it's gonna be a function called to string method here and hopefully it works so this time it works i'm going to quickly submit it now let's see what we have and as you expected it worked perfectly oh it gave us a wrong answer let's see return false when this child return true let's see where we got some problem j is equal to takes num strings and the i from zero okay sorry so this is going to be um if lane mod tools will be lane mod i yeah so i'm going to submit one more time okay so you can see it worked and it gave 77.9 percent uh faster so i think gave 77.9 percent uh faster so i think gave 77.9 percent uh faster so i think we did a good job i'm sorry i might have kind of mixed up things a bit uh i've not written java for some time i've been writing and biting all this time so please remember to just let me know something i can do to improve my lessons or my um my problem solving here in lead code i'd like to thank you for viewing and please remember to subscribe if you find this to be informative if i remain kind of the tech pro and i'm always there for you
|
Repeated Substring Pattern
|
repeated-substring-pattern
|
Given a string `s`, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
**Example 1:**
**Input:** s = "abab "
**Output:** true
**Explanation:** It is the substring "ab " twice.
**Example 2:**
**Input:** s = "aba "
**Output:** false
**Example 3:**
**Input:** s = "abcabcabcabc "
**Output:** true
**Explanation:** It is the substring "abc " four times or the substring "abcabc " twice.
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of lowercase English letters.
| null |
String,String Matching
|
Easy
|
28,686
|
832 |
Work in this area Ajay Ko That [ That [ That Hello Everyone and Welcome to New Video in this Video Before going to discuss another problem from code problem share and subscribe liquid liner meaning element village meaning first of all we Subscribe means to zero, subscribe means to subscribe every day, Nirodh will go to 1, 0 and this is what we did to zero, first of all we clicked it, now what we have to do, after that we have to fold it to 200 and do this entire operation. And lastly, what can we do if we do something like this in our metric result 2017, first of all we have to click on 100, what can we do to click, first of all we can do that if our number Of elements, be it China or old then and plus one, whatever our number of elements will be, divide it and get a number track - till, divide it and get a number track - till, definitely subscribe to ours, with whom, click on this, our last kind of last, click on both of them. Then we will click on it with this, so someone subscribe both of them and subscribe, we will run it and from where to where, whatever length it will be, and now we will do this inside this, now inside this, we will run another for loop, this Where will it work, here it will be equal to zero, six hydrogens, whatever the number of columns, every time again, we will do C plus one and divide it by two. Okay, till here we have to look at our rukh column, which we make. That I will be declared and update it every now and then, what will we do in this, we will have to change the reflective element in it and to entertain Roshni, whatever may have happened - whatever will be ours and whatever will be ours - whatever will be ours and whatever will be ours - whatever will be ours and whatever will be ours here. But the value of - - - - If we - If we - If we do this then this is our like this is our now along with this, if we want to do anything here then what can we do, we can run another form or we can subscribe to this and appoint on this Let's do let's marry it with whom by marrying it with and here if what we do then we will also get 1012 quote 7 in word and if our value of this is changed to one instead of zero then we will get 1410 then we will get what you Here in Melbourne, we will get zero down here, we will also have an inverter here, so with the help of these two for loops, we can solve our problem, now we will see how much the office tips will cost us, so for this we will get the number If we look carefully at how many steps will it take, then if we have embargo and problem, then the number we will get is office tips, home made of same cross, admin2 and this will be our skin, time complexity, Mintu, what will be ours, Mintu, if we look at these carefully. See, our N will be in, what is our number of elements in the matrix, then its time complexity will be omega of and here, what is ours and is our number of elements, if I talk about its space context, space complexity, we have no extra energy. If it is not made, then who is its friend who is its space, then its space complexity will be soaked after one, so let's go, let's write the code for it on the internet. Apart from that, I will tell you a very interesting thing here, first of all, I write for this, so first of all. Let us make a label, what will be our common, what will be our number of roses, how will we get the number of roses, whatever we take from our matriculation, she will give us the number of roses, what is the need of time, next we need the number of columns, so let's take the number of columns. Image of here, we know that if we do cross ends, then any gardener will be planted at zero and will take inches for it, this is no issues, what do we have to do and run that, where from where did it last 106 sex, how far will it last, that this is ours which is ours We will do the ghagra here, so we will do ours from here, this is my number, man plus one divided by two, till here we are going to run this and we will update this one every time, inside this, what will we do in this, mix it in and let us do. With this so that we do not have to face the second problem and what we have is here, what will we do, where will we sign in this, we will do this, instead of the image, we will click on the place, we will subscribe to this channel, we will do this in every village. What we are going to do are the fluoride clips of the image of I and J, that is, we will equalize the image of A and that means the first element of the letters, this will be our first element, that is, we will add the element from the front side to the last. Now what will we do? Now we cut this, I will make this equal, whatever we made time equal to time, apart from this, we have done one thing here, we have done non, here we will do this, with whom we will do this, definitely do this, village like these two are finished. And this will be our result then subscribe and submit the result subscribe and the question result comes and here if we see this is our faster than hundred percent of online Jawar combination, what is its time complexity Vivo and where is the number of elements Space solution Explain how we have decided that here we have used it first of all and every day element we have taken it from the front side we have taken it and the one that has traveled from the back side we have taken it - verb - step And after that, while doing both of these things, he is taken it - verb - step And after that, while doing both of these things, he is taken it - verb - step And after that, while doing both of these things, he is also doing this, with whom, like our country, ours, we are doing it, thank you, do it MP3, do it
|
Flipping an Image
|
binary-tree-pruning
|
Given an `n x n` binary matrix `image`, flip the image **horizontally**, then invert it, and return _the resulting image_.
To flip an image horizontally means that each row of the image is reversed.
* For example, flipping `[1,1,0]` horizontally results in `[0,1,1]`.
To invert an image means that each `0` is replaced by `1`, and each `1` is replaced by `0`.
* For example, inverting `[0,1,1]` results in `[1,0,0]`.
**Example 1:**
**Input:** image = \[\[1,1,0\],\[1,0,1\],\[0,0,0\]\]
**Output:** \[\[1,0,0\],\[0,1,0\],\[1,1,1\]\]
**Explanation:** First reverse each row: \[\[0,1,1\],\[1,0,1\],\[0,0,0\]\].
Then, invert the image: \[\[1,0,0\],\[0,1,0\],\[1,1,1\]\]
**Example 2:**
**Input:** image = \[\[1,1,0,0\],\[1,0,0,1\],\[0,1,1,1\],\[1,0,1,0\]\]
**Output:** \[\[1,1,0,0\],\[0,1,1,0\],\[0,0,0,1\],\[1,0,1,0\]\]
**Explanation:** First reverse each row: \[\[0,0,1,1\],\[1,0,0,1\],\[1,1,1,0\],\[0,1,0,1\]\].
Then invert the image: \[\[1,1,0,0\],\[0,1,1,0\],\[0,0,0,1\],\[1,0,1,0\]\]
**Constraints:**
* `n == image.length`
* `n == image[i].length`
* `1 <= n <= 20`
* `images[i][j]` is either `0` or `1`.
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
| null |
1,171 |
this question is you need to remove a zero sum consecutive note from linked list you can see one input and output given I'll explain you the approach how we solve this question with proper diagram first we will create a domino with value 0 next Domino next will be initialized to head node second point is I will take one current note and current node will Traverse the list till it reach to the end of the list so initially current node will be initialized to dominode so next I will take I'll create one has map name is prefix a map it will store prefix samas key and list node as value will Traverse the whole list so I am taking one while loop and condition is while current node not equals to null it will move to next node based on our another condition I will explain that one now calculate prefix sum so now current node is 0 so prefix sum is zero so now I will check if prefix sum present in map or not if it is not present then I will store the key and value into map next at the end we will move our current node to next node that means now our current node is one again it will check current node is not null yes it is not null then calculate prefix sum now current node is one so prefix sum is before prefix sum was 0 so 0 plus 1 is 1 now prefix sum is one now again it will check prefix sum Keys present in map or not it is not present so we will store Key and value into map so key is prefix sum and value is current node we are storing so after storing key and value at the end we will move our current node to next node that means now our current node is 2 again it will check current node is not null yes it is not null then calculate prefix sum before prefix some value as 1 and current node value now is 2 so 1 plus 2 is 3 so prefixion value is now 3. now it will check prefix some key is present in map or not so this key is not present in map show we will store Key and value keys 3 and value Min current node is 2 that will store after storing that we will move our current node to next node so now current node is -3 again it will now current node is -3 again it will now current node is -3 again it will take current node is null or not yes it is not null calculate prefix sample prefix sum was 3 and now current node is minus 3 so 3 minus 3 is 0 so now prefix sum is zero again it will take that prefix sum is already present in map or not yes it is already present in map here what I will do I will remove all that entry in between and from least I will ignore all those node in between so how we can do this I will explain here now so our current node is minus 3 and prefix sum is 0 and 0 key is already present in map so we need to ignore all the node in between getting prefix sum 0 so for this I will search the prefix sum node value from map next I will initialize current node to next node of reflection node so my current node is now one now I will take some variable to get the sum for those node I am going to skip so calculate sum physicsum plus current note value exam is now zero and current node value is now 1 so now sum is 1 now taking one more while loop while some naughty quest of ref exam when this condition will be true will give our next condition that will be executed so when sum and traffic sum is not sim we are going to remove this entry from map next we are moving our current node to next node that means current node now is 2 so calculate some value current node value before some value was 1 now current node value is 2 so 1 plus 2 3 so sum is now three again it will check sum and prefix sum is not same yes it is not shame so we will remove next entry from map next entry having key is a three we are removing this entry we are moving our current node to next node that means current node now is -3 node that means current node now is -3 node that means current node now is -3 sum is before it was minus 3 now plus current node value min 3 minus three zero now sum is 0. again it will check sum and prefix sum is same or not yes it is same so condition is false our while loop will not run at the end get the prefix some node from mapping next this prefix some node next will point to current node next you can see how we skipped all these node in between where we'll get the sum as prefix sum value at the end we are moving our current node to next node show or current node is now 3. same thing again current node is not null so we will calculate our prefix sum of 0 now current node is 3 so 0 plus 3 now prefix sum is 3 is present in map no it is not present so we will again put all those entry when prefix sum as key and current node as value next we'll move our current node to next node so now current nourish one so again it will take current node is not null yes it is not null so it will take prefixion prefix sum before it was 3 and current node is now one so three plus one four so prefix sum is 4 so is there any entry with 4 no so in math we don't have any entries over here putting current node one at the end we are moving our current no to next node show our current node is null so our while loop will not run at the end will return dummy next node that means it will return three Bond null so coming to the solution okay so here is coding but taking uh creating one dummy node type is list mode value we are keeping zero taking one more note that is current node it is to dummy next is initial is through next dummy next is initial is through head node now taking one variable prefix sum that will sum all the traffic node taking one map integer key is integer type and value is list no type now a one while loop it will take current note is not null and it will move current note to next node based on our condition and put all the details later now at the end we will return Dominic's not that means we are avoiding that extra node zero okay so it will check before that before checking only calculate prefix sum value so Perfection will be Perfection plus current node value if this prefixion key is present in map already and I'll check and write letter else if K is not present in map we are putting k n value into map so now if K is already present in map I will initialize my current note 2. where I am getting prefix note value on that note to next node now I am taking one sum foreign so if sum and prefix some value is not shim then we will remove entry where Keys some and current node will be next node of cardinal now when sum and Perfection will be same I'll get the node where prefix sum value is there and that node next will point to current node next no run okay H is missing now we can rerun again yeah it is accepted on the code now I can submit so you can see the details of this code yeah thank you for watching this video
|
Remove Zero Sum Consecutive Nodes from Linked List
|
shortest-path-in-binary-matrix
|
Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences.
After doing so, return the head of the final linked list. You may return any such answer.
(Note that in the examples below, all sequences are serializations of `ListNode` objects.)
**Example 1:**
**Input:** head = \[1,2,-3,3,1\]
**Output:** \[3,1\]
**Note:** The answer \[1,2,1\] would also be accepted.
**Example 2:**
**Input:** head = \[1,2,3,-3,4\]
**Output:** \[1,2,4\]
**Example 3:**
**Input:** head = \[1,2,3,-3,-2\]
**Output:** \[1\]
**Constraints:**
* The given linked list will contain between `1` and `1000` nodes.
* Each node in the linked list has `-1000 <= node.val <= 1000`.
|
Do a breadth first search to find the shortest path.
|
Array,Breadth-First Search,Matrix
|
Medium
| null |
52 |
hello friends welcome to joy of life so today we are going to look at the heart problem which is uh problem number 52. the problem is and queens too it's the extension of the main problem in queens um which i have done a video previously you can check it out before checking this as well i'll share the link as well in this video description below so let's look at the problem the end queen puzzle is the problem of placing n queens on a n into n chessboard such that no two queens attack each other given an integer n return the number of distinct position of position to the end queen puzzle so we are supposed to return the count of possible safe configuration that we can have given a board of size n so here you can see that these two are safe here none of the queens are under threat by other queens right so if you see here that uh all the queens are pretty much safe so we need to see how many such placements are possible how many such configurations are possible so we are going to look at the problem in much more details and also come up with the code but as i always do recommend that do give it a try yourself you can refer to my other video which pretty much explains the solution as well and then you can resume this video or after you give it a try so we have taken the example uh from the lead code where n equals to 4 and we have also taken a chess board of size 4 by 4 wherein we have marked it with also numbers so that it's easier for you to understand we have markings like a1 b1 a2 b2 and so on and so forth so what happens over here so when you are given with the empty chessboard and you have no queens and you are supposed to fill up the first row which is this row over here so what are the valid choices that you can make over here so all these are valid choices because there are no queen and if i have to place one queen that queen will never be under threat right so what we are doing is we are trying to see our possibility space at every level and then go to the recursion so at the first level of recursion there is nothing on the board and what are my valid choices at this level is we have all the choices are valid over here so let's start with a1 so we at level one there are four choices that i can make from a1 through d1 so let's say we choose a1 so if i place a queen over here what happens is these cells are not accessible to me for the next row right because they are under threat of this queen so if i place a queen here this queen over here can kill this queen right so that is not a valid choice for me wherein the other two cells which are c2 and d2 they looks pretty safe and a queen can be placed there so if i make a choice that is a1 my next two available choice would be uh c2 and d2 so c2 and d2 are the choices that i'm left with so let's say i and mind it we cannot place in the same row so i am not talking about them so that is negated by itself right so when i uh say put a queen at c2 what happens is for the next row my these options are gone so you can see here that from c2 there is no way it is possible for me to go into level three so if i choose a2 and then i make a choice c2 then i cannot proceed ahead so this is taking me to a dead end so i am not going to use c2 let me see if i can make use of d2 so if i put a queen over here what happens is my these options are gone but i still have a choice to make at b3 and let me draw the lines so this denotes the different level of recursion so you can say this is my level one this is my level two and this is my level three okay so if i make a choice at b3 which is over here what happens is my oh god i'm again left with no choices so b3 is also pushing me to a dead end so d2 b3 and i do not have any other child under a1 so we have explored the possibility space that if i place a queen at a1 that do i have any other choices to make and i see unfortunately there is no choices that i can make so a1 could not make it so what we'll do next is we'll check with b1 so now we put a queen over here so once i put a queen over here these choices went off for me so the only choice that i am left with is d2 so d2 is my only option going with b1 so if i place a queen at d2 what happens is my these options are gone i can still afford to uh put a queen at a3 so let me take that into consideration so a3 is my viable option so i put a queen over here so once i put a queen what happens is i check what are my eligible places over here so as you can see that if i put at a3 now i can put one at c4 and let's say this is my level 4 of the recursion so when i come to c4 and put a q and i see that my level is 4 which is my n as well so at that point moment i know that this path this part the entire path is a valid configuration for me when no queens will be under threat so if i remove this crosses from the table what you will see is no queen is attacking the other or all of them are safe so if you say this queen over here diagonally it can go here this side anyways at the row and column there is nothing this queen is also not attacking anybody this is also not attacking anybody so all of them are safe and nobody is attacking anybody so this is one valid configuration that we have found b from b1 but keep in mind that we still have c1 and d1 on explode and we can find more such configurations from there maybe so let me put a queen at c1 at putting at c1 what happens is my these options are gone and the only choice that i have is a a2 from c1 so let's say i have a choice a2 and i put a queen at a2 and for the next row my valid choices are only this cell which is um d3 so d3 is a valid choice for me so let me put the lines okay so i put a queen at d3 and what i see is my this option is gone this will be attacked by it and i still have a choice to make and that is um b4 i place a queen at b4 and what i see is that i have reached the level 4 of the recursion again so that having said that means that i can have a valid path which is not putting any queen under threat so i have found my second options second option from here as well as you can see over here this is my second option so here also if you look closely that no queen is attacking any of the other queens all of them are placed safely right now we have we still have one more um uh choice to make at the initial level that is d1 so if i put a queen at d1 what happens is my these two options are gone and i am left with two choices a2 and b b2 so d1 can have two choices a2 and b2 so let's say we are putting a queen at a2 and putting a queen at a2 what it means is my these options are gone i still have c3 only option that's spawning out of a2 which is c3 and if i put a queen over uh queen at c3 what i see is that my this is not a valid option so i see that again i hit a dead end over here so c3 a2 so no other a child of a2 is available so this part is a dead path so i still have b2 to look at so what i'll do is let me remove from here so i put a queen at b2 and placing a queen at b2 means that my these options are gone this is also gone oh my god i instantly came to a halt right b2 cannot be proceed any further so my this option is also gone so as you can see here there are two valid paths that we can figure out from here so these are the two parts and all other parts are leading to a dead end so what is the basic idea over here so i have a possibility space at every state so when i am at this level i have a possibility space which is equal to the size n right i can place anywhere and now i am trying that if i place it over here what is my possibility space so that is when depict all my possibility is coming out of a function right a recursive function basically so what are we checking from this function that initially everything is empty then we are putting uh putting a queen at a one when i put a queen at a1 what is happening i have two choices to make c2 and d2 if i go at c2 i cannot proceed any further so i fall back and go to d2 and from d2 i can see that i can go to b3 but from b3 i cannot proceed any further so i fall back because i did not complete the board fully then i see that a2 has a1 has only two childs then i fall back to the main function again and i start exploring b1 what if i put at b1 then i have a choice at d2 and then at a3 and i could see that i could find a path over here so this is how this entire problem breaks down into different choices so at every level if you look closely that you have some possibility space and we are exploiting this possibility space to see where we are meeting our uh exit criteria or the success criteria so these are all my exit criterias these are also exit criterias but they are not successful exit criteria this these two are my successful exit criterias and when we write the code we will also see that how this will be mapped into code right so let's move over to the code and look at the solution so we are going to look at the solution which is pretty much the same as the end queen problem but here we need to return just the number of configuration that we have seen so here the solution is pretty much the same as the end queen problem but we need to return the just the count of the configuration valid configuration where queens are not under the threat so we'll be returning um integer in this case and we'll be calling our solve function and just like the previous problem we are going to create a boolean array of the which is of the size of the board and we are going to check uh for each of the rows so we are going to check for the zeroth row starting from the zeroth row and if you remember uh that in the zero way through all the combinations are valid so we are going to uh choose each one and then we are going to see on the next row what are our valid placement that is possible so we will look at the solve function here which will return a end and which will take a boolean board and it will also take the row that we are filling for so initially it will be passed with a 0 from the total end queen function and as we progress we'll be incrementing the row and sending and if we see at any point that our recursion has reached n which is nothing but the size of the board or the length of the board rather then we can say that we have found a valid uh valid configuration and we are going to return a one in the in that case otherwise what we are going to do we are going to uh we are going to write a function we are going to like uh going to write a loop which will check for all the possible um possible options for us over here so we are going to check for each of the cell in that row so we are going to go through all the cells for that particular row and we are going to ensure two things firstly that cell should be a false it should not be a true so let's write down the condition over here so board of row and i should be a false and then we are also going to check that is queen safe at that position or not is queen safe so we'll write a method screen safe which will take a board we will pass the board to this function and we'll be passing row and i so let's write this function so this function should return a boolean is queen safe and which will take a boolean array which is the board and it will take the row and the column all right recall that if we are checking for this cell so we need to validate this and this so horizontally and vertically so if you are doing for this cell so we will only check the top part because we have started filling from the top part right so when i'm filling this i'll check this and this so nothing up here so for this cell we'll check this and this for this cell we'll be checking this and this so we'll also check the diagonal but first let us do for the horizontal and vertical cells so what we are going to do we are going to write a loop for this so we will be basically going through the board dot length and for e and for any of the cell if we see that uh we are getting um so let's say row and i so i am keeping my row fixed and i'm just incrementing my i so i'm checking this my row is fixed right if i'm getting a true anywhere over here or i am checking uh my i and i am checking my calls so i am keeping the column fixed and just incrementing this part right so i am checking for all these cells right so if i see any uh any of the fields to be true what i can say is that this queen is not safe over here so it is having a threat otherwise what we are going to do we are going to increment uh we are going to set i to row minus 1 and j call minus one so what we are going to do is we are going to so for this cell say we are putting up putting a queen here so i minus 1 j minus 1 indicates this cell over here so i is decremented by 1 j is decremented by 1 so row is decremented by 1 column is decremented by 1 so what we are going to do we are going to say while i greater than equals to 0 and j greater than equals to zero we are going to continue this loop and since we are going towards the left top diagonal from the position so what will happen is i will be decremented along with the jail also be decremented so if you see here this is row minus one call minus one this is again from that cell row minus one call minus one any point of time if we see a board i or j is set to true that means the queen is not safe there so we can safely return a false that queen is not safe so just uh take this scenario if i am placing over here and i start from here and going all the way diagonally to the left top corner and if i see any of the fields to be true i can that means that there is a queen here so if there is a queen in this cell so i cannot place my queen over here so that's why i'm returning a false similarly for uh for the other diagonal say i am placing here so we have considered this diagonal but we have not considered this diagonal yet so we are going to do for this diagonal so for this diagonal what will be my initial condition so i will decrement my row one and uh for j which is my column indicator i'll say column plus one so if you see here uh if you take from this cell if i go up means i am decrementing my row so row minus 1 and i am looking at the right diagonal so this one so if i uh say this call this column so that means this is plus 1 from relative to this column right so i is initialized to row minus 1 and column is initialized to column plus 1 and we will continue to do it while uh so in this case it is a little different what is happening is i is decrementing so i have to check that i should be greater than equal to 0 and at every point the column is incrementing so column j should be less than my board length so as you can see here what we are doing basically is we are decrementing i but we are incrementing j right that's how we are uh going vertically towards the right top corner okay and the condition remains the same if at any point of time i see that my board i j is a true is having a true that means the queen is not safe here so i will return a false that means if i am placing a queen over here i should see that all of these should be false if i see there is a queen over here that means this placing this queen is unsafe so if this can if this if none of these conditions are met that means my queen is safe and in that case what i'll be doing is i'll be returning a true that means my queen is safe there okay so since my queen is safe here so what i'll do is i what i will first up update my board so i will put board of row and i to be true and what i'll do is i will uh call the solve function again right so i'll be calling with the updated board and uh what i'll be doing is i'll be uh check uh filling up for the next row right so i'll be setting to row plus 1 and if you remember when we did the try done so when we explored all the option a1 and move to b2 we erased this so that when we erased it what does it mean we are setting it back to false once we have explored all it all the options so we are going to do something similar over here so we will say that board of row and i once we are done exploring we can say that okay i am done exploring it set it back to false and do remember at every point the solved method is returning me an integer so i also need to keep a track of the count which is initially zero and at every point what whatever i get back from count i am going to update so in this case count will return me a zero count will return me a one i'll continue with this i will do a count equals to count plus 1 so we'll do this which is count equals to count plus this will return me a 1 so the answer will become 2 and at the end count will hold how many combinations i have found so this is the entire solution this is the entire algorithm which is pretty much the same as the row queen row coin solution that we have looked at so we'll run the code and see laughs so yeah one few of the indentation were bad and this was badly written as and it should be our so i have modified it and did the indentation for you anyways the solution will also be posted along with the description of the problem so let's do a submit and check so yeah it has been passed so let's uh submit it for a wider range of test cases and see so yeah it has been accepted which is taking around two milliseconds of time but again the whole intention uh for solving this problem is to give you the idea on how we are coming up with the solution how we are exploring our option space and limiting our options and coming up with the solution so i hope you were able to get it if you have any doubts or question do feel to post a comment i would try to answer it as soon as possible so yeah that's all from this video i hope you liked the solution do let me know in the comments do share with your friends and also please subscribe if you haven't done so and that will keep me motivated on creating more videos and thanks once again and have a great day see you guys bye
|
N-Queens II
|
n-queens-ii
|
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.
Given an integer `n`, return _the number of distinct solutions to the **n-queens puzzle**_.
**Example 1:**
**Input:** n = 4
**Output:** 2
**Explanation:** There are two distinct solutions to the 4-queens puzzle as shown.
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 9`
| null |
Backtracking
|
Hard
|
51
|
1,043 |
Hello everyone Welcome to my channel here I solve problems Lead code Today I will solve the daily Challenge This is task number 1043 divide the array to obtain the maximum amount level average we are given an array of integers R we need to divide it into consecutive subarrays of length no more than K after what division, all elements under the array are replaced by the maximum element, it is necessary to divide the array in such a way as to obtain the maximum sum of elements, taking into account the replacements that I described earlier. This is clearly seen in example one. We have an array with a certain number of elements and K equal. That is, we can divide into subarrays with a length of no more than three elements, that is, 1D or three elements, we can divide this array in the following way: the maximum way: the maximum way: the maximum result is first taken the first three elements, that is, among them the maximum value is 15, respectively, we replace all three with 15 four elements and select it as a separate subarray then there is a value of dev and the last three elements have a maximum value - this is the elements have a maximum value - this is the elements have a maximum value - this is the value of the maximum element 10 That is, we replace all three with 10 and in the end the total amount will be 84 that is, this is what we need from us now how will we solve this Let's try to look graphically For example, we again have the same elements, that is, 1 15 7 9 2 5 10 such elements are Kara inside three, let’s elements are Kara inside three, let’s elements are Kara inside three, let’s write car inside three That is, this is the maximum value for the array, how will we solve? That is, I’ll say right away array, how will we solve? That is, I’ll say right away array, how will we solve? That is, I’ll say right away that my solution will be recursive then it is more understandable. Although you can decide to call the function iteratively to obtain the maximum sum of the entire array, that is, All elements and, accordingly, inside the function we will look at the result of calling this function, that is, how it will look, that is, we take a subarray sequentially from one element from two elements and out of three That is, in this example it’s either from three That is, in this example it’s either from three That is, in this example it’s either from one to k, that is, K is the maximum number of elements under the array, and that is, we take, respectively, let’s say the is, we take, respectively, let’s say the is, we take, respectively, let’s say the first element, then call the same thing, let’s say same thing, let’s say same thing, let’s say function F is marked here and call the first element plus this sum f from the first element and further, that is, from the second element and to the end, the second option is possible. For example, we can take the maximum from the first two elements, we will count the maximum sequentially. That is, the first element is the maximum, then the maximum from two elements. That is, this is 15 then that is, we take the maximum of two elements and multiply by the number of elements, that is, two we get 15, that is, 30 is the sum plus and call the function again, this function f from the remaining part and the last option is the third, we take the maximum of the first three elements, that is, 1 5 15 and 7 that is, accordingly, from three elements the maximum is also 15 and therefore we multiply 15 by 3 and from the remaining elements we also call the recursive function F so when the function is added inside, the maximum option from three options will also be taken, that is, when we take one element two elements three elements and until we reach the end of the array. That is, until we pass an empty array inside the function f, then we calculate. Let’s then we calculate. Let’s then we calculate. Let’s look at this recursively, that is, what we need a recursive function, let’s need, we need a recursive function, let’s need, we need a recursive function, let’s say traditionally Helper and we will call it from with parameter one hundred this the index from which we start our subarray inside what we need to check so first let's create a variable result Zero by default - this will be result Zero by default - this will be result Zero by default - this will be the sum that is our maximum sum we also need so we need a variable for the maximum sum of the array let's say we'll call it mom too for now but also we need to check all subarrays respectively in the interval, that is, I in this case there will be an offset, that is, how many elements besides the current one We take into our subarray, that is, the options will be either only current ones, then with the index Start or Start start and start P 1 or Start P 1 and start P 2 that is And here we need to update the value of the maximum sum at each step That is, this is equal to the maximum value of max and the current element is the start element plus I so And by the way we need to Just check that our element is one hundred n I it is less than the maximum size of the array That is, we are in the affairs of the array. Thus, it turns out that at each step we find out the maximum value from each of the three elements, that is, it will be like this in example one then one maximum value one then 1115 is already the maximum 15 and 1 15 7 the maximum is also 15 that is, we get the maximum value of the sum and add to the result the maximum value of the same result, that is, Our task is, again, in the figure, the solution is circled in green, orange and blue, choose which one of them will return the maximum sum since we ultimately need to return the largest result of all possible ones, that is, we will return the maximum value and at each step the maximum is the max value multiplied by the number of elements, that is, again, look here in the first case 1 y by 1 in the case of two elements 15 y by 2 since we have two elements in the subarray and in the third case 15 y 3 the number of elements in this case is our offset I P 1 that is, we add a call to the same function from Start plus I P O like this and as a result, we return this is our auxiliary function and in the main function we return a function for any element, that is, we need to calculate the maximum value starting from index zero and throughout the whole According to the array, in theory This is the whole solution, but as happens in recursive functions, especially those that are called more than once inside, that is, the function is called once on itself. Well, in the body of the function, in cases where you need to add local caching, which will significantly speed up the execution of the program, there is a local cache that remembers the intermediate result and the Start index has calculated the value, then there will be no recursive calls and the answer will be returned immediately the function the cash function is in the Fun Tools package now it still works but much faster Let's try to send the whole solution, it was made quite efficient in time and quite from memory, for today we have the complete solution as always, look in the description, see you tomorrow Bye
|
Partition Array for Maximum Sum
|
grid-illumination
|
Given an integer array `arr`, partition the array into (contiguous) subarrays of length **at most** `k`. After partitioning, each subarray has their values changed to become the maximum value of that subarray.
Return _the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a **32-bit** integer._
**Example 1:**
**Input:** arr = \[1,15,7,9,2,5,10\], k = 3
**Output:** 84
**Explanation:** arr becomes \[15,15,15,9,10,10,10\]
**Example 2:**
**Input:** arr = \[1,4,1,5,7,3,6,1,9,9,3\], k = 4
**Output:** 83
**Example 3:**
**Input:** arr = \[1\], k = 1
**Output:** 1
**Constraints:**
* `1 <= arr.length <= 500`
* `0 <= arr[i] <= 109`
* `1 <= k <= arr.length`
| null |
Array,Hash Table
|
Hard
|
51
|
59 |
hey so welcome back in this another daily code problem so today it's called spiral Matrix 2 and actually yesterday's problem was called spiral Matrix so it's kind of the what's the second version of it so very similar algorithm they just change it up a little bit so yeah let's get started so it's a medium level question and it's pretty popular is 5 000 upvotes and all that you want to do is you're given a particular number n and you want to construct an N by n array and so it's a two-dimensional Matrix with n rows and N two-dimensional Matrix with n rows and N two-dimensional Matrix with n rows and N columns and basically you just want to populate this Matrix oh my music's a bit too loud you want to populate this Matrix so that um in this kind of spiral order it increments by one each time so if you kind of followed it you'd expect it to be incrementing by one each time okay so oh I'm gonna not show you this yet but we're going to take a very similar approach or the same approach that I did yesterday where all that you have to do is you have four different variables that you're keeping track of and that's just like the starting column which is this one here the ending column the starting row and the ending row and you just kind of move these uh pointers around as you populate this Matrix so first you start off with populating the top row here from left to right then from top down then the bottom row from right to left or from the right side to the left side and then up and then you just kind of keep repeating that algorithm so yeah let's go ahead and implement this so first we'll want to make that Matrix so we'll just call it mat for short for Matrix and in Python it looks like this where initially set it to zero and we have n columns and we'll have n rows okay and so that's our Matrix and at the end of this we're going to want to return it and then we want to have those four different pointers so we have our starting column our ending column our starting row and our ending row and that will be equal to let's see um 0 for the starting column since it starts at column zero and then n minus 1 since it's like non-inclusive since it's like non-inclusive since it's like non-inclusive and then we just repeat that for the number of rows since they're exact same great and so now we'll have our core kind of algorithm that we're going to implement here and the first thing that we want to do is find out what's kind of our exit case or the when we stop Computing this result and that's going to be whenever the starting column or the ending column or starting row overlaps with the ending column or ending row and that looks like this so while the starting column is less than or equal to the ending column and the starting row is less than or equal to the ending row great and so we want to just keep processing while these remain true oh and forgot to call that end row okay and so we'll then have our four different cases which is like left to right top down right to the left and then bottom up okay so first one is let's go from the left side to the right side and that's going to be okay for every column in a particular range which is from the starting column to the ending column plus one fantastic and we're just going to be populating this Matrix as we go so for every column at the starting row so this is the starting row because we want the top row and we're just kind of populating it from left to right with this index here okay and that's going to be equal to and we'll just call it current which will be a variable tracking the current number that we're on which it initially starts at 1 here great and so that's the first case and now we want to basically repeat this logic four different times and we'll just modify it with each iteration or with each case and so this next one is from Top down and we want to go through every row here in the range from the starting row to the ending row plus one okay and so we want to iterate through all of these rows with this variable here and we want to use the ending column because we want the rightmost column and that will be the current so after each iteration we want to be incrementing this value by one that way so as we're going from left to right we keep populating these values and increment our current by one so that does that here same thing in this case we won't be incrementing this by one each iteration okay and so let's copy this another time over for our next case and this will be from the right side to the left side which will look like this great so from the right side to the left side and this will be okay let's go through every column in the range of our ending column since we're starting from the rightmost column to the starting column uh let's see starting column and we want minus one since in Python it's like non-inclusive and we add a negative one non-inclusive and we add a negative one non-inclusive and we add a negative one here since we're going backwards okay and then we want to iterate through the bottom most row which is the end row here in every column we want the N row because we're um oh let's see is that right this is no what we want yeah we're going from the right side to the left side that's right we want the ending row because we're using the bottom of this row okay and that looks good and so then finally we have one more case here and I'll have to do one other adjustment but I'll just move me down here okay and let's place that here and now we just want to go from the bottom up so top and wait uh no this from the bottom to the top there okay and so we want to go through every row from the ending row to the starting room and we just do minus ones and then we want to go through every row here and just be on the leftmost column since we're going up on this left side which will be the starting column great and we once again just want to be incrementing in our current by one each time so there's two extra things that we have to consider one thing is as we're kind of traversing this topmost row and then down this rightmost row we're kind of bringing in those bounds um because we're shrinking the size of the ray that has been populated or hasn't been populated and so to do that is after these iterations we want to be kind of closing in these parameters so when we evaluate the topmost row let's set our topmost Row the starting row and bring it down one so now the topmost row is one step lower since we just evaluated row zero here and then similar thing here on this case is when we go on the rightmost column we want to bring our um ending column inwards which is this so This rightmost column goes inwards and then similar thing here when we do the bottom most row we want to bring our ending row up one so we subtract one by it and then finally we just want to do the leftmost column so we want to bring in the starting column up by one okay and so that's all good we just have one other thing and that's okay as we're bringing in these bounds the starting row and the ending row these might not need to be evaluated and so because this while loop is kind of very long like this case should be checked multiple times here and so we just want to include this check at these additional points here so if this case is true then let's evaluate that condition and same thing here okay and let's try and run this looks good and submitted I'm surprised there's no bugs there just there's a lot of code here so it's easy to mess one of these conditions up so for time and space complexity for space complexity um it should be pretty natural to assume that okay since we're producing an N by n Matrix the time complexity would then be or the space complexity would then be N squared and I'll just write it out so there's no confusion so N squared which you might be used to this notation and then for time complexity it's the exact same thing and that's because well we're just going to iterate through every cell at most once and because the cell is an N by n Matrix it will be running in N squared time okay so yeah I hope that helped and good luck with the rest your algorithms thanks for watching
|
Spiral Matrix II
|
spiral-matrix-ii
|
Given a positive integer `n`, generate an `n x n` `matrix` filled with elements from `1` to `n2` in spiral order.
**Example 1:**
**Input:** n = 3
**Output:** \[\[1,2,3\],\[8,9,4\],\[7,6,5\]\]
**Example 2:**
**Input:** n = 1
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= n <= 20`
| null |
Array,Matrix,Simulation
|
Medium
|
54,921
|
173 |
um hello so today we are going to do this problem uh part of lit code april daily challenge uh binary search three iterator um so the problem asks is um we get a binary search tree root node um and we want to um we want the iterator over the in-order traversal the iterator over the in-order traversal the iterator over the in-order traversal so in order traversal is left right first left first and then the node and then the right side and we get um the constructor gets past the root node and the root the dimension here the printer should be initialized to an existing number uh smaller than any element in the bsd uh it seems to be a suggestion but we don't have to follow it um and then here we have two functions that we need to implement has next and next as next returns a true if there exists a number in the traversal to the right of the pointer basically has next needs to return true if there are still elements to pass us in the inorder traversal and next returns the element itself then each time it written the next element in the in-order traversal so element in the in-order traversal so element in the in-order traversal so that's kind of what we are asked um so we need an iterator that iterates over the tree in an in-order fashion um the tree in an in-order fashion um the tree in an in-order fashion um okay and then uh we can assume that next will only be called um if the tr the traversal still has some nodes so we don't need to check if uh if there are next elements using maybe has next we don't need to do that since we are guaranteed that there is um there will be a node when next is called okay um so that's pretty much it uh on the description side if we take a look at this example um first when next gets called here we return the far left that's what um what in order traversal does so we return this node three that's what we have here and then after that next gets called again so now we are pointing to here in the in order traversal it's left then the root um and now we're returning so return seven and then as next gets called we'll still have elements right and so uh we return true and then next gets called again now this is important so the after the node we process the right side but the subtree this sub tree here what it does is also in order traversal so we start with the left side and then do the node and then do the root so that means that this is the first one we need to return so we written nine and then has mexico is called again we still have elements and so return true um and then after the left so it's always left node and then the root and so after that um the node right so 15 gets returned we still have elements again so that are true this is we called this and we called this um now next gets called again now we did the left side the note side we need to return the to go to the right and so we return 20. and now we are done after 20 the children are all none and so it has an extruded term false so that's what we do here um so this is kind of what the what is ask it for from us um now let's see how we can implement it so in order traversal is very simple we can do it recursively um traversing the left the node and then the right the simplest solution would be to just construct a list of the in-order traversal so of the in-order traversal so of the in-order traversal so in our case here that would be just 3 7 15 9 20 right and we can just have an index who starts out at the first position and then we keep going each time we do next we increase our index and so first we return three then we return seven and then the next call to next we increment i and then we return 15. and for has links we just check that i is still less than the length of the array because that means we still have elements to traverse okay and this is the in order the result of the in-order traversal the in-order traversal the in-order traversal um so this is the simplest solution we can do it's um it of course uses extra space here of an extra space because this is the number of nodes um it's uh so there is that downside there but or the next getting the next element is of one because we just return array at position i uh hazmat is also of one right so but memory is memory wise it uses oven so in the follow-up here they ask us to so in the follow-up here they ask us to so in the follow-up here they ask us to implement it with next and has next um running in all on time and of h memory and so this doesn't satisfy that but at least but we can um implement a second solution that potentially does that um yeah so let's jump into this first solution and then we can uh iterate from there okay so we need to do uh first our in-order traversal um so we need to in-order traversal um so we need to in-order traversal um so we need to define our in order function um i will define it here um you can define it as a class function here if you want but i'll just do it here so to do that we need to check for our base case and then return an empty list and then in here go left add the node passes the node and then go to the right and return this so this is very simple in order to traversal now what this would mean here is that we need to store the values right so self downloads or we call them in order nodes is going to be just calling in order on the root right um and now in next we need to initialize also our index that we mentioned here right uh so index starts out as zero and so next needs to return in order nodes at position i and then we need to return node and then we need to increment i right so that's the first step for next what about has next for has next what we said is just we need to make sure that the index is still smaller than the length of the of our array we can also just make sh initialize here the length but otherwise we can also do length of that in order nodes because has next will be called multiple times i suggest you can do just something like this to make this faster and that's pretty much it right so let's run this uh yeah this should be soft that eye let's use more examples okay let's submit um okay so this process test cases um now how can we do it in a way that doesn't use extra space we have two ways to do this one is using doing iterative traversal uh in iterative inorder traversal the other option is to use keep using the recursion but use a generator so we'll see those two solutions i'll start out with the generator solution and then from there switch to the iterative version okay so let's switch to the iterator version first so for the iterator version we need to do the same thing but in a way where we use a generator here so let's first switch to a function here i just make this easier to see and don't call it in order generator right and now since we are no longer using a list we'll just return when we reach the base case and let's separate these two here and now what we need is um to just use yield that allows us to each time we call next from the generator we go get the next element in the right order um so here we'll do yield from and here we'll do as well the front now here we'll do yield this value okay um and now what we can do is so now that we get the value from that we no longer have an index and we no longer have an array so let's get rid of these and this um however let's keep track of our generator so it's going to be generator here and this will need to be self that and since this is a class function now we need to do self um and now that we have the generator we need to uh return it here right so how can we do this so one way we can do this is to keep track of the first of the next element in a variable so to get the first element from a generator we just use next um and so here we can just do next from the our generator here and now here we can return that solve that current however each time we get next we need to advance where our generator is pointing the first time here we want to just put node val or maybe a value here is equal to self.current so that we can is equal to self.current so that we can is equal to self.current so that we can return it and here now we are free to change self.current change self.current change self.current what should i point to the same thing we did here so next step basically you can think of an iterator like pointing to wherever we were in the right order in the um in the in order traversal and each time we just do next and go to the next element um so basically what this would mean is that since we do this yield from in order traversal it will go all the way down to the left side and so it will be pointing to three and next time we do next it will point to seven after that when we do next 22.29 after that when we do next 22.29 after that when we do next 22.29 and so basically in the next function we prepare for the next iteration uh hopefully that makes sense and now we return the value and then here we do next generator and then what should we do for has next now that's um that's where the problem is so with the generator you don't have a way to tell that you are at the end the only way to do it is to call next on your generator and then have that throw a an exception in python called stab iteration only then you will be able to tell that you are done right so what this means here is that um we need our function here to support um to support when we are done and so to do that i'm going to do a small change here i'm going to return just nodes and so this would be node it's still the same thing except the generator returns a node instead of its value and now for hazmix what i will do is i'll define a function here um or actually let's do it here so what we can do is say whenever so for next when we call next we assign some that count to the next value we will do has next basically when this is not none basically there is still an element but this can throw an exception it can throw an exception when our um when we reach the end with stop iteration so to do that we'll just do try and then here we will catch the stop iteration which means we are at the end and with that we will mark that we are at the end by assigning none and basically that will cause this to return false okay um and that's pretty much it um yeah so each time we do next um and then here we have our generator um yeah so that's pretty much it let's find this um so yeah so we need to call the same function so self dot sub that um okay so looks like there is a little bit of a set of problems here um okay so these are correct um and then we initialize our generator here we call next on the generator and for next we initialize the node to this we go to the next iteration and then yeah we need to return the value not the note sorry about that okay so that works let's run it on more examples and now we can submit okay so that passes um one thing though you can think of is so the number of nodes in the tree in the range is one to ten to the power of five so that's why if we don't get ever none uh but i wonder what happens if we get um a bst with just maybe no values so maybe something like just no okay see okay so lead code doesn't accept that as input but if we want to make our um our code handle that we can just refactor this portion here into a function and call that here so what that would mean is something like uh next node okay we'll pass the generator and we can have this be done here so this would be just return this otherwise return none if we reached the end and now we can just call this here uh so here since we passed the generator we can just use that and we do the same thing here so that we can avoid if we get past an empty node we can avoid problems yeah let me use the examples okay so this is just an indentation problem and their passes test cases um one thing we can do is not this is the same thing as doing this so we can remove that there um yeah so that's pretty much it in terms of time complexity here we are now using an extra space really only have we have this variable um and then this here is just one constant operation uh same thing here we do only one next uh same thing here um yeah what's important is these two operations um and then in terms of the initialization as well it's we do only one step right one step of the generation so that's that this is a good solution um yeah so this is the generator version now let's see how we can do the in-order now let's see how we can do the in-order now let's see how we can do the in-order traversal with uh iterative version um yeah so with that one what i want to do first is just show you the implementation of in order um without any logic here and from there we can um without this just the vanilla in order to iterative traversal and then from there we can adapt it to solve this problem um okay so i have i modified a little bit the examples that they gave us so that we can run our code for the in-order traversal so our code for the in-order traversal so our code for the in-order traversal so just to explain what it does you know the traversal so the code itself is going to be something like uh we need to initialize our stack and then we need to actualize a current node that points to where we are at basically each time so this is our stack and this is the current node it points to the root initially and then while there are elements in the stack but this will fail in the initial iteration because the stack is empty and so we want to also check or we have a current pointing still to a node so when the stack is empty which means we pop everything out and we are we current is equal to none which means where we are processing right now we finish that up right so that will happen in this case when we do current that left 420 which is none and so we'll know we finished okay and then here what we need to do is go all the way to the far left because remember um in order traversal is left node and then right and so what we need to do here is while we have current we want to go all the way to the left and so we want to do current equal to counter left each time until we reach the last one but to keep track of all the left elements that we go to we need to add them to our stack here so we add the element and now once we process it or the left side so in this case let's do it for our example here um so let us have our stack what this would mean in our um test case here we go turn that so we start at the root here current is we go to the left okay so count that left and so first we add current which is five so we add it okay sorry let me just do this let me have spaces here for our tree so this is our stack um yeah to show that it's empty actually let's just yeah leave it like this okay so we have five right now we go to the left at three and so we need to add three here and then go to the left again with this kind of dot left and so we add two and then we go to the left again we add one and then we try to go to the left again but the left of one is none and so we exit this while loop so what should we do actually this is being all the traffic so we should process one first which means we need to pop this value and so what we do here is current is equal to stack that pop and so now our current value is equal to one and so we'll pop one out of the stack here um and now what should we do well we sh we should if one had a right node let's say maybe something here x we should process that first before moving up sorry we should process uh one first which we did but after that we should process right because it's left node right for each subtree and so what we need to do here is we need to assign to our current value so here we say current um let me do this here current equal to calendar right and here whatever processing we want to do we should do it here node current because we extracted one we need to process it before going right okay um so this is the code for the inorder traversal and now let's just go and iterate through this list and see what we have so let's say here if we are just adding it to a list just so you can see that we get a final sorted list so if we have that we'll pop one and then we'll go to the right but it's none and so when we go again um we will find that current is empty but we have elements in the stack and so we will pop from the stack and so we'll pop and now what we should have here is two okay uh and so now we have two we need to process it we add it to our list we have two um and then we um we go we do current equal to current right and so 2 doesn't have a right so it's also none so when we go back up current is none and so we pop the stack again which means here we pop our stack and so here we have three okay and now we um we do we pound the stack we process it so we need to add three to our list and then we do current equal to current.right current.right current.right uh now our current is pointing to four okay and so what do we do next uh we go to the tree again we go to the loop again current is not empty it's equal to four and so we add four to the stack so add four here okay um okay loss actually since we popped from the stack four would be here and so we do kill that left the left of 4 is none and so we find that this is none now kemp is none so we go to stack pop we pop 4. so here it was none but we pop again so it's four and so we add four to our list um and then we what happens again um so once we have four we check if four has a right it doesn't it's none and so when we go again to the loop we pop again so we pop at four uh we pop five this time okay so part five we add it to the list uh and we keep going basically now we process the light of 15 um and then we plus we go all the way to the left so we are at nine we add it to the stack we pop nine and then we process it and we keep going until we reach 20. so but this is the idea of the in order traversal we have our stack and the current node we keep traversing we go all the way to the left park the node process it go to the right and then go to the left of that right so that's a main idea now let's see how we can apply it um to our code here um okay so i added the stack um i added the implementation that we did for in order um iterative traversal here now we just need to adapt it to support this so the first step is installation we want to do that in the constructor uh so this would be since we will access these in next we will do um do this here now in our next um you can think of the calls to next as well and then for next we just need to do this logic here we need to go all the way to the far left first um so that would be uh self.current uh self.current uh self.current self.stack self.stack self.stack we just need to change the variables between to point to the south version um and this here so we go all the way to the left and then for next what do we need to return well it's the processing step that's and processing here for us in this case is just returning next we're just returning the node right and so what we do is current is equal to uh this so we'll make it a node actually and this is the node that we need to return this is the processing step however uh you can see here after the processing we need to move to the right node right because we already returned this so next time we want to return the right node if there is any and so we want to or at least to go to the right and then go all the way to the left and then go to the left of that node right so this is what we want to do here so we need to do this assignment here um and now we just need to replace with self again um and when do when is the end that's the when the while loop ends right that means we are done we process it all the nodes and so here we need to return either stack or current still have elements and then we still have elements to pop from the stack and so here we'll do pop or current still contains uh contains a node so we need to process that node uh and so we need to just do self dot stack so you can see how it maps very nicely to the you know the traversal this here we put it in next this condition here is in has next because this determines whether we are done or not and then the installation needs to be um in the unit function right and so uh just go through it again the logic is for next we go all the way to the left okay and then process the leftmost node and then next time we do uh we do we get to the right so we process the load we need to go to its right uh because it's the left node right and then we keep doing that essentially um and yeah this is pretty much it so if we're on this um okay looks like we have one small thing here and this is because it's not self that cannot write what we are doing here is the elements will pop that's what we get the right for and so here this needs to be known right okay uh if i had said self.current here okay uh if i had said self.current here okay uh if i had said self.current here i could say maybe if this is clear we can do node equal to self dot current so that we can return that and then do this and that way we could do this if this is closer to this and easier to understand that works as well um okay yeah sorry this is this needs to be a copy i think um okay yeah let's just do a simpler the simpler version which is this and then we need to return the node and then this needs to be not that right uh we need to return the value sorry okay and if we submit this that passes test cases as well um yeah now uh let's yeah let's go back to i think it should work let's go back to what we are doing here which is uh we said we want this but we want node to be equal to or maybe we can do vowel equal to self.karen deval so this is our self.karen deval so this is our self.karen deval so this is our processing step and that way this here can be the same as this okay let's try it again um okay this is here this should be file because we are no longer assigning a node sorry about these errors um okay so that should work now let's use let's submit and that passes test cases as well um yeah so um i think for in all the traversal it's good to be really familiar with both versions and the recursive version and the iteration version just because some problems are easier to solve with an iterative version um yeah so that's pretty much it for this problem thanks for watching and see you in the next one bye
|
Binary Search Tree Iterator
|
binary-search-tree-iterator
|
Implement the `BSTIterator` class that represents an iterator over the **[in-order traversal](https://en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR))** of a binary search tree (BST):
* `BSTIterator(TreeNode root)` Initializes an object of the `BSTIterator` class. The `root` of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.
* `boolean hasNext()` Returns `true` if there exists a number in the traversal to the right of the pointer, otherwise returns `false`.
* `int next()` Moves the pointer to the right, then returns the number at the pointer.
Notice that by initializing the pointer to a non-existent smallest number, the first call to `next()` will return the smallest element in the BST.
You may assume that `next()` calls will always be valid. That is, there will be at least a next number in the in-order traversal when `next()` is called.
**Example 1:**
**Input**
\[ "BSTIterator ", "next ", "next ", "hasNext ", "next ", "hasNext ", "next ", "hasNext ", "next ", "hasNext "\]
\[\[\[7, 3, 15, null, null, 9, 20\]\], \[\], \[\], \[\], \[\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, 3, 7, true, 9, true, 15, true, 20, false\]
**Explanation**
BSTIterator bSTIterator = new BSTIterator(\[7, 3, 15, null, null, 9, 20\]);
bSTIterator.next(); // return 3
bSTIterator.next(); // return 7
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 9
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 15
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 20
bSTIterator.hasNext(); // return False
**Constraints:**
* The number of nodes in the tree is in the range `[1, 105]`.
* `0 <= Node.val <= 106`
* At most `105` calls will be made to `hasNext`, and `next`.
**Follow up:**
* Could you implement `next()` and `hasNext()` to run in average `O(1)` time and use `O(h)` memory, where `h` is the height of the tree?
| null |
Stack,Tree,Design,Binary Search Tree,Binary Tree,Iterator
|
Medium
|
94,251,281,284,285,1729
|
280 |
what is up youtube today i'm going to be going over wiggle sore it's a medium problem on leak code if you guys haven't already check out my channel subscribe hit that like button and now let's get to the problem okay so we have wiggles or given an unsorted array nums reorder in place such that nums zero is less than or equal to num to one which is greater than or equal to num to two which is less than or equal to number three so you see here this one is um the odd indexed if we're doing zeroth indexed arrays is greater than the odd uh no even index so the odd index is i have it on my whiteboard so oh that's not my whiteboard the odd index so we have zero one two three four five so the odd index is supposed to be greater than the uh even index and even indexes are supposed to be um well i did that backwards oops sorry guys so it's supposed to be greater than and these are supposed to be less than basically so basically all we need to do is the code is um first we need to check if i modulus 2 so we just want to check if it's zero and if it is if um nums of i is greater than the if this so we're at the even index if this is greater than say this five was here instead say five was here and three was here we'd have to switch them so we just we have we can't write a swap function basically um so and then we just have an else statement and inside that statement if num so now we're at odd indexes if nums of i is uh less than numbers of i plus one then swap and i forgot to write swap up here so that's our pseudocode um that's how i do my student code i know it's like really sloppy but that's like all i need to do it i don't even think this needs to be a medium but let's just code it out um so we can do a swap function to save us a little space not space but like space in the editor um so we're just uh looping through the array so it's oven runtime and over one space complexity we're not using any data structures so it is constant um or linear i'm sorry so private void swap let's do nums and so this is just a basic swap function i'm sure you guys written one before um equals oops okay so now let's go back to our pseudocode we just have to um write that out basically so if well first we need a for loop so equals zero i less than nums dot length minus one if we do nums that length the length is six and we're using indexes so we got a minus one we're using zero in zeroth index so we do have to do minus one i'm sorry and so if i oops and so we can combine them and numbers of i what is it gradyland i mean there's so many different ways you can do the if else statements it doesn't really matter nums and we want to pass in i and i plus one and um and then we can do if i does not equal zero oops uh then we just swap them and we don't even have to return anything because it's just a void function so let's try that um that's actually different than my last code i wrote i wanted to just try different okay sweet so it works and we have like i said oven run time 62 really bad memory usage don't know why because we're not using any data structures uh okay that's a little bit better i don't know i feel like it's arbitrary like always um if you guys need any help with anything leave me comments in the section below i love to actually answer your questions yeah i like to when you guys make me revisit the questions that i haven't done in a while and like re-look at them so i look at them re-look at them so i look at them re-look at them so i look at them multiple times so if you guys ever need help don't feel free to ask and uh if you like the video hit that like button and i'll see you guys in the next video
|
Wiggle Sort
|
wiggle-sort
|
Given an integer array `nums`, reorder it such that `nums[0] <= nums[1] >= nums[2] <= nums[3]...`.
You may assume the input array always has a valid answer.
**Example 1:**
**Input:** nums = \[3,5,2,1,6,4\]
**Output:** \[3,5,1,6,2,4\]
**Explanation:** \[1,6,2,5,3,4\] is also accepted.
**Example 2:**
**Input:** nums = \[6,6,5,6,3,8\]
**Output:** \[6,6,5,6,3,8\]
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `0 <= nums[i] <= 104`
* It is guaranteed that there will be an answer for the given input `nums`.
**Follow up:** Could you solve the problem in `O(n)` time complexity?
| null |
Array,Greedy,Sorting
|
Medium
|
75,324,2085
|
1,696 |
Loot Hello Guys Welcome To Your Dhund And Today We Will Discuss The Question Part Subscribe Withdraw Appointed subscribe and subscribe the Channel and subscribe the Related Question In The Last Decade Next Index And On Instagram Twitter The Video then subscribe to The Amazing Subscribe Particulars In Talking About This point to point is the life can not job mode on spare time election lad backup from individual can reduce plus minus wave subscribe - 2 - 151 subscribe to the valleys and to index to reduce amazon more Current Affairs - 2nd Oct - 263 Loot Subscribe Indian More Three Languages subscribe and subscribe the Video then subscribe to the Page Robinson That We Can Get On The Particular Intellect Will Get 1000 Below The Current Value subscribe and subscribe the Video then subscribe to subscribe कARE लोग संग सेतल आसन Next you liked The लोग संग सेतल आसन Next you liked The लोग संग सेतल आसन Next you liked The Video then subscribe to subscribe our Channel Please subscribe And subscribe The Amazing subscribe Chinese Ad Gifts for Dowry What is basically Thursday starting from the mid term subscribe and subscribe this Video subscribe and subscirbe Aisi Drishti Video Note Scientific Approach subscribe and subscribe the Video then subscribe to The Amazing Hair 's Login Order to Reduce Time 's Login Order to Reduce Time 's Login Order to Reduce Time Complexity subscribe The Video then subscribe to the Remind Change Isabgol Veer Vasundhara Ahirwal Area Hello Also The Maximum A Particular Indexes A Answer for the Indian Civil Line that person Video give me kyu Waqt Inflation in Wave Top 10 Value Present in this Question in Mid Term Subscribe and they will send you a fan in decreasing order Mandsaur Bill-2010 E Event with R Ashwin Umesh Yadav Sudhir and Appointment presents subscribe Current Simply Remove and Appointment Subscribe with U Alarm set will not be removed from being ridiculed Maximum Vikram Clear the person so that in New Delhi Reddy Top and be done with ur will just get bored Interactive Content subscribe The Channel and subscribe the Page if you liked The Video then subscribe to the Video then that I tried it immediately with default sample test Switzerland successfully set fluid alarm and submitted successfully in this a peon times for too long subscribe and subscribe And subscribe The Amazing subscribe The Channel Please subscribe And subscribe Modi and effective listening tried to define middle aged person ridiculous not to withdraw them which Arvind Sir did just in the starting point so in order to remove all the best good thoughts electronic what we can do am I and subscribe now to Receive New Updates Reviews The Amazing The Value Of Birth Current Indic Im Up To 200 Fabric Why Is Greater Enrich They Will Remove The Experiment And Will Decide For Boys In Knowledge Screen Subscribe Updating Subscribe Now To Receive New Updates Reviews And Values In Values In Values In Removing values from this staff also values from this staff also values from this staff also in line with what they will discuss through doing the same thing this time person subscribe Video to like subscribe our Loot Train Successfully Lets Rich and Time Complexity Subscribe Not Doing Any Thing in This Subscribe by clicking Subscribe latest videos have arrived please do
|
Jump Game VI
|
strange-printer-ii
|
You are given a **0-indexed** integer array `nums` and an integer `k`.
You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive**.
You want to reach the last index of the array (index `n - 1`). Your **score** is the **sum** of all `nums[j]` for each index `j` you visited in the array.
Return _the **maximum score** you can get_.
**Example 1:**
**Input:** nums = \[1,\-1,-2,4,-7,3\], k = 2
**Output:** 7
**Explanation:** You can choose your jumps forming the subsequence \[1,-1,4,3\] (underlined above). The sum is 7.
**Example 2:**
**Input:** nums = \[10,-5,-2,4,0,3\], k = 3
**Output:** 17
**Explanation:** You can choose your jumps forming the subsequence \[10,4,3\] (underlined above). The sum is 17.
**Example 3:**
**Input:** nums = \[1,-5,-20,4,-1,3,-6,-3\], k = 2
**Output:** 0
**Constraints:**
* `1 <= nums.length, k <= 105`
* `-104 <= nums[i] <= 104`
|
Try thinking in reverse. Given the grid, how can you tell if a colour was painted last?
|
Array,Graph,Topological Sort,Matrix
|
Hard
|
664
|
991 |
welcome to february's lego challenge today's problem is broken calculator on a broken calculator that has a number showing on its display we can perform two operations double multiply the number on the display by two decrement subtract one from the number on the display initially the calculator is displaying the number x return the minimum number of operations needed to display the number y so initially this sounds like a very simple problem all we have to do is have a while loop and say while x is less than y or rather while x is not equal to y if it's less than y then double it and if it's greater than y then minus one and we could simply write it write an algorithm like while x does not equal y if x is less than y then we double it else we subtract one something like that right and we'll keep track of number of steps by saying steps plus equals one something like that and the return steps now this would work for certain test cases like this one but say that we had one like 5 and 8 what would happen then well this actually wouldn't work my algorithm would return 3 but the expected answer is 2. the reason for that is my algorithm will multiply this by 2 making it 10 and then subtract one and then one again so like 10 9 8 so that's three steps but it's better actually to subtract one make it a four and then multiply by two which would be two steps uh oh so this algorithm would not work how could we improve it well the problem is the path that we can take to get there if i used this would always take this weird path where it would double and then subtract what if it'd be much more um see the other way other path going subtracting and then multiplying by two the way we need to figure that out is actually to go back backwards if we start at the y and try to figure out is it better to um well okay there's two things if it if we start the y um if it's odd we would have to add one to it and then divide it by two and that's two steps now uh if the y is less than x then we don't really have much of a choice we only have the option of adding or decrementing this by one right and if we just go backwards this algorithm actually can work um we wouldn't need to do anything recursively we wouldn't have to like figure out what all the paths are uh we can mathematically prove that always it would be better to plus one and uh divided by two rather than minusing one all the way back down to where the x is okay so if we did this what we the algorithm would still be something like this but we had to simplify a little bit first thing is say if y is less than x well if that's the case then there's only one thing we can do we can only uh decrement the x right so we don't even need to go through loops with that we can just say steps plus equal it would be x minus y and that would be it would then just make the x equal to y to get out of the loop now otherwise if x is oh i'm sorry if y is greater than x then we need to figure out is it odd or even so if y is even then simply divide it by two otherwise if it's not well then we would need to actually add one to it so that on the next loop we can divide it by two and each time we do that we have to add one step so this would actually work we're kind of just going backwards here um now let's just see if this works yeah and there we go so that would be um in terms of time complexity it's not quite o of n um there's some sort of log involved in here not sure log n uh something like that yeah okay i'm just gonna end it here um yeah you can definitely simplify this algorithm a little bit with some tricks and stuff but this is more understandable so i'm just going to keep that yeah so thanks for watching my channel and remember do not trust me i know nothing
|
Broken Calculator
|
array-of-doubled-pairs
|
There is a broken calculator that has the integer `startValue` on its display initially. In one operation, you can:
* multiply the number on display by `2`, or
* subtract `1` from the number on display.
Given two integers `startValue` and `target`, return _the minimum number of operations needed to display_ `target` _on the calculator_.
**Example 1:**
**Input:** startValue = 2, target = 3
**Output:** 2
**Explanation:** Use double operation and then decrement operation {2 -> 4 -> 3}.
**Example 2:**
**Input:** startValue = 5, target = 8
**Output:** 2
**Explanation:** Use decrement and then double {5 -> 4 -> 8}.
**Example 3:**
**Input:** startValue = 3, target = 10
**Output:** 3
**Explanation:** Use double, decrement and double {3 -> 6 -> 5 -> 10}.
**Constraints:**
* `1 <= startValue, target <= 109`
| null |
Array,Hash Table,Greedy,Sorting
|
Medium
|
2117
|
790 |
Hi gas welcome and welcome back to my channel so today our problem is domino and domino tiles so what have you given us in this problem statement here you have given us tiles of two types whose size is yours 2 * 1 and your shop is yours Domino is yours 2 * 1 and your shop is yours Domino is yours 2 * 1 and your shop is yours Domino is in the apple and domino is in the apple, okay what do we have to do tiling in the word of 2 * N. what do we have to do tiling in the word of 2 * N. what do we have to do tiling in the word of 2 * N. Okay, if we have to lay out the style, then in how many bases can we do that, we have to find that number of wedges, okay? What do we do? Let's understand this problem through an example, what is our problem and how can we solve it? Okay, so what have you given us here, you have given us types of types, I think that's enough. Okay, so what do you have, yours will be like this, okay so this is done, now what do we have to do, so what do we do, so which tiles can you put here, you can lay this or You will do this and this, do it like this, people, okay, can you do this? It will go here but the extra tiles will remain here, so it will not sit perfectly, so here we can only do this and that, so here. What will be your number of waste? Van will be the same, okay and the other one is your N2. N is your board. So, this is 22 of your board. Okay, one here and the other one here, how much do you have. Look here also, make it your time. It can be done, ok, but is it full for you, or is it not? So, how many are these? How much will this cost? This will be of van in van, so do we have any tiles for this? No, we cannot do it here. If you can't cover then here your trimming will not be there so they will be your own here ok now we also see for n3 what will happen to you in n3 and in three it will be you it will be of 2 * 3 na it will be you it will be of 2 * 3 na it will be you it will be of 2 * 3 na it will be you Here van tu and three so supos will be up to here, so what can you do here, see, one, you can lay it tight by doing this, okay, I laid it here like this, second, one base is done here, okay, what else? The second one could be that what do you do here, give the idea of van in tu, put it here, what can you do, how you here, people like this van, these you, what van is there for us, 3 In how many bases can we go, we can do it crying to trimno, one, this is yours, this is done, second, this is yours, it is right, third, what can happen to you, here, this is yours, this is done like this, right, one, this is yours, see four ways. Why am I showing you, if you ever face any problem, if your number is of the number of status, if you have to form something, then how come the number of waste, whenever it comes, you should try to find a pattern. Okay, so basically what we are doing here is we are looking for and one, we are looking for tu, we will look for three, we will also look for four, we will look for five, so here you will see multiple test for whom and try Will you not? Do we find any pattern? If we find any pattern then how can we solve this problem. If we find the pattern then we can soften the problem. So this is your problem for the end four. If you find If you do, I will show you, it is okay for four and then I will tell you how much will be for each. Okay, so look here, what will it be? It will be worth Rs. 224, so this is a van, this is one, this can also be yours. Till now both of you are here like this, it has become the fourth date, okay then what can happen, you have put it on the side here like this, if this is what we do, put it here then what will be the fourth here, you can do it in four ways. Meaning, put it once on the right side, put it once on the left side, here pickle punch is done in four ways, milk is done in nine ways and this one of yours can be done here also. It is like this, here you have done this van has become four, what to do now what will we do here, okay, this is done for the van, sorry, another way it also happens that you Do it like this in the direction, then do it like this in this direction, put the tiles here, then this is you four, this is you and here, van, this is you, if it becomes four, then how many ways are there in this way, the total becomes 11, right van, you three four. Five six seven right six seven and here 7 these are your tu ways in two ways these are two ways on one side here i.e. seven plus four yours becomes 11 and here i.e. seven plus four yours becomes 11 and here i.e. seven plus four yours becomes 11 and what is yours for four and got 11 Look what will be yours here For n1 will be your van For van your will be van For tu will be your five For four your will be 11 For five your will be 24 For this your will be 53 For 7 your will be What will come out will be 117, ok for coming here you can go to 258, ok, we have seen so much discus till now, we have seen what is right 11th, you try to find here also, this video will go on for a long time like I am not showing you, I am telling you what will happen for and five, what will happen for n6, what will happen for n7. Look, now what we have to do here is to find the pattern, so the pattern, what do we do from here. Let's start, okay, let's start from here, how can we do 11 here, see, if we do 10, then we do 5 * 2, so if see, if we do 10, then we do 5 * 2, so if see, if we do 10, then we do 5 * 2, so if we do 5 * 2 = 10 + 1, then we will get 11, okay, so we do 5 * 2 = 10 + 1, then we will get 11, okay, so we do 5 * 2 = 10 + 1, then we will get 11, okay, so we Let's see if the same thing is happening for 24. For this, 11 * 2 = 22 same thing is happening for 24. For this, 11 * 2 = 22 same thing is happening for 24. For this, 11 * 2 = 22 and this for this we have done this and that for 11 we will do this and that. You are getting 24 then what do we do now for this Let's see, this is 53 A. What is your A for right and six? What is 53 A? So what is 48? We will add 5 to it, so what is our 53 A? What is Han A? 53 O. Meaning, we will multiply and for this we will add 11, so is this what is happening? Look at the six, add this 10, 11 and get 117. Okay, here also you are getting 117, that is, this pattern is happening, so is this for five? What also happened, so there is no one here for five, okay, there is no one here, otherwise, we will take a man here and for zero also, we have our own van, okay, we will take a man here for now, it is also for and zero. So what should we do here? How will we find five even for 5? 2 * 2 = 2 * 2 = 2 * 2 = Tu tu go four plus van will do whenever n give our less equals tu will be van then what will we do return so your starting from van. This is just to solve this problem, we have made it zero, okay here, let's take van man for zero, whenever we have here, the record that we are going to solve, we will just see the solution first, okay so here. What will we make based on the condition N? When our N is greater than 1, what will we do in return? Here, when our N is 2, what will we do? Here 2 * Here 2 * Here 2 * n - 1 will come as much as plus and minus will be n - 1 will come as much as plus and minus will be n - 1 will come as much as plus and minus will be in three. Okay, what should we do here? How are we finding 5 for five? We are looking at you, we are doing 2 * 2 We are looking at you, we are doing 2 * 2 We are looking at you, we are doing 2 * 2 for 3. What do we do with this, we are multiplying 5 by tu and adding van, we are getting 5. When we are searching for four, what to do in n3, we are multiplying 5 by tu and this van. Right here, when we are looking for this, we are looking for five, so in 11, we are doing 2 * looking for five, so in 11, we are doing 2 * looking for five, so in 11, we are doing 2 * and after that, we are adding this tu here, so this is the pattern we are doing. No, for everyone, here for everyone, so this is what will happen to us, this will be the solution, so first I will show you the request solution, then we will see the best, then we will see the basis on BP, Total DB, so here it will be till A, okay and here also this It has been given that your solution is neither this answer nor it can be big, so now do it modular, so that is why we got modules here, so you have given the number of tilings here, this function M has given, we have made a finite function. What are we doing in this? Here we are doing base condition. Jab n less dene van hoga return van karega and jab tu hoga to tu return karenge adervise What we will do 2 *5 and -1 pe hum We will find whatever we *5 and -1 pe hum We will find whatever we *5 and -1 pe hum We will find whatever we get at n-1, we will multiply it by you get at n-1, we will multiply it by you get at n-1, we will multiply it by you and plus find n-3, and plus find n-3, and plus find n-3, ok, we will plus it and here we will take the mode of it. Okay, so what will happen in this way, you will get the answer, but this is yours. NTL will give it ok, so what we will do is we will memise it, what do we have to do to create memories, we have to create extra space, so what we are doing here is that we are taking a vector, we have kept its size up to 1000 vans. Why have we kept it because the consent has been given up to thousand, so we will index it till WAN. If we want till thousand, then what will be the size of the vector, we will have to keep it till 1001. Okay, then we will do this and will slice these from the mines WAN itself. Will do DP 0 will be changed to 1 DP will be made Van to Van DP will be done to Tu Ko Tu We will keep the base condition, what will we do with it here, will we fill it and by calling the find function, there was already n in it and We will also insert the DP. Okay, now here we will keep the condition that DP and is not equal to -1, that is, that DP and is not equal to -1, that is, that DP and is not equal to -1, that is, if you have found it, then what to do with it at that time, you delete it, okay, fill in the adervise DP and you have. 2 * 5 & -1 here is ok, again there will be a method * 5 & -1 here is ok, again there will be a method * 5 & -1 here is ok, again there will be a method here, you will do 10 DP ok, in this way you have done it, now what can be your second method, complete it completely, if you do not want to do anything here, then what can you do Total DP here, if you can do it, then what have we done here, DP has been taken, DP has been resized to 0, DP has been done to P van, DP has been done to you and started from n3, now how far will it go from three to Will go till the end. I need the answer to come, so to find n, what we have done here is a for loop, we have done that and to find dp i, what we have done is dp * dp - 1. Okay, models in this. * dp - 1. Okay, models in this. * dp - 1. Okay, models in this. Then DP is I - 3. Okay, once we have done the module, Then DP is I - 3. Okay, once we have done the module, Then DP is I - 3. Okay, once we have done the module, then DP and we will return it in the last because we need the answer for N, otherwise in this way we will erase it. Okay, so I hope you have understood this. If you liked this video then please like, share and subscribe. Some people comment that you don't run the court. Look, whatever code I show you, I show it only after running it. I do n't show it to you just like that, so please. You guys please check once, I have provided the link of the gate, so give the code to that also because it is possible that you might be making a mistake somewhere, then you tell me that you did not call and your court is wrong. So that this does not happen, I check many times, after that I make a video, okay then, no one, bye.
|
Domino and Tromino Tiling
|
global-and-local-inversions
|
You have two types of tiles: a `2 x 1` domino shape and a tromino shape. You may rotate these shapes.
Given an integer n, return _the number of ways to tile an_ `2 x n` _board_. Since the answer may be very large, return it **modulo** `109 + 7`.
In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.
**Example 1:**
**Input:** n = 3
**Output:** 5
**Explanation:** The five different ways are show above.
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 1000`
|
Where can the 0 be placed in an ideal permutation? What about the 1?
|
Array,Math
|
Medium
| null |
824 |
Yes dad don't remember I will be there with the prick for it though because once in you again the and a Beat when you to the fruit Is All we need to use and domestic tourists to you that s and in the Center of computer with several cases It will consist of markets and of working on which would like to converter tentacle thrive chocolate need some help yourself for tourists and screenshots looking up at any time and Again And Again the word of existing content of live beautifully flash of Time left and right and tagged with open brothers lamp family is a Tender kiss and if your mother of Fresh leaves are the wanted a second were added to the word Which is simple to use and wanting What IQ Intel Core duo d'accord efficient use the secret of the fastest swish page which people Have fun with iPhone and the US and Now it's Everything find work and Everything into One will appear that Winter the first day of The Power of now with Samsung tool with you You're welcome to the world I Speak Of True Justice Thai jaccar Thanh Chairman Switch and of us is a Yo you and your help to Sit in paper is not have to use it to the West and There is one of our work with the test of English of clean water about dice the Deputy Minister Cao because of the energy news from the above newspaper in Bao Yen Bao Tran our work are many tourists when you press the first people and its I help me the first contact the condition and English Acoustic swastika is very the first in the standards that work ethic and then was Last Christmas dress Which is the presence of any comment about in spite of Art of It will increase number is ended in a person i think about you deserve to you are the world it's just know what and how it means I can pass the book Smash You are beautiful and tagged with love It is accepted and Transport and stochastic you Thank you em
|
Goat Latin
|
number-of-lines-to-write-string
|
You are given a string `sentence` that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only.
We would like to convert the sentence to "Goat Latin " (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows:
* If a word begins with a vowel (`'a'`, `'e'`, `'i'`, `'o'`, or `'u'`), append `"ma "` to the end of the word.
* For example, the word `"apple "` becomes `"applema "`.
* If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add `"ma "`.
* For example, the word `"goat "` becomes `"oatgma "`.
* Add one letter `'a'` to the end of each word per its word index in the sentence, starting with `1`.
* For example, the first word gets `"a "` added to the end, the second word gets `"aa "` added to the end, and so on.
Return _the final sentence representing the conversion from sentence to Goat Latin_.
**Example 1:**
**Input:** sentence = "I speak Goat Latin"
**Output:** "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"
**Example 2:**
**Input:** sentence = "The quick brown fox jumped over the lazy dog"
**Output:** "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"
**Constraints:**
* `1 <= sentence.length <= 150`
* `sentence` consists of English letters and spaces.
* `sentence` has no leading or trailing spaces.
* All the words in `sentence` are separated by a single space.
| null |
Array,String
|
Easy
| null |
72 |
in this video we'll be going over the memorization approach of edit distance in the previous video the recursive approach was very inefficient due to overlapping recursive calls and we are going to optimize it using memorization which means caching let's go over the thought process so the recursive approach is inefficient due to overlapping recursive calls we can avoid overlapping recursive calls using memorization now would ask yourself what do we need to cache in each of the recursive call we are trying to find the minimum number of operations which we'll call ops at the current indices ing this means we can cache inj with ops for the minimum number of operations now let's go over the pseudocode so we're going to create 2d images so we're going to create a 2d matrix nemo to cash previously calculate the results or we can say cash the minimum number of operations or we can say we can cache i and j with ops so the rows represents i the columns represents j and the values represent ops then we can implement the top-down then we can implement the top-down then we can implement the top-down memorization approach the parameters we need to add our cache to our parameters list and what's the base case if memo i j is not equal to zero this means we have already calculated the results for i and j so we can just return emo ij now for this one we're gonna put the recursive results of moving both pointers forward add mo and then we can return nemo this means caching it and then we're gonna put the minimum number of operations of the three types of operations inside memo and therefore which means caching it so we can return remote ij now what's the time and space complexity so the time complexity is of m times n or m n where m n are the lengths of the two input strings this is because there are m times and possible states in our recursive calls now let's go over space complexities space complexity is m plus m n plus of m plus n which will default to m n this is for our the memo matrix and plus n is our recursive call stack memory now let's go over to code so we're going to first clear memo if memo i j is not equal to zero this means we have already calculated the result for i j and we can return mimo ij now before we turn the minimum distance i'm moving both pointers forward we want to cache it and also here too we want to cache it let me know if any questions in the comment section below in the next video we'll be going over the bottom up 2d matrix approach of at a distance
|
Edit Distance
|
edit-distance
|
Given two strings `word1` and `word2`, return _the minimum number of operations required to convert `word1` to `word2`_.
You have the following three operations permitted on a word:
* Insert a character
* Delete a character
* Replace a character
**Example 1:**
**Input:** word1 = "horse ", word2 = "ros "
**Output:** 3
**Explanation:**
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
**Example 2:**
**Input:** word1 = "intention ", word2 = "execution "
**Output:** 5
**Explanation:**
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
**Constraints:**
* `0 <= word1.length, word2.length <= 500`
* `word1` and `word2` consist of lowercase English letters.
| null |
String,Dynamic Programming
|
Hard
|
161,583,712,1105,2311
|
856 |
hello and welcome back again to lead coding on this channel we discuss problems which are frequently asked me programming interviews and try to approach them in a step-by-step manner approach them in a step-by-step manner approach them in a step-by-step manner we also discuss the space and the time complexity and several other approaches with which the question could be solved today we are solving a very interesting problem from deck name of the problem is the score of parentheses now let us look at the problem statement we are given a balanced parentheses string s we have to compute this cool of this string based on the following rule the rule number one is if there is only a pair of parentheses it is opening in the closing parenthesis then we have to return this core s1 if the string is the concatenation of two balanced parentheses strings then the score is the addition of those two strings and if there's a nested parentheses then let us say that a is nested inside opening and a closing parenthesis then a will be multiplied by two so these are the rules let us look at certain examples to clarify the problem statement so in the very first example the answer is when according to the rule number one in the second example for the parentheses which are marked which are highlighted with blue the answer is 1 and then 1 is inside another pair of parentheses so 1 is multiplied by 2 according to the rule number 3 so the answer in this case is 2 in the example 3 we have 2 parenthesis 2 strings which are balanced so the first one is highlighted with blue for this one the answer is 1 and for another string this is also a balanced string and the answer for this is 1 as well so the addition of these two will give us 2 so this way we have to approach the problem now let us look at another example and try to build up a common solution for this problem as I have already disclosed that we are going to use the stack in this problem let us take this example so let's say we have these parentheses now if we see the mapping so the first opening parenthesis is mapped with the last one the second one is mapped with the third and this is mapped with this so these are the mappings and if we somehow know the mapping then it would become very easy for us to think of this problem in a recursive manner so let us say that we know that the mapping for first opening parenthesis is the last one so we would know that the whatever lies inside whatever lies in between these two that has to be multiplied by two so let's say we know this starting point and the ending point and we somehow calculate whatever lie inside these starting and ending point then we will simply multiply that value by two and return our answer so if we somehow know the mapping if you know the mapping then it would become very easy for us to calculate the solution in a recursive manner so now let me take an example and try to yes let us try to simulate this recursively so let's say there is a function so help is a function and we pass a starting point and an ending point to help and then help will give us integer answer between this starting and ending points so initially we will be passing 0 and n minus 1 to help now if we are implementing help then the first thing that we have to look for is a base case and the base will become when we have only starting and closing parenthesis in this case we will simply return one so this is the base case so the base case can be denoted by if s plus 1 is equal to and in this case there are only two or two parentheses and these two are all these two are balanced so there's one starting in one opening and one closing parenthesis so in this case we have to return one now for the further cases we know the mappings already and we will be checking the mapping so when we pass the 0 and n minus 1 to help we will be having a for loop in the for loop we will check for the opening bracket so if we get the opening bracket we will see whatever pairs with this bracket so we will send this much part to help and again this much part to help so help is going to give us answer for let's say a and for B and we are simply going to add them both and then finally we will be returning a plus B this is our final answer multiplied by 2 so this is what we have to implement let us try to see the code for this and then I will try to simulate it on another example so this is the helper function and it will be having a start and end it will also have a vector of int pair so pair is the mapping that we are doing and of course it is string so if start plus 1 is equal to end then return 1 this is the base case else initially we will take an answer which is zero and V will be traversing from start plus one is a smaller than end so now we are going so initially we will be having something like this is our start this is our end we are traversing from this point to this point and as soon as we get an opening parenthesis we are going to call helper function again with start as this and end as the pair of this or the mapping of this so the mapping for this opening parenthesis is this one this information is provided in pair so from I equal to 1 I is smaller than and I plus answer plus equal to help of I comma pair of I and pass on the pair and as I don't think that we actually need s anywhere so let us drop this s so this is how we are calculating the answer initially the answer is 0 then help will be called on this part then again help will be called on this part and help will be called on this part so these are a B and C and we have to add them all so this is what we will be getting as our final answer so initially we have an opening parenthesis and a closing parenthesis so we have to multiply this summation by 2 so this is what we had written finally return answer multiplied by 2 now let us try to construct this pair that this could be done using stack so I am going to implement stack using vector so vector have a function called push back so it acts as stack if we are going to push from the back and pop from the back so I am taking vector of type int V and pair that I have to construct this will be of size N and is s naught size how we are constructing this so let us take the same example and let's say we have a stack this is the stack and inside stack the first parentheses will be this corresponding to index 0 then again and opening parentheses corresponding to index 1 0 1 2 3 4 5 6 & 7 now a closing index 1 0 1 2 3 4 5 6 & 7 now a closing index 1 0 1 2 3 4 5 6 & 7 now a closing parenthesis as soon as we see that we are having a closing parenthesis and the top of the stack is a is an opening parenthesis then we are going to do the mapping so the opening parenthesis is lying at index 1 and the closing parenthesis at in index 2 so for the index 1 the mapping is with 2 & 4 to the index 1 the mapping is with 2 & 4 to the index 1 the mapping is with 2 & 4 to the mapping is with 1 so we can only have one sided mapping that is from 1 to 2 that would also work then this will be popped out then again we are coming it and opening parenthesis at index 3 then a closing parenthesis at index 4 again this is going to pop out and for the mapping will be from 3 to 4 and from 4 to 3 as well so this part is not required we are simply keeping it for the generalization again at index 5 then at index 6 it is again a closing parenthesis so it is going to pop out and the mapping will be from 5 to 6 and from 6 to 5 then a closing parenthesis again so it is going to pop this one out and the mapping will be from index 0 to index 7 and from 7 to 0 so this is how we are clearly creating this mapping which is our pair in this case so starting from I equal to 0 I smaller than n I plus if s of I is an opening parenthesis then simply push this into the stack so stack is V or V dot pushback we are going to push the index so that is what we are required when we are pairing this so instead of pushing the closing or the opening parenthesis we are simply pushing the index and if it is nor the case then we have to pair them so pair of I equal to V dot back and V of V okay pair of V dot back is equal to I and simply pop it from V dot pop back so now we are ready with our pair now we have to calculate the answer so we will have to simply return from 0 to n minus 1 and answer so let us see if it works okay let us see for this example all right answer plus equal to i purify and it is not i plus actually we have to jump to the index so if this is our i and the pair of i is the next index so this will be passed on to help again we will get the answer for this if we again call the helper function using this as the starting and this as the ending index then the next i will not be this it will be this one so it is the next element that comes after the closing parenthesis so i will be i will now become pair of i plus 1 so this is giving us correct answer but there's a case here the example number three although it is a balanced parenthesis it comprises of a plus B if we look in terms of the first sub string and the second sub string but then as a whole if we are implementing the same logic it is always having an initial opening and a last closing parenthesis so it is not present in this case so whatever the case is if you simply put the initial opening parenthesis and the last closing parenthesis we will be getting the answer twice as what we require but it will generalize our solution so if we make s equal to we simply add another pair of parenthesis or in terms of the question we are simply multiplying the answer by two so now we should get 12 as the answer because we simply added another pair of illnesses so 12 is the answer and we can simply return answer divided by 2 it is going to handle all the cases even when there is a case such as the example number 3 so if we don't do this and we simply remove that as well and then try to run this case it is going to give us d le so in order to handle this case we are simply putting another pair of parentheses and then dividing the answer by 2 so in terms of time if we look we are creating this pair and this creation is going to take Big O of n time the next thing recursion is again taking Big O of n time the space complexity is big off and again because we are creating a stack and a pair vector so this is it for the solution to this problem if you have any doubt please feel free to ask them in the comment section and if you want to provide me any suggestion for my future videos please comment them as well please subscribe to the channel if you like the video thank you
|
Score of Parentheses
|
consecutive-numbers-sum
|
Given a balanced parentheses string `s`, return _the **score** of the string_.
The **score** of a balanced parentheses string is based on the following rule:
* `"() "` has score `1`.
* `AB` has score `A + B`, where `A` and `B` are balanced parentheses strings.
* `(A)` has score `2 * A`, where `A` is a balanced parentheses string.
**Example 1:**
**Input:** s = "() "
**Output:** 1
**Example 2:**
**Input:** s = "(()) "
**Output:** 2
**Example 3:**
**Input:** s = "()() "
**Output:** 2
**Constraints:**
* `2 <= s.length <= 50`
* `s` consists of only `'('` and `')'`.
* `s` is a balanced parentheses string.
| null |
Math,Enumeration
|
Hard
| null |
818 |
hey what's up guys chung here again and so today let's take a look at another lead cold hard problem here number 818 race car so you have a car and the car at position 0 and speed then you need the initial speed is 1 and at each step you can do two things either accelerate if you do accelerate your position the next position or the current position of your car will be moving to the current speed plot basically your position will be moving to the next position by adding the current speed and after doing that your speed will become twice as before so that's the that's what's the acceleration a what were able to and another option is that you can do are here so if you two are basically you just simply stop first your position will stop at a current step and if your speed is positive then you get a speed equals to minus one basically you turn around right otherwise your speed equals to one basically it's turning around on each direction if you are facing to right and then it will be turning around back to one to the left with a speed one and if you are same thing if you are iffy if your current status is a coin is heading toward left I need to are again you'll be heading to the right side again with still with a speed one okay and it asks you give you gives you a target and ask you what's the minimum the shortest sequence of instructions to get there so today I'm gonna talk about two solutions here the first one is a PFS which is the kind of Intuit a little bit more intuitive and second why is that DP then I mean programming so let's take a look at the first solution the BFS search and so I think this thinking process to come to the BFF Serge's the when you will say when you find this length of shortest sequence basically that short is the path right to get to the target you know you guys see a quite find a problem with anything that has a shortest something you know it's not a hundred percent sure but uh could but you for the BFI search right one of the purpose of BFI served is find of shortest path right from shortest path from the from start to the end right there are a bunch of other shortest or shortest the result problem like you can also do a so for a binary search problem it'll become it may also ask you about shortest answer but for the binary problem to be able to solve reusing a binary problem all the other candidate they I have to be sorted right but in this case it's not stories because you can either go to the right or even go to the left and another way of doing the lat the length of the shortest thing is by using the DP of course right and the third one will be a the BFS right because with BFS is easier to find if you do a PFF if you peel the graph and if you build a graph and you have a give up EF and you need to find a whistle with a graph and you to a BFS search it's easy it's easier to find the length the shortest line so and the graph for this is like basically you need to know the address from one node to all these neighbors right and for this problem it's always to address four from the current state or current known to its neighbor it's either accelerate or reverse right and for each node we need to store its state right or a unique key for that in this case it's going to be the position plus the speed right that can uniquely identify the each node it just similar eyes daddy P problem for ya for DP problem in this case we're also gonna need like the 2d TP because we need post-petition 2d TP because we need post-petition 2d TP because we need post-petition and the speed to annotate current state same thing for the BFI search so let's take a look at the PFS search so for the BFS search it's a like just regular BFS search at each opposite way our we'll try to branch out by either a or our of course we're gonna need to track in fact if this state has been had been visited before right and another like some like improvements for BFI search HDL when this like the speed or a position reaches certain point we don't want to continue so ours our stop point will be a if the speed the absolute value of a speed if the absolute value of the new speed of the speed or new speed is greater then that then the two times of the target and same thing for absolute position right it's also greater than the then two target so either the speed or the position has exceeded more than two times of target with the stop why there's a like there's not like very strict a proof for this stop point but it kind of makes sense right because let's say the speeds are all way over it's way over on either side right so there's no point of continuing continue doing the continues keep going right because the speed is too fast right so if you're going keep going on that direction there's no point because we're really too far away from the target all right and same thing for a position right so the speed if a speed is two speed is too fast it means that we there's no point of keep going at the current speed we should just stop all right and same foot up for a position here right so if the position is like it's a way to over its way to over on one side right as and we also need to stop okay cool so let's try to call this thing so other than that it's just like very standard PFI search template basically we're gonna have a scene set right and then at the beginning right the first step the first state is going to be that at position 0 with speed 1 right and then we're gonna have a queue here right so since it's gonna be the klaxon start DQ right so mmm yeah and the steps right steps equals to zero while Q right well Q and then we do a range and this is how it will be fi search by the way there are there's a lot of ways you can do it but I prefer using a for loop here so the position and speed right top left right so and the new position will be we're gonna calculate a new position first right the new position is the position plus speed right and if the new positions is equal to the target right we simply return the steps plus 1 ok so after this the new speed will become the new speed will be 2 times that of the old speed ok so now the acceleration so now the first is the keep the first case will be a right so like I said when do we when should we keep accelerating right do we need to keep accelerating basically we reach our if the position right if the current position abs of the speed okay the new speed it's smaller than the two times target right and abs of the new speed sorry the new positions are the new position is also within the two times of target then we can continue otherwise like I said if there if either one of them is like this as it has exceed two times on the target there's no point of continuing and of course right so and the new position had a new speed has not been seen before right if that's the case we just add this new state to the queue and new position and the new speed okay and don't forget to add this out to do there right okay so that's the a right and further be the first results for the are here right so for our there's no there is no like there's no like this kind of check because we are there basically that the states the position didn't change and this the position stays V is the current position and speed will become either 0 either become minus 1 or 1 right so we don't need to track this because they will never appear over the boundaries in this case so we simply just get the new speed ok news newsfeed to write equals 2 it's minus one if the speed is greater than zero right else one right so same thing so here we just need to check if the position the old position since it's not moving and the new speed who is not in scene that's all we need to track right if that's the case then we just do this but remember gonna be the old position the new speed - and the old position the new speed - and the old position the new speed - and here - parenthesis here right so yeah I here - parenthesis here right so yeah I here - parenthesis here right so yeah I think that's that so we needed to a return or not but because it doesn't really matter because we will definitely find our answers here we'll return here so it will never reach here so yeah so basically that's the very basic BFS search for the excel oh sorry let's try to run it first oh my god three okay target and position and not in st. and at you I think I know what happened here so I forgot to increase the steps here in the end yeah right so every time the BFS the most important step for BFS maybe increase the steps alright let's try to run it yeah so you had passed all right so yeah very super BFS it's to recap about thinking process so you get you need it you're asked to get the shortest length or sure it's a step from one state to another right and then on each of the states you have several address you can choose in this case either a or R and then you can start thinking about can I solve this problem by the BFS search right and what are the conditions to add a new edge and how was the was a stop point stopping point right okay so cool that's the basically the BFI search now let's go to the DP solution here so the DP solution is more difficult to come up with the state transition function okay so okay let's say you have a I'll destroy it here let's say you have this one line here and assuming we have all the a right and you know what I will open the whiteboard here it's easier for me to draw so let's say you have a you have KS right and basically in the for DP you have to think about how many how to get to the target right to get to the target like the how many ways we can get to the target let's say we have a target here T right so if you do a let's say you have a K minus 1 a so basically if the K if the T is between the K minus 1 step and the case step all right this is okay this is a K minus 1 and this is the K let's say T is somewhere in between right so when I say came or K minus 1 I means the how many accelerate continuous acceleration we have been made here okay and so that the value is going to be that what's the value of this so what the rider is the like the to the position yeah so the position for this place is it's like two to the - to the K minus 1 right K - to the K minus 1 right K - to the K minus 1 right K minus 1 yeah 2 to the K minus 1 to the power of K minus 1 and this position is the 2 to the K minus 1 right because we are keep accelerating every time the speed doubled up right so that's the position we can get as the 2 to the K minus 1 plot plus 1 right you can this is like the math formula here right so because you do a 1 plus 2 plus 4 plus 8 right so in the end you can conclude with two this like 2 to the K minus 1 and this is the 2k 2 to the power of K minus 1 right so let's assume at the T somewhere in between right and what are the ways we can get to the T right so first we can go to the K 2 K minus 1 which is that we have already passed the T here right so if okay 1 so the first condition is let's say we already reach the K which is already passed the T then what do we need to turn around right so and when we turn around so when we turn around okay so the distance right the distance between the two K minus 1 minus T right that's the distance from here to here ok so what I'm saying is that so from K here we're gonna turn around we're gonna hide him back to the T right and then you guys maybe have already realized that for this T here for to turn him back from here just once we have already turned back to starting the speed we'll start with one and it will hide to the T right it's this subproblem right basically this so this part from this k from this one to t here so we're gonna have like a DP sub-problem right sub-problem right sub-problem right the it's that the - time of K minus 1 minus T alright so - time of K minus 1 minus T alright so - time of K minus 1 minus T alright so that's the problem right because the problem is that so dpi we are defining like from speed 1 or from speed 0 right what's the minimum step we can get to this current to this position right so by turning around I took at this position K here we can transfer transform the this part to another DP to it not a DP per sub-problem because we can easily sub-problem because we can easily sub-problem because we can easily prove that this subproblem is a smaller sub-problem because we are is a smaller sub-problem because we are is a smaller sub-problem because we are we have already been calculating calculated this is like this value before because we are calculating from the left to right and when we reach the k we have already passed this DP problem already right so ok so and that's the sub DP problem and how many steps we need to take to get to this DP state right so first we have K steps right that's the K and we do 1 reverse right so we need to a reverse we need to plus 1 here so this is the reverse here basically when we reach K here we turn back and then the rest will be converted to a sub DP problem here right from 1 to the target but in the dip in the opposite direction ok so that's the first up first scenario which is kind of easy to understand and the second scenario is more complicated basically and so the first one is one after we pass the tea second one is the it's right before we reach T which is the two to the K minus one basically we stop from here once we stop from here we'll try to turn around we try to turn around here and then right we try to turn around and then it's we're gonna reach a post a certain point here right so let's say the point here is selected j steps here right j step J ace so basically once we turn around from K here we are we do J's acceleration and then we turn around back again to another I do another are here okay so and from this point over from here to the T basically from here to the T again so from this point to the T again so this will be also become another subproblem right and but in order to get this disposition here we basically we have to try out all the check a pulse about possible J's here because i say for example we can do we can accelerate once excited once and then we turn around and we can assign rate twice we have two eight three eight five ways until the K minus 1 K minus one eight right because I think the maximum we can go back is basically before heating to your right so basically if your or even if you Traverse turn around too far away even like bypass our original starting point that you will not definitely not get a better answer so basically that's why at each point here at each up that the two to the K minus one point here we only try the possible ace up to the K minus one times and then once we have that J step fixed then we'll do another turn here we do another turn to make it reverse it back towards T and then the rest will become another sub-problem become another sub-problem become another sub-problem so then what's the DP transition function state transition function for this scenario right so first we have a you never came K minus one step to get to this position right so that's the first step right second is the first is the tape K minus one step to get here and then we do a turn here right that's going to be a block plus one right we do a plus one and then we have a we have J step to get to J right we plus J k plus one okay one to see yeah so right so and do we have another we turn around once here to get two to the J's acceleration and then we do another turn around okay right so that's the steps we need to - I mean to take if the steps we need to - I mean to take if the steps we need to - I mean to take if before converting this problem before in converting the rice into another DP problem right so what's the DP problem here so now the DP we need to let the DP here so DP should be from the current state the distance between here and the T here right so what's that then what's that was a deal what's the difference the distance R the distance it's the as you can you guys can see right so the distance is the T miners this part right - from the start miners this part right - from the start miners this part right - from the start - right before we do it a Jace like - right before we do it a Jace like - right before we do it a Jace like turn right then this start in this place this distance equals - the what - the this distance equals - the what - the this distance equals - the what - the position here - the miners the - the position here - the miners the - the position here - the miners the - the route the reverse distance right so it's going to be that the position of here is like - okay - one right and miners - I mean - one right and miners - I mean - one right and miners - I mean I'm talking about the distance I don't do what - one because if it were - one do what - one because if it were - one do what - one because if it were - one here I also need to a - 1 here and so here I also need to a - 1 here and so here I also need to a - 1 here and so I'll just use that the relative ability the distance because we want to get the difference right so the 2k miners on miners 2 to the J right so basically so this 2 to the power of K minus 1 minus 2 to the power of J will give me the difference from the beginning to here right and then I just - I do what T miners then I just - I do what T miners then I just - I do what T miners disposition it will give me the distance between the current position and the T which will be another sub problem right and so for the so the J here it's gonna be we're gonna basically we're gonna do a minimum right minimum of this one so the J is like starting from 0 to the K minus 1 right sorry k minus 1 that's the range of J because we will not go over to 0 here ok cool so that's basically the tool the two scenarios to get to the T here you know someone may argue that how can you prove this prop this solution right these scenarios can give you the optimal result right I mean you can also argue that you know like let's say why do you have to stop at case here right why don't you stop at anywhere like before K before 2 to the K minus 1 right can you stop somewhere here right in between right then we'll that may give you like a better option right yes that's possible but the problem is that if you stop somewhere between the T and a to K minus 1 we don't have a sub problem to - I mean - to use right sub problem to - I mean - to use right sub problem to - I mean - to use right so basically and if you stop adhere right even stop here but we are since we are also like calculating all the possible ways we stopped before the K minus 1 right so that can somehow guarantee in that guarantee not we can get a best we can get a to get out and get the correct answer out of these two scenarios here and yeah so I think you guys can just assume yeah this will give you the best answer out of this to two possible conditions right so and here is the like one this is our right it's also our here yeah I don't know how can I approve this these are solutions to be correct but I'm just thinking of this like the only ways I can get close to the answers otherwise if you don't use this k point right you try to use somewhere in between here and you don't know the step basically right so at with this K steps here this is like a K 2 to the K minus 1 we know exactly that we know how much how many steps we need to take we need we know exactly how many steps we need to take to get to the current state which is the K and here's the K minus 1 right if you were to use anything in-between here the step is not it's not in-between here the step is not it's not in-between here the step is not it's not fixed right so basically we cannot - fixed right so basically we cannot - fixed right so basically we cannot - we cannot do like a state transition function here so we have to basically so now it cannot be solved by a TV problem that's why I so we have to rely on these two like conditions here right oh and one of the edge cases if the T if T equals to this if the T equals to the 2 to the K minus 1 then the answer will be K itself right that's uh that's the best scenario writes the t's we just keep accelerating only with K steps we'd never need to reverse right cool okay so let's try to code these things up so and ok so with the DP we're gonna create like DP array here right since we're getting the max the minimum we're gonna initialize everything to be the maximum and the size will be the target minus 1 the target plus 1 okay and then we do off start from the first position right in range target plus one okay so we start from here and so and now we have a target right in the target we need to know how many what we need to know the range of the steps that those how many accelerations how many days we need to take to get to the to this target right so in Python there's like AI still a target here in Python there's like functions called beat lens which will give you the beta lens to get to the current number that's exactly the numbers we need basically we need to get like the - to the time of K minus 1 like the - to the time of K minus 1 like the - to the time of K minus 1 right and less than K I send 2 to the K right so we need to get the target here basically to the 2 to the K right so in Python we can simply use a bit length to get to the dislike the K number very easily right and then we have a spec special case here so if the t equals to 2 to the time of K minus 1 right and then we simply do a DP our T equals to K right well actually we can simply return o or not return sorry we cannot return it we have to do continue because that's the tested that's the best answer for the current target here so we don't have to try audio all the other possible ways so else right else basically we are basically the DPI would be good equals to 1 equals to the minimum right of dpi every time we do so the first step is going to be that we passed past target a pasty and turn back right like I said in this case and so first we'll we will need to K steps to reach that step the point that passed the T right and then we do what another we use another step to do a turn around right and then the rest will become the so the current position of K is a - who so the current position of K is a - who so the current position of K is a - who - the pay right that's the positions - the pay right that's the positions - the pay right that's the positions - went right so that's the current - went right so that's the current - went right so that's the current position minus 1 and minus T right so the position is 2 to the power of K minus 1 that's the current position and then we do a - the TT is the current then we do a - the TT is the current then we do a - the TT is the current target right so that's the range basically right from that point and when we turn back to the T so that's this first scenario second scenario is we stop at 2 to the power of K minus 1 and see exact ok yes so this thing's like a zigzag right zig zag back ok right and so for that we have to do what I'm going to use j.j in a range of the I'm going to use j.j in a range of the I'm going to use j.j in a range of the basically this J means how many accelerations we will take back right and then would will turn around back right will do basically to reverse so the range will be a K minus 1 and opt in to 2 K minus 1 so the DPI will be comes to the DP I to the so first we'll take K minus one step to get to that starts first stop point right and then we do a reverse right and then we take Jace that we took J accelerations and then we do another reverse to come back right and the rest will be the DP like the T miners right like the difference right the difference is the okay so that's the two to the power of K minus one minus two to the power of J right yeah and in the end we simply return the DP target right so that's the last one mmm okay let's try to run it I sorry DPT yeah as you can as you guys can see this DP problem is it's much faster than the attend the previous one because the oh sorry okay let me finish the to recap here so you know the code it's kind of short but the thinking process is it's long hard especially for these two scenarios and it's very fit for this one basically when you will turn we know to its exact right you have like K minus one option to choose your turning point right but when you pass the T here you have we only give him we were only giving you one options so right after you passed it this dislike this T here you only have one options but to turn back okay I put here we have a K options K minus one options to go back with Jace acceleration and then turn back again mmm okay so I'll how about the time complexity here and space complexity so first for the BFS search right so for the BFS search yes you can squeeze you can see every time we have two options here and we have a basically we have at zero we have all target we have targets like the note here right or possible cut our target nodes here no I'm sorry not possible targets nodes so every time we have an we have a new position where or we have a new state will be having like mmm basically we're gonna make them in into 2 times that many nodes right so basically the time comprise here for this BFS there's going to be some somewhere for the and sorry it's the to ^ n the N is somewhere sorry it's the to ^ n the N is somewhere sorry it's the to ^ n the N is somewhere close to the target right but since we have this kind of like a boundary check here the time comprises is much smaller than this but for but in the normal case right so this the time compressor is going to be 2 to the power of n because each time right we haven't we have a new node we're gonna have gonna spawn two different branches right and the space comprises still this is also the same to the time of because that's the numbers we were gonna have in this queue here yeah so okay so that's that and how about this DP problem right it's over DP problem we have a target here right so the first one is the so let's see this is n right okay I'm gonna use the end here so the first one is N and how about the second one here so within the end loop here right so we have a we have another for loop here right but the for loop here is not it's not in right because we are only looping through by the power of two right so we're looping through the cave you're not looking through the target here right so then the inner loop will be like the log end here right because we only look in through the power of two so the time complexity for this DP is that unlock - complexity for this DP is that unlock - complexity for this DP is that unlock - how about space we have a space complexity we have an L here right that's the that's a DP here and you will have another space here no I think that's it yeah we just use this deep Oh n space here DP yeah so the space is just Oh in here hmm oh and before finishing up these videos here so for DP problem the reason we can define like a DP at most two target or target plus one is because you know even though we're gonna have like I said even though we're gonna pass the target somewhere on the K here so like I said we have a target here right and there's a like K minus 1 2 to the K minus 1 and then 2 to the K right so even though we're gonna pass the T to and then advance to the 2 to the K but we can approve that 2 to the K minus 1 minus T is always smaller than the target okay that's why we for a DP here we only need up to this length of DP because it did this one is smaller than the previously target that's why we can reuse the previous previously calculated DP results to help us get to the current state that's basically that's the a sturdy that's the sense right of the DP or I think essence snotty sense I think sorry about my pronunciation is that I sense of the DP we use the previously calculated result to get to the current state right yeah okay I think that's pretty much it is for this problem I know it's a hard problem you know think free for you guys if you guys find this DP solution is really hard to and to understand during an interview I believe this while at this BFS solution should be enough yeah because it's more intuitive right you just start with one state and then you try to find the shortest path to another state and you just need to be careful about so you cannot branching out indefinitely well you have to stop somewhere right and then for a DP it's a little bit tricky and it's hard to prove it's kragnes right and cool I think that's it for this problem thank you so much for watching the videos guys and stay tuned I'll be seeing you guys soon bye
|
Race Car
|
similar-rgb-color
|
Your car starts at position `0` and speed `+1` on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions `'A'` (accelerate) and `'R'` (reverse):
* When you get an instruction `'A'`, your car does the following:
* `position += speed`
* `speed *= 2`
* When you get an instruction `'R'`, your car does the following:
* If your speed is positive then `speed = -1`
* otherwise `speed = 1`Your position stays the same.
For example, after commands `"AAR "`, your car goes to positions `0 --> 1 --> 3 --> 3`, and your speed goes to `1 --> 2 --> 4 --> -1`.
Given a target position `target`, return _the length of the shortest sequence of instructions to get there_.
**Example 1:**
**Input:** target = 3
**Output:** 2
**Explanation:**
The shortest instruction sequence is "AA ".
Your position goes from 0 --> 1 --> 3.
**Example 2:**
**Input:** target = 6
**Output:** 5
**Explanation:**
The shortest instruction sequence is "AAARA ".
Your position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6.
**Constraints:**
* `1 <= target <= 104`
| null |
Math,String,Enumeration
|
Easy
| null |
667 |
Ajay Ko Hello Everyone Welcome to Code Scan Subir World Tarf Write Challenge and Problem subscribe and subscribe the Video then subscribe to Ka Selection Distance Problem Daily Sample Consider This Example in Easy Way Two Three Four Number This Side Subscribe Ka Main Tera Blood Pressure Number Stuart 3.2 Main Tera Blood Pressure Number Stuart 3.2 Main Tera Blood Pressure Number Stuart 3.2 Subscribe To That Combined Report Differences Between Increase This 2 And 110 Test Similarly Shoulder Suna Two Ko Pure Possible Arrange Will Mix This Equal Two Corner Arranged A Means To Quench Your Products From One To 6 Difference Between December 1872 Number Difference Between the Number Subscribe Now to Front Subscribe Number to You Need Difference Between All the Best That in Reverse Order Cutting One to Different 16 Difference Between One Subscribe Pimples and First Number subscribe and subscribe the Channel Please 220 points Two Left Right Left Hum Subscribe to this number 9483's pick up to the number one position from three plus subscribe button Chhote Kaun Tha 500 se Rang Gora Heave two point se left starting from one sheet to one Android MB in one variable two-fold index off MB in one variable two-fold index off MB in one variable two-fold index off Hain Shri Ram Good Morning Teacher Result Loot is 100 times favorite oil in left spain point Tomorrow morning Bank Sheth only Mickey is greater than one India Loot-Loot in odd and even one India Loot-Loot in odd and even one India Loot-Loot in odd and even position Ajay ko aap is mike ki is 98 hai tej namak And output tax plus it's not any one position gorakhpur tweet - not any one position gorakhpur tweet - not any one position gorakhpur tweet - point hai main itna 12th ki reach from rain in the case on september 16th the cast system finally return and result hai ki electronic on karo hua ki luck submit ki this solution acid and 210 mil sake so thanks for watching video subscribe to
|
Beautiful Arrangement II
|
beautiful-arrangement-ii
|
Given two integers `n` and `k`, construct a list `answer` that contains `n` different positive integers ranging from `1` to `n` and obeys the following requirement:
* Suppose this list is `answer = [a1, a2, a3, ... , an]`, then the list `[|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|]` has exactly `k` distinct integers.
Return _the list_ `answer`. If there multiple valid answers, return **any of them**.
**Example 1:**
**Input:** n = 3, k = 1
**Output:** \[1,2,3\]
Explanation: The \[1,2,3\] has three different positive integers ranging from 1 to 3, and the \[1,1\] has exactly 1 distinct integer: 1
**Example 2:**
**Input:** n = 3, k = 2
**Output:** \[1,3,2\]
Explanation: The \[1,3,2\] has three different positive integers ranging from 1 to 3, and the \[2,1\] has exactly 2 distinct integers: 1 and 2.
**Constraints:**
* `1 <= k < n <= 104`
| null |
Array,Math
|
Medium
|
526
|
1,277 |
hello friends today lots of how to square sub-matrix with all one's given square sub-matrix with all one's given square sub-matrix with all one's given an M times and magics of ones and zeroes return how many square sub-matrix have return how many square sub-matrix have return how many square sub-matrix have all ones let's see this example first we will how to the lens you go to one of squares so we have 1 2 3 4 5 6 7 8 9 10 so we have 10 and then we need to act out there to have the lens to this is 1 square this isn't to an R squared this is an R square so we have 4 how about the dance equal to 3 we have only 1 so we so in turtle we have 15 squares so how to solve this problem well I think you should dare think about dynamic programming because we needed to know previous accumulated o once right like if we are at the row 2 column 3 we needed to know how many ones before it in the same rows M : in the same rows M : in the same rows M : in the diagonals so first I will breathe introduce a run solution I thought it had first glance of this question I think I can use a 3 you know a 3 elements that you accumulated the ones in the same rows M : in the same rows M : in the same rows M : and the diagonals so for example if this is a given matrix then TP 2 3 0 means accumulating ones in the same row so it's a 3 and the DP 2 3 warming's the accumulate kiddo once in the same College and also is also sorry and TP 2 3 2 which means the accumulated ones in the same diagnose so it's also through so in the case you will know that the max man square the cam foam is length of 3 it is seems correct but it's wrong I see this example if we are at this element there you will see the left part is for I the rock the up I mean the same : the accumulated ones is also sorry I'm : the accumulated ones is also sorry I'm : the accumulated ones is also sorry I'm sorry for and the diagnosed it's also for so maybe we can gather the conclusion that the maximal square we can form is a length of 4 but actually we cannot because this also have zero so we can not form a square have the length of 4 so that's the problem of this solution so how to solve it in a correct way well actually we can um think three cases one case is the cell is actually 0 so we just give it if it's one we actually have two cases one is it on the border if it's on the border we just accumulate accumulator this one to the result because it can never form a square have a length larger than 1 right this is only 1 squared so we just added to the result but inner ones we may form a length greater than 1 so this is a foster row after iterate eight we just get a 0 1 and the we accumulator this is ritu the result means the total number of the sub-matrix there to help have all ones sub-matrix there to help have all ones sub-matrix there to help have all ones so then we go to a step in the road it's also one we just write one here we needed to compare if it can form a length of 2 square but this is 1 and 0 so cannot we just write 1 and then we go forward it means in this case it's laughter is one is right is its up is 1 and the diagonal is also 1 so we can form a square length of 2 so we write a chill here what are them mean actually we have two more squares one is the same length of 1 square the second square is this square we have length of 2 so this is the 2 means we actually have two more squares and the wicked go then the same for this part we actually have 2 more square so we add we write a chill you should notice that we change the value in the matrix Y you will see afterwards then in the third row 0 just skip it and this is 1 right we can it's left up and a diagonal so it's also 0 right because the minimum is 0 so we just write a 1 and go here it's 1 so the minimum is 1 and we know it can form a length of 2 square and for yourself either is at length 1 square so we add a 2 just as this example so we write a chill here and then we go we are at here in this case is the left is true and then it's up is true and it's diagnosed - so the up is true and it's diagnosed - so the up is true and it's diagnosed - so the minima is just a - and though we know minima is just a - and though we know minima is just a - and though we know it's it itself is one so we write a three here how to understand the district actually the means we have three squares more this is a first one it's a length of one and this is a segment of one length of - this is the segment of one length of - this is the segment of one length of - this is the third one length of three and we do not repeatedly calculate other squares because this two length of 2 square we already accumulated before so easy in this case we just have three more which is this one in this one so you should notice that in the end we accumulated this so the results 15 okay so we know this is the relation we first check whether is the row index J so calling ducks if it is in the boaters just add the result increment by 1 if its inner we update the sail we can it's s3 neighbors minimum and we accumulated this value to the original matrix value and there in the end we added this value to the result so the time complexity will just be big-oh M times M okay now will just be big-oh M times M okay now will just be big-oh M times M okay now let's write the code M is the matrix talents so quick check if m equal to 0 just return 0 and n is the matrix $0 we just return 0 and n is the matrix $0 we just return 0 and n is the matrix $0 we need a result global variable and so in I equal to 0 I less then and I plus 4 into J equal to 0 J less than n J plus check oh if matrix IJ equal to 0 just to continue if it's 1 which I whether it is in the border J equal to 0 then the result just increment by 1 and we continue okay otherwise we get a minimum the 3 neighbors so minimum matrix I minus 1 J minus 1 and math minimal matrix I and the J minus 1 matrix hi minus 1 J and though we accumulate this value to the matrix and the result just plus this matrix I J so in the end just a return result ok thank you for watching see you next time
|
Count Square Submatrices with All Ones
|
largest-multiple-of-three
|
Given a `m * n` matrix of ones and zeros, return how many **square** submatrices have all ones.
**Example 1:**
**Input:** matrix =
\[
\[0,1,1,1\],
\[1,1,1,1\],
\[0,1,1,1\]
\]
**Output:** 15
**Explanation:**
There are **10** squares of side 1.
There are **4** squares of side 2.
There is **1** square of side 3.
Total number of squares = 10 + 4 + 1 = **15**.
**Example 2:**
**Input:** matrix =
\[
\[1,0,1\],
\[1,1,0\],
\[1,1,0\]
\]
**Output:** 7
**Explanation:**
There are **6** squares of side 1.
There is **1** square of side 2.
Total number of squares = 6 + 1 = **7**.
**Constraints:**
* `1 <= arr.length <= 300`
* `1 <= arr[0].length <= 300`
* `0 <= arr[i][j] <= 1`
|
A number is a multiple of three if and only if its sum of digits is a multiple of three. Use dynamic programming. To find the maximum number, try to maximize the number of digits of the number. Sort the digits in descending order to find the maximum number.
|
Array,Dynamic Programming,Greedy
|
Hard
| null |
1,170 |
hello everyone a leak of the day today our question is leaked out 1 7 l compares dreams by frequency of the smallest character this problem is favored by Google we can see Google has interviewed maybe like 17 times in the recent six pounds let's look at the question so first define a function f as over a string s and calculate the frequency of the smallest character in s so for example if as is dççe the FS is 2 because the smallest character in as it's C and it's frequency is 2 okay after giving this function the input for our actual function is queries and words so given the queries and words so queries are lists of strings and words are also lists of strings and by giving that we want to return an integer every answer so for each of the answer it's like f query I smaller than F W so basically that means for each of the query how many of the word in words have larger F than the current query and then we return the result at this it sounds complicated so let's look at example first so for this example query contain both queries and words only contain one string so Korea's CBD and this is Z a Z and F of CBD is 1 because be the frequency of P in this string is only one and F of Z is 3 because a appears three times in this string and because Y is smaller than three so there's only one here right let's look at this example so here careese is Bibi PCC so f of those queries are like 3 & 2 so 4 3 those queries are like 3 & 2 so 4 3 those queries are like 3 & 2 so 4 3 let's look at how many word in words have more frequency than 3 and we can see it's this one is we have 4 so that's why there is only one element in the words have a higher score than this guy so we put 1 here similarly we put 2 here okay after know we know what's a question so let's look at the solution part because first we define a function so we try to write the function first because we need we want to count the frequency of each of the element so we import a counter from collections and the F is basically first create a counter so counter is a dictionary the keys are the elements in the stream and the value is the number of appearances of course and we take the minimum we take the smallest character in the string like minimum s so in this case we got F working after that in our problem so the first step is definitely to create a half words so afterwards means for each word in words we calculate its F right so it's like forward in words we append the app score of the word into the result here and after we got that we want to sort it so because we want to know how much how many words have a higher app score than the current query right so we need to sort it and finally what we need to return is actually a list and each of the element is for each query how many word are have a higher F score and then for each query we will try to get the number for each query and we call it current here so current first is 0 and we use F to calculate F query like this and for each of the word actually for because since we already got this list of Oh f words so we just check where is the first one first app where's larger than F query if we find it then all the remaining elements should be larger than have query right and the current would be like this and we can break so here is like the essential part for this code basically we sort the app words and if we find the smallest one that are large that is larger than half query then all the remaining are larger than have query if I if we didn't find anything then current is still zero so we just append zero here so finally we after this for loop for all the query we return the result so because we have a sword here so for the time come Class D it's big all n log N and for the let's say for the space complexity we create a F words which is let's say Big O end and another yeah that's it so that's it for this algorithm if you think this video helps please like and subscribe my channel thanks for watching
|
Compare Strings by Frequency of the Smallest Character
|
shortest-common-supersequence
|
Let the function `f(s)` be the **frequency of the lexicographically smallest character** in a non-empty string `s`. For example, if `s = "dcce "` then `f(s) = 2` because the lexicographically smallest character is `'c'`, which has a frequency of 2.
You are given an array of strings `words` and another array of query strings `queries`. For each query `queries[i]`, count the **number of words** in `words` such that `f(queries[i])` < `f(W)` for each `W` in `words`.
Return _an integer array_ `answer`_, where each_ `answer[i]` _is the answer to the_ `ith` _query_.
**Example 1:**
**Input:** queries = \[ "cbd "\], words = \[ "zaaaz "\]
**Output:** \[1\]
**Explanation:** On the first query we have f( "cbd ") = 1, f( "zaaaz ") = 3 so f( "cbd ") < f( "zaaaz ").
**Example 2:**
**Input:** queries = \[ "bbb ", "cc "\], words = \[ "a ", "aa ", "aaa ", "aaaa "\]
**Output:** \[1,2\]
**Explanation:** On the first query only f( "bbb ") < f( "aaaa "). On the second query both f( "aaa ") and f( "aaaa ") are both > f( "cc ").
**Constraints:**
* `1 <= queries.length <= 2000`
* `1 <= words.length <= 2000`
* `1 <= queries[i].length, words[i].length <= 10`
* `queries[i][j]`, `words[i][j]` consist of lowercase English letters.
|
We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming. We can use this information to recover the longest common supersequence.
|
String,Dynamic Programming
|
Hard
|
1250
|
667 |
welcome to april's leeco challenge today's problem is beautiful arrangement 2. given two integers n and k you need to construct a list which contains n different positive integers ranging from 1 to n and obeys the following requirement suppose this list is a1a2 a3 all the way to a n then the list a1 minus a2 the absolute value and a2 minus a3 has exactly k distinct integers if there are multiple answers print any of them or return any of them so say that we had the number three we can have the output of one two three because we already know that we have one um a list with like three distinct integers and if we want to get the differences to be one for all of them we can see that the way to do that is just to put them all in order so it's like one would be the difference now say that we had uh up to five digits right here this would be n equals five and say we know that k has to be less than n so say that k equals four that would be the maximum k that we could have right how would we construct this array well it's kind of a zigzag pattern here right it would be like one go to the end five then two then four then three uh this would be the maximum and we can see here where the differences would be like four three two one uh so this kind of maximizes how many different k's that we can have but it's always going to be less than n now what about if n equals or k equals three then it becomes a little trickier but if you think about it carefully if we just start with like one two and just do the same pattern at this point say two to five then three then four this would be k equals three right because this is one difference this would be three two and we know at the very end this would be one so that kind of gives us a little pattern here what we can do is just get n minus k numbers um all the way up to whatever this value is and then at that point we'll do this zigzag pattern to get the k amount of differences or k mount absolute differences at that point so if we had like whatever long number this is it would be an o of n time because we just go up to the point where it's n minus k then we start this zigzag pattern by keeping i guess we'll have like a direction integer that's going to flip every single time and we'll have a difference that's going to subtract from k um one every single loop so let's see if that works what we'll do is first initialize an output and we'll have i for i in range of 1 through n but keep in mind we have to minus k here because we want to go up to the point where there's going to be k differences now if it's one then we just want to go from one to n plus one right so make sure to put plus one here um now assuming that we have some k what we'll do is say for i in range of k let's initialize some variables here the direction which start with the positive one as well as the difference now what's the difference going to be here uh the difference is going to start with k because that's the many as many differences that we want so that just starts with k and what we'll do is add to our output get the very last digit here whatever we have at this point and what we're going to do is add to that the i um no we don't need i guess we're keeping track of differences so that would just be that plus the difference times the direction right because that's gonna go yeah so that's gonna be a direction now we just flip our direction to go the opposite way now so we'll multiply by negative one and we'll subtract our difference by negative one here and that's gonna allow us to make sure that our numbers are within the range of one through n finally we just return our output and let's see if that works so that does look like it's working so let's submit it and there we go accepted time complexity wise it's o of n and we use constant space because we this is it the output that shouldn't count as space all right um this was a pretty hard problem but um once you figure out that kind of zigzag pattern i think it's fairly intuitive to come to this conclusion um but it definitely is not an easy problem here it's pretty difficult so all right thanks for watching my channel remember do not trust me i know nothing
|
Beautiful Arrangement II
|
beautiful-arrangement-ii
|
Given two integers `n` and `k`, construct a list `answer` that contains `n` different positive integers ranging from `1` to `n` and obeys the following requirement:
* Suppose this list is `answer = [a1, a2, a3, ... , an]`, then the list `[|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|]` has exactly `k` distinct integers.
Return _the list_ `answer`. If there multiple valid answers, return **any of them**.
**Example 1:**
**Input:** n = 3, k = 1
**Output:** \[1,2,3\]
Explanation: The \[1,2,3\] has three different positive integers ranging from 1 to 3, and the \[1,1\] has exactly 1 distinct integer: 1
**Example 2:**
**Input:** n = 3, k = 2
**Output:** \[1,3,2\]
Explanation: The \[1,3,2\] has three different positive integers ranging from 1 to 3, and the \[2,1\] has exactly 2 distinct integers: 1 and 2.
**Constraints:**
* `1 <= k < n <= 104`
| null |
Array,Math
|
Medium
|
526
|
57 |
in this video we're going to take a look at a legal problem called insert interval so we're given a set of non-overlapping intervals non-overlapping intervals non-overlapping intervals and we want to insert a new interval into the intervals that we're given and if there's overlapping we want to make sure we merge the intervals that are overlapping right so you might assume that the intervals that are initially sorted were initially sorted according to their start times so here you can see we have intervals and then this is the new interval so in this case if we were to insert this interval onto this interval we have to merge this interval right here with this interval so in this case we going to return a non-overlapping interval which looks a non-overlapping interval which looks a non-overlapping interval which looks something like this and here you can see we have another example where we have one two three five six seven and eight ten twelve sixteen so the new interval is gonna be this one so we're going to merge those intervals right here because these intervals are overlapping with this interval so we're going to merge them with this and notice that once we merge them the start time is 3 and the end time is 10. okay and because new interval 4 8 overlaps with this these intervals so we're going to over uh we're going to merge them if there's only one intervals then we're just going to add that onto our list and return that at the end okay so there are some more examples basically the goal is that when we deal with intervals problems it's very important to consider the base cases right so some of the coordinate cases so there are a couple situations where we have intervals like this where there's no overlapping right and there's could be a situation where um where there the b is overlapping with a right and there could also be a situation where a is completely overlap overlaps with b so there are some cases that we have to consider and to solve this problem basically what we're going to do is we're basically going to add all the intervals right all the intervals that are not overlapping with the current interval that are that we're going to plan to insert so let's say this is the interval that we're going to insert and we're going to basically add all the intervals that are not overlapping prior to this interval um onto our list like for example one two right then what we're gonna do is because those intervals right here are overlapping with our current inserted interval or our uh current new interval then we're gonna do is we're basically just going to merge them right so we're just going to merge them into one interval and add it to our list then what we're going to do is we're going to add the remaining intervals that are after um do after the current interval the newly um the new interval added to our list right so there are three step process this is our first step at all the intervals that are not overlapping with the new interval onto our list then we're going to add um yeah so then what we're going to do is we're going to add merge the overlapping intervals onto our list right so i merge the overlapping intervals onto our list merge them and then add to our list then the third part is going to be we're going to add the remaining intervals onto our list okay so now let's take a look at how we can do that so to do this in code first we're going to completed step one right we're going to add we're first going to define our list that we're going to return at the end then our step one is basically to add all intervals that are no non-overlapping non-overlapping no non-overlapping non-overlapping no non-overlapping non-overlapping to the new interval right to the new interval onto the list okay that are prior to the new interval of course then once we found a situation where the new intervals is where the current interval is overlapping with the new interval then we want to make sure we merge the new interval right with the overlapping interval okay so once we've done that we're going to add the remaining intervals onto the list at the end we want to make sure we return the list okay so first let's define our list so we're going to have our integer uh list which is type of integer array and then we're going to say list is equal to new linked list okay once we define our list we're going to have our pointers let's say i is equal to 0 n is equal to intervals that length so we're going to do is this we're going to say while i is less than n okay and we want to make sure that the current intervals is not overlapping with the new interval and to do that what we can do is we can check the end of the current interval right let's say this is the current interval we want to check the end of this interval compare with the current so let's say b is the new interval so we want to check with the end with the start right the end of the current interval with the start of the new interval right if it's less than then we know that they're not overlapping so what we're going to say is this if intervals at i at 0 so i have i 1 is less than u interval at 0. then we know that they're not overlapping so what we can do is we can say let's add intervals at i okay so we're adding this current interval onto our list okay so once we have add all those elements right we will realize that there is a situation where there's overlapping where the end time of this interval is bigger than or equal to the start time of the new interval then what we're going to do is we're going to compare with the start time of the current interval with the start time of the new interval see if those are overlapping to each other because we know that current situation where we know that current interval is overlapping with the new insert new interval then we want to make sure we basically um update the new interval to merge all the intervals that are overlapping with the new interval so to do that what we're going to do is we're going to say still y while i is less than n and intervals at i at 0 is in this case is less than new interval at 0. sorry at 1 because in this case we're comparing the end of this with because in this case the current interval is going to be overlapping with the new interval so what we're going to do is we're just going to compare the end time with the new interval with the start time of the current interval while the end is bigger than the start time of the current interval we're just gonna compare to see how can we merge those two intervals right so for example if we have something like this then to merge those two intervals we're gonna have b right so we're pretty much gonna see how we can be able to merge those intervals right so we're gonna do is this we're gonna say new interval at zero right the start time is going to be the minimum number right we want to find the um the start time that has the smallest element the smallest value so either the current start time or the current new interval start time or the current interval start time which is intervals at i um at zero and one thing that i forgot to do for the previous stage is that we have to increment i by one every single time when we iterate okay and then what we're going to do here is we're going to also update the end time which is going to be the maximum between interval at 1 or interval at 1 right so either the current interval and time or the new intervals in time so once we update our new interval end time what we're going to do then is we're going to make sure we add right we merge all the overlapping intervals now what we're going to do is we're going to focus on like adding the new interval onto our list okay then we're going to add the remaining integrals onto our list so we're going to say while i is less than n right so while i still less than n uh what we're going to do is we're going to say list dot add and one thing that i forgot to do is i make sure to increment i by one for sure so what we're going to do then is we're going to say let's add interval so intervals at i right so we're adding the remaining intervals onto our list and at the end we want to convert our list into a integer array so we return list dot 2 array okay we say new integer size is going to be list that size and then in this case we have two um elements in the um in the array so it's the start time and the end time right for each array in the intervals um so basically this is pretty much how we solve this problem um the reason why we are comparing with the end time here is because we want to find the maximum right so for example let's say here you can see we have the end time is bigger than the start time of this interval then let's say this number right here is not a 10 let's say this number is 11 or 12 right so we want to make sure we want to update the maximum interval the maximum end time okay so now let's try to run our code cannot find interval okay so it's going to be intervals instead of interval okay now let's try to run our code try with a few more examples uh we got a wrong answer let's see why okay so the reason why we do that is because we want to make sure that if um if intervals the start time is less than or equal to right the end the current in new intervals end time then we want to make sure we merge it now let's run our code and submit and here you can see this is how we solve the insert interval problem so there you have it and thank you for watching
|
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
|
456 |
hello and welcome to today's daily lead code challenge today we'll be solving question 456 called 132 pattern we'll be going through my thought process as I come up with solution and then stick around for the end of the video where I compare my solution to the solution of others that let's begin the question uh and so here I'm given an array of n integers nums a 132 pattern so three two pattern is a subsequence of three integers so in the array a subsequence of sum 1 2 3 integers such that I is oh such that I is less than J is less than k and num's I is less than nums K so nums I um let's draw this as a graph or as a chart um some I some J and some K such that um I is less than k um K and K is less than J so something like this boom problem cool uh so we're looking for this one three two pattern in our nums array and if we find one return true otherwise return false um so what's an example of these 132 patterns well one three two so um an array with values one three two would be valid an array of size of elements 1 4 3 would be valid all because they follow this pattern that I is the smallest element uh J is the largest element and K is somewhere in the middle okay cool uh I think I understand the question pretty well um let's look at a couple of examples uh so we're given nums one two three four um this is false I can't find anything um within there that follows that pattern let's look at three one four two um what about one four two one four and then two so this passes uh let's look at another one negative one three two negative one three and two somewhere in the middle so also passes okay this um yeah Yep this is definitely uh legitimate I think uh let's see what would one kind of um approach be well I wanna iterate through sorry the simplest approach would be to have three uh for Loops uh bounded by what I J and K could actually be uh so for example I is not going to be the whole range it's going to be from 0 to length minus two not inclusive um and then have those three nested Loops within that nested Loop we would have a um we would have like a condition that if basically num's I is smaller than nums K smaller than numbers J then return true however the chances of a array that is of size and let's see let's look at the size uh the size could be of five to two to the power of 5 to the 10 to the fifth so that's it's going to be o of n uh cubed which is there's no way that's going to be possible right um so we probably have to do it in one passing and in one passing the most uh like the idea that I get right away is well why not um as we're going through the array we find something like the bottom and the top for each element and what that would mean is um if we're finding bottom and top for each element then we are then we know at each second or at each new um element what are these values here the bottom and the top and then if the value that we encounter here is somewhere in between those two then we would be fine right we would be fine the problem there is that uh what if it is a situation like this one two and three we would still have the bottom we would still have the oops sorry we would still have the top and the bottom but they would be in like in not a correct order in an incorrect order right so we really need to know what the um what the order is there one three two um okay so this doesn't work let me actually just get rid of that so it's not confusing um okay so what's another approach well what if we're going through the array but from the back so I'm gonna draw this array as like a chart um boom if we're going through the array from the back we could keep track of the highest element high and previous High um and if we do that then and set the high and the previous High to some initial values then if we encounter an element somewhere down the line that is less than so that is less than the previous um previous High then we could essentially say that we found this element that um that is less than high and previous High and the reason why we know that this high would be further down the line from the right than the pref highs because Prep High is only set when high is when a new high is found right so um I think that's that should be the way that we go about it uh let's start implementing Let's uh let's have high is just equal to nums minus one Prep High is equal to some insanely large value um what was it nine I think was the top right of five this is also possible okay and now we say that for n in reverse foreign I want to say uh if n is less than prev high then return true uh and if we find a new high so if n is larger than High then I want to say prev hi is equal to n and high is equal to oh sorry hi is equal to n and that's it return uh fall false if we don't ever find this condition cool let's see if that works uh awesome oh no we have an error let's test use case um okay so what is happening here one three two four five six seven eight nine ten huh okay so actually what What's Happening Here is probably that there is a high and a prev high but if I draw out one let me actually just yeah let me remove all of this here and draw out what a one three two five six seven eight nine would look like would look something like one three two four five six seven eight nine ten Boom boom okay so we have high set at this element um oops uh prev hi is just in some insane number uh and so we're moving oops we're moving uh one by one and we still don't find anything and then at some point we encounter a situation where we do have this fluctuation right we do have this um we do have this essentially number being greater than the number here so you know what we could do we could memorize what the values of high are so that we could essentially set prev High to the value that we need which is actually this one in the case where there's a value that basically overrides one of these like previous highs because initially this is almost like none this is not set at all so okay the way that we could do that is have a stack um we could have a stack keeping track of all the elements from uh from low lowest to highest so in this case highest would be on the bottom second of the bottom third fourth fifth sixth seventh then eighth then we would have to pop this eighth element uh in order to remove it for the ninth but when we do that eighth would be going to previous High um and so actually let's just look at what the elements would be in the stack and how the stack would look like throughout this um throughout this journey so first it would just be 10 then it would be 9 10 8 9 10 7 8 9 10 6 7. 8 9 10 5. six seven eight nine ten four five six seven eight nine ten all of this time prep is still set to none then I have not three four but I have two uh two four five six seven eight nine ten and all of a sudden I encounter a new value three that basically beats this two right so initially this was two but I would replace two with a three four five six seven eight nine ten and only at this point prev I just realized you guys didn't see this only at this point um previous high would be now set to um to two and then when we encounter this last element we found the three uh the one three two pattern okay let's make that modification real quick uh so instead of high we have us Pi stack which is just equal to an array we still do this reverse we still do previous High uh let's say while high stack and high stack negative one is less than n we're simply going to say previous high is equal to high stack pop and yeah let's um append and so let's see if this test if this modification takes care of that test case it does we've done exactly that we've kept uh We've kept the stack consistently increasing and when we pop something is only then do we essentially say that we've populated this previous High and okay let's see if that works um should be should work awesome so this is an on solution uh let's see are there any other no this is identical actually so yeah there are no other solutions for this and yeah this is a very clean approach I understand that it's hard to see but maybe this iteration of thought uh helped you guys um okay well with that uh let's end it for today thanks for watching see you later bye
|
132 Pattern
|
132-pattern
|
Given an array of `n` integers `nums`, a **132 pattern** is a subsequence of three integers `nums[i]`, `nums[j]` and `nums[k]` such that `i < j < k` and `nums[i] < nums[k] < nums[j]`.
Return `true` _if there is a **132 pattern** in_ `nums`_, otherwise, return_ `false`_._
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** false
**Explanation:** There is no 132 pattern in the sequence.
**Example 2:**
**Input:** nums = \[3,1,4,2\]
**Output:** true
**Explanation:** There is a 132 pattern in the sequence: \[1, 4, 2\].
**Example 3:**
**Input:** nums = \[-1,3,2,0\]
**Output:** true
**Explanation:** There are three 132 patterns in the sequence: \[-1, 3, 2\], \[-1, 3, 0\] and \[-1, 2, 0\].
**Constraints:**
* `n == nums.length`
* `1 <= n <= 2 * 105`
* `-109 <= nums[i] <= 109`
| null |
Array,Binary Search,Stack,Monotonic Stack,Ordered Set
|
Medium
| null |
212 |
hi everyone I'm Dr Singh today we'll talk about the lead code problem word search second this is a good example to explain the use of try let us begin we are given a board consist cons in of an array of letters we are to search a given list of words in the board such that the letters in the word are adjacent that is horizontally or vertically neighboring cells we can move around the board and look for various words and check the presence of given words one way is to convert the list of given words into set in Python we know that the presence of a word in a set can be decided in a constant time but since we are using backtracking the effort will be reduced if we inspect just the prefix of the words using try if the prefix is not present there's no need to go further and we can skip the neighboring letters and backtrack right away try also helps in identifying words that share a prefix note set is useful if most of the words generated near ring backtracking are present in the given list of words while try is a better choice if the words generating during backtracking are rarely present in the list of given words consider this board which is an array of letters first we will build a try using the given words we Define dollar as the marker named word key and initialized try as a blank dictionary we process every word in words first word is dig starting node for every word is the root try first letter in dig is D key dig is not present in try so we create a default entry in it with current letter D as the key whose value is a blank dictionary which becomes the new node we show the node as a pair of braces in green color next letter is I within node we make an entry for I its value becomes new node third iteration gives another nested dictionary processing of current word is over in the present node we save word against word key dollar next we process oath that gives new entries in try has now two keys D and O next word is dog D is already present in try so we don't create it but retrieve the existing D and its value becomes node next letter is O for which we make another entry in node for letter O and its value that is empty dictionary becomes the new node similarly we create node for G in which we save dog against dollar for the last word dogs three nodes are already present for S we retrieve nodes D and then o and then finally G and make a default entry in it for s in which we save dogs against the word key we have built a tri TR using all the words number of rows and columns in the board are four each matched words is an empty list now we will develop the backtracking function to scan the board and turn by turn try every element on the board to be the starting word letter at z0 is H we call backtracking if this letter is present in try but D and O are the only nodes in try so we move to the next iteration even a is not in try that means no word starts with a so we move on o is present in TR therefore we will call the backtracking function in which TR becomes the parent node it is shown by magenta color presses letter becomes o and node is value of key o it is shown by braces in green color dollar is not one of the keys there so the pop function returns false this indicates that o alone is not a word and we skip the if statement we mark letter O on board as visited by replacing it with hash this saves us from duplic in searching words turn by turn we will process its four neighbors offset of first neighbor is min -1 0 for which new row column is min -1 0 for which new row column is min -1 0 for which new row column pair is out of bounds so we continue with next offset 01 gives position 03 where n is present but n is not present in node so we move to the next offset gives position one two which is within boundaries but the letter X is not in node last offset gives position 01 where a is present which is a key present in node therefore we call backtracking for 01 in which node becomes new value for parent letter becomes a and node becomes value of key A dollar is not a key in node so the pop statement returns false and we skip the if statement we Mark a as visited normal practice of saving visited cells in a set has lot of overheads so instead we modify the board now and will restore it at the end of the recursive call we now process the neighbors of position 0 one neighbor is out of bounds and another is already visited out of T and H T is the only key present in the node so we call backtrack for position one and node becomes new parent letter becomes T and value of T becomes node dollar is not present as a key in current node so word match becomes false and we skip the if statement we know Mark T as visited H at position 21 is the only neighbor of which is present in node so we call backtracking for position 21 and node becomes new parent letter becomes H and node becomes value of H this time dollar is a key present in current node so we pop it out and value of dollar that is oath is saved as word match the if statement is true this time and we append oath to matched words we replace H in board as visited no neighbors of 21 are present in node before closing the backtracking function we restore letter H at position 2 one as node is empty we delete Ed from the parent node and get this new try this technique is called pruning of dry only Leaf nodes can be pruned so we delete letters of oath from try as far as possible this call of backtracking is over so node and parent get their previous values restored from the call stack we restore T at position 1 one node is empty which means that there's no other word with prefix o and we delete not T from the parent node this call of backtracking is over now we restore a at position 01 once again node is empty and we remove a from parent node this call is over we restore o at position 02 once again node is empty and we remove key o from parent node this way we have removed word oath from try along with all its prefixes as they do not belong to any other word this optimization will save time in future processing remember duplicity is not allowed in the output list matched words all calls of backtracking are over and we go back to the main function Loop over row column will continue none of the letters n e t x are present in try till we reach D at position 13 where another recursion starts which goes to O and then to G at this position dollar key is found in the node which will be popped out and dog is saved in word match and then in match towards however this time node G is not a leaf node so it cannot be pruned we will continue to look for dogs as an extension of dog here before we conclude this call stack however dog present anywhere else on the board will not be saved because it has been pruned from triy luckily s is found as a neighbor of G dogs is popped out and appended to matched words now that node is empty which means it is a leaf node now so s is removed from parent and restored on board G was not earlier a leaf node but after pruning of s it has become a leaf node and we prune G and restore it on board and then o however no D is heared by dig and is not a leaf node and will not be removed we restore D without pruning program will continue further to look for dig till entire board is scanned next D is found at position 33 recursive call for D is shown here I is not a neighbor of D on board while we had pruned the O Branch of D in try earlier so this fruitless call of D ends quickly it is clear that this pruning algorithm increases efficiency when both the for Loops of main function are over it Returns the Matched words dig remains in trite to show that no match for it has been found there are M cells on board and L is the size of the largest word all the M letters on board are tried as starting letters for word searching for each one of them cell in the initial recursive call has four neighbors in each of the subsequent L minus one calls maximum three neighbors each are processed excluding the cell we came from so time complexity is as shown in the expression if total number of letters in all the words is n then there are n nodes in TR so the size of TR is of the order of n additionally there are word key nodes in try that store all the words Total Space used by these nodes is also of the order of n maximum call stack size L is negligible thank you for your time please stay tuned for more such interesting problems
|
Word Search II
|
word-search-ii
|
Given an `m x n` `board` of characters and a list of strings `words`, return _all words on the board_.
Each word must be constructed from letters of sequentially adjacent cells, where **adjacent cells** are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
**Example 1:**
**Input:** board = \[\[ "o ", "a ", "a ", "n "\],\[ "e ", "t ", "a ", "e "\],\[ "i ", "h ", "k ", "r "\],\[ "i ", "f ", "l ", "v "\]\], words = \[ "oath ", "pea ", "eat ", "rain "\]
**Output:** \[ "eat ", "oath "\]
**Example 2:**
**Input:** board = \[\[ "a ", "b "\],\[ "c ", "d "\]\], words = \[ "abcb "\]
**Output:** \[\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 12`
* `board[i][j]` is a lowercase English letter.
* `1 <= words.length <= 3 * 104`
* `1 <= words[i].length <= 10`
* `words[i]` consists of lowercase English letters.
* All the strings of `words` are unique.
|
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier? If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.
|
Array,String,Backtracking,Trie,Matrix
|
Hard
|
79,1022,1433
|
1,592 |
that's all we code 1592 rearrange the spaces between words so the question goes like this so you are given us string a text and with a lot of spaces and that spaces could be anywhere before the sentence after the sentence in between the words and there could be any number of spaces like there an l could have three spaces in between them is an a could have two spaces a and sentence could have one space or more there's no fixed number of spaces there could be any number of spaces minimum one and maximum could be any number of spaces but the length of the string will be not more than 100 uh characters so that limits the number of spaces to maximum having say 99 if I have just one letter word like an A and then 99 spaces that's the or 99 spaces and then there a that's the longest it can go number of spaces right so we need to take the string and convert it into uh a string with equal number of uh spaces between the words so if there are say 10 word the 10 spaces in the sentence then we need to distribute that 10 equally between all the SP all the words and in case there are still more left then we need to add it at the end right for example this one where they have got three year and then one year so that makes it seven spaces so they have added three year and one year at the end so how am I going to solve this it's very simple we need to do a little bit of calculations we're first going to go and split the entire string and store it in an array we call it words this split will remove all the spaces and uh get all the words of the sentence then I'm going to count the number of spaces that are there in this text that input text that we get right after this I'll put an edge case say my word count is just one right in that case whatever the spaces are before or after I'll just return the word as uh the word as it is and attach all the spaces at the end so that's what I'm going to do I'm going to return words at zero index which is the only word that is going to be there since the length is one and then uh since I've taken the number of spaces that are there in the string I'll multiply that uh space with that many spaces and attach it at the end and return right after this I'll calculate uh since this Edge case is over after the I'll calculate the number of gaps they I need to fill right so that many uh I'll split the spaces in that many different smaller strings so I'll calculate this gaps as length of words minus one so that will give me the number of gaps for example here this is a sentence this is four words right length of words is four and the gaps is three in between them that is words minus one right so if my length of words is say one in that case it will turn out to be zero so I'm doing an R1 right although that will be handled here so I need not worry about this so after this I need to calculate the space length or basically create a string of spaces so I'll do what I'll do is spaces will give me the number of spaces that are there divided by the gaps which is say three in this example so that gives me number of spaces I need to add in middle of the words right after this I'll calculate how much how many should I put at the end which is the remaining spaces so I'll calculate spaces percent gaps so this will give me the remainder gaps remainder amount of spaces after the rest has been used in the middle and then I'll multiply that with the space this will give me a string that I need to attach at the end finally I'll just join them all so middle do join words so middle is the spaces right since I'm calling middle do join it is going to add this middle spaces between all the words and create a string out of it and then at the end I'm doing a plus ending which is again attaching the ending string to the string and returning right let's run and see it works let's submit and that worked 12 milliseconds I could reduce this code by removing this of course because when length is one that is already been handed L but what about when length is zero will that be handled or should we handle that also let's look at the edge case there so 8 milliseconds better than 92% of milliseconds better than 92% of milliseconds better than 92% of solutions let's look at the best one they're doing in a similar fashion as we are doing dividing and finding the spaces taking a remainder using um percent dat sign and then joining both the remainder and the spaces with the words so that's exactly how we are doing so that's how we solve the problem 1592 rearrange spaces between words see you in the next video
|
Rearrange Spaces Between Words
|
rearrange-spaces-between-words
|
You are given a string `text` of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that `text` **contains at least one word**.
Rearrange the spaces so that there is an **equal** number of spaces between every pair of adjacent words and that number is **maximized**. If you cannot redistribute all the spaces equally, place the **extra spaces at the end**, meaning the returned string should be the same length as `text`.
Return _the string after rearranging the spaces_.
**Example 1:**
**Input:** text = " this is a sentence "
**Output:** "this is a sentence "
**Explanation:** There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces.
**Example 2:**
**Input:** text = " practice makes perfect "
**Output:** "practice makes perfect "
**Explanation:** There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string.
**Constraints:**
* `1 <= text.length <= 100`
* `text` consists of lowercase English letters and `' '`.
* `text` contains at least one word.
| null | null |
Easy
| null |
226 |
okay guys thank you for joining um today i want to solve with you lead code 226 which is inverting a binary tree if you're like me and you've never encountered binary trees before don't worry they seem scary but they're not that scary actually you just have to realize that they are data structures that you can manipulate so let's read the exercise given the root of a binary tree invert the tree and return the root so even if you don't know anything about binary trees looking at the difference between the input and the outputs you can clearly see what they mean with inverting a binary tree so if we look at the root node or at the root we see 4 here so the root node stays the same now if you look at the children at the left and the right children of the root node we see that they're swapped so the 2 is now here the 7 is now here similarly if we look at only the left tree we see that the left node and the right node of the two are also swapped so this is exactly what is meant with inverting the tree it's basically visiting every node and then swapping its children so that's also gonna be the algorithm we're gonna just visit every node and then swap the left and the right algorithm the left and the right node now so we do that here and then we get to this node and we also do it we do it here and then we end up at this node but this node doesn't have any left and right children so then we go back up the tree as you can see this is a perfect way or perfect time to use our depth first search and recursion technique to solve this problem so let's start with the base case and if you now the base case is basically this where we have no uh left or right anymore so then what we're going to do is we're going to say okay we're gonna stop and we're gonna go back up the tree so let's go here so we say okay if root is none or if not root return we don't need to return anything and then if we are not in a base case so if we are in for example this one if we are at the root node then what we need to do we are in this node then we just need to swap the left and the right one so you just swap the left and the right one so if we are in a root node we swap left and the right so we say swap left and right root right is root left root right is root right root left and then if we do that if we swap them then we also need to recursively call the algorithm but then on this sub problem right and then we need to call it recursively on this sub problem until we end up in the base case which is covered by exactly the last leaf node so all that we so we went to a node we swapped the left and the right and now all we have to do is call it recursively on the left and the right node so call on left and right node until exhausted so now we say um self dot invert three root left self invert three root right and then if we are done we need to return the root so let's see if this works and this works um cool so how do we now remember this we remember this by making flashcards so let's add a flashcard and let's copy the description so how do we invert a binary so once you have this flashcard you will never ever forget it solution so how do we invert a binary tree so first we work from the base case and then we swap left and right children and then we call and then we do recursion so actually it's like just recursion and swap left and right now of course because we use flashcards we also need to uh review our old ones so uh what's the brute force solution for containing a duplicate uh if it has at least twice you just go over every array or you build up a hashmap it's kind of the same how do you invert a binary tree this is the card i already added accidentally um in a previous uh take of this video so we take the base case then we swap the children and then we call it reverse similarly what's the solution to twosome okay here we build up a we tried to build up a hashmap of the values with the indices and then we look for whether the complement can be found in the hashmap but not with the same index as the one you're comparing it to and with binary tree we had this already so we base case swap to children and then we call it recursively similarly the space repetition uh forces you to do it sometimes multiple times so here we for the two sum what we do is we make a hash map of the values as the keys and the indie sets as the values and then we go over each element and for the complement we want to look whether the complement is actually in there oh that's the brute force solution i messed it up but that's okay invert binary tree base case solve the children call recursively same base case swap children co-workers co-workers co-workers and that's it that's how you remember them i hope you found it useful for me it was also my first time inverting a binary tree as you can see it's not very difficult you just have to you know do it get used to it a bit and it always helps to try and reduce it to like a base case and then to see how you can build it up from there so thank you thanks for watching i hope you enjoyed it and see you next time
|
Invert Binary Tree
|
invert-binary-tree
|
Given the `root` of a binary tree, invert the tree, and return _its root_.
**Example 1:**
**Input:** root = \[4,2,7,1,3,6,9\]
**Output:** \[4,7,2,9,6,3,1\]
**Example 2:**
**Input:** root = \[2,1,3\]
**Output:** \[2,3,1\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
345 |
guys uh today we're looking at uh the lead code 345 reverse spouse of a string write a function that takes the string as input and reverse only in the vowels of a string um input hello uh so vowels or aeiou um so e and o gets reversed and lead code uh we reverse the e right here and then we will reverse the e and o so the output should be here um the vowels does not include the letter y uh yes the vowels are only a i o u um so basically the idea is that you're going uh from left you're yeah you're basically just kind of reverse the vowels so if a alphabet is a known vowel you just skip it and go to the next one uh yeah so the technique we are going to use i think it's called two pointers so basically the idea is to scan from um have two pointers one at the index position zero one at the last index position and kind of like going back uh going from outer to the inside and uh if um the index is a non-vowel number we um the index is a non-vowel number we um the index is a non-vowel number we just skip it um if it's a until we get both the index or add a vowel number and we basically just switch it and uh go to the next one so yeah basically two pointers nonviolent number skip it until both pointers are pointing at round numbers and we um swap it okay uh yeah that's the basic um idea of the solution let's code it up okay um so in order to like switch or swap the alphabets we just convert the string into a list so we can implement that operation okay list s and uh let's see yeah oh let's call it just call it list okay and we have two pointers i and j and uh it's starting at zero and uh length of s minus one yeah starting from here and the last element and so while i is less than j um we check so if um if a list at index position is not in uh and uh okay a e i o u or a e i o u then we just skip it basically i plus one um
|
Reverse Vowels of a String
|
reverse-vowels-of-a-string
|
Given a string `s`, reverse only all the vowels in the string and return it.
The vowels are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`, and they can appear in both lower and upper cases, more than once.
**Example 1:**
**Input:** s = "hello"
**Output:** "holle"
**Example 2:**
**Input:** s = "leetcode"
**Output:** "leotcede"
**Constraints:**
* `1 <= s.length <= 3 * 105`
* `s` consist of **printable ASCII** characters.
| null |
Two Pointers,String
|
Easy
|
344,1089
|
759 |
cool so we are given a list schedule of employees okay which represents the working time for each get each employee okay so it's like a schedule zero element will kind of contain the working time of zeroth employee each employee has a list of non-overlapping intervals has a list of non-overlapping intervals has a list of non-overlapping intervals each employee has a list of non-overlapping intervals fair non-overlapping intervals fair non-overlapping intervals fair and these intervals are in sorted order okay return the list of finite intervals representing common positive length free time for all employees so let's first understand our output here because when these questions get too real uh it kind of becomes slightly difficult to understand them so what you have to return is a list of positive length free time for all employees so it's like i1 or say or i1 e1 or say s1e1 right this is start and end and say s2 e2 and say uh s n e n this is what they want as return where now s one and e one should or s i and e i should not essentially should not exist or yeah should not be overlapping with any working time of any employee right okay so one thing that i can think of is as we go through employees one by one uh given the uh the their times are sorted we can generate candidates from first employee itself and then we can keep shortening the intervals of candidates or add new candidates by the time we have processed all we'll have a list of candidate intervals that don't lie in any of the employees work schedule even though we are representing intervals in the form of x y the objects inside are intervals not lists or arrays for example schedule 0 means zeroth employees zero uh dot start is equal to one zero n equals to two oh yeah schedule of zeroth employees uh his zeroth interval of working start is one and end is two um object inside are intervals oh okay they are these classes basically they are not like that's what they meant okay it's not a list also we wouldn't include intervals like five in our answer because they have zero length okay that makes sense so remove any candidates having zero length so now if this is given to us schedule and say first employee and let's just keep like this so first employees work timings are one two and five six and the second employees were coming there one three and four ten right so what i was proposing here was that uh we can go through this list right and given that our so are starting for any schedules starts with zero it can be zero and ending can be tens for it oh wait 410 that's how it is yeah uh the total of three employees and all common free time intervals would be minus infinity to one three to four and ten to infinity we discard an individual that contains infinity as there are they aren't finite okay so actually when once we come here right uh come and realize the first thing here then we can make an interval there which is minus infinity to zero right one at one they start working so we one can't be a interval uh but here 3 to 4 is considered interval so i think when 3 to 4 we are considering it's not existing here but 4 exists here so they can be starting points so infinity to 1 is one then when we proceed to the next interval we check the uh starting time of this minus ending time of previous so that gives us the thing so like starting would obviously be after this which is 3 and ending would be after ending would be before this or add that actually say 2 to 5 that's his break times now the next thing we'll have is we'll go to the next employee which will give us minus infinity to one so this becomes common and then he'll give 3 to infinity and this guy will give minus infinity to 4. and 10 to infinity now how do we come up with three to four hmm this is a good question essentially if you are seeing this on number line then say this was like 1 2 3 4 5 10. say 10 is here then we have one three which goes like this another one which goes till two to five another one which goes to 3 to infinity and the one which goes from minus infinity to 4 and 10 to infinity now we can clearly see that 3 to 4 is like one period so this was by first guy this was also my first guy this was by second guy oh this is also my second guy actually first and second okay this is my third if you see the only place where first second or third all three are intersecting as this three to four period now it's easy to visualize this but how do we solve this uh so given i have kind of gone through first and made these candidates i need to only add those candidates which intersect with these because otherwise anyway first one intersect like you say something like this comes up first is not going to intersect with it makes no sense for every new interval and every new candidate interval that we get so from second if we get minus infinity to 1 that is an intersecting interval so we'll keep that uh but from second when we get this like three to infinity we're gonna check whether three to infinity has an intersection with any of the intervals previously which now it will it has to change two to five toward somehow it has to change two to five to a three to five how will we do this and these intervals can be very long like they can go till 10 is for it i'm feeling we need to do something off like hmm before every candidate interval we have to go through every previous interval to see if there's some intersection that will make it n square uh not really n square in a way because for every interval you'll just be checking the candidates and what if candidates are like n like all of them have the same free slot then you are checking n time like then it's getting n square yeah so in the worst case in that case we'll have n square which does not seem like a very good idea it'll mostly go time limit exceeded because if this is going to tennis bar eight there's a good chance it won't accept it so what are we uh what are we doing there which is a like duplication of efforts let's just try to think from that aspect um as because we have to get this down to o of n or max to max of n log n in some sense so when a new interval comes up right you need to make sure you need to just check directly if that exists first of all otherwise you need to kind of see where that will lie now once you have a starting and the ending point like if i have a three right i know that i in the previous candidate slot as long as candidates are sorted i can find a three or if i can't find a three i can find a uh maybe i can find closer to three i can do a binary search there and find something that starts around at 3 in log in time right once i find that i can check when it ends so instead of doing n i'm doing n log n now right so n log n might suffice once i do a log n i find the interval i can check like say initially i'll have this as my candidate so let's say candidates will be something like this and now a new interval will come up as we'll be processing the second guy which is one three we'll get the first interval which is minus infinity to one since it has infinity we are gonna yeah so since we have here in what's happening let's get back to this yeah now so what minus infinity to 1 and 2 is 5 actually uh what is somebody else comes up with the 0 to 1 that intersects so we need to keep this we will disregard all the infinity ones later on so now when a new thing comes up and we get a minus infinity to one say we are able to form that right based on this guy uh then essentially we need to do a binary search for minus infinity or we need to do binary search for the end point that's what i'm thinking about will we do a binary search for the starting point or in the end point we can do for either let's just do a starting point for example if we do and it's gonna find this guy when that finds this guy we're gonna see what's the intersection between these and these so binary search login then it tries to find intersection uh which is going to be like for intervals s1 e1 and s2e2 uh this is going to be max of s1 s2 and min of e1 e2 right correct so max of s1 is 2 will be minus infinity here min of even e2 will also give us 1 only we will get that correctly now the next one comes up which comes up as 3 to infinity so when 3 to infinity comes up we'll again check on the starting point we'll try to search for three we won't find three but uh then we'll be able to find either uh like we'll find this index probably as the next best thing so once you find this thing uh what we're gonna do is uh we're gonna do a intersection here so 2 to 5 and 3 to infinity so that will give us a max of s1 and s2 which is 3 and min of infinity and 5 which is 5 so that way we'll have this intersection and that becomes a new interval right and so that's how we are actually changing the candidates interval that we find using binary search so find intersection and change this index found by binary search and finally when we are done processing all employees we can pass through the candidates and um create a new list ignoring the single length ignoring ones having zero length or uh infinities or minus infinity okay time to probably code this uh why does it another oh it's a list of indoor okay so candidates for employee skid in schedule this is essentially yeah the first guy right uh what we're gonna do is for work interval in employee schedule what we can do in this case is like the first one is coming up we need to just uh get start end of work interval so here we can probably use an i because the first one will have infinity and the other one won't so if i is equal to 0 we'll have a special case if i lf length of m plus squared minus 1 we'll have us special case here else we're gonna base it on previous guys so when we are processing five or six uh what we have to do is the free time will become free time candidate is basically uh like employee skilled i minus one will itself be an interval now this interval dot in comma uh current one so work interval dot start this becomes our three time candidate if it's the last thing then pre-time if it's the last thing then pre-time if it's the last thing then pre-time candidate is work interval dot n comma float of infinity and if it's the starting case then free time interval is a float of minus infinity and the work interval dot start right so once we have a candidate for a given uh once we have one candidate what we can do is we can try to we have to try to search it right so if not candidates if there's nothing in candidates right now we're gonna just add it so candidates dot or in this case also like as long as we are just processing the first guy we have to just add the candidates second guy onwards things change so for index enumerate it x is equal to 0 basically the first employee then we just add it right else binary search logic which will just finish right now so say we are able to binary search and change the intervals then this is and this is all we are doing right after this we have to pass through the candidates for our interval and they want us to give an interval only so let's create an interval here or we can do that later so for interval and candidates output list if interval zero is load of minus infinity our interval one is load of infinity or interval 1 minus interval 0. is equal to 0 then you have to just continue else what we are going to do is we have to convert this into an interval proper interval and append it so output list dot append interval which is going to have a interval 0 as the starting and interval one is the ending and we can return this output list now the thing that spending is binary search logic so we should probably use bisect here because otherwise it's too much import bisect uh so by six let's say let us do binary search uh now what we want to do here is once we find our free time candidate right and this is not index is not zero so what we are going to do here is try to find it its starting point so bisect dot bisect left and this is where i have gotten stuck because i don't remember the definition of bisex so maybe right now we're just practicing so it's okay we can just check through this and learn what happens uh okay then so for bisect lift it's like look at the insertion point for x in a to maintain sorted order we're going to blow an i specify a subset of the list which should be considered by default entire list is used okay bisect right is similar or similar to bicycle bicep is equal to bicep left but returns an insertion one which comes after to the actual bisector and bicep biceps right and bisect are the same so these two are the same and they first take so x is the key you want to find and a is the thing is your array and this return in session one which comes to the right of any existing entries of x do you want to do afterwards what do you want to do before and this will do to maintain sorted order so if you use bisect uh the thing is it can give us something like the bigger problem i have here is what if you want to have bisect but it's not a simple array here how do we do that uh okay sadly bicep will only work with so okay now candidates have yeah actually we have fine candidates in our case will only have list of regular intervals it's not like these intervals uh these kind of interval classes so then we can kind of work with it uh it would have been good actually if we would have used tuples here because no oh yes come on i'm not sure if we can use bisect and doubles uh it sucks if we have to write the binary such as it sucks what if when i maintain candidates i also maintain candidates starts right so whatever candidates is getting appended i'm gonna open free time dwell so now i can do so this is like of an extra space but it's fine we are anyway using this so a and rx is going to be a free time candidate right this is going to give us a value after which we have to check now this give us index some index right and uh if we inserted that index everything after that will anyway shift so we have to kind of check with the same index so we want to check for the same index so in that case maybe we just add some print debugging yeah right so once you find the index right so index what do we do with the index once we find a free time candidate uh come on what do we do with this i'm gonna let's just look at my notes so when we search find intersection yeah you have to store that in this section so we're going to change candidates index to max of whatever existed zero and the current interval so free time candidate zero and min of one and free time candidate one and now that we have changed this we need to change candidate stats index also zero right so this will change all the indexes uh we should probably debug these so we let's add candidate starts looks like this value finding is this index returned is this so we'll know if we have to do it for index or index plus one that is the only worry i have uh and let's just try to run this and see what we have what we get fine and that's not a problem if you're getting we will fix things so one two uh can actually let's just print maybe uh for print candidates so initially there's no candidate then after one we have a minus infinity to one and six to infinity uh then for the second guy it comes up here uh now candidate uh what's happening here let's do this after this guy and minus why didn't give 2 to 5 what the hell so if i is equal to zero when is i when i is equal to 0 it's going to be 1 to 2 oh okay understood so these are some extra conditions but we always have to this is like an extra thing if it's not zero what if it's anything other than zero we will have a previous employee so something some issue happened so minus indian6 still not happening oh we are replacing this that's the problem uh okay we always have an extra pre-time we always have an extra pre-time we always have an extra pre-time candidate in case of i equals two i equals to zero this is a nice problem so it's not always going to be free candidates but it's gonna be free candidate list sadly as much as i would have liked it to be one so what i've done is we'll try to process both so sometimes this extra one can come up in the end and so i've kept it as free candidate now instead of free time candidate and let's just see what happens now right where is this happening 931 here so if this isn't oh this we can push here right minus one minus into one two to five six to infinity can it starts minus integrated two uh okay minus infinity to one six fair value finding minus infinity index returned at zero so it will try to change that uh value finding is three index return this two oh okay so here's a problem now right so in this case index is two we it'll try to change this value which will not work what if we use regular bisect next return is one in this case next return let's do still ah this sucks oh no if we use bisect and we always use index minus one it will work right so in this case index return one minus one zero is the one we choose here index redundancy index and return is two so we can always work with one so we're gonna now just do a simple a nex minus equals to one now things should seem fine in every case output is three five okay why is it three five because now can after candidate one is process this is three five now third employee is four to ten so minus infinity to four ah damn our logic is incorrect because then minus into 4 comes up then it belongs into multiple different so it needs to be in it needs to be uh there can't be binary search here then it needs to just check for all different ones so like for every free candidate it will go through all the candidates and just see if there's some intersection so let's try to do this so this entire index drama won't work uh what we need to do is we have a free candidate i will go through 4k in range candidates we don't even require this candidate start anymore so we can get rid of that although i have a feeling that as soon as we get rid of this our solution kind of turns into n square problem anyway let's try this and let's at least submit something even if it's time limit exceeded so for k in range candidates right we pick up intersection so intersection would be max of x some k our count is candidates okay so we're gonna do curcan zero and pre-candidate zero pre-candidate zero pre-candidate zero common of curcan one and three candidate one now once we have something like this interaction is possible right we need to just check that if intersection zero less than intersection 1 that is if only criteria is it like that intersection 0 can't be greater than or equal right that is the only thing then you can kind of change kanji k to intersection range of then of candidates raw so minus infinity to 1 2 5 6 to infinity minus infinity to one three to five six to infinity minus infinity to one three to four ten to infinity and now when it goes through this infinity ones get discarded and three two four is the only thing left uh i am like almost hundred percent sure this is gonna give us a time number exceeded um if it doesn't that'll be like surprise because of the length of the inputs that they have uh spoken up uh let's just still do a complexity here so we are given that schedule length for any one total there are about 50 employees and total work times also would be 50 but starting and ending can't be anything so now what we are doing here is we are going through this is though which can run so that let's just say this is n right so this is gonna be n and into this is n square this itself isn't square but inside what we are doing is of one or font oh fun this is okay two only sub two doesn't count uh length of candidates so whatever candidates will have so this candidates could itself be in right so 50 are there maximum 49 could come up yeah max to max 49 uh or it will be lesser than 49 so here again we are doing 15 to 50 that's like 1000 only it actually might get submitted i'm not sure now uh a feeling it might get submitted because we are only dealing with starting and ending points let's try this i have not considered oh 45 56 89 86 5 21 57 output was supposed to be 56 57 but we've gotten okay so the problem here is that when we find an intersection is it always good to change the previous sky or is it better to append the center section so in this case what would have happened is 45 to 56 so 56 to 89 would have been one right and here we have 20 21 to 56 21 50 57 houses 21 to 45 coming up it's coming up because there's a minus infinity to 45 and when you couple that with 21 to 56 we will get a 21 to 45 yeah we will get at 21 to 45. and now only if that 21 to 45 has you know like we should change it should have changed minus infinity right so let's try this test case actually for minus infinity to five which would have come up here it would have checked i converted that this then what's happening is here to 57 and it would have checked and it's checking all these candidates and generator 5 what is x 289 hmm so the problem is that we need to not change the existing candidates for every after every new employee there will be a new set of candidates essentially so we will have this whole thing new candidates and whenever we find an intersection we're gonna append that new candidate dot open intersection and every time at the end of this thing you can dance oh brilliant so it wants some for some very simple case of empty schedule or something i'm sure we'll give some wrong answer for that uh output limit exceeded oh wait um we'll just remove this print and see if it gets submitted it can go time limited series that's fine with us yes we solved a hard problem yay it's not at all fast memory usage is less compared to others so it's fine but good to have solved a heart problem
|
Employee Free Time
|
set-intersection-size-at-least-two
|
We are given a list `schedule` of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping `Intervals`, and these intervals are in sorted order.
Return the list of finite intervals representing **common, positive-length free time** for _all_ employees, also in sorted order.
(Even though we are representing `Intervals` in the form `[x, y]`, the objects inside are `Intervals`, not lists or arrays. For example, `schedule[0][0].start = 1`, `schedule[0][0].end = 2`, and `schedule[0][0][0]` is not defined). Also, we wouldn't include intervals like \[5, 5\] in our answer, as they have zero length.
**Example 1:**
**Input:** schedule = \[\[\[1,2\],\[5,6\]\],\[\[1,3\]\],\[\[4,10\]\]\]
**Output:** \[\[3,4\]\]
**Explanation:** There are a total of three employees, and all common
free time intervals would be \[-inf, 1\], \[3, 4\], \[10, inf\].
We discard any intervals that contain inf as they aren't finite.
**Example 2:**
**Input:** schedule = \[\[\[1,3\],\[6,7\]\],\[\[2,4\]\],\[\[2,5\],\[9,12\]\]\]
**Output:** \[\[5,6\],\[7,9\]\]
**Constraints:**
* `1 <= schedule.length , schedule[i].length <= 50`
* `0 <= schedule[i].start < schedule[i].end <= 10^8`
| null |
Array,Greedy,Sorting
|
Hard
| null |
332 |
oh hey everybody this is Larry this is day 14th of July challenge do we have a new weekly problem now that's tomorrow okay hit the like button hit the Subscribe button join me on Discord let me know what you think about today's Forum uh I today I play pickle pickleball is it for the first time and I hurt myself uh this is what happens when you're playing when you're old and you play an old person's foot and you still hurt yourself but I mean I've had a bad hamstring for a little bit so uh so I'm gonna try to see how much I can do with this one and then going to uh ice it a lot and quite an early night all right today's problem is 332 we construct itinerary all right so your thumb and two all the tickets below depart from JFK yeah that's me maybe it must have stopped JFK and the smallest likes a graphical order when we turn as a single string uh okay fine what am I doing oh so every ticket has to be used is that it uh can you always have an answer uh okay so then in this case it's a very um it's a directed graph and it is uh what you may call it or Lillian uh path right yeah it's not a cycle because we don't always stop JFK so yeah so there's an audience path you have to kind of look at dth once and um and in this case uh just to be quit actually I don't know if that's true let me double check I mean I think it is unless I'm misreading it you can go between two cities multiple times so uh yeah and so then now and yeah and so then now uh I do wonder if there's a uh straight for let me type that up real quick so directed or Lillian path is kind of what we want right we want to look at each Edge once and the way to kind of think about it is there's um yeah I mean I there was an algorithm I forget the name of my head I think it's like it's named after some dude but basically the idea is to kind of use depth for search um I think it's called like the hose something that one the hosing your whole singer uh horror singer okay fine uh so yeah you have this algorithm um but at the end of the day it is going to be um yeah the idea is kind of using that first search by using stacks and basically you wanna this is a kind of advanced thing I don't let me finish explaining and then let me take a look again to see if there's any like more easier way to do it um it is going to be linear but maybe we don't need linear but ID behind in this algorithm is just that um when you kind of see a cycle then now you can kind of take out that cycle and then kind of combine all these Cycles in a way so that um when you combine these Cycles in a way then you get one path right because when you kind of visualize the Cycles you can um and I don't know if I should join but you can kind of visualize that psychos and they kind of connect in some way you can kind of think about the um maybe another way to think about it is that when uh when you have these notes you can kind of collapse these paths and of course once you collapse them then now yeah you have a you know you have these cycles and then you can kind of just it doesn't matter where you go because you can always go back which is the def you know the thing about a psycho right um and because of that if you didn't take the same way in let's take the same way out you have you know another way in uh you have uh given a psycho given a note on a psycho data you know if you have multiple psychos the number of outpath is always going to be the number of empaths right so I mean that's kind of you know like if you're in two cycos then you have two paths going out and you have two paths going in that's um at the very least uh because that's you know that's how psychos work um that's kind of the general idea um that's gonna be read plus e and um yeah I mean it's fine of course I mean of course it's gonna be fast enough but it's maybe too fast uh yeah uh just because you know with n is equal to 300 or this is Yi actually and it's maybe less than 300 bit of property is testing well I guess it could be more than 300 it could be like 200 times two or something like this though it won't be connected so maybe that's a little bit odd maybe like about 300 say um that's the max anyway so then we probably could do some end Square stuff uh I actually don't remember let me see if I could prove photo of my head but I think the idea is that you kind of take one take the path um and I think the The Lazy way to do it or like the way that I think could be done is just you know uh take a note right uh so we started to start at JFK right and then now um we take the smallest and by smallest I mean the lexicographically smallest because that's one the constraints right take the smallest node that still leaves us a way to um to kind of to uh for an Orlean uh or Lillian path to exist so that's basically the idea and if you are and if you do it this way or it's going to be N squared but and you know n is 300 so it's going to be good enough uh and in this case n maybe B plus e and also 300 is going to be good enough Square um because you could check this in um pretty straightforward uh do I can you well I mean I'm pretty sure you can I have to think about a little bit because I usually do this with or this comes up for undirected graphs but I have to think about how to kind of check this for directive graphs what does it mean to have a path right it means that every so it has to be connected the entire uh your you have to be able to reach every node um so what makes so I'm just to be clear like I'm not reading off anything I'm just trying to think about it from a first principle thing right uh and of course I don't know I've read this debate recently with on Discord people talk about memorization and stuff like this and you have memory stations would make it easier but the thing is or you know faster anyway but you know you don't need it right like when you learn you can figure out these things just by you know some observations right um and in this case yeah I mean obviously has to be connected if it's not connected there's no auditing in path Lobby's reason and then every node other than one node has to have um the same in degree as you would out degree right except for two I suppose and two being like one note in the big uh actually the it has to be the node that we're starting from which is which would have to be the smallest node and then one so yeah in degree you go to our degree so what uh minus one yeah uh wait so for the current note you want to have a degree Plus one all right well maybe I said it wrong um so you're going to have one more out degree than in degree because this is the one that's going out right so then you come in so yeah uh this is for starting node or current node maybe and then in degree of degree plus one is some random last node I think these are good enough uh definitely that's good enough for undirected but to be honest I'm not I think that's still true for directed um and one directed the definition of in degree and our degree is a little bit trickier right um because then in that case it's not even just in degree and I'll decrease it is just the number of degrees right and then in that case that's right a number of degrees have to be given except for two of them the beginning and the end uh which they have to be odd okay so I think now we uh I mean definitely if you're interested in this algorithm and I think it's still based off the same idea of just like connecting psychos and circles and so forth um and you could kind of do a kind of a depth first virtual stack or something like this uh and this is going to be linear time but I think we kind of came up with an n-square thing which for this up with an n-square thing which for this up with an n-square thing which for this particular problem is good enough and probably what they're asking for anyway uh so I mean I think for an interview the end square is probably good enough uh in the sense that it actually requires some kind of thinking uh I mean you know I mean I hesitate to you know generalize because who knows these days right uh I think I talk about this sometimes with respect to like to be frank a lot of interviewers are not good either with what they're looking for and if they just kind of copy this problem of like a problem bank or something like this and like oh yeah the optimal is obviously linear but without really giving a thought about it then you know um they'll be like oh yeah then they'll judge people whether they know this random algorithm and to be honest like I said I don't know I mean I could probably come up with it and put I know the ideas because it's been a but I you know like I it would take me forever to kind of actually do it even on an interview right um like I mean even for me on explaining it's kind of a little bit hand wavy and I understand that because you know uh but you know uh if you don't get a crappy interviewer who don't know what they're doing uh or you know maybe they know what they're doing and they're infecting pain then you know maybe you need linear time but I think like the non-linear one but I think like the non-linear one but I think like the non-linear one the quadratic one is a little bit more interesting for me and I'm so I'm gonna just type it that way I mean otherwise it's just you plug in Play-Doh otherwise it's just you plug in Play-Doh otherwise it's just you plug in Play-Doh women's Library I don't know like what do you actually learn I mean and then there's the other thing where as an interviewer to think that I look for is just you know Prime solving skill right that's why you know that's the main idea here uh and not someone's memorization skill uh or at least not during that component right there are other like if for whatever reason if you're in a job that needs this to know this particular algorithm then fine but do it during like a trivia problem a trivia portion of the interview and not the problem solving point of interview which is what I'm more interested in kind of communicating um I think that's all I have for the chat so let's kind of get started right so uh so first of all let's just do out degree let's have a uh yeah collections.counter uh yeah collections.counter uh yeah collections.counter in degrees also collections.counter in degrees also collections.counter in degrees also collections.counter right and then now we have for um was it source and sync oh just UV let me just use more standard graph terms uh so our degrees of you in degrees and then now we have answers you go to JFK just because that is the hard-coded JFK just because that is the hard-coded JFK just because that is the hard-coded thing right um and I know what uh yeah um what I want to do um let's think about what's the best way to represent this I mean I think it's fine I'm just gonna be a little bit lazy uh I think I need to construct a naturalist I think that's what I need to do actually um yeah uh and here keeping in mind the reason some of the reasons why I do it this way instead of the uh here how is the algorithm I'm pricing that one uh is there that there is an additional constraint of uh the smell smaller lexicographical order which to be honest uh I kind of get the idea about this but it would take like I don't know that uh it would be easy to kind of do the lexicographical order where here um the way that we do it is just that we choose to concode the smallest node so we know that's going to be the best lexicographical order as long as we have a routed solution because it only matters you know it's like the most significant bit thing right like only your most significant bit matters um you know at least your least significant bit matter as a type breaker so if you greedy every step of the way assuming that you're still able to get an early linear path then you should be good of course and here we that is part of the constraints which is why you know we are a good um oh yeah right all right so then now uh let's just say m for edges is equal to length of tickets foreign yeah I mean I think there are a couple of ways you could do it but I'm just going to do a very standard used frame um I mean there's only 300 tickets so not gonna worry about it and we iterate 300 times for whatever so um yeah you're gonna end the last City and then now what do we want to do right uh actually yeah actually what I want is actually just sort this anyway so that selects a graphically so then we don't have to do a loop I mean we still will have to do a loop so I think in the worst case it doesn't change anything but I think it allow us to do like some early termination thing that makes it slightly easier to read maybe I don't know if that's true so yeah so for key in either keys that saw it okay and then now we start at the current and then we just you know for next in g dot current and then now if good of from current to next then into that append next and then we break out this Loop right otherwise um this should never happen but I don't know maybe there is some bad coding so that I want to put an instruction there and then at the end we just return answer I think that should be good of course you have to write this good function which is easier said than done but you know uh maybe just previous current right or candidate Maybe we just have to implement this thing right so um let me think about this for a second I mean the other stuff is easy to do uh the connected part uh we want to do a definite search but we also want to disconnect the stuff that we've already done right so I think about to be a little bit careful about it foreign oh I guess that's what they use this for um but I don't tie this to anything so it's a little bit awkward um I mean there are two ways to do it maybe it's there's one way but you're just this and then the other way which is um which is just removing this which uh which means that we want to be moving better than all of n times though I guess so event times when that matter was only removed once but yeah that's just we'll probably have to uh there's this we probably have to think about just a little bit if we want to optimize but I think something like this is probably okay um let me just return true real quick uh I don't know if this once into like the uh iteration cocurrency or whatever ever okay it doesn't seem like it I mean I think it might be if we didn't have to break because I think we modified uh okay well that maybe that's a thing because removing things in the middle of an innovation is a little bit sketch I'll keep it here for now but hopefully the idea makes sense in any case um yeah and it actually returns some stuff though actually it's what the it's just very lucky that this happens to be maybe there's only like one way of doing it that's why but it gets a little bit more complicated or at the way at least you have to deal with tie breaking when there are more than one ways of tying things together uh and this one there's no yeah that's just so lucky it feels a little bit silly but uh okay so then now we want to calculate if we are at candidate can we is the graph still connected right so yeah um the remaining graph is still connected uh man this is a I mean the way I'm writing is kind of yucky but I guess it's just oh and here I think I have to write something like in degrees of next we recommend from one out degrees of current we also subtract one yeah because we removed the edge right Wonder real quick okay so then now I guess it's just for keys in for key and degree uh in degrees of keys uh just like things that we have to consider right um so notes as you go to I guess a set right so that no start at I guess this is just actually this plus out degrees of keys oh no uh reason why I can't do it and that's why Voda is that I have to make sure that um this is greater than zero yeah I guess you could kind of bite it you could still bite in one loop I suppose one statement but I'll just write it out since I don't know I'm gonna make a lot of silly mistakes lately so let's I don't know just kind of do the not trying to be too clever over here uh okay right so then now these are the notes that we care about um I think it's a little bit tricky because now we have to write something like uh oh degrees of current in degrees of candidate um almost like a you know like um like a default search State thing right because we want to make sure that um like we're treating it as if Now we move we use this node from current to candidate or this ticket from Crown to candidate and then now from candidate is there a way to kind of uh reach every node right so that's basically the idea so then in that case I have to do this thing too um so yeah not remove candidate and then here is that current dot depend kind of get so now it becomes uh this is a little bit yucky actually because then now this may not be sorted anymore you know I mean definitely not if you're going to be moving then put it at the end and this is probably in the beginning the way that we do it uh this is such a mess how did I do last time I probably just grind but uh I mean okay I gotta try to avoid it but I think just using sorted this would solve this uh what is it from sorted containers all right and then now I can just do an ad or insert is it oh no add is fine we don't need to sort anymore and then here I think this is fine maybe well I just wanted real quick uh sort of can okay fine um Keys yep yeah uh yeah I knew that I just didn't know where I have it I might have another one okay uh yeah because we don't return anything uh okay right okay so this kind of uh sets everything up right and then now can uh is the graph connected from candidate right and uh maybe even before we do this we'll do the other checks first because the other checks are much cheaper uh so these things right so yeah so maybe um uh how do I want to write it right so for key and in degrees that Keys f I want to make sure that both keys have the same both things have the same keys so I'm just going to write something like this to kind of what if um to make sure that it they exist right so that you know uh now we can instead write it this weird way we can actually just go in the same Loop but and then here um and you could actually probably just like put on an actual list I'm kind of taking a long time and I'm also very tired okay what am I doing so for key and keys um okay so if in degree sub key is you go to out degree sub key then we're good right so if it's not then it has to be one of these two cases right so if um key is you go to current and um and in degrees of key plus 1 is equal to out the degrees of T then maybe I sort of like uh start film because you go to force and found is to go to force right uh okay so if this is true then self found is going to True otherwise then um otherwise if in degrees of key plus uh is equal to out degrees of key plus one then n found as you go to true of course we have to kind of um you know if start fail for whatever reason I don't think this can be possible because of the key as you go to current but if you start failing then we return Force but uh we have to kind of um fix the states so we might have to write a raptor about this so that's a little bit easier to do um right so uh right so maybe we do something like um or maybe the other way uh so yeah if uh degrees okay but uh if this is not degrees it's not okay then uh we um then we want to return Force kind of but we have to do the other things first right so um and maybe I should just write a decorator but that's just confusing if it's not okay we want to return Force um but maybe we just do if returns is okay then we do something right and then we return Force yeah this is a little bit yucky it's a lot Jackie okay let's finish this part first uh yeah and then also yeah if we if and found then we have two of these for whatever between and then we turn fourth otherwise if it's Eco is fine otherwise if it's not the same then we return Force at least we return true I think hopefully this is right this is where you would maybe have a unit test for just this uh I mean not quite just because we can't deal with weird States here so I'm already kind of violating that a bit but I do rely on a lot of global States why is this so long uh okay now let's take the degrees part is correct uh this may be one of those days where I have a lot of submissions uh then now we can do the connecting part so now okay uh these are the things that we care about and then now we want to see if we can visit all of them so a new current right uh could and then parent and then for V and E of current um I'm trying to think whether we need this to be connected or strongly connected I think connected is probably fine given all the other conditions but maybe I'm wrong on this one I don't know to be honest uh we'll play around with it I mean if it's wrong it's well okay uh yeah if we is not you got a parent actually I guess it doesn't matter because in theory we can go back and forth and back and forth so as long as we have to oh no I mean that part is true but I think for connectivity we don't need it so yeah okay fine um I don't know if I'm convinced but uh so Dad but also and we haven't seen it yet I guess right and then now we just uh if scene is equal to notes then we're good maybe I just do a pause even force and then true because then it does to clean up this is so yucky though not gonna lie uh so what this means is that this is returning Force for everything so that's not great uh do I just do it for okay I don't know cat doesn't say uh definitely not great but hmm is it disappoint or one star one n um I think there's an additional case where this is one which is if N Found is true but if like if start found and not and found or uh I guess technically only one of them so you could do like an INT ad or something but I think that's like less readable something like that but that doesn't change our thing because that makes it even more unlikely but I wouldn't hmm where am I getting this one uh let's see Canada does that even come up with anything before we crash no so that means the degrees okay is kind of awkward for sure okay maybe just here first key yeah that doesn't help enough I guess it was to see huh that doesn't not even that so what is going on it's not here all right let's just see that we actually getting here at least okay uh so the first one is JFK to Munich right and here it is going to remove these nodes or whatever so then now we're at Munich and for each degree where is this not the case I just print everything out real quick so yeah okay Munich uh yeah some minute just to start we start as far okay in degree um actually that's why do I have to end two degree for in degree did I mess up no that's just one so huh did I add one somewhere by accident oh huh why do I do this is not why would you add one that was just really bad okay uh I don't know why though okay all right at least this now is sensible uh our degree is one in degree is zero and then and I guess that starts first versus return to force for whatever reason but that was pretty bad okay so then now what is it doing my watch is always telling me to stand up and I'm always telling it I'm lazy uh okay so the degrees thing something failed so if key is you go so okay in degrees so no this is good this is what we want and it starts to go to true and then we go on right so why is that returning Force already hmm key is equal to curve what is card maybe current as well current doesn't make sense there's no current I don't pass it in so that's why this is weird um and like current is the last current possibly so it's not consistent uh yeah I meant candidate uh that is one thing that's kind of sometimes a little bit sketch about python is that it's very easy to make mistakes like this um okay so then now it's still going ever uh Munich that thing passes SJC one zero oh yeah that's the outbound right so in degrees you could that's fine right and found hmm it should be here right but if it's not then somebody's a little bit awkward yeah so that finds it here and then the next why is there only two things that's not true I mean it finds the SJC so it's here so then it should go to the next Loop right oh because they're all equal the same so that's why it's not printing okay that I could understand so then why is it uh do I have like a bad conditional Maybe kind of I mean I have bad typing so why not bad conditioner like true okay so if it is true and false or force and true so yeah uh so this should return true then right why is that giving me a search now so it is giving me here and then still give me an assertion though let me print out what this means this is after we do an iteration I guess now I thought that returns good okay I guess this thing now I wouldn't say it's fixed but it's doing maybe more course than we expected because that means that this DFS thing is kind of being bad Soca so let's see print scene and notes uh okay seen as nothing oh I didn't call the DFS did I so uh so candidate and I mean it doesn't matter where the parent shouldn't be used here so okay but both of these things are kind of one why is note only these two um yeah why is it only those two yeah I don't know how to code today all right yeah so it should have a bunch of stuff and in fact it does I guess right okay so it does and then it returns true right so does it not return true after this tell me why where's this print from to finish from here right so then why is it what oh and then now it goes to okay fine let's add a thing here for do and then now it goes from JFK and then next iteration it goes to muc uh is it Munich I actually don't know what I'm curious I just keep saying Munich I guess it is Munich okay so I'm not making things up I've been to that airport but I've been to a lot of airports um okay so then now that means that this is the first Loop actually turned out okay goes to Munich and then this is when things went awry uh why is that tell me why okay so I mean it does note the local to lhr right um empty plugging this so badly uh okay so Munich average okay but it's giving a force somewhere that's a little bit sad but oops okay so that means that degrees part is one right did I know this I don't know so lhr okay so why is this returning is it here nope so it terminated a little bit earlier let's kind of look at both I suppose I can take a shower and sleep maybe I should do these in the morning I don't know anymore uh okay Mr hero4 again no this one uh okay oh do I oh these things we have to add back in okay I am a silly boy I don't know why I was so inconsistent there's so many silly mistakes to be honest uh but yeah one look hmm oh so we're good kind of I might have maybe this is M minus one two three four I don't know um now we're in SFO so SFO we have to go SJC but maybe there's something with uh of The Emptiness uh okay let's take a look SFO to SJC degrees okay and then I'm gonna do that first search uh the number of nodes are actually the no notes but we've seen SJC so that's not right okay so we just have to fix this I guess hmm huh uh let me tell us about I was gonna say let me look at prom two or another example two but how do I fix this I mean this seems we're pretty much done or well if it's correct we're pretty much done but we have to figure out how to do our scene thing I guess we could do something like this instead but that just seems a little bit weird to be honest all right yeah and now this terminates earlier uh because in essential we're just not we're just skipping the first thing but then the notes is a little bit awkward um it should be just SJC is it because it's assuming that uh okay fine maybe I can just do notes that add um candidate because that's the thing that we're always going to visit uh it looks okay for these but then you know for the example it worked okay even on crappy like when we just returned true for some random stuff right so I don't know that I put that much stick in it but let's uh you know I guess this one I believe in because that's just so anyway so it should never happen um it happens and you know uh yeah let's at least add some weird slightly more weird uh cases right something like that I'm not confident about that one to be honest seems okay though What's the timing looks okay too uh I mean this isn't you know crazy intense and apparently we have some extra print statements that we've actually got rid of so that would actually be sad and I could find them it's fine here okay there we go um is there a bigger case um I'm just going to submit just because I'm lazy but I'm like not super confident but I guess we're fine um I mean it's fine this is a tough one um isn't it I mean it's fine I think I just kind of took my time to be honest um to kind of go for it step by step it's been it's a very long step what I do last time I got a one uh I guess the last time I did use uh what's his name's album poser uh that woman um oh I think um this is a really weird way of doing it I think the observation here which I did not use this time is I think the thing is that uh because it will always have at least one answer the I think that this other one is probably a little bit a lot smarter because they're now just saying okay take and the reason of having this is just so that we have it in order because otherwise you can take anything and I guess it always it's impossible to get stuck is that true foreign I thought that there may be a weird case where I don't know you go to ABC and then hmm oh I see this is actually a pence at the end so this will come so you're kind of man I do not know this one not gonna lie I don't it's been a while so I might not be strong enough I mean this was three years ago hmm I mean this is just uh the algorithm but okay uh yeah let's go over the complexity really quickly I mean I think we kind of laid out what we're trying to do here um so it should be pretty straightforward um this has M Loop so this is all of M iterations and for each one we uh you know we do a thing right we look at the next node and for each node we do a linear thing so but keep in mind that uh and there's some log Factor here so I'm a little bit sloppy with this one but keeping your mind up for each one we um is that true I don't know I think maybe there is some like crook of the thing because I'm trying to finger file like this case where you have something like JFK ABC right and then maybe I don't know JFK uh DF I mean this is gonna work for me but I don't know how this works for the older example I think that's the thing that I was trying to do let's see I mean this pretty straightforward here because we're literally doing the end Square solution but if we look at this one um how does this work I mean it is just algorithm but I'm telling that I don't even need non-local I think that was when I was non-local I think that was when I was non-local I think that was when I was just still starting python doing because I had python 2 experience prior but basically saying if there's an edge we recursively constructed oh yeah I don't know I don't have I don't know today I'm just tired but I think hopefully uh let's take a look at some solutions maybe I'm just being silly yeah I mean I don't know what's going on here I mean this is basically the way that I was doing it but I don't understand this way it's just I feel like it I don't know I might have to watch Larry's older video um I think this is just what the guy is having room I think trying to find the window for ah it's fine anyway uh sorry friends if this kind of left out a hip hanger uh hopefully this was understandable uh this is not the code I want to show you the code that I wrote today um yeah let me know what you think this is the top and this is the end and you know this comes up quite a bit this kind of thing uh it's just not for each Edge we are gonna you know do it I guess this is always good maybe so I don't know anyway that's what I have for this one let me know what you think and yeah stay good stay healthy to go mental health I'll see y'all later and take care bye
|
Reconstruct Itinerary
|
reconstruct-itinerary
|
You are given a list of airline `tickets` where `tickets[i] = [fromi, toi]` represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.
All of the tickets belong to a man who departs from `"JFK "`, thus, the itinerary must begin with `"JFK "`. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.
* For example, the itinerary `[ "JFK ", "LGA "]` has a smaller lexical order than `[ "JFK ", "LGB "]`.
You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.
**Example 1:**
**Input:** tickets = \[\[ "MUC ", "LHR "\],\[ "JFK ", "MUC "\],\[ "SFO ", "SJC "\],\[ "LHR ", "SFO "\]\]
**Output:** \[ "JFK ", "MUC ", "LHR ", "SFO ", "SJC "\]
**Example 2:**
**Input:** tickets = \[\[ "JFK ", "SFO "\],\[ "JFK ", "ATL "\],\[ "SFO ", "ATL "\],\[ "ATL ", "JFK "\],\[ "ATL ", "SFO "\]\]
**Output:** \[ "JFK ", "ATL ", "JFK ", "SFO ", "ATL ", "SFO "\]
**Explanation:** Another possible reconstruction is \[ "JFK ", "SFO ", "ATL ", "JFK ", "ATL ", "SFO "\] but it is larger in lexical order.
**Constraints:**
* `1 <= tickets.length <= 300`
* `tickets[i].length == 2`
* `fromi.length == 3`
* `toi.length == 3`
* `fromi` and `toi` consist of uppercase English letters.
* `fromi != toi`
| null |
Depth-First Search,Graph,Eulerian Circuit
|
Hard
|
2051,2201
|
106 |
EPF and Compression Request Today We Are Going to Saab The Great Wealth and Valid Challenge and Today's Problem State Me Problems Caused by Negative from India and World Tamil Sunrise Subscribe * Input to Injured in Acid Subscribe * Input to Injured in Acid Subscribe * Input to Injured in Acid Info Someone with the Introduction of Love You for Trade Union President Mirwaiz basically so let's move will improve what is the co subscribe toe hai butt hai poster work hard for girl f9 david roup related to avoid ko subscribe and subscribe for More Video subscribe abs ki Bigg Boss hai so aayi Will Cover Left To Take Nobel Prize For Truth In District Students Roasted Travels The Well Withdrawal Subscribe To That Similar Key Food Poster Is So Difficult To Start From Every Visitor Every Day Tubelight Left With Tutkar 800 Again In This Case Which Starts From Left Dene Ke Ignore Drive 15th Abs For The Video Must Subscribe That Aapke Saurabh Any Shift 120 Logic You Can See But Always And Noida Right And Poster Singh And Festival Light And Its Root Will Always Live In The Use This Subscribe To ki aisa inter root nodi liquid soap improve your spoken and witch sweet smile know what will oo that Arvind check will visit actually ignore died in amlon is look like this loop root and saw your profile root 999999999 subscribe must subscribe now subscribe to 80k security Mail Vishnu Note Aisa Ek Inverter Hai Will Do Main Secondary Fuel Filter Itna Dont Tension The Second Phase To Builder Loop Chithi I Know That Subscribe My Channel Ko Subscribe Video Plz Subscribe Channel Subscribe Ski Rides On Hello How Can You Let A Swag In This Case Wedding Reception More Interest Subscribe School Inter College Were Corresponding Child Rights 19's Cancel OK More than 120 Left or Right Sowinder Feedback Hair That Android Lite Will Win The Seven Brothers Seven OK Now Viewers OK Let's and by-products of water And subscribe button that this minor daughter length is not equal to poster dot length date return run loot note side channel subscribe poochga pass my location to my channel subscribe not lose - 1929 Scientific channel subscribe not lose - 1929 Scientific channel subscribe not lose - 1929 Scientific Society - 1864 Society - 1864 Society - 1864 A nerve tonic loop control less previous Ravana builder Function ok to builder and for spirit of light illuminate servi and subscribe and friends fast subscribe The a poster audio apart from vestige scientific we are one such hundreds to in this also source you ine gantok sexual last day in the history of Education Ride To Loot Will Be Written In No Case Till Now Thank You To Take Hai So It's Not Satisfied With His Condition Which Can Build An Old Water Is No The Last Suid Content And Roots Value And The Indian Values In Which The Can Identify Me Indian Values In Which The Can Identify Me Indian Values In Which The Can Identify Me Root Not from the Posted on December 19, 2010 Let It Snow and Want to Create Custom Soret Limited North End Will Be Nutrifluid Ki Ab Tay Download Pass Donkey This Show Poster And Will Be Index Main Headlines 312 in the World Not The Location of The Amazing Channel subscribe If not done then inverter that these days I will check dam resort blast - I am not equal to poster blast - I am not equal to poster blast - I am not equal to poster according to Bilaspur Postal Index type that we are a silent as my so what are they doing this is tasting do subscribe my channel subscribe to Let's move father sweater me to morning in this case and decided define take root note index in The Video then subscribe to subscribe our A a game of death and so is this is my location Rajeev no in this if doubt is power drive time acid website Listen start video phase but I don't subscribe Video subscribe - - - - - Similarly for not - - - - - Similarly for not - - - - - Similarly for not rise after this will not write all subscribe tweet - subscribe tweet - subscribe tweet - ki i plus one in the index kospi index - 1m index - 1m index - 1m ho chuke hai aapke west bengal to return utho ke Sholay completed check ho jaaye i.e. ke Sholay completed check ho jaaye i.e. ke Sholay completed check ho jaaye i.e. North 1512 fasting is not passing the last 10 years paste absolutely not just electronic entry for doctors yes it will be Jaimal type electronic and 19 doctors compiling North hua tha mushkil song time Anokhe Yashoda resubmitted gyaras uski builders loot aapke electronic Mukesh Vacancy Which Lands Express Train States of Matter and 167 Acid Sluices Subscribe to Channel The Video then subscribe to subscribe and subscribe the Channel and subscribe Sleep Location of a Root Node in Dahez Location Somewhere IS Spent Checking for Last Night and Meetings of Value Solve Will Find A Way Which Will Find Acid Subscribe Now To Subscribe My Channel Subscribe My Location Last - - - - - - 121 Location Last - - - - - - 121 Location Last - - - - - - 121 This Point Distraction Only Right Similar Iam Rule Vidic According To Which Give Lift - Location Subscribe To Reddy Labs to the Video then subscribe to the Page if you liked The Video then subscribe to the 8 - I Valve Vansh Dainik And Class One Night Sweet 8 - I Valve Vansh Dainik And Class One Night Sweet 8 - I Valve Vansh Dainik And Class One Night Sweet Dream Into Soft Pitch Se Location Right To Subscribe Miding subscribe Like the Video and subscribe to a lip with friends Meeting more than one and a half percent submission and rate items on that memorial girls 2.77 OK definition on that memorial girls 2.77 OK definition on that memorial girls 2.77 OK definition Video Please subscribe our Channel thanks for watching device
|
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
|
237 |
hello guys welcome back to tech doors and in this video we will see how to delete node in a linked list so this is from lead code day 2 of the June challenge so let us now look at the problem statement the problem says that we are given a linked list and we are given just a single node in a linked list and we want to delete this current node in the linked list so we are not given the head of the linked list we are just given this single node you can see that if you remove this current node 5 then your linked list will become 4 1 & then your linked list will become 4 1 & then your linked list will become 4 1 & 9 but how do you delete this current node actually in order to delete this current node you will have to make this link point to 1 okay so there is no way to reach to this 4 because we are not given the head of the linked list and also this linked list is not holding any special property like it is not a doubly linked list it is not a zorb linked list or it is not a circular linked list so this linked list is just a plain single linked list and in a plain single linked list if you are at a current node you cannot go backwards ok so how do you remove this node actually we will not actually remove this node we will copy this next node to this current node and then we will remove this next node in this way we can delete this current node but then you can see that we are not actually deleting the current node we are deleting the next node ok so in this case it is asking that delete the given node except the tail because this method will not work for the tail case because if you are asked to delete the current node then what we were doing we were just copying the next nodes value to the current node and we were deleting the next node but then if we are asked to delete this last node that is the tail node then there is no next node it is null therefore we cannot copy the value of next node through current node and delete the next node there is no next node therefore this technique will not work if we are asked to delete the tail node therefore the question is saying that delete the given node except the tail node now the linked list will have at least two elements so we are not asked to delete the tail node so it is very logical that the linked list will have two elements because if you have only one element then head and tail will be the same okay so there are basic two cases and the node will be some middle node or the node will be pointing to the head node both these cases can be solved by using just a single method so if you are given four five one nine and let's say you are asked to remove this node five then what will you do we will store the next node of this current node in our temporary variable now since this is stored in temp so we will just copy the next node value to the current node so this will now be equals to one we will remove this link and then we will make it point two nine and then you will see that your linked list is now four one and nine but it is always a good practice to remove the next pointer of these type of nodes so we have taken this temporary variable and we will make the next of temporary variable equals to none so this will be gone and now your linked list is just four one nine this will just take order of one time now the code is self-explanatory and I hope I code is self-explanatory and I hope I code is self-explanatory and I hope I don't need to explain it if you have any other approach of solution in different languages then please post below so that everyone can take benefit from it this was a very simple question see you on our next row thank you
|
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
|
338 |
hey everyone welcome back and today we'll be doing another lead code 338 counting bits this is an easy one given integer and written an array such that e for each i in a n s i is the number of ones in a binary expression so what they are trying to say is if we give you a number two you will compute the binary one at the b first of all com seeing their binary if they have one how many one they have one bits in them so zero has zero one has one and two also has one like you can see here and also four five zero one two like you can see here and that's it now let's understand how this will work so starting from the zero and till the eight we will be seeing so you can see zero has zero uh one bits one has one two has one three has one four three has two for as one so five has two and if you look closely the pattern is being repeated the most significant bit is added by one to the very left but the pattern is repeating like 0 1 and 1 0 to 6 11 not 11 but 1 in 7 and 3 and 8 and 4 note 8 and 4 8 and 0 adding the most significant digit to the very left and no digit bit so how this is working is we are adding like one plus to our most significant bit to the very left significant bit you understand now what we will be doing is making an array and computing all of just taking uh the binaries of all of them and adding how many the ones they have as their bits so what we can see here is we have already computed these four and now we can take the reference by just taking the base and subtracting it by our current iteration what i mean here is for example our current iteration is 5 okay this is our iteration like you can say i and subtracting it by base so what is the best the base is going to increase like this is always one two three four multiple of four that this is a multiple of two this is why it is called binary so at first it will be one so the first iteration and so the second iteration it will be two and three and now it's going up and four and delayed it will be going so how it is increase when our base like this when our base if you multiply it by 2 becomes equal to a current iteration we are on so for example for the second iteration 2 we updated our base by 2 like this we have done like base is equal to i and we are going to do the same with four you can just say whenever the two uh match like the number for the base and the number of iteration same is going to happen at 8 what we will do is subtract it by our current iteration that will give us a r for example this was our array so 5 minus 4 will give us the 1 location and we have already computed 1 we already know there is going to be 1 now let's calculate 6 will have a r 6 minus 4 and 6 minus 4 will be two and obviously it has one bit so it will be added here and four seven it is the same so that's it now let's code it down so first of all making an array let's write it down okay so first of all making an array for i in range for i forgot to put for i in yeah now it is good so for i in range starting from zero and then plus one because we want to include our last digit and base will be starting from z uh not zero from one so for i in range will be starting from 1 to n plus 1 because there is for 0 there is 0 we have already put it 0 in our list so we don't have to uh go again to look at it so if ps if you multiply it by 2 becomes equal to i the current iteration we are on so we will just yeah make our current iteration our base so now what we are left to do is just ar at i our current iteration are index adding one significant one bit and now what we will do is subtracting i by our base we have already computed and will be using them again and now just return ar and that's it let's see if this works it works and let's submit it okay if you have any kind of questions you can ask them in the comments and if you have any kind of question in the comments or you can just reach me out to the my instagram update956 and that's it
|
Counting Bits
|
counting-bits
|
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`.
**Example 1:**
**Input:** n = 2
**Output:** \[0,1,1\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
**Example 2:**
**Input:** n = 5
**Output:** \[0,1,1,2,1,2\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
**Constraints:**
* `0 <= n <= 105`
**Follow up:**
* It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass?
* Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
|
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
|
Dynamic Programming,Bit Manipulation
|
Easy
|
191
|
981 |
hello everyone today we will solve a lead code problem 982 so in this problem we have to design a time-based key value data structure that time-based key value data structure that time-based key value data structure that can store multiple values for the same key at different time step and retrieve the key values at a certain times so like here we have one class in that we have one function method set and one get set method we have key value and timestamp and we have to store these values and also we have one get function in that we have to return a value such that was called previously with time spent previous will be less than equal to time spent if there are multiple such values it Returns the value associated with the largest timestamp previous if there are no values it returns this input test drive so let's try to understand this Solution by one example like here first of all we have to initialize then we have to set it now here in our data structure we have this key Foo and for that we have currently one value bar and the timestamp is one now uh when uh the timestamp now let's assume we want to get the value for Foo in that scenario 1 so the previous time spent it will be less than or equal to that current so yeah it is less than or equal to n43 also it is less than equal to then we add one more key and value pair here then also we did the same thing and one more thing is that whenever we are setting some values we are always getting the timestamp increasing order and here these are the constraints and here we can see that at most 2 into 10 to the power of course at set and get so basically we have to solve this problem in off and time complexity or of an login time complexity so let's first of all try to set the value here so just start with the okay so here uh when we can set if our key is not yeah so here we have to Define our data so we can Define our data like that and if keynote in self.data in that scenario if keynote in self.data in that scenario if keynote in self.data in that scenario if keynote in self.data then we can perform one operation self taught data dot key will be a empty string so here now let's assume the key is not in our data sheets then we have to create an empty string a list and now we can append the new data like value and timestamp pair in our Dash dry structure like this dot append here we have our value and also our timestamp okay now this is for uh so you know whenever we call the set function and the time complexity of this thing is often now let's try to get the value so here what we have to do here let me explain you this thing by one example foreign key and also value in value we have two thing first one is value and second and times time so now let's assume we have any value one and here let us know how time is 4. then also we have some value V2 time will be eight then P3 time will be 13 so like that we have so many values and as we can see that these things these time stamps are in increasing order and if you want to get a position of some number here we can use binary search because uh in the getter method let me show you in the getter method here also we have time stamp and we have to get the value from our list that is less than or equal to this time stamp so for that we will use binary search here so now how we will solve this problem so first of all we have to create a function here binary search foreign also we have our array we have left we have right and also view Target so here now the first condition is that our right always greater than or equal to left else in else condition uh in the else condition here we will add some code after some time so first of all here we have to get the Met commit is equal to f plus right you like to and also now we have to get the value from our array that will be made often because in that array we also have one more array with two elements first one is value and second is timestamp so we are getting the second value here now here if our value is equal to Target that scenario we can simply return the index mid else a power value is less than Target then we have to move to then we have to move in the right side so here we have to return self Dot binary search here we have a array then mid plus one also we have our right with the target value three Target value in the else condition we will do the same thing but in this scenario we have to move in the right in the left side so here we have to write left and right not right mid minus one so now here we have to write some conditions in the else condition also now let's assume if like in our timestamp we are starting from 5 10 12 15 when we want to get the value for the times time value 3 in that scenario there you know we don't have any answer so then we have to return a empathy list so for that here let's assume in each time we are going to call this function if our value is very small and that does not exist in the given array so after some time our right value will be negative when you know in we will call this code whenever write is greater than equal to left but when left is greater than equal to right in this scenario here our right will be negative so if right Less Than Zero then we have to return minus 1 because we don't have any solution in the else condition if our right is not equal to 0 then we will you know we are getting values from the this function so here now the value does not exist and it is a very big value so then we have to return our right index that you can you know fetch the value from that index so like that we can write the code for binary search now let's try to uh no write the code for the get function and then we will see that it is working or not okay so here we have the first thing if key in cell dot data if it is not in this then we have to return empty list the first thing then in second thing we have one array that will be self dot data of key okay and also we now we have to get to the index because we want to print the value you know for a particular time stamp the index will be self Dot binary search in that first of all we have to give our array then initial index then right part after that we have our timestamp this is our Target value so here if our index is equal to -1 is equal to -1 is equal to -1 and also we have to return the empty list in the in um other scenario we have to return ARR of index of 0. now let's try to run this code we got some error not if key in sorry here we have to write like this if Keynes help dot data DOTA pan we are getting some error so self dot data of key dot append first of all if key not in my dear we did the small mistakes here let me see it is yeah it is working fine perfectly fine now let's try to submit it and then I will explain you again what we are doing yeah it is running perfectly fine there is no error now let me explain you this thing again so first of all we have to use a data structure in that we can set a key and value for pair so for that we have to use hash map so for that the time complexity will be often then we have to use a get function so in get function here also you know we totally we have to perform 2 into 10 to the power five operations so here we can do this Operation Log of and timer of one time so now here we are getting always you know time is time value in increasing order so in that scenario we can basically use binary search here so uh for that we used binary search here to get the index now that is uh which values is less than or equal to our timestamp for that we used bin users to get the index of that particular value and then we are simply printing the solution and in binary search we did the same thing like this code is similar but here we did a little bit you know different thing whenever the write is less than 0 we return minus 1 else we return right so like that you know we can use binary search here in this problem and we can solve this problem in a very simple way so this is for this uh problem if you face any difficulty in this solution then please comment and also if you want to get the solution of some other problem then also you can comment the problem name in the comment section thank you for watching this
|
Time Based Key-Value Store
|
delete-columns-to-make-sorted
|
Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp.
Implement the `TimeMap` class:
* `TimeMap()` Initializes the object of the data structure.
* `void set(String key, String value, int timestamp)` Stores the key `key` with the value `value` at the given time `timestamp`.
* `String get(String key, int timestamp)` Returns a value such that `set` was called previously, with `timestamp_prev <= timestamp`. If there are multiple such values, it returns the value associated with the largest `timestamp_prev`. If there are no values, it returns `" "`.
**Example 1:**
**Input**
\[ "TimeMap ", "set ", "get ", "get ", "set ", "get ", "get "\]
\[\[\], \[ "foo ", "bar ", 1\], \[ "foo ", 1\], \[ "foo ", 3\], \[ "foo ", "bar2 ", 4\], \[ "foo ", 4\], \[ "foo ", 5\]\]
**Output**
\[null, null, "bar ", "bar ", null, "bar2 ", "bar2 "\]
**Explanation**
TimeMap timeMap = new TimeMap();
timeMap.set( "foo ", "bar ", 1); // store the key "foo " and value "bar " along with timestamp = 1.
timeMap.get( "foo ", 1); // return "bar "
timeMap.get( "foo ", 3); // return "bar ", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar ".
timeMap.set( "foo ", "bar2 ", 4); // store the key "foo " and value "bar2 " along with timestamp = 4.
timeMap.get( "foo ", 4); // return "bar2 "
timeMap.get( "foo ", 5); // return "bar2 "
**Constraints:**
* `1 <= key.length, value.length <= 100`
* `key` and `value` consist of lowercase English letters and digits.
* `1 <= timestamp <= 107`
* All the timestamps `timestamp` of `set` are strictly increasing.
* At most `2 * 105` calls will be made to `set` and `get`.
| null |
Array,String
|
Easy
| null |
460 |
Hey everyone, I hope people will be well, friend, after a long time there has been a video, you know about it, I have always been following my rule of inconsistency, I do n't know when the size will be correct, there is a question, if it is okay, it is a very good question. And I am truthful, this problem comes in hard category, but after looking at this question, don't think that this question belongs to heart category, it means hard, I am truthful, read this question, I am telling you it is hard, forget it's okay. Read the question in search and see how you are able to attend it, what is your approach, how are you thinking about it, okay and what are you thinking about it and I am really facing the problem, definitely attempt the input. Understand the example given and understand the output given and also understand the exclamation given here. It is better to sit carefully and watch this video completely. I am sure you will learn a lot. Okay, let's start the question without any rate and I am assuming that you must not have cheated, you must have attempted it, you must have read the questions, please read the questions and it is not like that, let's see. Read from the example given and understand the explanation given. There is a lot of understanding to do so much. So let's start the video. Let's understand the questions. Actually changed after a long time. Okay, so you understand the question. What is the question? Fu catch you. Basically, three functions have been given in the question, in which a variable named capacity is going. Okay, what the capacity tells us is that we can store so much data in the cache. There is a gate. If we give a key, then we get a value return in return. The output is of print type meaning we are inserting the key and value. Now there are different cases. If the key is already present then we will update the values. If the key is not present then when we call the get function then all the people call get. If five is not present, if I take it then it will return -1. Let me talk about this example. return -1. Let me talk about this example. return -1. Let me talk about this example. I am explaining from this example hospital. The first one is full catch and you mean that now the capacity of Alpha is ok, come on, you are talking about the capacity. Then comes put meaning to insert van less van then 1 is inserted then van less van and count is done van and tu kama tu if you have to insert 2 then what is there in the dictionary this time tu and van are ok And what is the count of you? What is the van count telling? Basically the count is telling how many times we have accessed that key or updated it or gated it here. Increment the value of the account. If we are updating it, even then we have accessed it, then still we are incrementing the value of the account. Now for the first time when someone is inserting, the butt offers are its count. Value will be van till here so sure walk then put is 2p get van part van is doing so we accessed van so now what do we mean now we incremented the value of count so will return van And the count of van kya ho jaayega tu ho jaayega kyun because we accessed 1 again so it means now list recently used l r u what does list recently used ab ki man lo kisi a gaya aate problem fansenge Okay, so if we are asked to whom we have done it the least, then the one who has the least account means Van, then we have done it the least number of times till now on 2 because till now we have done it the least number of times. Just inserted it once and what happened in the case of van, inserted it and also got it once, now let's put 3, we will insert 3, but the size is you, already, we have the van and you are present, is it okay in this, so now Will we delete one? No delete whom will we delete? Whose count value will we delete? What will we delete? Okay, so now 3 will be inserted and the value of account one will go to you and three is okay and this time we will increment the count of three. We will give you and the count of you is also incremented, you are sure, now let's come but already we have two elements present, which three and one are okay and but both of them have value of comment, so whom will we take out this time? If you have to go out, then the list of LRU is constant. Recently used, who has happened to him the least number of times, then if we check like this, then look at everyone, both of them have happened to him more than two times, it is okay, but who has happened to him first, is okay. First he had one and then three, okay look, a lot of one and three have de count but one is LR you list the recently used one, the one which has happened to him the least number of times and has not happened to him in the recent times, why because, look at the recent ones. So three has happened to him, right in the region, so three has happened to him, so what have we done, so what will we do, we will delete the van. Okay, so the van will be deleted, 4 and 3, we will have the answer A, the amount of four is done, the van and Account of three is done, you are fine, very good, get one, then van will not be given to him -1 ok, then come gate 3, account, then -1 ok, then come gate 3, account, then -1 ok, then come gate 3, account, then we returned three, then 3, this is our pro output from the internet, so understand. What is the problem, what is the problem, there is nothing, some, all cases will be made, I will keep explaining to you will understand, in this we have a selection of data structure, which data structure we have to do the thing and how much data structure we have to do it, data structure. The whole game is done on this itself, friends, I am telling you that I would have written this question in the design forward that you will be samjhaunga later when I will tell you the proper actress, okay let's come to the data structure in the next time, now we design the solution, what is the solution? We will have to now look at these three points, this is the root of it, if you understand these three structures, how we are doing this and that, then you will understand all this, I am telling the truth, that is why most of all This is your main part of the video. Okay, so what's the point in sorry brother? What is the value of your solution? What is the value? Is it storing the value map like we store that? Okay, let's store that now. And together we store this key of value and frequency on the foot side, how many times have we counted, how many times have we called, so how will we slice these, is the foot ok, is the value, frequency ok, this is the value you have and this Do you have the frequency or the number, which one is it? I have taken the frequency and its value, we have made it here, no problem, second frequency list, what is the frequency list telling, frequency and we have these notes, this is called doubly linked list, okay, we have made a thin list. We are storing it in the form of link list that three key van ki tu will be like this, frequency and list. Now for those who do not know the list, okay list is a data type in HTML with which we create, what is the benefit of it. Made a list and gave a list of keys. Okay, so what will we do in it? Now we are asked how many such keys do we have whose frequency or count is low van? Five and three are the two keys whose frequency count is still van. How many such people are there, everything will be understood in the future, like don't panic, it is okay, there is also a position called anode of map in which we store keys and like if you are okay, then you will reduce it like here and If this note is made then there will be some address for this note, so that address is let's assume what address will we install the address and what is the address is the key and list colon is the resolution operator okay, this is how I defined that this is And what is its address so that we can access it at once. We have defined the frequency list and position by name. We are creating a capacity which is a variable. Capacity is creating a minimum frequency. You will understand everything about it further but a. Just keep this in mind, rather write it down in the copy, I am saying that I will understand it, write it down in the copy so that while I keep reading, keep checking it side by side in the copy and those who are looking at my solution without wearing the copy. They will not understand the lesson. Friend, if I teach you, then please I say every time, sit with a copy pen, whenever you watch any of my videos, then move ahead and like I have divided it by three, no problem here. No problem, first comes the cash space, the capacity becomes 2. Okay, so what did I do in the capacity, put in the capacity, is there any problem, then comes put van [ __ ] van means insert, comes put van [ __ ] van means insert, comes put van [ __ ] van means insert, so what capacity do we have? So far it is zero, okay, right nine, what is the capacity we have, if it is zero, then what we did is put WAN in the value of WAN, what is WAN, what we did is put WAN in the value of WAN, what is its value, because value is also WAN and key is also WAN, so WAN is there and given the count. Van, there is no problem till now, there is no problem, what is already written, do not pay attention to the one who is marking with red pen, understand that I have also inserted the value, there is no problem, now there is frequency list, what is frequency list, count, van count. What did I store the van and what did I do in the van here? Basically, this is the van, it belongs to us and what we have is the value, list of notes. Okay, so I inserted it here and inserted something. N, I must have got its address, definitely I must have got the address, so I will remove it here, okay son, you will understand once and then I made us a position, what is position? What is WAN? What did we have to store in the position? What was the exact address to be stored? What is WAN and what is address? I am fine, we have updated it, rather 2, do we have this capacity, we have one, I have stored 2, you will insert van, because the first one was being inserted, what will be the frequency, will van be ok, now again van will be there, so pay the van owner. We will go to our and insert two, we got its address and then we will map this address with this key in the position map, no problem, now let's come to get off van, like apan, now everything will start to be understood, get off. The van is on payment, so we want the value of the van, so what did we do, but will it not be enough? No, we will also have to update what we need to update. First of all, we will check whether the value of this van is present. If yes, if no, then we will return its value. How will it be done by returning the value? No, we will have to increase the frequency also, because we have accessed it twice, insulted it once and are fetching it once again. Okay, so what is the frequency now? Okay, so what will we say while holding this van? We will get up to this van. Now if we get up from this van, then we will go to the frequency one because the frequency of the van will store its key, which will store this one. What is it and will we delete it from here? Okay, pick up this address and where did we get this address from? We went to the index of van and where did we get the address from here because this address was already mapped, your address was already mapped, so when this address was already mapped. What we did was that we deleted it from here and also deleted it from here and increased the frequency to if you are ok, so now we have increased it, so you are here, in the frequency list, now we have a van here. Then some or the other address has become There is no problem, there is no problem, now let's put 3, let's come on 3, brother, very good, so now we have the capacity of full because the capacity was somewhere, so what will we do, the minimum frequency is here, the minimum frequency is the minimum frequency. Done Van kill, okay because we have, look at what the frequency list is telling now, basically why is there frequency, it means that this is the list of van frequency ones, you will have some numbers of notes from those of frequency ones, okay, you will have some numbers of frequency ones. There will be some numbers of off notes having 3 frequencies. Okay, so but off is not the most list. What will come out of us when we delete, which is the most list? It happened to him less often and who also happened to him less often, he happened to the one who is here the most, okay if let's suppose a frequency, first van is this kit van, this is kitu okay and then K3 comes, so three will be here and recently. Now if it is 3 then the one with lowest frequency and the first element which will be there will be our LRU, try to understand it, I am explaining it again, I am understanding it, so as you are the one with van frequency. The frequency one is three. This is the frequency one. This will be some note. There will be some note here. There will be This will be some note. There will be some note here. Okay, this is the main key, this is the key, 5 this is 3 2 6 7 Now man lo, we have inserted a new one, that is, three man three inserted that and this key and this is the value, so now the first one is inserting which frequency will it go to? Three was already there and makes it 30. So, three will go here, okay, so now we should ask it, what is the list of recently used frequency? List recently. When we have the lowest frequency, then what is the option that we have, which is the first one? First of all, there was four, then date is the reason behind it, what will we do, we will go to the minimum frequency, whatever is the minimum frequency in the frequency list, whatever is the time, now here is the van, what will we do, if there is a van, what will we do, this has already happened, how to mark it? Let's delete it like this, it's okay, it was already there, so you will come, okay, so what will we do, we will delete you, no problem, so when we deleted you, it became empty, now is there anything on the van index or not? Now if there is nothing then it will not be a problem, we will delete you from here too and we will delete the 2nd from here, okay remember, as soon as we point to the first whatever minimum frequency, this is the minimum frequency that we have. So the first note will have to be deleted because it will be the LR only. From there we will get the key. If found, we will delete the data from the key value and delete it from the position. Now what have we done to the 2nd data? This data has been deleted, this data is over, there is no problem, but now what is the problem that the frequency of the van has now been deleted, but the van has already been deleted, you too have been deleted, so now there is nothing left, so we People will check whether any note is present in the minimum frequency to which the person is pointing and if not, then we will increase the minimum frequency, then the minimum frequency has been reached, this is ok, then the minimum frequency has been reached, sure Yadav, there is no problem, there is a problem, let's go. Now let's get off, you are sorry, put off three, if you do put off three, then you have to insert 3. Brother, if you have to insert 3, then three, earn 3, earn van, it is okay, as if you have given 3 1, then again now van wale. In the index on frequency, if I write this here and then again three A, some address must have been created, X G, zero will not be suitable here, then what has happened on WAN, now the minimum frequency will again become WAN, why because on the frequency of WAN. The data has come back to us, it is okay, if there is even one on the WAN frequency, basically the minimum frequency is telling us, not on which frequency out of the list of minimum frequencies that is being made, we have data because LRU will be the same, remember this. It is okay to keep LRU, it will always be the same, the first mode in the minimum frequency, we have three, so three, now the first element is its account van and the count of this van is tu, if the frequency is tu, then the question of deleting the butt will come. So we will go to the minimum frequency and see which note is present, then first of all we will delete it, no problem till now, then we come to gate of three is as it is, then from here we will increase 3, increase three. And we will group three here. Do you understand why we will have to increase the frequency of development? We will then put off for because three has been recently used, okay, recently used by, that's why there is a in the end, okay which will be recently used. When it comes to the end, we will increase WAN for put off for. The data of WAN will fly from here. The data of WAN will also fly from here and we will insert four and if we insert 4 then we will have 4. Then we will insert it here. Remember in the frequency list. Keep four in the frequency list, it will be stored here and then the data of four will come something like So we will have gate of three, then we will start it again, it will go to the third one, so gate of three is done, we will have some address here, address will be whatever X 0 1 2 4, whatever address will be updated every time here. The address will be updated again here. Do you understand that the address which was on the three's X G Will the Will give again and will increase the meaning, further you will understand what I am trying to say and in this way I will reduce my whole, it is very easy, I am telling you the truth, gradually you will understand everything. There is one simple thing, please make sure everything will be understood, how the thing is being moved on the list, I don't understand, nor have I told you the list, it is a list, okay, we are directly finding the address and deleting it, this is the benefit of it to no one. What it means to be listed is the vector. The factors can't do it like this, but we can use any note directly. If we can access it, then how else can we access it. With the help of address, now see, I will tell you the details of every point. Funda, what does it mean that if we have just updated the gate also, I am telling you, I am fine, if your gate of put of five came, this gate of put of five came and which is the case of update, there is one thing common in both the cases, what should we increment? is its counter and whenever the counter is incrementing it means that the frequency is incrementing whenever the frequency is being implemented then it is but of frequency. If the position of the note changes in this frequency list then it will change the position of the notes. There is a map where its position will have to be updated. It is understood that if there is a value then the one with five is here, so what will we extract from it? First we will extract the frequency, list of which current frequency is the current frequency and in that we will erase which one. The one that has to be erased is five, how will we know its address, where is the address stored, is it at the position, what is the position of the key is 5x505, so this thing will be deleted, okay, so this race, if the position of the key is off, then its address is given. I went to this address in my frequency list and deleted it, no problem, now what we did is its current aa what are its values so the value of key are its values so the value of key are its values so the value of key dot second is telling this dot first is this dot second is this Okay, so what is this frequency in dot second, we will increase the frequency, we have increased it because get this update here, we will have to increase the frequency, now what new frequency has come, again what did I do in the current frequency, I stored this one which is new. The frequency came from Aaya, the same thing is done here also, no problem, keep reading, keep seeing how I go about the court, keep understanding, it is not rocket science, you will understand this, then what I did, I called the frequency list, then I called the frequency. List and the new frequency you will come and insert it here, will you insert five here then the address will be made Now, whatever frequency I inserted, no sleep, how will it come out, like if I inserted you, now I can sleep first, not you, I can sleep, already here snowdoll is six, three, okay, now what I did is five insert. If this is done then how is the frequency list obtained? Dot is the current frequency which is to be placed on this frequency and dot is pointing to the end which is the end. This is the rule like dot end is always in the last position and points to the ones after that. So if we mine one mine then we will get the index address of this one. Okay, so go to the frequency list. Current frequency on current frequency. You are okay and it will run on dot and end. We always find it. I did mines. Now you are pointing to it, so what did we do with this address? We updated it in the position of the key. Okay man, if it was like this on the van one, the van person would have only five and on the tu wale, you would have the frequency list. I am telling you the frequency. I am talking about the list, I am fine and you are on the first one, you have 3, then there is six, okay, so like we deleted 5, then here is five, if you are on one, then there is nothing left in five. Now the minimum frequency is pointing to this. Okay, which is wrong. We checked whether you have any note left in the minimum frequency. If it is empty, then we will point the minimum frequency to this. Why is it necessary to post the minimum frequency? To update because when we have the turn to delete, when we delete, okay, let's have an extra variable, now we have to delete, so we will go to the frequency list and point to the minimum frequency, where is the minimum frequency. We are going to delete the front element of it because it has been deleted. The position of the deleted key is the front element of the pop which was the minimum frequency because if we delete it on its basis, then it will then be added to its own frequency register. Will delete it is okay, so like if the frequency is saying closed, it is called WAN, then the van owner is of this key, then the WAN is of this key, then what is the value of this delete, if it is deleted from the key value, then it is deleted from the position. Okay, now from here too, the minimum frequency in the Datsun frequency list has been deleted, which was Pop Front, that is, delete the front element, we will have only this. If you want to insert, then it is simple, tell me by commenting because but officer for the first time. Inside, his account will be van, ok, van wala pay and pushed back that there is no problem, he is on position, pay and frequency list is not from van wala, nor from his end, he is pointing to the end but us. We need mines so that the new block we inserted also gets its address in the frequency. We got its address and updated it. Now we reduced the minimum frequency. Why did we do WAN again because now we have something on the index of WAN. That's why I have divided the frequency, you will understand how to write the important functions, I have written the functions here, let me explain to you what I have written there, see, I am explaining it very well, okay these three. I didn't want to do it by slicing, okay, this is what I sliced, how to do value frequency list and position, do it like this, no problem, this video has gone too long, understand what I am doing, I am coming now. It is okay on put. First comes on put. If capacity comes first, it is okay on capacity. If capacity, I have created a variable named capsity. By doing this dot capacity, what did I do in this capacity, I have given the variable capacity, no problem. Minimum frequency has been set to zero, no problem. Now let's come, we have the first function on put. When put comes on put, what did we say? Check whether the frequency is zero. If sorry, the capacity is zero. If it is zero then please return it. When The capacity is zero so we don't have the option to do anything. Now let's check whether the key that you want to insert is already present or not. How is the key updated? Do we understand the value of what we did? Okay, after updating, what do you have to do, tell me, if it is a case of update, then what we do first is that we updated its values, we went to the value dot and the first is telling the values and the second is telling its frequency. Okay, I called the function named update frequency and returned it and broke it. Brother, what is the update frequency? What did I tell you, whenever there is a case of update or get case, we have to do a common step and What is it? Update its frequency. Now look at that function, what did I do? I did not do anything. Update frequency function. What is called first? Delete the key from the current frequency which is the current frequency. Delete whatever is there in the frequency list. Because its frequency has increased, then what did we do? What is the current frequency telling? What is the value dot second telling? The frequency is in the frequency list, where the list with the current frequency is there, in place of the current frequency we got, we have called it frequency list. We have erased which address is stored in the note, we have deleted it, what we have done is increased the frequency, store it again in the current frequency, without the frequency it will be +1, we will without the frequency it will be +1, we will without the frequency it will be +1, we will directly pay the current frequency plus also. You can do it, but now I had to update it inside as well, so I updated it here, now what we said is that we have recreated the current frequency which is in the frequency list and the new frequency that has come, its current frequency is its own, you want it. New frequency can also be said as per your wish, I have proposed what is there here that wherever we have come, its new frequency which is its plus van, you will be the frequency before the previous one, then it became three and went to the third frequency in the frequency list. And what we did there is that we pushed that now we have to update the position, what is the address of the new address that is created, then what is the position of keep? What is the frequency list of current frequency dot and mines? We would have checked. Is the minimum frequency mentioned in the frequency list now empty? What can happen after deleting it and not the current frequency which was on you? Just this note has been presented on you, so we will read it in future as well. No brother, if it is deleted, if it is empty, then we will change the number frequency to plus, so simple, I have written this step clearly here, check if you have understood, if you do not understand, watch the video for sure, you will understand for sure, please. Friend, please give a little update if you understand the video, so that's the date, I feel good that the children are understanding here, okay now let's come here, okay understand one thing here, what is the understanding that now like It is understood that if by updating it like this then now it is not a case of main update. If new insult is to be done then we will check whether the capacity is equal. What is possible is that the capacity should become equal. Brother, the capacity we have is already full. Delete it. Now who will have to be deleted which is the minimum frequency? If you want to delete the first element of it, which is the first note, then it is simple. What will be deleted? What is the frequency list? The one which has the minimum frequency is okay. The frequency list which is the minimum frequency is on the list. OK, let's check what is the front element. If you want to delete the element which is in front, then when you find the delete key, guess on the value of the delete key and position the delete key. Our mapping was being done at both the places, we deleted both the sides, now we delete it in frequency, so in the frequency list, the first elements which were at the minimum frequency, which was the first element, which was in the pop front, we deleted that which was in the front, that's it now. We will set this, what is the value of the key to be inserted, in the value of the key which we have, it is ok, in that we have added the value 'Kama Van', 'Van', we have added the value 'Kama Van', 'Van', we have added the value 'Kama Van', 'Van', because it is being inserted for the first time, then the frequency of that key will be 'Van', then the frequency of that key will be 'Van', then the frequency of that key will be 'Van', then the frequency list will be given. Will update the ones and will also update the position which came, then what will be the position of keeping? Why are you doing frequency list of van dot and van? Brother, because this is the first time element and its frequency is van. The frequency of the first element in it is the one with van. There are lines, right? We will go there and insert them. I have inserted them. I have taken out the position and set the minimum frequency. We have a van, we have notes A in the frequency list, so I have inserted the frequency, no problem, now we come. If the gate is on the gate, then is the key present? If the key is present in the value, if not, then it will be returned to the mines and if you are doing the gate, then you will have to call the update frequency again in the gate, then the update frequency is called, that is fine. We reduced ours and returned the value of key dot first because here the value has to be retained, we are updating the values by doing a little bit of empty gate updating the values by doing a little bit of empty gate updating the values by doing a little bit of empty gate but we have to take care of the one who increases the frequency, we have inserted Given simple, now let's submit it simply, so simply accepted and I hope you have understood this thing. Please friend, if you like the video then tell us by commenting below, brother, did you understand, brother, there was a doubt, brother, you can do it like this, I told you here. I even thought about it, which gives me motivation, am I really interested in learning and did you really understand, please don't leave after watching the video, you will get a lot of confidence after completing it, thanks a lot, see you next
|
LFU Cache
|
lfu-cache
|
Design and implement a data structure for a [Least Frequently Used (LFU)](https://en.wikipedia.org/wiki/Least_frequently_used) cache.
Implement the `LFUCache` class:
* `LFUCache(int capacity)` Initializes the object with the `capacity` of the data structure.
* `int get(int key)` Gets the value of the `key` if the `key` exists in the cache. Otherwise, returns `-1`.
* `void put(int key, int value)` Update the value of the `key` if present, or inserts the `key` if not already present. When the cache reaches its `capacity`, it should invalidate and remove the **least frequently used** key before inserting a new item. For this problem, when there is a **tie** (i.e., two or more keys with the same frequency), the **least recently used** `key` would be invalidated.
To determine the least frequently used key, a **use counter** is maintained for each key in the cache. The key with the smallest **use counter** is the least frequently used key.
When a key is first inserted into the cache, its **use counter** is set to `1` (due to the `put` operation). The **use counter** for a key in the cache is incremented either a `get` or `put` operation is called on it.
The functions `get` and `put` must each run in `O(1)` average time complexity.
**Example 1:**
**Input**
\[ "LFUCache ", "put ", "put ", "get ", "put ", "get ", "get ", "put ", "get ", "get ", "get "\]
\[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[3\], \[4, 4\], \[1\], \[3\], \[4\]\]
**Output**
\[null, null, null, 1, null, -1, 3, null, -1, 3, 4\]
**Explanation**
// cnt(x) = the use counter for key x
// cache=\[\] will show the last used order for tiebreakers (leftmost element is most recent)
LFUCache lfu = new LFUCache(2);
lfu.put(1, 1); // cache=\[1,\_\], cnt(1)=1
lfu.put(2, 2); // cache=\[2,1\], cnt(2)=1, cnt(1)=1
lfu.get(1); // return 1
// cache=\[1,2\], cnt(2)=1, cnt(1)=2
lfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.
// cache=\[3,1\], cnt(3)=1, cnt(1)=2
lfu.get(2); // return -1 (not found)
lfu.get(3); // return 3
// cache=\[3,1\], cnt(3)=2, cnt(1)=2
lfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.
// cache=\[4,3\], cnt(4)=1, cnt(3)=2
lfu.get(1); // return -1 (not found)
lfu.get(3); // return 3
// cache=\[3,4\], cnt(4)=1, cnt(3)=3
lfu.get(4); // return 4
// cache=\[4,3\], cnt(4)=2, cnt(3)=3
**Constraints:**
* `1 <= capacity <= 104`
* `0 <= key <= 105`
* `0 <= value <= 109`
* At most `2 * 105` calls will be made to `get` and `put`.
| null |
Hash Table,Linked List,Design,Doubly-Linked List
|
Hard
|
146,588
|
1,329 |
One We are We are We are going to clear the solution Soft Matrix Regularly Okay, so let's see this question, what is the best one, we will get 11 class tenth invitation matrix in food, M cross tank and eminent people cannot be okay, possibly different If possible, like this cream, it has some three, this is from one to hundred, 100 means that their range is either made, then there is some disturbance in between 170, so now what do we do, we have got this input, today we will tell you. We have to return this font for and as it is, so if we talk about it on a regular basis, then finally 123 Okay, so if we look at the point window in this from top to bottom, then it should be clear, come on this is haunted. It is on this and it is a solid and spoiled sport, either if you want to download it or listen to the song, then you will do it from your account because if the ghee is limited, then in this you can use more than one hundred to one hundred, okay, first of all green diner pendant. Like I have gone to this dinner that Sindh P that loot in this subject that foam in it so this 30 pimples of 2012 which is this 201 is that Jyoti is the maximum this is fine at 400 I have kept the account shot function which is this Aaro Which road will the machine take and which problem will it have to solve? If I have major zero in it, then stop that account, which is this one, which means the designer, which is this one, will fold it and give it to him. If I get him zeromile 2 this. The one who will put the starting key will fold it and give it. If I send 108, then that is this one's line, he will go after softening it, so the one who will write something like this will write a normal control, okay, this will put a call to the bangles in the account that you and C, this is this time, please contact this diner, okay, so how am I going to apply for that account, as if someone does all the diagnostics, let's pick this one, see, we have sent something in this, domestic is okay for which one? If we have to take action then we will explain what is the size of the map called 101 Reliance because we have values from one to hundred so it is okay to close my ns200 so that is why I have started traveling at the same time now if you like this recipe I am traveling, so I took the idea, I C, I made tissue travel, till the time we enjoy and validity towards Vid U, we will do the first test match, we will start the create, then see how for me, if I came here like me, then it is okay. Meaning, I will go to this time by doing the frequency plus of *. Quietly well, frequency plus of *. Quietly well, frequency plus of *. Quietly well, subscribe that whatever value is there on the metric hole, I will like that 80 of yours. Please like and what is to happen after this, I plus and A plus, so what is the result of this. I When I'm doing something else in this diner, okay, which one will I come to first? 0.11 shift up, I will come to this one, 102, okay, 0.11 shift up, I will come to this one, 102, okay, 0.11 shift up, I will come to this one, 102, okay, you are one, three, two, Means I10 Magna Plus, here our map will be created, in the map it will be that How much was the appointment of something means guest means loot a little bit of Ajay Jhal is basic account and stability Jhal tractor check here whether it is pimple or not the length of all problems now I came another interesting loot started thinking like this and here But if I have time days here and end columns, then first of all it is fine till 0021 207, how will it work in this, after 1045 104 100, there is add option 2030 020, first of all I have called people go from equal to zero to organizing study account. Control whom to take this matrix only IS Road New Delhi-110003 Delhi-110003 Delhi-110003 then take this how to do this and subscribe to 159 do this matrix is forced with 100 159 do this matrix is forced with 100 159 do this matrix is forced with 100 notice this here it is zero earning this is forced how 2010 setting parameter in this It is written here that the channel is the first parameter change, so let's go here now which Phalke award function I have done so right, so there is so much account function properly which is caused by some sort of matriculation or there will be a problem in the morning, it is okay. Senior Court copy pastes from behind. Okay, now see, now I have kept I in zero, I have kept Echo in zero, many people have back 1 lakh pending that the first set of A was created map that one map show how many size albums that Sanjay Leela Bhansali sa after this class tractor film app hai pata khush doing r best travel karo aur app in it again kaise ho ki jab tak aayi is length hai and jainism end tak plus kya hai abhi sakta matrikar map ke aayi end here But after coming plus it means this is ours or again how to check two my tab page I am traveling ok plus this will have to be drank America is that glycerine look till the value of i on my map is with letter and which is due to which that character Minimum so what will I do Matric Dhak kar donga main hai andhasvishwas i plus ek bus aur ek aur cheez hai Previous Song Play Ko Share - - Treasure End yahaan par aa raha tha Ko Share - - Treasure End yahaan par aa raha tha Ko Share - - Treasure End yahaan par aa raha tha main for kids hai to ek bachche aate hain isse chord Ajay ko jhal lootere some Ujjain ok Ajay ko jhal looter ki a this map ajay ko this body leaving is good and here Abhishek is at matriculation level rock band does that you have created the situation see this is a mistake I am in this I pass, it came from zero, this means that if there was such a matrix, 0345 to 100 districts, the NDA's effort was ok, it was not done, let's submit, ok, so we are getting accepted, two in the next video.
|
Sort the Matrix Diagonally
|
minimum-cost-to-move-chips-to-the-same-position
|
A **matrix diagonal** is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the **matrix diagonal** starting from `mat[2][0]`, where `mat` is a `6 x 3` matrix, includes cells `mat[2][0]`, `mat[3][1]`, and `mat[4][2]`.
Given an `m x n` matrix `mat` of integers, sort each **matrix diagonal** in ascending order and return _the resulting matrix_.
**Example 1:**
**Input:** mat = \[\[3,3,1,1\],\[2,2,1,2\],\[1,1,1,2\]\]
**Output:** \[\[1,1,1,1\],\[1,2,2,2\],\[1,2,3,3\]\]
**Example 2:**
**Input:** mat = \[\[11,25,66,1,69,7\],\[23,55,17,45,15,52\],\[75,31,36,44,58,8\],\[22,27,33,25,68,4\],\[84,28,14,11,5,50\]\]
**Output:** \[\[5,17,4,1,52,7\],\[11,11,25,45,8,69\],\[14,23,25,44,58,15\],\[22,27,31,36,50,66\],\[84,28,75,33,55,68\]\]
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 100`
* `1 <= mat[i][j] <= 100`
|
The first move keeps the parity of the element as it is. The second move changes the parity of the element. Since the first move is free, if all the numbers have the same parity, the answer would be zero. Find the minimum cost to make all the numbers have the same parity.
|
Array,Math,Greedy
|
Easy
|
1895
|
503 |
we're going to take a look at a decoy problem called nest greater element number two so this question is very similar to the nest greater element number one question so i highly recommend to check out that question before this one so basically what we're trying to do is we're trying to find the nest greater element for each and every single element that we have in the input array but the input array this time is a circular integer array right so you can see the next greater element number of each and every single element in the array is the first greater element to its traversing order nest in the array so which means that you sh you could search circularly to find an escalator element if it doesn't exist then return negative one for this number right so you can see here we have an example of one two one so one the next greater element in this case is two so we put two at this position and then for number two right the next greater element is just gonna be negative one because in this case there's no element that are greater than the current element right and then one in this case we can search circularly right so we look back and in this case what we can do is that the next greater element in this case is basically two right so in this case um you can see here we also have another example right we have something like this so the next greater element for one is two is the next greater element for two is three then that's greater elements for three is four right so four at this position and then that's greater element of four in this case even though if we search circularly right still is nothing right there's no element that are greater than four so we put negative one here and then for three the next greater element is four right so we just loop back we circular or we circle back and then the next greater element in this case is four right so you can see here the constraints that we're guaranteed to have at least one element in the array and then for each and every single element we could have a negative value we could have a positive value right so in this case how can we solve this problem to solve this problem what we're going to do is we're going to do very similar to what we did in nest grader element number one so we're going to use a monotonic stack to solve this problem basically a monotonic stack is like a stack but we're just basically keeping the ordering of each and every single element that we have in our stack in a increasing order or a decreasing order right so let me show you why we should use this so let's say we have this is our input array uh we're starting from the first index right from the first element that we have in our array and then what we're going to do is that we're going to have a result array that's what we're going to return at the end right we're going to return the result array at the end basically filled with each and every single element's nest greater element right so what we're going to do is that we're going to have our stack and then we start at the first element so if the stack is empty we just insert it right onto the stack and then um what we're going to do is that we're going to move on to the next element in this case then this element is 2 right sorry we should we're going to insert the index of each and every single element onto the stack so in this case for element 1 has index 0 so we insert it onto stack uh so we inserted zero right onto the stack um so we're gonna do is that once we visit this element in this case this element is actually greater than the top elements right that we have on our stack in this case nums as zero right so the current element right if the current num is greater right it's greater than nums at stack dot peak so in this case if that's the case then we're going to do is that we're going to pop the top element off the stack and then we're going to say result at index 0 is actually going to be the current num right because we just found the nest grader element for the top element that we have on our stack so we pop that out right and then we're going to say for this for index 0 and result is going to be two right and then what we're going to do is we're going to move our element or our pointer one to the right so before that we have to insert this element's index onto the stack because we haven't find the nest grader element for this current element right so in this case it's going to be index one so what we're going to do then is we're gonna move our pointer one to the right so we have element four is bigger than the top element that we have on our stack right in this case nums uh nums at one is basically two so in this case two is less than four so we just say at index one the next greater element is four okay we pop that element off the stack okay and then we move our pointer one to the right but before that we are going to add this current element's index in this case is two onto the stack because we haven't found an escalator element for this element right so we move our pointer one to the right and the reason why we're using this stack this time is because we want to find the most recent the most up-to-date the most um up-to-date the most um up-to-date the most um nearby greater element right so in this case we have to use the stack to be able to find the last element that we inserted right now we haven't find the net squared element right so we can be able to compare so the next element is three so three in this case is actually less than uh it's actually less than four right or less than num set two so in this case we just have to add this element onto the stack because we because three is less than four right it's not greater than four if it's greater than four then we find the net square element for four but in this case it's not so we have to put that on the stack so in this case we have two elements that we have not find the next greater element so we're going to do is that we're going to circle back we're going to do our one more iteration right for less greater element number one question we probably can just return this result array right but the thing is that in this case we have to find we can be able to circle back we can be able to search circularly right to find um the next greater element right so in this case what we're gonna do is we're gonna start over right we're gonna iterate one more time so basically total we iterate the nums array two times so in this case one we're basically trying to find the next greater element on for the top element that we have on our stack right so this is our top element that we have on our stack so in this case we basically iterate so one is le is less than three two is less than three four is not less than three so in this case we're going to uh pop the top element off the stack so num set three is basically three right four is bigger than three so in this case uh four is basically the next greater element for index three right so then what we're gonna do is we're gonna move our pointer one to the right so the top element that we have is basically four right so you can see that before that you can see that our stack is in the increasing order right so this is our top element on our stack this is our um this is our uh the nest element right so in this case you can see that we have a deep uh increasing order or decreasing order it doesn't matter how you say it but basically you can see that it's basically sorted right so you know that top element is always less than the um the lower elements that we have on our stack so you can see that what we're going to do then is that we're going we know that we moved our pointers one to the right so in this case this element is not greater than in this case num at two so therefore we move our pointer one to the right and now it's out of bound so you can see that therefore we just leave it as negative one right in this case we cannot find it so at the end we just return this integer array so in the code basically we um we do exactly that right so in this case we have a stack to the structure we have our result array which has the size of nums we fill initially we fill the result array with negative one and then we add all the next element for each element onto the result array but if there is uh if there is an element that we haven't find in this greater element of course it will be kept on the stack so then what we have to do is we just have the circle back and we just do one more loop right try to find an element that's greater than the top element that we have on our stack if it is then we just pop it out and the result at current index is equal to no right so current num is basically the nest greater element okay so in this case we just put that there in our result array and then if the stack is empty we can just break out of the loop and then we just return a result right so it's pretty simple and as you can see that the time complexity in this case is going to be big of n where n is number of elements that we have in our integer array right and then the space complexity is also going to be big o of n where we are using a stack to keep the elements right and the worst case scenario we're inserting each and every single elements onto the stack right where for example let's say we have like five four three two one in our input array then we're basically inserting five four three two one onto the stack so therefore the space complexity is basically going to be big of it right so there you have it and thank you for watching
|
Next Greater Element II
|
next-greater-element-ii
|
Given a circular integer array `nums` (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return _the **next greater number** for every element in_ `nums`.
The **next greater number** of a number `x` is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return `-1` for this number.
**Example 1:**
**Input:** nums = \[1,2,1\]
**Output:** \[2,-1,2\]
Explanation: The first 1's next greater number is 2;
The number 2 can't find next greater number.
The second 1's next greater number needs to search circularly, which is also 2.
**Example 2:**
**Input:** nums = \[1,2,3,4,3\]
**Output:** \[2,3,4,-1,4\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-109 <= nums[i] <= 109`
| null |
Array,Stack,Monotonic Stack
|
Medium
|
496,556
|
1,372 |
Hello everyone welcome, we are going to do video number 25 of my channel 1372 but it is a story based question, you will write a story and it will become a question, so it is actually easy, ok, so let's move ahead, the name of the question is Longest Zigzag text, is n't it binary, it is ok but more. It is not okay, you will write the story, it will become very easy from the story. Generally, the question of Reconciliation can be completed only by writing the story. Okay, in this question it was said that you will be given a binary, you have to tell the length of the longest zigzag text and What does it mean that if we take mother and go left then after left we have to go right? After right we have to go left, it is not that after left we then go left, it cannot be like this, we have to go left right left like this, okay then as if we take mother. Pay attention here, I went right from here, then went left from here, how many passes did I get, one or two, but if I start from here, went right, went left, then this is where I will tell our answer. Okay, let's see from one approach, very basic Saroj. It will be okay, you will also improve this and tell us an approach. So let's come to approach one. So look, understand approach one like this, you are standing here right now, this is a route, so it is possible that you might have left side. Okay, you may have it on your left side, you are on your own, okay now you are here, what will you tell your left side that brother, you go to the right direction from your side, only then the zigzag thing will be made, right brother, you love. Even if I know, the word 'Jiksak' will right brother, you love. Even if I know, the word 'Jiksak' will right brother, you love. Even if I know, the word 'Jiksak' will be formed, it is clear now, see what it means, here I write it is right for my love, what does it mean that if you have said your left side, then you have already reached here, it is okay. You see, okay, I have been told to go right, okay, so I am fine, I will definitely go right, I will go right, what does it mean that I have been told to go right, and I am also going right, what does it mean that The thing is that it will become even, there was one here you were because I am going right, I am going zig zag because I was told to go right but if I go left then it is okay if I go left. So okay I will start a new lesson here value will be one okay so started a new one from here why did you do it because zigzag is being formed okay similar here if you took mother you came here okay So, were you told that brother, if I want to go left, then it is okay. If I go left, it was here, then by doing plus one here, you will go right, but if I go right, then now I will have to start a new lesson from one because I was told to go left, if I go left then there will be plus one i.e. you will be there and then there will be plus one i.e. you will be there and then there will be plus one i.e. you will be there and if I go right then one will have to start a new lesson. Okay why will I have to do a new password because brother I was told to go left but I will go right. I am here, right? What will happen to me, if this will not become my object, then a new lesson will have to be started from there. Okay, so think of something that you believe in being here. Okay, then you should be told two things: Shakti, Goal, Left. You were told to go left, okay you were told to go left, so what did I say? If you were told to go left, then okay, I will go left. Okay, I will go left. Whatever my steps were, add plus one to it. I will go right because it is going to be exact, because I was told to go left and I am going left, that means I will go ahead by doing plus one in the steps. Okay, if you go your way, it is okay to go right Okay, obviously. It's a strange thing, why are you saying this now because so that you can get the zigzag pass, but if I went to the right of the route, I was told what, I was told to go left, but I went to the right of the route, so now I will start from one, okay and If I go right, that is, I took the mother, I went right, then what will I say to the person in front, that brother, you go left, that means, what will I say to the person in front, that brother, it is okay to go left, that means we are passing the message to the people in front of us. The guy asked where do you want to go, okay so we will do it tomorrow, I have written a function named solve, I saw him saying ok, I have to convert it from story, I made a story, wrote the story, now look, I have written the solve function, now I understand that Yes, let's write the function only, okay now let's come here again, if I had been told to go left then this would be the story. If I had not been told to go left then I would definitely go to the right. Okay, I have to go right. What was told to me? If I go right for my life then it's an obvious solution. If I go right for the route, it's okay. I was told to go right for my love, so if I go right then it's a matter of course, I will go by doing steps plus one because I was told right, love and right. I am going so that it can become one, okay and let's see here, you have the right of the route, it means what are you doing, you are going on the right of the route, so now you are like that, what will you tell the person in front, brother, then left. Go, then what will you write here, goal left is ok till now it is clear, after that if we take mother, I went left, I was told to go right but I went left, then a new lesson will start from one, it is ok i.e. then a new lesson will start from one, it is ok i.e. then a new lesson will start from one, it is ok i.e. You are going left and if you go left, then what will you tell the child on the left that brother, go right so that the matter of exit can be resolved, then I am sending the right here, okay, it is clear till here, right, and the left here is okay, now attention. Two, what am I sending here? I am sending it right, but I will send it here, that is, I am saying that it is okay to go right. Pay attention, I am repeating again what I said here that I was going right. What will I say to the person in front that if you go right then it means that brother, don't go left then I will send left in the left variable that brother, it is okay to go left only, on this I will send true, here say right for the sake of life, say six. I am okay, he himself will understand that brother, I have to go right, okay, I will go less than left, okay, so this has to be done, if it is not true, then it means that if you have definitely said the right for your life, then it will go only in health, okay and What I will do every time, I will create a variable, talk max text will be starting, only then it will be said, then I am doing sex plus one, but if I go reverse right, then I will start from one, then you have seen, then I will try both the possibilities. I am looking for a place from where I can get the maximum pass. Okay, similar here too. Right was said for life and I am going right, so to give sex + 1 right We have also written the code, so now we will write the code. What did I say to write? Let's keep a global variable named max text. We will keep it zero in the beginning and then we will keep updating it later. Okay, I had a function named wide solve. What was I sending here in these three notification routes? Steps, how many steps can all be taken and one bid is a variable, should brother go left or right? First of all, check that brother, if the route I have taken is correct, then return it, do nothing. Route N is done, okay, and one thing I told you is that every time we will keep updating the max point, comma steps on max of max, whatever we are getting, now after this you have two things, a power that if you get the goal. You have been told to go left. If you have been told to go left then it is okay and if you have gone left then it is good. It must be making a zigzag. Then subscribe plus one. Okay, if I go left then the one on the left. Tell the guy that brother, don't go left, go right because now we are making zigzag, okay then go left, we will send water to the left, okay, I was told to lie down, but if I go right, okay then a new one. The thing is that I will tell the person in front that brother, you go left because we have to make a zigzag, so you are sending me to the left, okay, you are seeing the benefit of the story, see how clean it looks from the story, right in writing the code, solve me right. It was said for the sake of my life and I went on the route right, okay then we will do steps plus one. It was said that right, I am going right, it is okay and further, when I am going right, I will tell the person in front to go left. If I go then I will send it true, it is okay because we have to make a zigzag. I was told to go right but if I went left then one will come here, a new lesson will start and if I am going left then I will tell the person on the left that brother, don't go left. Going forward, if you go right, do n't go left, it will be done tomorrow and I will be updated with Max, okay, so now look at what I said here that in the goal left, either true will come or water will come, okay so when I will do it for the first time tomorrow. So it is obvious that we would like to try both the things, once we will try left, once we will go left, whichever one gives a good answer, okay, once I will say brother, go left and once I will say route setting, do n't go left. Going right, wherever I get the maximum pass from both, I will just return the max text. Okay, it's a very simple story, the story and the correct one, they have passed, which is the best cases, they have this question using approach one. Okay, that's why I have to speak, the questions of the tree of questions are made very well from the story, make a story, just convert it into code, okay, so this approach is one, you go to your approach, now see, you understand every day, how to take neither or two in this. Let's go, how one is fine, so see, understand something like this, we know what we will do, we will store two counts on each note, that means, brother, we will keep in mind how much count is running on the left and how much account is running on the right, okay. Either this is called la coma r like this, we go by the mother, okay, so as if we believe, then we take the mother, we have a trick like this, right now, this is the root and there is a child here, okay, there is a child here. And here also there is a child route, so what did I do because right now, look, pay attention, from here, where can I go from here, can I go left, okay, so now I went here, okay first. I was here, now I went here. Okay, so now tell me one thing, how will he know that I have come from the left? How will he know that I have come from the left, there is a left here, so what will he do to know that? The thing is that this route will have to send something to the guy, he has come from the left. Okay, so what will this route do? This route will send it to its own person, but what will he send, guess what will he say that brother, you have come from the left. That's why I am sending the value of your right side to be zero and the value of your left side, I am sending plus one to my value, okay, it is clear till now, it will be more clear in the future, don't take tension, okay, this guy will take care of it, okay, what is this? In this, it is from the left, right value is science, the value of left is one, that means I have definitely come from the left, okay, this is clear, okay, now look, now pay attention, now let's take this Banda Maa, went to the right, will also go to the left, later first. Let's take a look at the right is gone, okay, so now you are here, okay, so you don't know, does he know a little about you, how will you know from the right, then what will this guy do, what will the upper parent do, he will take this as his own. This one will send it but he will send it right, brother, you have come from the right, then what will it mean that if it is right then the value of left has been reduced to zero, this fellow will not come from left, so if from right. Even if he has come, what is the length of his text, then what will he do, what will this guy do, he will say that brother, I am sending the value of my left by adding plus one date, it is 2, it is fine and now pay attention, it is going absolutely correct. Look at our zigzag lesson online, you are one and these are two. Okay, now let's move ahead. The more you move forward, the better it will be cleared. Okay, now where can this guy go from here? He can go left, okay? Now, how will he know that brother, I have come from the left, how will he know, then what will this fellow do, he will send his button to this person and see how he will play the button on the right, he will send it by adding plus one to it, he will send it by doing 3. Now look, now look. This is the right thing, we are going absolutely correct, look at the time of our cigarette talk, it is three, we were going absolutely correct, right, now look here, now let's take the mother that there are five choices in this, go left from here, if you go left. Okay, if we go, we will check both the places where we can get a good answer. Like, here I have got a three, otherwise I will keep updating that yes, after max, I have got a three, it is okay now, let's take a left from here. If this person knows a little bit that he has come from the left, then what will he do to tell, he will pass it on to the left and right person and will say that brother, you are sending the value of our left and right is zero and what will be the value of your left. The value of my right plus one is also correct, this is a new chapter of this thing, see, it is not being made, where is it being made, it has started from here, it will become a straight line, information has been sent to the note, okay one comma. By doing zero, send your information to him. By doing zero, comma, it is okay, in the left one, it has become the right value of plus one. Why, because it is going zigzag, left right, it is going like this, okay, till now it is clear. So now how do you see, okay, it is absolutely similar, there is nothing new in it, how are you, I, what is this, the root was made here, look at it here, let's take the right here too, okay. It is right here, how does this fellow tell it that it has come from the right, he gives it his own, okay, I have to write here but if it has come from the other, what will he do, will he send zero for the left and what will be the value of the right key? Value plus one came here, okay, then from here we take mother, left is okay, but to show that you have come from left, the value of right will be made zero and it is related to the value of left, how come there was no mention of 12 here, I was My point was that what you are sending, how are you sending it? Okay, so look here, you have got the text, don't look here, you have the maximum value, so we will also keep checking every time that our max. The value of the text is and the value on the left is the maximum which will be in any stage. Okay, now you pay attention, see the best part, I am repeating it again, the story has to be written, so sorry, now we understand. Now see how well you will write its code. What did I say that right now I am in the root and the value of my left is zero, the value of right is also zero, okay, I solved it yesterday, okay Max. But the one which is mine will keep getting updated. It is a global variable, it is ok till now, it is clear. Now look at the solve function which is mine, what I told you, in this I am sending the root and I am sending the left, I am sending the right. It is ok till now, it is clear here. In the return thing, if I am going left, okay, I am solving, if I am going left, look at the left of the root, pay attention, how will I tell the left of the root that brother, you have come from the left. What will I do? I will send the value of the right key to be zero. Here, I have sent zero, otherwise the left one will know. Well, my right one is zero, which means that I must have come from the left. Okay, and which value of mine will I send to that one? I am in the root of science. If I am going left, then this guy who is the root will send the value of his right plus one, he will send r+1 to his left and if I am going right, okay then how will I tell the right guy about the right of the route. How should I tell the person to whom I am going that brother, if you have come from the right then what will I do, I will send zero to his left, this is what I was sending, I sent zero to the left and I will say, if I have sent zero to the right, then he will understand that I am good. I have come from the right, I am sure I will come from the right, it is okay and the value of right left is sent to the left as zero and what will be the value of right, the value of its left i.e. whatever be the value of right, the value of its left i.e. whatever be the value of right, the value of its left i.e. whatever is L is plus one is fine, send your left plus one to its right. Why is it given because making zigzag is simple and every time we will keep updating the value of max text it is equal you max of max text left and right and 's it is max text left and right and 's it is max text left and right and 's it is even more simple understand it no repeat it and see it once again dry and also You can see, but you have heard this story, it is nuff, whatever will be the value of its left, whatever will be its sum, it will go to its right as plus one and it will go to its left as plus one, okay and so on, so it is exactly the same. Look, the right side of the root went to the left. Okay, the value of the right side here was sent to the left side of the root. By doing plus one, if we went to the right side of the root, then the left side of the right side of this side, the value of the left side of this side was sent to the right side of it. Plus one, then why are you doing this because we have to make a zigzag? We have to make a zigzag, so let's convert the story into code. Okay, this is the old code, let's remove it. Okay, what did I say here? I will do it only once tomorrow, the value of right is zero, okay and here I will take left and what will I take here, then make it zero, I am removing all the rest, I will be okay, now what did I say that brother Max text is equal. Tu max of max text left and right, I will go to the left of the root, I have come from the left, so I will send the value of its right as zero and in its left, I will send the right plus one of the current, why send right plus one because I am going to be rejected, okay. Solution: because I am going to be rejected, okay. Solution: because I am going to be rejected, okay. Solution: If I go to the right of the route, then how will the person to whom I am going know that I have come from the right? How will I know? I will send zero to his left and to the right I will send the left plus one of the current. Why am I sending the lesson in a zigzag manner in the hope that it will be created next? I am sending it by adding plus one. Okay, this will make my entire code. It was a very simple story. I think this is a more buttery code as well. Submit it and let's see. It should get submitted. You can write different types of reviews. Okay, but I think these two are the best, that's why I have told the story of these two. Okay, if you have other approaches, please write in the comment area. Share it in it will be even better, so you can see it in the next video, thank you.
|
Longest ZigZag Path in a Binary Tree
|
check-if-it-is-a-good-array
|
You are given the `root` of a binary tree.
A ZigZag path for a binary tree is defined as follow:
* Choose **any** node in the binary tree and a direction (right or left).
* If the current direction is right, move to the right child of the current node; otherwise, move to the left child.
* Change the direction from right to left or from left to right.
* Repeat the second and third steps until you can't move in the tree.
Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).
Return _the longest **ZigZag** path contained in that tree_.
**Example 1:**
**Input:** root = \[1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1\]
**Output:** 3
**Explanation:** Longest ZigZag path in blue nodes (right -> left -> right).
**Example 2:**
**Input:** root = \[1,1,1,null,1,null,null,1,1,null,1\]
**Output:** 4
**Explanation:** Longest ZigZag path in blue nodes (left -> right -> left -> right).
**Example 3:**
**Input:** root = \[1\]
**Output:** 0
**Constraints:**
* The number of nodes in the tree is in the range `[1, 5 * 104]`.
* `1 <= Node.val <= 100`
|
Eq. ax+by=1 has solution x, y if gcd(a,b) = 1. Can you generalize the formula?. Check Bézout's lemma.
|
Array,Math,Number Theory
|
Hard
| null |
1,022 |
in this video I will solve with you challenge number 1022 some of route to leave binary numbers so in this challenge we are given a binary tree each node of these three has value of 0 or 1 and each pass from the root to one of the leads represents binary number and our task is to compute the sum of all binary numbers represented by the passes from root 2 weeks ok let's look at the example shown here so let's take the rightmost path it has value 1 it's a binary number and to compute this number we will multiply its first digit by square of 2 will multiply it second digit by the last digit by we will multiply it by okay we'll get someone here but we can write the same expression in another way you can write it this way two times one plus one so why do I write it this way because we can solve this problem recursively so at each level we can pass a number we will start from N equals zero we'll pass to the first level of the tree and then we will multiply this number by two at each level and we will add the value of the current node to it so in this case it's one and number is zero so our current number at this level would be one and equals one then we'll pass it to the next level we will do the same calculations here so multiply it by two and we'll add one to it so and would be three at this level and then we'll pass it here we'll multiply by two add one and seven here and in the case of this node whoo-hoo it would be six in case of node whoo-hoo it would be six in case of node whoo-hoo it would be six in case of this node will multiply and by two and zero and would be in this case we'll multiply it by two and at zero it would be four and in this case we'll also add one to it so it would be five and now for each node who will compute the sound it's children so it's clear DS so for dese notice our children is 6 plus 7 which is 13 for this note it's 4 plus 5 which is 9 and for this note it's 9 plus 13 which is 22 so the answer is 22 and now let's write the code so we will use digital parameter here which is n we will set each default value to 0 and each iteration will multiply by 2 and add the value of current not to it so what's its name is node not root node and its value is so then we'll check if note is no then we will return and because eat sleep this is the base case of our recursion but now we will compute okay so if note left is now here are then the left sum is zero and if it's not then we'll call this function recursively is note left and we'll pass an to it and we'll do the same for right note so right some note right now are the same here and then we'll turn left that's right okay let's check this solution okay it was accepted um please subscribe my channel and ask me to solve another early code video and thank you for watching
|
Sum of Root To Leaf Binary Numbers
|
unique-paths-iii
|
You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit.
* For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`.
For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return _the sum of these numbers_.
The test cases are generated so that the answer fits in a **32-bits** integer.
**Example 1:**
**Input:** root = \[1,0,1,0,1,0,1\]
**Output:** 22
**Explanation:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
**Example 2:**
**Input:** root = \[0\]
**Output:** 0
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `Node.val` is `0` or `1`.
| null |
Array,Backtracking,Bit Manipulation,Matrix
|
Hard
|
37,63,212
|
144 |
hey there welcome back to lead coding in this video we are going to solve the question binary tree pre-order traversal question binary tree pre-order traversal question binary tree pre-order traversal so we have already covered the inorder traversal of a binary tree and in this video we will be covering the pre-order video we will be covering the pre-order video we will be covering the pre-order reversal using both the recursive as well as the iterative solution and the iterative solution is frequently asked in interviews so let us see what is a pre-order so let us see what is a pre-order so let us see what is a pre-order traversal we have a tree a binary tree and if you want to perform a pre-ordered and if you want to perform a pre-ordered and if you want to perform a pre-ordered reversal on this tree so initially we are at the root node which is one and as the name suggests a pre-order and as the name suggests a pre-order and as the name suggests a pre-order traversal means the value of the root will be printed the first so one value will be printed and then we are going to go to the left subtree so this is the left subtree and when we send this to the recursion or to the same function then we pass 2 as the root and the same thing is going to happen here as well as 2 is the root so 2 is going to be printed and left subtree will be called so here the left subtree is 4 and the root itself is 4 so 4 will be printed again the left sub tree will be called which is null and we will return back to the root now the root is going to call the right sub tree and in this case the right subtree is null as well so it is going to return back now when the flow is going to return here as we have already covered the left sub tree now a call will be made to the right subtree and we can see that the right subtree here is null so it will be returned back and it is going to return to one now one is done printing itself and then it is done printing the left subtree now it is the turn of right subtree so one will call to three now three will be passed and the root here is three so three will be printed and again three is going to call to the left sub tree which is null it will return back and to the right subtree which is null again so it will return back to 1 so this is the pre-order traversal of so this is the pre-order traversal of so this is the pre-order traversal of the given tree now let us see the recursive solution for this so let us say we have a function help so this is going to print the pre-order traversal of any tree the pre-order traversal of any tree the pre-order traversal of any tree which is passed to the function help now help is going to receive the root so the first statement in the function should be to print the value of the root so the value of the root will be printed the next statement will be to call the same function help on the left subtree and then the next statement should be to call the same function help on the right subtree now there should also be a base condition and that base condition would be to check if the root value is null so if it is null we simply have to return back so that will be the base case of the recursion now let us go and try to code this out so first we are going to see the recursive solution let us create a helper function here avoid help and it is going to receive two arguments one is to store the value of root and another one is a vector of int answer and as i told you the base case when root is equal to null then simply return back otherwise store the value of root inside answer that is equivalent to printing the value of node so answer dot push back roots value then the next statement is to call the same function on roots left this is the left sub tree and then call the same function on roots right that is the right subtree now here let us create a vector of hint answer and let me call this function help and i will pass the value of root and answer and then i will return answer let us try to run this and we should make sure that we pass answer as a reference so we are getting correct answer let us try to submit this now and it got accepted now this is a very simple solution and most of you must already be knowing this so what is asked in the interview is the iterative process the iterative solution to the problem and now let us go and see the iterative solution now let's see how we can implement the same using iteration now whenever we are performing recursion we know that an implicit stack is being made so in order to do it explicitly we can use a stack as well now we will see using a stack how we can implement the same thing so let me just get rid of this all right now let us have a stack so it is going to be our stack now we had the tree as one two three and four now first of all we are going to put the entire tree onto the stack now how we can put the entire tree a tree is denoted by the root value so we are going to insert the root value onto the stack so once the root value here we are going to insert it into the stack and that means that we have kept the entire tree onto the stack so initially we have the entire tree so we have one two three and four now we are going to pop this out and after popping it we are going to print the value of the root so one will be printed and then we are going to disconnect the left as well as the right subtree so we have the left subtree as this and the right subtree as this now this is the root that denotes the left subtree and this is the root that denotes the right sub tree now we know the concept that whatever we are inserting onto the stack later is going to be popped out first so as we want the left subtree to be printed first before the right subtree so we are going to insert the right subtree first so we will be inserting three that means the right subtree onto the stack and then we will insert the left subtree which is 2 and 4. so now there are two values on the stack now again we are going to pop this out so we will be popping out this tree so this tree as soon as we pop out this tree we are going to print the value of the root and that is equal to 2. again we are going to distribute it into left subtree as well as right subtree so four is the left sub tree and the right sub tree is null so we are not going to insert null we will simply insert four that is the left subtree so let me get rid of this and insert four now when we are going to pop out four we are going to print it and then we will see the left and the right subtree both are null so nothing will happen and same is the case with three so three will be printed so finally this will be the configuration so this is printed first then two then 4 and then 3. so now let us see how we can implement this using c plus let me create a stack will be of type pointer to tree node and we are going to insert the entire tree into the stack so s dot push the root denotes the entire tree also we should handle the case that if root is equal to null then we can return the answer from here and what is answer is a vector of int which we are going to return finally so this is the root we have inserted the root onto the stack there's only one value onto the stack right now so while s is not empty or s dot size we are going to perform these operations take out the topmost value of the stack so that is auto a or we can write a tree node pointer auto a is equal to s dot top so now this is the tree and we will insert the value of the root to the answer so as to print it so answer.pushback roots value or ace value and then a will be having some left subtree and some right subtree so first of all we are going to insert the right subtree because the right sector is the one that we want to print later so whatever you want to print first we will be inserting it or we will be pushing it later so we will be pushing the left subtree later because we want the left subtree to be printed first so first we'll be inserting the right subtree so if a is right exist if it is not equal to null then we will push is right and yeah for sure we have to pop this out as well so p dot pop and if is left then insert is left i think that's it after this we have to return answer and let us try to run this we are getting the correct answer let us try to submit and it got accepted so the space complexity in the worst case could be equal to the number of the nodes so it could be big o of n in the worst case and the time complexities of course big o of n because we are going to each of the nodes so this is it for the solution if you like the video please subscribe to the channel please hit the bell icon so that you can get notification to our latest videos thank you
|
Binary Tree Preorder Traversal
|
binary-tree-preorder-traversal
|
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[1,2,3\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
**Follow up:** Recursive solution is trivial, could you do it iteratively?
| null |
Stack,Tree,Depth-First Search,Binary Tree
|
Easy
|
94,255,775
|
1,022 |
Hello hello everybody welcome to my channel its all related problems mom root to leaf minor number se zor fruit lift representative number starting with most valued for example 5000 for lips in the tree white from delhi to the number subscribe Video from this Hair subscribe to that sister Hair to hair and hair to hair the year to all the four lips will have to solve v0 subscribe 30 this 5 second and third earthly one 0 subscribe last wave lift and representation from this point to 4 subscribe to that and a trident to as an answer That show first of all they are converting a representation to the decimal what we will do will start from Delhi significant bete and multiply date with to the power zero and the water number is 12351 Adherent to the power to do this point to 4 plus two In 205 120 subscribe for 10000 Video then subscribe to the Page if you liked The Video then subscribe to and list of spring and convert after finding hollywood lift and convert between passed into decimal and regulatory system and subscribe ka use this point like this and subscribe Number 116 Subscribe Now to Receive New Updates Reviews 100 to 120 B Multiply 23051 Subscribe 250 This Time Double This Plus Patience Take Unique Style to the Next Level Pin Number Weaver Multi-lingual Multiply to subscribe our One Day I Will Call the Left Right of this youth Sameer V0 2069 Vishwa Ise Zoom will convert to in to-do list Radhe Shyam into to plus wave 3823 line 123 subscribe to the Page if you liked The Video then subscribe and subscribe the first of all villagers free mode version for This is absolutely free mode on impossible loot amazon will get 9 news room first will not written e 10 and will check is the current note via processing is left video channel and finally condition for the left and right side channel subscribe button is this divine 210 Cons Updates Value From It's Like Land Acquisition Two Star No A Plus One And Not One The Current Value Of The Root Sudhir And Others Absolutely Free Subscribe Online Free Mode On The Order Root.right End Party Updates The Order Root.right End Party Updates The Order Root.right End Party Updates Amazing Patient Previous Report Subscribe No-Derivative Works subscribe And No-Derivative Works subscribe And No-Derivative Works subscribe And subscribe The Amazing Subscribe What And Expected To What Is The Time Complexity Of Dissolution Live Near Processing All Notes Once Upon A Time And Space Complex It Is The Height Of The Record Memory Clear This Multiplication Channel Subscribe Edition You Can Also On 8 minutes passing all cancer medicines work so let's servi can implement it solution ncrt solution veer user data structure first and will check epheus no like subscribe and subscribe but instead of leading use page subscribe that and different from which is the interior type So initially I will not before starting this track route will not withdraw into the fort and subscribe will update we do number same number will be Vikram the water number is here to * number plus shravan subscribe now to receive new updates Time Will Also Be Able To Find The 210 Is Aap Roz Mirch Use Hai So Pause Video Tried To Implement This Interactive Solution It's Not That You Can Implement So That Is The Solution Implemented Already And Sister Quotes On Complete Raw To Do Subscribe Time After Space Complexity subscribe thanks for watching
|
Sum of Root To Leaf Binary Numbers
|
unique-paths-iii
|
You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit.
* For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`.
For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return _the sum of these numbers_.
The test cases are generated so that the answer fits in a **32-bits** integer.
**Example 1:**
**Input:** root = \[1,0,1,0,1,0,1\]
**Output:** 22
**Explanation:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
**Example 2:**
**Input:** root = \[0\]
**Output:** 0
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `Node.val` is `0` or `1`.
| null |
Array,Backtracking,Bit Manipulation,Matrix
|
Hard
|
37,63,212
|
138 |
Submitted to Live Today When Solving a Question of List Start the Name of the Question is Copy List on Random Contest Video Also Question and a Very Special for Electrification of Doom Swelling List Friend Thanks Giving Subsidies Note Contention National Anthem Point at Which Should Point To in Odisha Health is basically normal list this next point but you are alone with next point this random points inside and important point to fuel mode turn point to make some where suggested to construct a gift from the list and difficult words just exam clear and you Know who where is not have its value from to the value of its corresponding original note that un dimple yadav new notes point to the new 90's play list decoration points exist relation to play list represent the same list say no point in unison point notes in Original list is basically the questions of doing that you have to get duplicate for general list and winning process person duplicate your support to create new note national sports news in doing a copy of the earliest and then returns the u languages and all select initially returns the u languages and all select initially returns the u languages and all select initially e Will give The Lord of the Rings So let's see how to solve this passion for the Let's go to the white board to see how to solve this software According to the question is created list detergent powder and some point and will be using this is what to Do the time complexity of algorithmic revenue records and space of and so let's see how to the question basically what will be doing his light will be creating note and will give to rename app and this point has two origins basically for each of the notes in the original List will be creating separate on annual basis point in map and test cricketer correspondence Vitamin B-12 is that was correspondence Vitamin B-12 is that was correspondence Vitamin B-12 is that was created new notes for your support to create per equal and playing his father in all Android the same thing to be done with the original with new List Narao Apne Alarm Waqt To Basically A What Will Be Doing His Works Were Trading To Original List And Whenever E See No Evil Regretting Notes For Example In Dahez Noida For The Moment So Noida Greater Noida And Chemicals At That Time Files To The Amazing Corresponded Back To Member is snake so lets voice avoid traffic cop in value induced in the next9 indore channel its next notice avoid getting a name doon vikas hi sambhava regional language so lets 500ml store dubai whose respond * 500ml store dubai whose respond * 500ml store dubai whose respond * wife and also validates to and in the moment is seen that Seemed like after now mode electricals and in some extreme cases correspond to see in the voice of love you to the your relax point is point bill should withdraw it to the original linguist and moment regret not in the map see what is a corresponding 220 To But You Aware Next Point Wife And Saint In The Father And Points Suryavanshi Dashrath Border Is Point * C Source Random Point Is Border Is Point * C Source Random Point Is Border Is Point * C Source Random Point Is Point To C Quantum Hai Tuesday Egg The Note Kar Is Point Is Akshar A Bid To Also Point With Jain And Correspond To C A Boon Or Curse For Deposit All Basically Aggregator The Random Potter Fixed Point Used In This Will Be Don't Forget To Promote And Solid Ki And Because You Created Map To Solve This Question Eric Additional Professor And Author 959 Is The Little Bit Created A Ki And Rahul Gautam So Let's See How To Code Know Let's See How To Code Discuss Successful Meeting App Uttar Pradesh Map Also Use President Should Tender Newly Created Note Liquid Liner Temporary Counter That All Using A Temple For Your True Original Linguist's FlashLight So Original Name List loot ok myself hope invited to create new note flat in date that we united members problem rate and develop but this part time they should not will be id time table 12th part of the journey to the ka paste mp 09 oct 09 unique and Temples were originally a bid to update m10 suv in the universe and values in the mid-1960s I show you mp of time which corresponds to the new no and its next will be equal to the new not corresponds * to a template corresponds * to a template corresponds * to a template cigarette From 29 June Linguist and Important Places the new note this point to template Saturday 09 for 1000 and point a sample temperatures again the new point to 0.5 will appoint Rudra note new note 0.5 will appoint Rudra note new note 0.5 will appoint Rudra note new note basically been pointed temple run ok not getting temple run why not looted 102 Vinod The Time This Point Pass Wave Great New Notes And Value And Also Dravya Settings App And Second Password Global Created To Procreate Link For Next Point Andar And Contact No * Written And Head To Contact No * Written And Head To Contact No * Written And Head To Head The Point He Did Not Respond To The First Man In The World Is The First Day Of The Black 06 That All Accepted One Ko Samet Vote How To Cut Solve This View Time And Slap Lyric Transportation Express No This Can Be Sold In One Place Which You Want May To Solve In That Phones Persuaded Them Under One India YouTube Section and Animated Videos on Various Issues Paint Recording Hai Ajay Ko On Karo
|
Copy List with Random Pointer
|
copy-list-with-random-pointer
|
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`.
Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**.
For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`.
Return _the head of the copied linked list_.
The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where:
* `val`: an integer representing `Node.val`
* `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node.
Your code will **only** be given the `head` of the original linked list.
**Example 1:**
**Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\]
**Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\]
**Example 2:**
**Input:** head = \[\[1,1\],\[2,1\]\]
**Output:** \[\[1,1\],\[2,1\]\]
**Example 3:**
**Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\]
**Output:** \[\[3,null\],\[3,0\],\[3,null\]\]
**Constraints:**
* `0 <= n <= 1000`
* `-104 <= Node.val <= 104`
* `Node.random` is `null` or is pointing to some node in the linked list.
|
Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list.
For e.g.
Old List: A --> B --> C --> D
InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers.
|
Hash Table,Linked List
|
Medium
|
133,1624,1634
|
799 |
hey everybody this is Larry this is me going to do day 24 of the September Lego daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's Farm is 7.99 today's Farm is 7.99 today's Farm is 7.99 champagne Tower okay let's see so we stack classes in the permit okay something like this uh now after pulling some non-negative uh now after pulling some non-negative uh now after pulling some non-negative in it how full the jave class and the iPhone is okay um so I guess it's like a percentage from zero to one uh okay I mean I think this is just in a way simulation uh it's gonna be like a little bit of a dynamic programming man one of my doors not closed tight and it's like making a clicking sound but yeah but I think that should be fine and we have only less than 100 rows and 100 columns so I'm not even gonna um no make an optimization because I think you can do a sort of a space optimization to kind of get it down from all time C to uh just off or something like this but we don't even have to worry about it given that it's such a small thing um we do want to return a float which we have to be mindful about but that should be fine so okay so first thing first let's uh yeah let's set this up so let's just uh actually I'm just gonna write it the other way yes I think instead of a queen so let's say we start with uh Port right and maybe we'll just convert the flow right off the bat why not right so then now and this is uh first whoa okay zero index that's what I was looking for I was just checking to see if it's the zero index um wait why is that not oh because this is still index okay yeah so then now we can do something like uh query well um what am I doing is that right so because one then we do this once that's not right so because we already kind of did one well so then now next is equal to is this and then now for yeah maybe I'll make it the other way so 0.0 times length of current plus one 0.0 times length of current plus one 0.0 times length of current plus one right and now for um I guess for R is equal to well because on the iPhone um or off well there's gonna be all elements so I guess even and I guess I could just write this also um or plus one or something like this right uh maybe I could also just like from one to maybe that's a little bit cleaner uh yeah and then now for C in range of um I guess I'll pass one which is the number of columns right um I guess the two ways to write this actually now that thing about it I mean it should be obvious I just didn't think about it uh which is that you can kind of fetch it from the previous one or you could get it from the next one right so actually I think this is a little bit cleaner to weight getting from the previous one so then now you have current of c um you know minus one is the amount that floats and then over two for um you know left and the right so then now uh overflow is gonna be you go to this thing right uh for each thing so then now next of C we added to the Overflow and next of C plus one we also added to that before um we also want to make sure that this is at least zero uh yeah which can happen if you know this is less than um less than one I suppose yeah and then at the very end yeah oh and it will obviously we have to update the stairs and then I think at the very end we can just return current of uh query glass which is column I suppose and I think technically you don't you can also just do like a Min here because um one or something like this because things that go straight to the right you don't really care about but for simplicity's sake we can do something like this uh did I mess something up I probably did hmm foreign should be inclusive if that's what we're looking for yeah okay all right that looks good um under this is actually a good test um because on the last thing we it continues to overflow we just haven't kind of done it yet so I guess we should add that to a thing and I think we should be Gucci uh actually definitely would have missed this one I'm not gonna lie um a little bit lazy today maybe let's give a submit hopefully you didn't miss another silly case and yep last time what did I miss last time I don't know what that case is but yeah um that's pretty much all I have for this one uh it's kind I mean you could kind of frame it as dynamic programming and I think that's what you know uh rigid labeling is kind of tricky right because in a way yeah this maybe you can look at it and think of it as dynamic programming but the way diving by just simulation right you just start with the amount on top and then you gotta simulate one row at a time and it just so happens that the structure and the code and things like this look like dynamic programming but um I don't know all right uh that's all I have for today I am right now on like a 24 hour fast I'm doing another fast um so I don't know maybe I'm a little bit cloggy as if he's out but uh yeah that's what I have this one uh the contest is like an hour or so good luck to that uh that's all I have stay good stay healthy to go Mental Health see y'all later and take care bye
|
Champagne Tower
|
minimum-distance-between-bst-nodes
|
We stack glasses in a pyramid, where the **first** row has `1` glass, the **second** row has `2` glasses, and so on until the 100th row. Each glass holds one cup of champagne.
Then, some champagne is poured into the first glass at the top. When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it. When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on. (A glass at the bottom row has its excess champagne fall on the floor.)
For example, after one cup of champagne is poured, the top most glass is full. After two cups of champagne are poured, the two glasses on the second row are half full. After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now. After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below.
Now after pouring some non-negative integer cups of champagne, return how full the `jth` glass in the `ith` row is (both `i` and `j` are 0-indexed.)
**Example 1:**
**Input:** poured = 1, query\_row = 1, query\_glass = 1
**Output:** 0.00000
**Explanation:** We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty.
**Example 2:**
**Input:** poured = 2, query\_row = 1, query\_glass = 1
**Output:** 0.50000
**Explanation:** We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange.
**Example 3:**
**Input:** poured = 100000009, query\_row = 33, query\_glass = 17
**Output:** 1.00000
**Constraints:**
* `0 <= poured <= 109`
* `0 <= query_glass <= query_row < 100`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Search Tree,Binary Tree
|
Easy
|
94
|
938 |
hey guys welcome back to another video and today we're going to be solving the leak code question range sum of a bst and a bsd is basically called a binary search tree and it's a tree based data structure which follows a certain set of rules and i'll be going over what those rules are real quickly so first let's see what the question over here is so given the root node of a binary search tree return the sum of values of all nodes with a value in the range low comma height so the square brackets over here means it is inclusive what that means is our range is inclusive of whatever the low number is and whatever the high number is so a low number and everything between low and high and the high number is going to be in our range so now real quickly what is a bst so bst is a tree based data structure and how it works is given a certain root node everything to the left of that root node is going to be less than whatever the root node is simultaneously everything to the right of that certain root node is going to be greater than whatever the current root is so real quickly let's look at this example we have 10 so 10 over here is a root so everything to the left of 10 should be less than 10. so 5 3 and 7 are all less than 10 while 15 and 18 are greater than 10. one more example real quickly let's take five as our root everything to the left of five should be less than it and it is which is the number three and everything to the right of five has to be greater than it which in this case is the number seven all right so now that you understand what a binary search tree is let's see how we can solve this question so by looking at this question if you know how tree traversals work we will be using something called an in-order traversal in-order traversal in-order traversal so let's just go over what that means and it's really simple to understand how the question works all right so in an inorder traversal what you do is you go to the leftmost node then you go to the root node and then you go to rightmost node so an inorder traversal is best used in a binary search tree because the main idea is the leftmost node in a binary search tree is going to be the smallest value whereas the rightmost node is going to be the greatest value and that's pretty intuitive so that's kind of using that idea we're going to have this traversal and again real quickly it's called in order all right so let's see how an inorder traversal is going to work so in this case uh just for the sake of the question i'm going to ignore the low and high values just for now okay so let's see how the inorder traversal works so let's start off with our root so our root is 10 and now we're gonna go to the left of it which is five now we're going to go to the left of five which is three and now we go to the left of three so the left three is actually a leaf right so three is a leaf we don't have any children notes so in that case we're going to add 3 to our list over here and it also makes sense because 3 is the smallest number so now what's going to happen is we're going to go to 3 we add 3 and now we're going to go to the right of 3 and well there's nothing okay so now you go back one step five so in this case we went we already visited everything to the left of five which is the number three so now well since we already went to the left now we're going to go to root so we add five and now we're going to go to the right so when you go to the right you have the number seven so before adding seven technically what would happen is you would go to the left of seven which is nothing so now you would add seven and then you would go to the right of seven which also does not exist so by the end of this we have the numbers three five and seven and they are in ascending order so what this basically is telling us is that we've already taken care for everything to the left of ten so everything to the left of ten is taken care of so now we go back to the root node which is 10. so since we got everything on the left we're going to get the root note itself which is 10 so now we add 10 and now we look on to its right so now we're going to go on to 15 okay so before adding 15 we're going to go to the left of 15 which does not exist so then in that case we just add 15 now we're going to go to the right of 15 then which is 18 check the left of 18 does not exist then we're gonna add 18 and that's the end of it right so over here we have our uh inorder traversal and this is how it looks it is in ascending order exactly how it's supposed to be now let's see how we can get our answer using this so what we're going to do is we can just directly look for everything in the certain range itself so basically we have 7 then we have 10 and 15 oh sorry that's 15 not 13. all right so we have those three numbers and you can just add them up so 7 plus 10 17 uh and then 17 plus 15 27 32 right so you get an answer of 32 over here right and that is the correct answer yeah it is the correct answer right but in this case what we did is we actually traversed to the entire binary search tree and in a smaller binary search tree it doesn't really matter but what if you have a bigger bst it would just be a waste of time traversing through the nodes which we're not even going to end up using so to kind of save that time up we're going to kind of optimize this in-order traversal and optimize this in-order traversal and optimize this in-order traversal and let's see how we can do it side by side so now what's going to happen is the same thing we're going to start off at the node 10. i'll just use the color red to indicate this so we're starting off at the node 10 and now what we're going to do is we're going to go to the left so now we go end up at five so before we actually go all the way to the left we're gonna do a small check and before i say that uh one real quick thing once you go to the left of five everything to the left of five is going to be less than five and keeping that in mind we know that our lower bound value over here is seven so anything less than five is completely useless for us so in that case we are not going to go to the left of five so now in that case that leads us back to the number five so now the question is do we add five or not and to kind of check that all we need to see is five in between seven and fifteen and it is not right and again we're looking at the inclusive range okay so 7 and 15 are included so 5 is not in between so in that case we are not going to add 5. now we go to the right which is 7 right so again everything to the right of 5 is going to be a greater than five so the possibility in this case is six seven or eight right or nine right and again six is not going to matter since it doesn't meet the requirement but in this case we have the number seven so in this case uh since seven is in our range we are going to add it to our traversal now we go back up since we got rid of everything on the left so now we're going to check do we add 10 or not and to do that it's pretty the same thing 10 is greater than 7 and less than 15 so we add it over here all right so now we go on to the right and the reason we're going on to the right is because the height boundary over here is 15 so we are going to go to the right of 10 which has values greater than 10. so now we're at the number 15. so now what we're going to do is we're going to check is should we go to the left of 15 and the answer is yes we should go to the left of 15 because uh that is still going to be inside of our range but in this case there is nothing on the left of 15. we have none so in that case we actually won't be able to do anything so now we go back up to our roots which is the value 15 and we are going to add the number 15 because it is in our range and finally now the question is do we go to the right of 15 and the answer is no because everything to the right of 15 is going to be greater than 15 and our higher bound itself is 15. so there's no point in crossing whatever is higher than the higher boundary over here so now what you can kind of notice is we just got the three numbers that actually fit in our criteria which is seven ten and five and seven ten sorry not five fifteen and when you add them up you get the same answer of 32 it takes up a lot lesser time and memory okay so now let's just see how we can code this it should be pretty simple and yeah okay so over here we're going to have a variable and we're going to call this sum so sum underscore and i'm not using sum because sum is a function in python okay so this is going to end up equal to zero and the reason i'm doing using self is because i'm going to make it an attribute of the class so we can refer to it inside of our function so you can kind of treat it as a global variable all right so over here we're going to have our in order traversal okay so each time we're going to be giving it the root value and now inside of this we're going to have the two so let's just write it down real quickly what the three kind of things we're going to do so what we're going to do is we're going to do an order and we're going to call it on the left node okay uh then another thing that we're going to do is in between so first we go to left and then we're going to add that value so to add the value or in other words to take care of the root value we're going to do self.sum root value we're going to do self.sum root value we're going to do self.sum underscore and we're going to add whatever the value is for the root of node we're on so sub under self.sum underscore plus equals to root. self.sum underscore plus equals to root. self.sum underscore plus equals to root. and now we're going to go to the right okay so left root right that's exactly what i'm writing over here so this is kind of our template and this is how a normal inorder would look like but now in this case we want to add our conditions and before we do that there is really no stopping point to this right even once we reach a leaf this is going to keep going on and on there's no stopping point so to ensure that we end up stopping at some point we're going to check if our root has a value so if this is confusing this is actually the same as writing if root not equal to none all right and only in that case we're going to go inside of this so to just simplify it you can just check if root okay so now we have this perfect and this is our very basic inorder traversal so now let's add uh the conditions with the low and high boundaries so in this case uh what is the condition going to be for root dot left so for root dot left we're going to check if the root dot valve value so root.val has to be greater than value so root.val has to be greater than value so root.val has to be greater than our lower value and only in that case we're going to end up calling this function it's the same as what we just went over okay now when do we add the value so we're only going to add this value when it is inside of our boundary so to do that we're going to do if low is less than or equal to root.val if low is less than or equal to root.val if low is less than or equal to root.val and simultaneously we're going to check if it is uh if the root.val is less than or equal to if the root.val is less than or equal to if the root.val is less than or equal to our high value okay and if it is inside of our boundaries and uh since it's inclusive we're doing equal to as well and in that case we're going to put this inside and we're going to add it to our sum and finally uh when do we call on our right node so for doing this we're just going to do if root top vowel is less than our high boundary and in that case we're going to do the inorder function on the right node so finally all that is left to do is we need to call the function itself so to do that we're going to call in order and we're going to call it with the root note in the very beginning and at the ending uh this value is going to get updated and we're going to end up returning that to return uh self start self dot sum underscore and that should be it so submit our solution and yeah so thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe thank you
|
Range Sum of BST
|
numbers-at-most-n-given-digit-set
|
Given the `root` node of a binary search tree and two integers `low` and `high`, return _the sum of values of all nodes with a value in the **inclusive** range_ `[low, high]`.
**Example 1:**
**Input:** root = \[10,5,15,3,7,null,18\], low = 7, high = 15
**Output:** 32
**Explanation:** Nodes 7, 10, and 15 are in the range \[7, 15\]. 7 + 10 + 15 = 32.
**Example 2:**
**Input:** root = \[10,5,15,3,7,13,18,1,null,6\], low = 6, high = 10
**Output:** 23
**Explanation:** Nodes 6, 7, and 10 are in the range \[6, 10\]. 6 + 7 + 10 = 23.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 2 * 104]`.
* `1 <= Node.val <= 105`
* `1 <= low <= high <= 105`
* All `Node.val` are **unique**.
| null |
Array,Math,Binary Search,Dynamic Programming
|
Hard
| null |
990 |
Hello everyone welcome to my channel with Mike so today we are going to do video number 21 of our playlist of graph concepts and questions okay and before starting watch some speeches and words of knowledge l b always waiting okay achhe jab lage ka Okay, when someone is engaged in good news linking, when the dog is okay, right now, very happy and I'm really waiting for a date, okay, cup working hard, and no matter what happens, don't stop, okay, trust the process, cup working hard, you give the bill. Less is fine, so today we will solve Let's through Ka medium, but the most important thing is how would it have occurred to my mother that this ten U would be formed only. The most important question is if this happens, then it is okay, that too, we will see if the public question is okay. You must have given a vector and a string in the question. It is okay. You have given a vector and a string. Neither do indexing. 0123 You must be balancing these strings. Zero, one, two, three. It is okay till now, it is clear. After that, there will be zero and The one who will be the third character, what kind of alphabet will it be? Okay, the alphabet can be from A to C, till here it will be clear, okay, and the one who will be the second index will always be equal, see, you are equal here too, but which The first one is the index, it can be either equal tu like here or it can be an exclamation point, note the sign equal tu, it will be clear till here, it must have been given in the input and just this simple question to you. It is asking that it is asking whether all the equations which give so many questions in your input can all be true simultaneously, what if they can then it will be true, if not then it will be water, okay let's see, okay first question. But let's come to what is being said in this that brother, what is A is equal to B. Okay mother, this is what is B, okay, I understood A. Then on the second question, I have to say that brother, what is B is not equal to A. What is B is not equal to A. How can both be true? Both are together, right? A Banda is speaking, now equal to A Banda has to be said. B is not equal to A. Both the equations cannot be simultaneous. But it cannot be true. Thoughts are same D. Answer is equal to this false and you say a time is not equal to Ba, so now by the way you are speaking wrong, you date is A.D, all these equations come you date is A.D, all these equations come you date is A.D, all these equations come from D. time is not equal to Tenali. It may be okay, Das, the answer is this false, so it is understood that yes brother, the question is what to say, now the most important question is that brother, how did you think that it will be made through DSO and even if it is made, how will it be made, okay? Let's see how the question of DSO came to my mother. Okay, so it came to my mother from Yadsu. Before that, let me tell you that you can simply solve it from the map. Right now I will do it. You can solve it from the map. Yes, in the map you have every equation okay and here A = C so what does it mean that okay and here A = C so what does it mean that okay and here A = C so what does it mean that a is equal to and k is equal to okay here what is B = C is E is okay here what is B = C is E is okay here what is B = C is E is equal to and k is equal to here But what is a0 = A? Okay, what does it mean? A is a0 = A? Okay, what does it mean? A is a0 = A? Okay, what does it mean? A is not equal to A. Okay, so you think for yourself, first find A, where A is equal to B and where B is equal to C. Look here, right? And C which is equal to A, then finally A which is I went to B, from B to C I went from C to A and here A note is equal to I took out A which is possible, you will have to do a little coding. I but you can also make it from the map very easily, it is ok, so but what is the better way than that, how will DSC and ten U come, Maa, think about that, I will tell you, first look, first think about this, see this, what does it mean? It happened that both A and B are from both A and B. In the beginning, I did not know who was older, in the beginning I knew that yes brother, A is who is B, who is C and all are alone people, all are different. In the beginning, I would have thought that there is no tomorrow for anyone, then when I saw the first question, I came to know that it is good that A and B are different, I have put them in one set, so A and B should be the same. Well, I put them in the set, then later B and C came, okay, later B and C came, so first I will see, okay, so you have to find out that B and C must have been equal to what. Remember what we used to do, like when A and B were equal, I put both of them in a set, remember, we used to make a parent, it must be representing the area again, right? And remember, this is better than not making a diagram. A diagram should have been made which was more understandable to us. Similarly, if I make this diagram, learn how, I make it like this and carefully, when the big i of B and C of this equation is found, then I can directly find out B and not what B is equal to. It must be there, then I will come to know that well, B is equal to A, so here we write A and whatever C is, here C is equal to this. C is the owner himself, so C is equal to C, so both are looking. These are of different sets. Who is B? Who is the owner of B? Who withdrew the payment, Si has withdrawn it himself, okay, then it will be my wish, okay, I will tell Si that brother Si, now do another report, your parent is A, okay, till now it is clear, okay, now I will direct here. I can take it out, right, I will go to A, who is an area, this is it, and one itself, one's own, is A, so I can write, okay, it is equal to A, and here when I come to I am looking at A's. Who is the parent of I? A is the parent of The two videos which I have impressed are Baat and Rank. Today there is compression and rank in DSO. So, with the help of these three, I have made this graph. Now after doing Baat compression, F is opening Direct A, so I am using Direct A. If I can find out who is the parent, then directly I will find out from here that what will be the find A This is possible, it became clear, then from here I understood that when the good component was equal to BB, then put both of them in one place. Given then B when C is equal to C then I had to find out what will B be finally equal to then remember B belonged to this set and its parent was A then I will say ok if it is the parent of B then B = A will be similar. What would C be equal to? So B = A will be similar. What would C be equal to? So B = A will be similar. What would C be equal to? So C and A belonged to this set and its parent was A, so C was equal to I. Okay, and A and I are not equal, that means union both of them, okay, put ABC all in one set and said. That whatever is there is the owner, it is okay, then when the note comes here, look at the note equal tu wale, only equal tu will know who will be able to tell me whether this statement is right or wrong because in equal tu wale, remember, we have to do union. Isn't it a union? This union is done. Union is done. Then here this union is done, isn't it a union and a find? What is union in DSO? If find is given then it means that here it has been found out. Okay yes union. The concept of 'A' is happening to him, okay, then here, concept of 'A' is happening to him, okay, then here, concept of 'A' is happening to him, okay, then here, when the note is equal, how is 'A', then let's when the note is equal, how is 'A', then let's when the note is equal, how is 'A', then let's find out who is the parent of A, then find A's mother, okay, and it is written here, okay, so by relating like this, it is very useful. There are all such questions which in the end you are relieved that it can be done with DSC, it is fine and it is totally fine, what figure out will not be able to be done with DSC, even I could not do it, even I was not able to do it, okay, but as soon as I made the questions, I kept making a lot of them. If you have to make all the questions then it will start coming to your mind, don't worry about it is not coming to my mind, but what is the condition, it is ok to make many, read it, and if there are no questions, then you must have understood the solution here. Okay, how will it be solved with Find and Union, so let me show you once again how to solve this example with the final unit, so this is our example. I will blindly fold the code of Find and Union, multiply, copy paste. I kill it like I did in the previous video because I know that here in DSO these are the two things and nothing else happens, apart from this, brother fine union, so I write like this but yes, you write without seeing so that Once you are done practicing, okay, then finally, I know it happens in DC, so let's come to how we will solve it by finding and union, so first of all, what will we do, which is equal sign, like this is equal. One will be equal, one is done, okay, catch them and unionize them, because it is equal, the question is speaking itself, so union will happen, if A = B, then union will happen, if A = B, then union will happen, if A = B, then A has become a parent and union with B, okay, what have I done, union? How did you earlier ask about A's parent? So, in the beginning, A must have been its own parent, and in the beginning, C 's print must have been C itself. Okay, so if you make 's print must have been C itself. Okay, so if you make 's print must have been C itself. Okay, so if you make both of them parents, then I have to say, okay, you become its parent. I told Joe A that you become his friend, Joe B, who is your parent, then B will say, he is my parent, he has been thrown out from here, so now I will say, okay, if you make any one of the two the parent, then I will I make any one of the two the parent, then I will say, brother, it is okay, the rank and post compression that I had taught you, watch two or three previous videos, it will be clear very well, so what I did, I made it a parent and told A, brother, you also report this and post compression when If I do this then I will also tell C that he has to report directly to A only because if I ask C that brother, who is your pen, then C will say brother, he is my parent, then he is my parent, so you report directly to only one, this is mine. I am telling you about rank and post compression. Those who are not able to understand it, watch two or three previous videos, it will be clear there, you will completely understand what I am saying here, okay, those who have seen it must be understanding it, okay. So it is now, which child is which child, if we read the note equal tu one then first the note equal tu one is this one, this note equal tu one is the one, then first we say the end of the story, this was the story too, this was the story, there was nothing else. Union will kill them and then in the last note we will process those who are equal to you. Otherwise if someone like this is found in the quantitative set, then in the last, how will we proof it if it is not found on the story too? The only question is whether not otherwise, I will remove the story as well. I am going to click OK, so let's do the question in the lead code, let's solve it. Okay, so let's do the code. You must have understood the question. Okay, let's solve it with DSC. And what I said here, whenever DCO question. It comes, I silently paste the code of find and union, then go to my repository, it's okay, go to the interview repository, here you will get the graph, you have to go to the graph, go to the design set in the graph, it's okay from here, so this is what I do every time. I do it because friend, this is the best part that the function is available from everywhere. Finder Union. Okay, now after this you have to solve. Already what I told you in the beginning, whatever the parent will be, it is okay and also resize the rank because it is 26. The rank of all 26 letters will also be zero in the beginning, right, let's make it zero, and remember, we will not slice the parent, it will be equal to zero i < 26 i plus, right Right, and the third index will be alphabets. The second index will always be equal to you, but the first index will know whether it is equal to you or not, that is, S is one, if it is equal to you, then it means A = B. It must have been something like this, first A = B. It must have been something like this, first A = B. It must have been something like this, first index, this has happened or this. This one is fine, so what did I say, if this one is equal, how is it, you are there, then we will do the union and whom will we union which was 0 in the last index, sorry, okay Exclamation point meaning is fine, let's check this first, okay first this What are you equal here, A is taken out, it is saying here, put the parent first, okay, so what happened, listen again, it is not here, but it came to know that the parent of A is also A, which means it must have been equal to A and B. The parent of second is also A, here is the parent of second, that is also found to be equal to A, that is, they must be from the same area and they must be equal to each other, but here the note 'equal' has been given, which means this note 'equal' has been given, which means this note 'equal' has been given, which means this is a wrong statement. By the way, how can I burn the return, otherwise you will return, okay, dry iron with it, this code is fine, condition taught, try to run the dry iron in the example shown, I had made it with this very important dry iron only. If this question is correct then let's run it and see what mistake we have made here. What mistake have we made? We have to find the correspondent of any character. Mines A does not do zero. In the vector, mines used to come out one by one, remember, pay attention, don't miss, let's see by submitting this thing, now we should go, this was my friend, you had to put find and union, you had to find out, I found out and this one is IF. If the condition is important then see it has been submitted and it is available, you can help, if there is any doubt, then the reason is in the comment section, see out the gas video, thank you.
|
Satisfiability of Equality Equations
|
verifying-an-alien-dictionary
|
You are given an array of strings `equations` that represent relationships between variables where each string `equations[i]` is of length `4` and takes one of two different forms: `"xi==yi "` or `"xi!=yi "`.Here, `xi` and `yi` are lowercase letters (not necessarily different) that represent one-letter variable names.
Return `true` _if it is possible to assign integers to variable names so as to satisfy all the given equations, or_ `false` _otherwise_.
**Example 1:**
**Input:** equations = \[ "a==b ", "b!=a "\]
**Output:** false
**Explanation:** If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.
There is no way to assign the variables to satisfy both equations.
**Example 2:**
**Input:** equations = \[ "b==a ", "a==b "\]
**Output:** true
**Explanation:** We could assign a = 1 and b = 1 to satisfy both equations.
**Constraints:**
* `1 <= equations.length <= 500`
* `equations[i].length == 4`
* `equations[i][0]` is a lowercase letter.
* `equations[i][1]` is either `'='` or `'!'`.
* `equations[i][2]` is `'='`.
* `equations[i][3]` is a lowercase letter.
| null |
Array,Hash Table,String
|
Easy
| null |
1,685 |
so little 1685 sum of absolute differences in a sorted array so for this problem you're given an array of numbers of integers sorted and you need to return another array where every result of i is the sum of the absolute value of the difference between your current number and all of the other numbers okay right so let's look at that example here so like you could just do this like this is really similar to a list comprehension expression in python however it exceeds the time limit because a solution like this would be o of n squared and is the amount of numbers in the array instead if you can do a solution in o of n time complexity so let's look at an example here let's say that we're trying to compute the value of the result array for the position three so zero one two three or this position here so you have to do eight minus six eight minus four eight minus one and ten minus eight and sum all of those values together and you'll get fifteen but instead of doing that you can notice that whenever we are subtracting like eight minus six eight minus four eight minus one you're always subtracting from something from eight so instead you can group those eight together and do something like eight times three minus the sum of all of these numbers and you can easily keep track of the sum of all of the numbers that are previous to you by just keeping track of the sum of all of the numbers right okay and you can basically do the same for the numbers that are bigger than you as well so for example let's say that you start with some variable that keeps track of the sum of all of the array right then as long as you move forward every time you move forward one step you remove from that sum your current number because then that number is no longer bigger than you right so you remove it from the sum of numbers that are bigger than you and now what you can do for example let's say that we are at four right here we are calculating the result for the index one so we can do the same what i said before for the numbers smaller than me so in that case we would do four times one minus the sum of all of these numbers previous number which is just one okay and now what about the biggest one so the bigger ones i'm going to keep track since i've removed from the sum of all of the numbers one and four then now i'm left with only these numbers which are the numbers that are bigger than me and i want to remove from the sum of those numbers i want to remove my number times the amount of numbers that there are because i'd have to do something like 10 minus 4 eight minus four six minus four so i just group those fours together since i have three comparisons that i need to do i subtract from the sum of these numbers four times three okay so that gives me the result so let's just implement that real quick so as i said initially we need to have the sum of all of the numbers in the array and then also we need all of the numbers that are smaller than us and right now since we haven't started iterating yet the sum of all of the bigger numbers than me is all of the numbers and the sum of all the numbers smaller than me is zero because there are no numbers smaller than b since i yet have to start and then we iterate through all of the numbers with a for loop and obviously you need to also instantiate a result array now you iterate through all of the numbers in the nums array and since we are now on the first position you no longer have this as a number that is bigger than you so you want to update the bigger sum you want to remove the first position now right and you want to do this for any time you move forward in the array you want to remove from the variable bigger sum the current number okay so we take the number in the current position and we remove it from the sum of all of the numbers that are bigger than us because it's no longer bigger than that right okay now what is the difference of our number with all of the numbers that are smaller than us well it would be for example let's say that we were here it would be eight minus six eight minus four eight minus one so we have eight three times so just i times right and then we have the sum of all of the elements that are smaller than us okay and now you also need the difference with all of the numbers that are bigger than us so diff big which is just the sum of all of the numbers that are bigger than us let's say that we're calculating for four we'd have to do 10 minus 4 8 minus 4 and 6 minus 4. so we just sum all of these together which is the bigger sum and then we subtract from that four times the amount of comparisons that we make which is just three like the amount of numbers that are bigger than us and that's just nums double length minus one minus i okay so now you have the difference with all of the numbers that are smaller than us and the difference with all of the numbers that are bigger than us so now you can just add to the result the actual value of the result which is the summation you just add together the difference with all of the smaller numbers and the difference with all of the bigger numbers and get the difference with all of the other values in the array so that's it you just need now to don't forget to also update the smaller sum because like here we were updating the bigger sum but you also need to remember to update the smaller sum so now since we are moving forward in the array like soon we are going to be doing i plus you need to add to the smaller sum the current number because the current number will very soon become smaller than your new number since the array is sorted and you're moving forward in the array right so this number is going to be smaller than your next number so you want to update the smaller sum and you want to add to the smaller sum the current number so that's it i'll submit the solution to show you that it works and the time complexity here is o of n because it just goes through every element in the array once or like twice if you consider this setup as well and the space complexity is o of n if you could if you consider the result but honestly it's basically o of one extra space so that's it for me today thank you for watching and bye
|
Sum of Absolute Differences in a Sorted Array
|
stone-game-v
|
You are given an integer array `nums` sorted in **non-decreasing** order.
Build and return _an integer array_ `result` _with the same length as_ `nums` _such that_ `result[i]` _is equal to the **summation of absolute differences** between_ `nums[i]` _and all the other elements in the array._
In other words, `result[i]` is equal to `sum(|nums[i]-nums[j]|)` where `0 <= j < nums.length` and `j != i` (**0-indexed**).
**Example 1:**
**Input:** nums = \[2,3,5\]
**Output:** \[4,3,5\]
**Explanation:** Assuming the arrays are 0-indexed, then
result\[0\] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,
result\[1\] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,
result\[2\] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.
**Example 2:**
**Input:** nums = \[1,4,6,8,10\]
**Output:** \[24,15,13,15,21\]
**Constraints:**
* `2 <= nums.length <= 105`
* `1 <= nums[i] <= nums[i + 1] <= 104`
|
We need to try all possible divisions for the current row to get the max score. As calculating all possible divisions will lead us to calculate some sub-problems more than once, we need to think of dynamic programming.
|
Array,Math,Dynamic Programming,Game Theory
|
Hard
|
909,1240,1522,1617,1788,1808,2002,2156
|
1,023 |
hello hi guys suggestion or bantu discus liquid problem number 102 3 and problem name is camel kiss matching software been given in the list strings basically in yield squares and patterns string ok be happy return list of indian values where happy return list of indian values where happy return list of indian values where is boolean value research work very is matching Pattern And Very Definition Of Matching Gas Per This Problem Is The Pattern String And The A Query String Should Have Same In The Pattern Spring Shirdi Say Sequence Of The Query String And Dick Query String Should Not Have Been Clash Of But Not Present In The Answer ok so difficult a look at this is the two condition that they have come in pure pattern must be a subsequent of queries of life in the least squares of eyes query string so in that case like pattern dedh subscribe to return subscribe not present in a A query string additional Rokus alphabet letters for India but not the perks of it ok itself the problem and the spot on how to do it heres like and * loop Rudra paris list and for like and * loop Rudra paris list and for like and * loop Rudra paris list and for every string in this query list and vent To check weather patterns for subscribing or not and also this distributors do not have any additional I am your only better not present in this pattern spring ok sorry for the time looping start the very easier now so only are very present or its ring ok I will keep fighting Children And The State Which Alarm Ticketing Indices And Now That A Sure Not For Blue Picture Divine Life And White House Length Electronics Query And The Ka Juice Blood Bank Learn To Us APattern That Soviet Just Comparing With Strings Like Heaven After The Pattern Spring Software Tool Look Patidev Android Shoulder Twenty Minutes And Let This That Is Same thing Pe That Equal's Saree Slide The Character Some Particular Location Is Equal To The Character This Present In Query String's Day Will Simply Increment Bodh End Vs Aas Hai Andarwise Bihar To Check Weather The query string is those who need additional up case of its significance senior like this let's check the first verification behavior and no extra addition against they need additional of cases in the district Bihar only people only but not present in the 120 does not have anything so in that case Will Return Proof This Cream And But If This Trick Additional Subscribe Not Present In The Return Of The Day Today's Tweet Is That Case Law Will Take Its Last Point To Indicate That You've Found Something Really Strange Dhappa's Certificate Switch Off To Stop It Hair Stop Comparing Here And Have To Return For Slide Show For The Time Settings Flag G-20 And Breaking Owl Settings Flag G-20 And Breaking Owl Settings Flag G-20 And Breaking Owl Ki And In This Condition If Eye Drop 20 Cases Rectification Is Not Enough Dr To Cash This Day Will Simply Increment Daira Leaders S U Take This Lake will check the front of the lap of medicine and after that will reach to win treatment and it will be the chief but also reduced character not matching man tied in that case will decide Index 102 Which Complete Divine Life to Check Book the Flag point and also give value right this loop only and when ideals of distic as a main i d j equal to length of pattern and flags equal to zero and a great civil of those wicked are a great girlfriend soil check weather is here a slack Value is equal to one and gems is equal to length of pattern is didi success case writing on initially i lakshmi weekly lower is the flag point vansh soaye isse with clear hai or frequency in amlon kinnar initial khayal initial ice break point 80 meanwhile complete this is The Means Every Possible K And Subscribe And Complete This Looking Through This Pattern For Every Character In This Question In That Case Water Drop Oil A Part One To The List Of And 180 Dars List Swar Ki Hum Sab Station Mp List Show Airplane One In That Case E-mail tile up and zero the right but vansh i get out of this blog is also increase in is also a real life 11.21 under next set of words will be applied should speed life 11.21 under next set of words will be applied should speed life 11.21 under next set of words will be applied should speed up send that advice like this sexual return flight tickets at will Have seen there nationality and then the point of bomb 0 and this will reduce the development 0 flag quantum 0f don't in his alleged affair rights of your Hair and after this oil return dance on 210 answer list so this will be having or a sorry up and Show up or strong behaving and boolean value suspended a this activated gram has been a query is not defined that the patron of baris right ki pyas was placed against him in the audio query that this amchur's is not in this life is set sorry substance guys that Aishwarya Sheela Is Vansh In This Affair S That She Is A Tiger Fight Wave Girl Why This Friend Porn Back To Check Jai Hind Is Condition Right Because Even After Veer Is This End Notes Here Additional Upke Subscribe So This Loop Fast Ronit Ashamed Of Query Lights Off The Trees Unmute That Then Test Query String K Sono Let Me Give It Airplane A Fine Aankhen Hai Ya Shubh David Gaye Sif Inconsequence Please Leave A Comment And If You Have Any Suggestions Please Do Comment Close Is Or If You Really Like This Video The Like It's Good-Good Really Like This Video The Like It's Good-Good Really Like This Video The Like It's Good-Good Really Hot Flu Positive Videos Thank you for your time Ajay Ko
|
Camelcase Matching
|
time-based-key-value-store
|
Given an array of strings `queries` and a string `pattern`, return a boolean array `answer` where `answer[i]` is `true` if `queries[i]` matches `pattern`, and `false` otherwise.
A query word `queries[i]` matches `pattern` if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters.
**Example 1:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FB "
**Output:** \[true,false,true,true,false\]
**Explanation:** "FooBar " can be generated like this "F " + "oo " + "B " + "ar ".
"FootBall " can be generated like this "F " + "oot " + "B " + "all ".
"FrameBuffer " can be generated like this "F " + "rame " + "B " + "uffer ".
**Example 2:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FoBa "
**Output:** \[true,false,true,false,false\]
**Explanation:** "FooBar " can be generated like this "Fo " + "o " + "Ba " + "r ".
"FootBall " can be generated like this "Fo " + "ot " + "Ba " + "ll ".
**Example 3:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FoBaT "
**Output:** \[false,true,false,false,false\]
**Explanation:** "FooBarTest " can be generated like this "Fo " + "o " + "Ba " + "r " + "T " + "est ".
**Constraints:**
* `1 <= pattern.length, queries.length <= 100`
* `1 <= queries[i].length <= 100`
* `queries[i]` and `pattern` consist of English letters.
| null |
Hash Table,String,Binary Search,Design
|
Medium
|
2161
|
201 |
hey guys welcome to a new video in today's video we're going to look at Elite code problem and the problem's name is bitwise and of numbers range so in this question we are given two integers left and right which represents the left bound and right bound of a range where both are inclusive so our task is to return the bitwise and of all the numbers in this range inclusive so coming to the hand operators logic table here if you see X and Y table are given if you take X and Y only when X and Y are both one the output of X and Y is going to be one if either of them is a zero it will be zero and obviously zeros will give you a zero so now let's take this example and see how we can solve this question so let's take the first example left is equal to 5 and right is equal to 7 right so the Brute Force approach which comes into your mind is that you convert all the numbers within this range into its binary format so the range is 567 both inclusive and you Loop through the array and you take the and for the adjacent operator and finally you will get a binary number and that number if you convert it you will get your output but if you take this case if you take the range between 1 through 2^ you take the range between 1 through 2^ you take the range between 1 through 2^ 31 minus 1 you have to iterate these many number of times so this approach will fail so you have to think of a different approach so let's see so let's take the first example and write these numbers in its binary format so this is the standard way how you write uh binary formats so for five where you have to set the bits which sum up to five so 4 + set the bits which sum up to five so 4 + set the bits which sum up to five so 4 + 1 is 5 so rest of them are zeros and right is seven right so in between there is six so for six it is going to be you set this and this to one rest are zeros next you have seven which is right so for seven you set these three to one and rest are zeros and we have to perform the bitwise and operator right so for bitwise and like we saw If X and Y and we need to find X and Y right so 0 will give you 0 1 0 will give you 0 and 1 one will give you one so let's do the bitwise and for all these everything is zero it is a zero everything is zero it is a z 0 everything is one it is a one here there is a zero and rest has once but once you get a zero it will become zero here also these two are ones and this is a zero so entire thing becomes zero so this constitutes to four right because fourth bit is set to one so this will become four so four is your output so how are you getting four you're taking the common part of all the numbers mod so find the common part this row is common this is not common for all because there's a zero here and these two are ones so we can't say this is a common column so until here it's a common column so you find this it is 0 1 so the common number is one so this is equal to one right this is one so the common number is one so instead of finding all the numbers in this range you only have to check these two numbers because anyhow if one of the bits is zero if then the entire thing is zero so how do you find the common one among all so let me write this again so let's take L is equal to 5 one here and one here rest of alls are zeros and take the right we don't need the uh numbers in between we only take left and right so right is equal to 7 so seven is these threes are one and rest of all are zeros so we see this is the common row right which is set to one so how do you check you keep eliminating the last rows do right shift and do right shift so this row will come here so we right shift both left and right simultaneously in a single Loop so after right shifting this last row becomes zero so this rows goes here so this row will get eliminated and this will come to one so this will become 0 1 and this will become 1 one and rest are zeros so what is the value this is the second row right so the value of this is 2 and the value of this is three now we check if both these numbers are same no both are not same so again we do right shift so after right shifting this row will eliminate and you get one here and rest are zeros so what is this number this is one and this is one so these both are same right so how many operations you did one operation here and you did one operation here so total there are two shifts so total two shift operations you made to make left and right the same both are one and now we know left and right are same right take any of the numbers I take uh left is equal to 1 and this is the number of shift shifts is equal to two so I make two left shifts on left to get my answer so this one will move here so this will become one and these all become zero so which column is this it is the fourth column so L will become four so after doing two left shift L now has the fourth bit set so the value of L is equal to 4 so four will be your output now let's do the same by taking one more example so we need nine right so we have to set this and this to one rest of zeros now we need 10 so set this and set this to one rest of zeros we need 11 so set this and set these two to one rest are zeros we need 12 so set this and this to one rest are Z and what is the common part among all till here we have the common part so that will be your output right so this is one and rest of all are zeros so which bit is one it is eight so add that so eight will be your output for this example so how do you do that you keep on doing right shift until you get this row so you take left and right only and you don't have to consider all of them you take the left bound and the right bound and uh apply this operation on that left and right you have 9 and 12 so after doing right shift once so let me write this again so you keep on doing right shift until both left and right are same and then you count the number of shifts and then do a left shift on either left or right so let's do a right shift so this row will be eliminated and all the rows will come one uh step to the right so this will become zero this one will come to its right and this is zero we do right shift again this one will come here and this one will come here this will come here so what are these values this is equal to 4 because four bit is itself this is 4 + 2 is equal to 6 now both left and 4 + 2 is equal to 6 now both left and 4 + 2 is equal to 6 now both left and right are not same so do the same operation you have to shift again so after shifting you get and for this you get what are these values this is two and this is three both are not same again so do shift again so after shifting this will become one and this will also become one so this is one and this is one both left and right are same so how many operations you did so initially one was here now it became here so you did one 2 and three so total you did three shift operations and apply the shift operations on either left or right I'll do on left so take this so this will be shifted three steps to its left so after shifting three steps to it left one will become here and the rest of them to the right are zeros so now what is this entire row it is equal to 8 bit is set so this entire row is equal to 8 so 8 was your output for this question now let's take a look at the code coming to the function given to us this is the function name and these are the two integers left and right given to us as inputs and our task is to return an integer as our output representing the and of all the numbers in this range so let us start by creating a variable I'm going to call it shifts which is initially zero so this variable is used to count the number of shifts we are making that is first the right shifts so we do right shifts for the left and right variables given to us until they both are equal on so once left and right are equal this Loop will break and inside this Loop first we have to start with by right Shifting the left integer by one and storing it inside left itself let's do the same for right we right shifting right by one and storing it inside right itself and now we are incrementing the shift variable because this is one shift and then we do the same until the left and right are same so once this file Loop ends it means both left and right are same so let's take one of those left or right and left shift shifts number of times so now let's create our output variable I'm going to name it result and I'm picking the left variable now you can either do left or right because both are same you can pick either of them and now I have to do left shift so this is the left shift operator how many number of time you have to do it for shifts number of time and now we can return our result now let's try to run the code the test case are being accepted let's submit the code and a solution has been accepted so the time complexity of this approach is of one because there'll be fixed number of bits which have which we are shifting so for every integer there'll be fixed number of bits so this Loop is going to iterate for constant number of times so the time complexity is of one the space complexity is of one two because we're not using any extra space to solve this question except a few variables that's it guys thank you for watching and I'll see you in the next video my favorite lady
|
Bitwise AND of Numbers Range
|
bitwise-and-of-numbers-range
|
Given two integers `left` and `right` that represent the range `[left, right]`, return _the bitwise AND of all numbers in this range, inclusive_.
**Example 1:**
**Input:** left = 5, right = 7
**Output:** 4
**Example 2:**
**Input:** left = 0, right = 0
**Output:** 0
**Example 3:**
**Input:** left = 1, right = 2147483647
**Output:** 0
**Constraints:**
* `0 <= left <= right <= 231 - 1`
| null |
Bit Manipulation
|
Medium
| null |
263 |
hey yo what's up my little coders let me show you in this tutorial how to solve the lethal question 263 ugly number so write a program to check whether a given number is an ugly number and the ugly numbers are positive numbers whose prime factors only include two three or five so for those of you who don't know what is the prime factorization it is basically finding which prime numbers um to multiply together to make the original number however in our case we are limited to these three prime numbers two three and five only or so simply speaking if you are given the input number and we can multiply these three numbers somehow together and in the end by multiplying only any of these three numbers together we get the input value in this case if it's possible then we need to return true let's say if it's six we can just multiply two by three and we get six so perfect we just return true if it's not possible like this 14 then we just return false this is basically what we need to do now let's think about it let's consider one ugly number let's say 18 is an ugly number and i will prove you now why it is an ugly number so 18 how can we get to 18 okay what if we divide 18 by two doesn't mean that we get nine right so two multiplied by nine is eighteen however 9 is not a prime number and we can divide and we can make 9 by multiplying 3 by 3 as well right and it also means that like if we multiply 2 3 and 3 we get 18. so this is the ugly number and one thing to know so it's quite obvious but as you remember from your school lessons it doesn't matter like when you multiply the numbers let's say it doesn't matter in which order you do it because you can also for example divide 18 by 3 let's say so 3 is the prime number and then we get 6 here so 3 multiplied by 6 is 18. however 6 is made from 2 multiplying by 3 and all of these three numbers are prime numbers and they're included in this list as well so this is like another way of getting to 18 right so as you can see here the order here is different like three two three would say but here's like two three so the order doesn't matter so what does it mean for us okay let me just quickly write the code's name of spain what does it mean for us okay guys so what does it mean for us so first of all this is kind of the base case we check if the number is positive or not because it should be positive if it's not we just return false but after that so as we just discussed we will try to divide the input number by 5 3 and 2. so let's say consider 18 again right so we go to the file we cannot divide 18 by 5 and this is fine so we don't update the num after that we go to this value we can divide 18 by 3 so we will get 6 after that once we get six we can still divide six by three we get two we can divide two by three without the remainder so we move to the next while loop and we can divide two by two and if you can do it and then our number will be equal to one which will mean that like we have divided the original number uh by only by these three prime numbers and then we don't have any reminder left so and if it's the case it means that it's an ugly number and we just will return and then like num will be equal to one is equal to one we just return true it means that like okay this number is an ugly number if you will have a reminder and like the num by the end of this division of this while oops will not be equal to one then it means it's not the ugly number so we will just return false simply as that guys okay let me submit perfect guys 100 thanks for watching guys please remember to subscribe to my channel and challenge your friends to see if they can solve this question or not and guys remember elite call today keeps an appointment away so do lead code and watch this videos take care guys see you later
|
Ugly Number
|
ugly-number
|
An **ugly number** is a positive integer whose prime factors are limited to `2`, `3`, and `5`.
Given an integer `n`, return `true` _if_ `n` _is an **ugly number**_.
**Example 1:**
**Input:** n = 6
**Output:** true
**Explanation:** 6 = 2 \* 3
**Example 2:**
**Input:** n = 1
**Output:** true
**Explanation:** 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
**Example 3:**
**Input:** n = 14
**Output:** false
**Explanation:** 14 is not ugly since it includes the prime factor 7.
**Constraints:**
* `-231 <= n <= 231 - 1`
| null |
Math
|
Easy
|
202,204,264
|
77 |
hey everyone today we are going to solve the readable question combinations so you are given integer n and Care return all possible combination of K numbers choosing from the range from 1 to n so you may return the answer in any order so let's see the example so you are given n equal 4 and k equal to and the output is these list and one important thing is that one and two and one are considered to be the same combination so be careful okay so let me explain with this example n equal 4 and k equal to solve the discussion I use a bug tracking and first of all I pass the 1 to the backtracking function and then um in the back talking function we have one for Loop and every time starts from current number I mean in this case one and then first of all appends the current number to the list so now we are one and then after that we call the backtracking function again in the for Loop and passing the current number plus one that means two right and then after that we successfully create a one two combination in this case and now length of current combination is equal to K right so in that case um we append a current combination to our result variable and then return and after that we pop the last number in this case too so now we are regular one only one and then so in the next iteration in the for Loop so we call the backtracking function again and the current number is should be 2 right so we deleted from current number to n plus one so now um current number is two and they're passing of course the backtracking function again in the passing the current number plus one that means two plus one is three right and then create a one three combination and the ranks of current combination leads to K so we append the one three to result variable so and then pop the last value and three and then now we will have only one and the read the same thing called the back talking function again in the next iteration and the passing the current number plus one and the three plus one is four right and I create a one four and it appends the one four and then go back and then we finish this part and then after that so we pop one so now we have an entity list and then move next and the next number is two so just open the two to this empty list so now we have only two and then in the for Loop um we only care about like a larger number of current number in this case three and four so we don't have to care about the smaller number in this case one that's because we have or we have uh already one two combination so description set and the two one and the one to select the same combination right so that's why we only care about like a larger number of current number so in the for Loop um we call the backtracking function again and the passing the current number plus one that means C right and then we don't have like a two three or three two combination right so that's why uh this is a one of the possible combination here so and then ranks of current combination is reached to K so that's why I appended this 232 result variable and after that we pop the last value and then now we have only two and the next situation next number should be current plus one maybe three plus one is four right so that's why we can create a two four and as there's no two four or four two right so that's why this is also one possible answer and then now we reach the uh n right so that's why go back and then now we have empty and the next number should be three so up and three and then so as I told you we only care about like a larger number of current number that means four right only four right so that's why uh in the for Loop call the backtracking function again and passing the current number plus one is four and then we successfully create a three four function and there's an all three four and four three right so that's why this is one of the possible combination and that happened to the result variable and then pop 4 and pop three and now empty and then next um we have to check four right but uh um So Max number is four so n equals four so that's why there is no like a larger number so we stop iteration here so that's why in the end so this these combinations uh or I can read somebody yeah so that is a basic idea to solve discussions so without being said let's get into the code okay so let's write the code once you understand the main concept and the coding is not difficult so first of all initialize result variable with empty list and the combination list with empty list and a callback track and the first of all passing the one and then after that we should return results variable and let's create a backtrack function So Def back crack and let's say start number so first of all if lengths of current combination equal k in the case um we should open the connect combination to result variable so append and a combination and then we can copy if we put only colon and then be done if not the case we use a for Loop for n in um so we already use n so num in rent and the this for Loop always start like a start number and N plus one and the first of all um open the current number to combination list so append and a num and then after that call backtracking function again and in this case as I explained earlier so current number plus one and then after that just uh pop the last number from combination so just a pop yeah actually that's it so let me submit it yeah looks good and the time complexity of this solution should be order of n multiple i k that's because we call backtracking function n times and in the backtracking function uh we iterate through all K element right so in the worst case um time complexity should be hold out of animal spray K and the space complexity is order of K so that's because the combination lists store the utmost K element right so that's why yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
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
|
787 |
in this video lecture we'll be solving this problem cheapest flights within case tops we've already solved this problem with two approaches in my previous two videos and I've attached the links to those videos in the description below so make sure to check them out so in this problem we are given end cities connected by some number of flights we also given an array of flights where each element in the flights array is a tuple representing three integers where we have our starting City and ending City and the price to move from the starting City to the ending City we also given three integers SRC DST and K representing the source City destination city and the maximum number of stops which are allowed to move from The Source City to the destination city and we have to find the cheapest price to move from The Source City to the destination city such that we have at most K intermediate stock if there is no such route the we return -1 so the input will be given the return -1 so the input will be given the return -1 so the input will be given the flights array having n tuples a source City a destination city and an integer K representing the maximum number of stops allowed to move from Source City to the destination city while in the output we have to return an integer representing the cheapest price to move from The Source three to destination city so let's better understand the problem statement using an example so here we have an example test case where we have a network of four nodes numbered from 0 to 3 and 0 is our source node City number three is my destination node and the number of stops which are we which are allowed are one so we are allowed to have at most One Stop while we move from The Source City to the destination city fine so let's see how we can solve this problem so here we have my source city which is City number zero and one of the path to move from City 0 to City 3 would be move from City 0 to City 1 then from City 1 to City 3. fine while giving the price as 100 plus 600 that is 700. fine another way to move from City number 0 to City number three would be just move from City 0 to City one then from City 1 to City 2 and finally from City to City 3 giving me a total amount of 100 plus 200 which is 400 fine so but we can see that along this path we have two intermediate cities City number one and City number two which is not allowed because we allowed to have at most one city while we move from The Source vertex to the destination vertex hence this is out the only option that we have is the first path with its price as 700 hence the answer for this test case is 700 so we move from Source City zero the rest necessity 3 with a price of 700 units fine so let's see how we can solve this problem let's the intuition to solve this problem so here we have our sample test case or network fine so we have five nodes here the source node is node number one the destination node is node number three and we have at most two stops that means we have to we may have at most two stops while we move from The Source City to the destination city fine so in the previous two videos I've solved this problem using BFS and Bellman Ford algorithm while in this case I will be using diastra algorithm to solve this problem because this is a single Source shortest path problem we have a source node and we want to find the distance till each node of this graph or rather shortest distance till each node of this graph which can be found using diaster algorithm fine so we know how desktop algorithm work in diastra algorithm we greatly pick the node according to the cost so we pick the node which has the least cost so we start from the source node which is node number one then I push all its adjacent nodes into the priority queue so we use a priority queue which sorts the given nodes according to their distances from The Source node so I have pushed node number 2 and node number three into the priority queue they will be sorted according to the distances from this Source City so 2 will be at the top of the priority queue while node number three will be at the bottom of the product Cube because the distance till City 2 is lesser than the distance City hence and we know that the desktop picks the load which has the lowest price or lowest confines so I am assuming that so here at this point I'm assuming that you have a basic understanding of diastra algorithm how it works and its fundamental details if you do not have idea about dashed algorithm then I will try to read about desktop algorithm I will attach the resources in the description below so make sure to check them out and read about dust algorithm to better understand the solution which I am going to explain here so here I will simply be modifying my standard Astra algorithm a little bit so what I'm going to do we know that we have a constraint here so we cannot use a standard extra which is simply start from the source node and keep exploring its adjacent nodes keep picking up the nodes according to the distance readily and explore all the nodes of the graph and finally return the shortest distance till the destination city we have an upper Bound in this problem we can explore a path of maximum length of four nodes so we can explore a path having a length of Maximum three or having maximum number of nodes as 4 because in only in such path I will have at most two stops in any path which is longer than this path which is longer than 4 which I have more which have nodes more than four where is not a valid path because that path would have stops more than two fine so we have to modify our dust algorithm a little bit here so in the previous two videos where we used and Wellman Ford algorithm to solve this problem I used a distance array so what I did there whenever I arrive at a node with the cost lesser than the cost which we already have in the distance array and I performed a relaxation over that node and I update the distance array for that particular node that with the strategy which I used in the previous but in this case rather than using the distance array I will be using the stops so what does this stops array represents stops I represents the minimum number of stop which I have explored to reach the city number I fine so to reach city number 2 which is this the minimum number of stops would be Z to reach the city number four the minimum number of stops would be one because I can move from one to two then from 2 to 4 similarly to reach node number three the minimum number of stops would be zero and so go on so that's what I am doing here while so this will simply help me to find the cheapest cost path with minimum number of intermediate stops how let's see that in the priority queue which I use in diastra algorithm along with the node I will push its distance from The Source City so the first architecture represents the distance from The Source City the second integer represents the in my priority queue I will be along with the load I will be pushing its distance so first I will be pushing it first I will be using a distance so this dist represents the distance of the node from The Source City and I will also be using third integer which is stopped or let's call it stop because we have stops array so we call it stop variable so what does this represents or rather let's say let's call it steps so what this pair represents it simply says we have arrived at node we have arrived at this node its distance from the Solar City is this while the steps that we have taken to reach this node are these steps fine what does this steps represents so it represents the number of stops from The Source City fine so since I'm using a priority clue it will sort these triplets according to the first variable which is this in so as in the standard test algorithm I will clearly pick these triplets according to their distances from the source so initially I push this triplet for node number one or source that would be 0 1 and the steps would be easy so this is my priority while for the source City the stops array will have Z Storage now I popped this node from the queue from my priority queue so I have node number one now so I am exploring this city which is the source City and this is locked out and what I am exploring so here we will check for this triplet 0 1 0 first I will check in this stops array for the source CD if I have reached this Source City along some path which has few steps then the steps which we have here but you can see there is no such case the number of stops for City one in this stops array is also zero as it is in this or I've also checked if the steps exceeds the limit so what is the limit for the number of steps we can take a plus one step because we may have K intermediate nodes and one destination node so including the destination mode we may have K plus 1 maximum steps and K plus 1 is 3 and we can see that the zero is less than three so we haven't reached the limit fine hence I can explore the adjacent nodes of node number one so what are the adjacent nodes of node number one which is node number two and node number so I will push these triplets for these nodes into our priority two as so what will be this triplets for node number two you can see that the distance will become 10 because that's the distance of node number two from the suppose City and its number and the steps would become one because I take one step to reach this node fine similarly for node number three I would have 50 then I would have three and the steps would be one fine and of course these pairs into my Q so here I can see that these templates are sorted according to the distance so the stripper which I am going to pop out would be this top triplet which is 10 2 and 1. so I will pop 10 2 and 1 because this is present at the top of the cube so this is output so here I can check if the number of steps for this particular triplet so this stops and so I forgot to mention that this stops array is initialized with infinity why because I haven't arrived at any node yet initially fine so here I have taken one step to reach opacity number two and I compare this step with the steps which I already have in the stops array so for City number two the steps which I already have are Infinity so one is better than infinity so I store over here fine so why because one hasn't crossed the limit of three and one is better than infinity hence I update the number of stops for node number fine and then I explore its adjacent node the adjacent nodes of node number two which are node number four at this point I have the number of steps to reach the node number two I also have the minimum cost to reach the logo number two because that's for the diastra promises the cheapest price or minimum cost to reach each node fine so whenever I pop a triplet that triplet do contains the minimum cost for that particular mode to reach that node starting from the source that's what my director algorithm guarantees so the minimum cost to reach node number 2 is 10. so I have to check if node number two is the destination node or not it is not the destination node so I move to its adjacent nodes so what are the adjacent nodes of node number two node number four and node number three so I pushed the triplets for node 3 it would be so for node number three if I arrive at node number three Through The Notebook 2 the cost would become 10 plus the cost to move from 2 to 3 which is so which is 30. so I forgot to mention it here so it would give me 10 plus 30 which is 40 43 and the steps would become I have taken two steps to arrive at node number three to node number similarly the triplet for node number four would be the cost which is 10 which is the cost to arrive at node number two plus the cost to move from 2 to 4 which is ten so n plus 10 is 20 course and the steps would be so I have taken two steps to arrive at node number then I push these triplets into my priority queue fine so this is my queue that we have here so this will be the status for my queue we have these triplets sorted according to the distances from The Source node so I will pop the top triplet from this queue which is this 24 and 2 corresponding to the node number so first I will check if the stops has exceeded the limit or not and answer is no the limit is 3 while the stops here are two then I will check if the number of stops which I have here in this triplet is better than the stops which I have in the stops array and as it is yes because we have Infinity for node number four because I take infinite steps to know number four because I haven't arrived at noon before through any part this is the very first path hence I will update the node number 4 with this then so this is popped out then I will check if this node which is number four is the destination node or not because the distance here is the minimum distance for the corresponding mode because that's where the test draw guarantees and answer is no 20 is not the minimum distance to reach the node number 4. hence it Traverse its adjacent nodes which are three and five so for three if I read through node number four the cost would be 20 plus 15 which is 35 and this is node number 3 and the steps will be 3 now fine one two similarly for node number five if I arrive here through number four the cost would be 25 it is node number 5 and steps would become I push these triplets into the priority fine so this is my final priority queue after I push the node number 5 and number three arriving through node number four so then I would pop this node out of the cube which is node number five corresponding to that node we have triplet as 25 so here I can see that first time if I have exceeded the number of steps and answer is no the steps are 3 then I will check if the if I can if the number of steps which I already have in the drops array is better than the steps which we have here in this triplet so for November 5 we have infinite steps so three is better than infinite so I will update this stops array with 3 for node number five and I will check if node number five is the destination node and the answer is no it is not the destination node so I will move to its adjacent nodes so for so before moving to its adjacent nodes let's ask ourselves if it is optimal to Traverse its adjacent nodes I can see that I have already covered three stops to reach at node number five and to move to its additional nodes I will have to cover four or four steps and those notes will simply be discarded because I have exceeded the limit of the number of steps which is three year hence it is not optimal move to push its instant nodes into the priority queue so I simply pop this triple out of the queue fine then I will pop the next couple which is 35 3 so here I can check if the number of stocks which are here 3 are greater than the number of stops which we have here in this tops array so I can see that for node number three the steps which we have in the stops array are infinite so this three is better than infinite I can update it but I also check if the node which I have here is the destination and the answer is yes 3 is the destination node since this is a destination node the distance which we have corresponding to that node will be the shortest distance or it will be the minimum price or cheapest price because that's for the diastra guarantees in the extra whenever we pop a node the distance corresponding to that node has to be the short test distance fine so 35 is the answer for this particular test so I return my 35 right from here so what I checked here I checked if the tops do not exceed my limit and if I have arrived at the destination if these two conditions are satisfied then I can return my distance right from here fine and also for this test case is third let's see the implementation of the idea which I explained here so this is my find cheapest price function which takes in the flights array of size and soul City destination city and the upper limit for the number of intermediate stops I declare an adjacency list which will be used to store the graph I prepare my directed graph I declare a stops array of size n all the end nodes initialized with it with a very large value I declare a priority queue and I initialize it with the source node so I push Source node distance of the source node and the number of steps to reach the source node so this ID queue will simply sort these two books according to the first variable so here I'm running my test algorithm while the queue is not empty I pop the top element of the priority queue I segregate the three variables namely the distance the node and the step here I am checking if the steps which I have here for this particular node exceeds the step which I have which I already have in my stops if this is the case or the number of steps exceeds the limit then that means we already have a better answer so here we already have better answer and here we do not need to explore its adjacent nodes and in both of the cases we simply continue to the next node we do not have to process its adjacent nodes or to update the stops array otherwise I update the stops array to the new steps which I have here and here I have to check if the node which I have here is the destination node if it is the case then the distance corresponding to that node is the minimum distance to reach that node because that's for the Destra guarantee then I will explore its additional nodes and I will push the corresponding to pull for those nodes so for any neighbor node of the current node the distance would be the distance for that parent node plus the price to move from node to the neighbor node and I will push the neighbor node while the number of steps will increase by one fine if I have never arrived at this condition in this while running this algorithm if this condition Nevers is Never Satisfied that means I will never be able to reach my destination city hence I will return -1 right after I end hence I will return -1 right after I end hence I will return -1 right after I end my while loop fine so this is how the algorithm works and it will compute the shortest distance or cheapest price to reach the destination city starting from the source let's see the time and space complexity for this so in this algorithm I am processing each Edge at most K times which is giving me this time complexity a multiplied by K and for each Edge I am using the priority queue so I am pushing all those e multiplied by K elements into the priority queue and for each element the priority Q takes logarithmic time so this log Factor so to push and pop e into K elements it will take log of e into K time complexity while I am using a stops array that would consider a big off and time complexity so I'm adding a linear time complexity here because of the stops array of length n which I am using so overall time XT will become n plus e into K into log of e fine while the space complexity for this implementation would be big of n plus e into K because the N accounts for the stops array and E into K counts for priority queue I'm using because in the priority queue I may I can have e into K elements fine so let's see the code implementation for the idea explained here so this is my solution class where we have a fine cheapest price function which takes in the flights arrays so City destination city and the maximum number of intermediate stops allowed at declare an adjacency list to store My Graph then I prepare my adjacency list using the directed edges from the flights then I declare the stops array of size n and initialize it with a very large value then I declare my priority queue which will simply sort the tuples according to the first integer then I push my source vertex into this priority queue along with its distance and the number of steps to reach finally I run my algorithm Dash algorithm where I pop the top node from the cube I segregate all the three factors I check if the steps to reach this node see it's the steps which you already have for the stops array or the steps exceeds the limit which we are given for the problem there is one of these cases then we continue to the next node otherwise we update the stops array and I check if the current node is the destination node in that case I will return the distance and then I will explore its addition nodes and I will push the corresponding couples photo edges finally if during this entire process I do not arrive at the destination node in that case I will return -1 right from it so this is the -1 right from it so this is the -1 right from it so this is the implementation in C plus let's see the implementation in other lab so this is the implementation in Java and this is the implementation in Python language so that's all for this video if you like the video then hit the like button make sure to subscribe to my YouTube channel and give your feedback in the comments below I will see you in the next video till then take care bye and don't forget to the previous two videos for the same problem which I have explained here using VFS approach and using Bellmead Ford approach because that would give a better insight for the approach which I explained okay fine so thank you so much thank you
|
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 |
86 |
hello everyone welcome back here is when I'm saying today we are diving deep into lead code daily challenge number 86 partition list so our mission to partition a link at least around pivot value so sounds intriguing right so let's dive into a task so our task is simple given a link at least add value X we need to partition the list such that all notes less than x come before notes greater than or equal to uh X but here is the catch we need to preserve the original relative order so as you can see this is our link assist and pivot value x equal three so this is Pivot value and basically what we are asked so all values nodes that less than x come before notes that are equal or greater so those notes are equal or greater that I marked and those are moving here because they are less and also we are preserving the relative order of those greater or equal notes so it's 4 3 and 5. same as in first unprocessed list okay so now when we understand it let's dive into a visualization of the problem and how we can solve it so consider this list as a sorting game but we are not fully sourcing instead we are creating two partitions so partition before and partition after and think of it as we move all those nodes into one or a second partition to the left if they are smaller than our given X so it goes to B4 and if it's greater or equal it'll go to the right uh yeah if it's bigger so that's why uh if we look it's visualize we have value X that is free so x equals three and then we process every element so we process element one and it go before uh then we process four it'll go after then we process three uh it go after as well because it's uh greater or equal then we process two it'll go here then we'll process five it goes here then we process two it goes here and also because we preserve the relative value everything is in order and finally what we do we link uh to list so we merge this partition with our second partition and this is our result so as you can see Yep this is our result also we have the dummy variables so those zero were just dummy variables for efficiency so now let's dive into a code so we have uh our class solution implemented by lit code and our method partition and our first step is creating a two dummy nodes before and after think of them as placeholders so before yeah and after will be list node zero list node 0 and then we have before current after current and it will be before and after okay so now here is where the magic will happen so we will Traverse our list and if node value is less than x it join the before list else if it joins the after list and because we are working on list we need to also have a hatchet so while ahead if hat value less than x before current next before current so it will be heads and head so basically before current next is a pointer to next element and else it will be off after current next and after current and it will be hat and also hat and finally hat will be next so we are moving one element because it's linked at least and after current next will be known and before current will be next After Next and finally we return before uh next okay so uh this is our implementation so it's efficient because we are working on the list and not converting it to all right so this conditional right here so this is the hurt of our function so notes gracefully move to the right place so uh if it's less it go before and if it's uh else so greater or equal it go after and then we pick next note but by placing head to head next so uh yeah after we Traverse it's time for the final so we combine our two list and there we have it uh so this part is just a combination so after current next so it's uh after current it's known and before current next so we are merging uh it with our after next so finally we have both uh partition merged and we'll return uh the starting of merged partition so a pointer okay so uh that's it let's run it for uh these test cases hopefully it will work so yep all good and now we can run it for unsinterest cases as well to verify uh so constraints are probably harder so yep and our implementation bit 70 interesting so let's try to rerun it yeah 62. so probably those are different test cases and now we are beating 55 with respect to runtime yeah but basically it's quite efficient and it's time complexity of all and uh space complexity is o one so it's constant and as you can see free runs three different results so probably test cases and uh in optimal uh yeah test case I will be 90 with respect to random and 84 with respect to memory but all uh Solutions oscillate around 40 milliseconds and 60 megabytes okay so for uh other programmers that don't use Python I will post also implementation in other programming languages like go rust C plus and much more and here is a quick recap of our approach remember understanding the logic is a key so it's really simple but quite useful task especially for coding interview and once you get the coding logic coding become Embrace so that's it for today if you found this helpful give it a thumbs up and don't forget to subscribe for more coding tutorials and solution and challenges and much more and until next time keep coding keep
|
Partition List
|
partition-list
|
Given the `head` of a linked list and a value `x`, partition it such that all nodes **less than** `x` come before nodes **greater than or equal** to `x`.
You should **preserve** the original relative order of the nodes in each of the two partitions.
**Example 1:**
**Input:** head = \[1,4,3,2,5,2\], x = 3
**Output:** \[1,2,2,4,3,5\]
**Example 2:**
**Input:** head = \[2,1\], x = 2
**Output:** \[1,2\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 200]`.
* `-100 <= Node.val <= 100`
* `-200 <= x <= 200`
| null |
Linked List,Two Pointers
|
Medium
|
2265
|
483 |
The question has been asked that we have to find out, so if anyone has given us a number, but the example [ given us a number, but the example [ given us a number, but the example is fine, then what is a good base, if there is any one number, then any one such country, any one such base also. If we represent this number within it, then all the 11 numbers within it are the good base, so if we have any number from which we will get the result of one, then it will always be the good base, okay and the other one is good. The base will always be that if we take the smallest number from the given number and take a smaller number from it which is 12, then if we represent it according to 12, we will get one and one, so one is one and that too. What always happens is that the good base in the question is that we have to find the smallest one and yes it is modest, there is a condition given in it that the smallest one should be greater than you, that is, we cannot consider one. Now if we cannot consider one then what will be the biggest good base, it will be N - 1. N - 1. N - 1. Any other good base smaller than this is best to check. If any good base smaller than this exists then that will be our answer and there will be more smaller ones. There can be many of them, so we have to find the smallest one among them, so what is our approach that if we take the mother, any number is 13, it is fine and we take the mother, if any of its goodbyes are M, any max, what is its good base? And if he does it, then what will we do, that is, we will be one, some number of times one, inside that and M, we will be able to represent it in this form If we have to If we have to If we have to write it in 13, then how should we write it, then we will Let's multiply the last one which is one, the power of m is zero Okay, so basically we can write in this form [ Okay, so basically we can write in this form You can tell that this is not the life base. We know that whatever its range will be, which will be the range of good based, it will live from 2 tu to lake and mines one. Now if I take any of these, I will pick any M and I will see whether it is good base or not. So, mother, we will know from this whether this is a good base or not, whether to go right or left, we don't know, let's take another example, mother, if we have any number, then we and that one, we are three different people. It is represented in the bass, mother lo, it has three good basses, it has three basses, and if we look at the only, it has been represented to us like this, in K3 i.e. there is a number from the key, it has been in K3 i.e. there is a number from the key, it has been in K3 i.e. there is a number from the key, it has been represented in different basses and All three of these three have good base and if there is such a good base then this one is taking only three digits and it is taking even more than this, so what is it now, what does it mean that if there is a number and it is representing then What will it mean that k1 will be bigger than K3 and k tu will be bigger. The smaller the base of K3, the more will be the number of digits or terms. What will be the number of terms that we were considering earlier and now We have also got the number of terms that how many number of terms are we considering, so we were not checking here that if we have to go forward for any base or go back, but if we have to fix the number of terms. If we give this number of terms will remain five in this, we will take ad d next only five one, okay here, now we start considering the base, if mother, is there any base, five is the base, okay, so if We tried converting it from base 10 to base 5 and this life was in base five, so if we take whatever value it is, if that value x is greater than our original number N. And this, if I consider any base bigger than this, lo, I will consider 6, if I consider 7, then what will happen from that, this value will increase even more, then there is no point in checking the value beyond 5, if lo, this is the same thing. What happens is that if the value in 5 is small, the caste which is in 5 has become small, then if we check three or two, then they will come out small, so we will ignore them here, my brother. We will be able to just put it if we have fixed the number of terms, that is, we have fixed the number of terms, then we are getting to see the number of terms, that is, this will be the number of terms, how many can they be, meaning whatever is the base, it is the minimum. How in this, what we have will be the maximum according to the given constants, what is the value of N and what is K, meaning this is our base, it will have its minimum value, you take mother and the base is ours, meaning this is how. What will happen in this way is that our number of terms has become maximum and what will be the maximum, then that maximum will be 18 to the power of 10, so the power of 10 is 18 which is around 62 is around 63. There is a range so that means the approximates are around 63 or 64, that means when will any best be the smallest when we will consider the number in it, we will consider our mother, we have 63 times, according to that we will consider the base. If we find a base, that is, what it is, it will be the smallest base, so if we take 63, we have found a base, that is, in 63 number of terms, we have found a base which is equal to N, then That is, it means that it will be its smallest space, so I have to run a loop, that is, we will run the loop in reverse because we will first keep the number of terms, that is, a loop will run to fix the number of terms and what will be the number of terms. We keep going from 63, okay, that means from 63 to 1, we will have one person who will fix the number of terms, after that now we have the number which is the range of the base, what is the base, from tu to lek n - 1, okay. This is the range, tu to lek n - 1, okay. This is the range, tu to lek n - 1, okay. This is the range, without having a look at it, here we have written whatever is, it can be hi, whatever is our N - 1, it can be whatever is our N - 1, it can be whatever is our N - 1, it can be that that that as long as our low is hi, we will run and calculate. Now we have to check is this goodbye 63 okay number i.e. how many K ones will there be in that 63 times i.e. how many K ones will there be in that 63 times i.e. how many K ones will there be in that 63 times we will have one and M is ours here in this like 1 * M to the power zero then one in this like 1 * M to the power zero then one in this like 1 * M to the power zero then one in D power one then one in And we have to keep adding all these, there will be this number of terms, like here it is 63, we have to run this loop that many times, so basically what will I do here, I will write which will run from where to where, from zero to lake i, what is i is ours. Number of terms is ok, so I have written the loop which will run from zero to i and I will do this. What is the meaning of getting this product done and getting it added, then for that I will take a variable here and initially made it zero and always Here we start with one, that means the power of one is zero, one is 1 * 1, that is, the power of one is zero, one is 1 * 1, that is, the power of one is zero, one is 1 * 1, that is, the starting value will always be added If Maa, as soon as added If Maa, as soon as added If Maa, as soon as we have added the sum, then it is even, it has become greater than the number, that is, if The group that was ours has now become greater than us. The group that was ours [ that was ours [ that was ours So what will So what will So what will we do with it will be even bigger, so from here we will break it, got it made one plus, now here the value of But now we have to add m², that is, what we have to do every time is that we have to multiply our We will do it only till then, we mean IF < Show, then we have to check this thing first that if we multiply this thing, then we will know that it will overflow, then we We will do that multiplication, right, so what will we have to do for that, now how will we know that Time means m² or m means m to the power i represents time, so what will we do, we will write one more condition here, before doing this, we will check one thing that if our now, take the number which was our n. Out of that, this sum of mine is already ours, so that means that that that child, if it is reduced, that is, if that thing is reduced, then what M*X or It will be reduced, then what M*X or It will be bigger i.e. bigger i.e. bigger i.e. what will happen in this how it will always go bigger than our number i.e. if it is not our number i.e. if it is not our number i.e. if it is not broken, it will go bigger than that, so in this how and here we will check the same condition and with , i.e. this thing If it is with , i.e. this thing If it is with , i.e. this thing If it is smaller than this then what will we do in this also what will we do we will break the problem here is that this should not happen so we had got this condition checked earlier but if we have to get the multiplication done then what? It will definitely happen because this is what will happen, it will flow, what will we do to save it, what will we do with it, we will either send M there, send X there, then I will remove X from here, basically, we will multiply this X. Here, we will send What will happen after that we will come out and check that if our number was even, that is, where it was even, it is greater than our number N. The number which is even, was not greater than N, it was still smaller than N, but we broke it, but this which There is a break, he was also doing the same show and our even number was going to be much bigger than the number M, so we will have to check this too, even if this is a condition, our point is the same that if you think it is big then check it. For , let us flag check it. For , let us flag check it. For , let us flag that the flag was initially zero and if this condition is run then before breaking we will change the value of F to one and here we will check that either the sum has become greater den or we have Here we have broken with this condition i.e. the broken with this condition i.e. the broken with this condition i.e. the flag has become a band. For a particular base, our sum is going bigger, so we will check the value ahead of it, otherwise we will check the value behind it, so yes. Hai I which is ours, we will make it metal mines one i.e. we will bring Hi behind mines one i.e. we will bring Hi behind mines one i.e. we will bring Hi behind and the second condition is that it is LCM if mother lo that our time is less than N i.e. we will check it with the value behind it. If we than N i.e. we will check it with the value behind it. If we than N i.e. we will check it with the value behind it. If we check the next value, then that means that this is equal, you will become our M plus one and then similarly, what will be our else, that is, whatever is equal, it has become equal to N K, so if these two have become equal, then we What will we do, we will return, our answer will be the same, we will return, we will band like this, if we talk about One Plus City, then these people will do it 63 or 64 times and what is happening every time this Which is the binary search code, meaning this binary one, I know that people and time are late and how much is late, it demands the difference of this 'Ha' and 'L' demands the difference of this 'Ha' and 'L' demands the difference of this 'Ha' and 'L' i.e. it will run these logos 'H-L' i.e. Hi, 63 times. i.e. it will run these logos 'H-L' i.e. Hi, 63 times. i.e. it will run these logos 'H-L' i.e. Hi, 63 times. Mines, it has come from zero, I mean, what is basically the number of terms, so the maximum number of times it can run, then these are 63, so basically its time complex is is is not doing it at all.
|
Smallest Good Base
|
smallest-good-base
|
Given an integer `n` represented as a string, return _the smallest **good base** of_ `n`.
We call `k >= 2` a **good base** of `n`, if all digits of `n` base `k` are `1`'s.
**Example 1:**
**Input:** n = "13 "
**Output:** "3 "
**Explanation:** 13 base 3 is 111.
**Example 2:**
**Input:** n = "4681 "
**Output:** "8 "
**Explanation:** 4681 base 8 is 11111.
**Example 3:**
**Input:** n = "1000000000000000000 "
**Output:** "999999999999999999 "
**Explanation:** 1000000000000000000 base 999999999999999999 is 11.
**Constraints:**
* `n` is an integer in the range `[3, 1018]`.
* `n` does not contain any leading zeros.
| null |
Math,Binary Search
|
Hard
| null |
418 |
hey everyone welcome to my channel so in this video i'm going to try to solve this problem and at the same time i'm going to follow the general steps you should follow in the coding interview when i'm trying to solve this problem so first of all let's try to resort this problem to get a good understanding so during the interview if there's anything unclear to you feel free to bring the question to the interviewer so let's see so given a row times column screen and a sentence represented as a list of the strings return the number of the times the given sentence can be fitted on the screen so the other of the words in the sentence must remain unchanged and the word cannot be split into two lines a single space must separate two consecutive words in the line so let's see the example let's say okay so the first example might be a bit easy but let's see the second example we have a b c d and e three words in a sentence and the screen is three times six so we see we can first put a and b c d uh with a single space separate the two words on the first row and then we put e and a on the second row so the reason we cannot put another bcd is because we run the we run out of space for the second row so for this one we are going to be able to put two of the sentence on the single screen so that's pretty much it i think um yeah so i think we have a good understanding about the problem so let's see the constraints first so let's say we have the sentence containing words anywhere between 1 to 100 each word contains 1 to 10 letters so each so all our lowercase english letters and this crane row 1 column is anywhere between one two twenty k okay so it seems like the row can be row one column can be pretty long um so let's see so until now i don't really see any of the ash case that is worth to mention so let's see let's think about how to solve this problem then so how to solve this problem so the first thing i can think about is a profile solution which is to do some simulation so what i mean by simulation is that uh for each of the line we try to fill as much of the words as we can and then uh until we reach the end of the row and then we start another row so for example let's say for example two first of all we put a here and then we put another empty space here and we put a bcd here and we see okay we only have one space here so we cannot put another word there and then we start another line so on and so forth so for this one um the disadvantage for this approach is that when the when each row is very long then it is going to be very time consuming so for example here so for example let's say the row is one thousand uh space long then we are going to repeat the step like we put a and b c d e and a b c d e so something like that then it is going to be very time consuming so instead um one idea to make some improvement on top of this one is to uh is to actually not really do the simulation uh instead we could do something smarter so that's the second way i'm going to mention so the second way what we could do is we could change the words in the sentence together to get a real string so for example for this one you get a b c d and e as a single string so um in this way what we would actually we need to add another space here because if we have another sentence we want to add another sentence which is a b c d and e we actually need a space to separate them uh to separate the two individual sentences so here uh first of all we will change the words together and separate each of the uh and separate each of the word using a single space and then we have a string which contains all the words in the sentence and then we will see how many uh how many sentences we could fit on a single row so if we reach the end so for example let's say this is a three by 6 column here we cannot really fit all the words from a single sentence in the single row so we could actually fit entail this space so that's where we are going to continue but let's let me give you another um better example let's say if it is a 3 by 100 3x100 screen then it is going to fit actually more than one of the sentences on the single row so here what we could do what we would have is we could actually fit anywhere 100 divided by 2 oh sorry this is 0 1 2 3 4 5 6 7 divided by 7. so in this way we could save a lot of time when i save a lot of time when comparing with the first way which is about doing some simulation since that we could do some simple math to calculate how many of the sentences we could fit on a single line and then uh at the same time you're going to try to um try to compute where we should restart when we try to start a new line which means um for example if it is only going to fit the first two words um for the rest of the space on in the first line then we are going to start from e uh at the second line so that's pretty much about the general uh general idea how to solve this problem so let's see uh the runtime for this so here of course we are going to have the rows as a factor in the runtime so for so the runtime to fit the runtime for each of the to fit each of the row is gonna be so let's say it could be anywhere yeah so it could be anywhere between well i would say it would be max lens of word in sentence so the reason for this is because we just we are just going to try to find the first uh space we are trying to the first space so for example let's say we only have zero let's say for the last for the rest of the space in the first row we only have five space there then we are actually let's say we have all right so let's say we have six of them oh sorry um that's not a good idea so let's say we only have four of the space for the rest of the line then actually we need to find the first space that separates a and bcd then we go back until we find the first base so that's going to take the to find the space here like the space between and bc it takes uh like linear time of the length of the word so that's why i had a factor which is maximums of the word in the sentence so that's essentially the runtime and uh i think that's pretty much it for this solution so let's do some coding work on top of it and see how it works so first of all i need to have a string so let's say sentence str that's equal to a or maybe you need to have a string builder here new string builder there you go three two of the word in the sentence so if speed dot depend the word was a space there and then we have string as sentence steer is good asp.2 string steer is good asp.2 string steer is good asp.2 string and then let's keep another thing which is called sentence lens it's going to be sentence str until now we have finished the first step which is going to change all the other words in the sentence together and separate using a single space there and then the next part for us to do i would say i'll keep a another one which is the cursor so the cursor is actually uh the cursor with the cursor is actually how much of the space we have actually used to fit the wars within the string so the cursor is going to start from zero we are going to have let's say how the well uh row is equal to zero row is smaller than rows and uh plus zero so this is going to be a for loop to go through each of the row and the way in each of the row we are going to do the calculation on the mass calculation we talked about so here what we would do is we need to have the cursor to start plus equal to column so that's the new space we are going to allocate here and okay so let's see if well if i would say if cursor uh modular okay so this would be if sentence str the car at cursor modular the length of the string so let's say x cos in this lens so if this one is a single space so which means uh we so for example for this example let's say if the cursor hits uh here then it is a it's actually a space there so what you do is we could actually say okay we could just save this space instead of using more of the same space there so what we would do is um we could uh have cursor plus cursor you're going to plus the cursor here so like here we are having the space then um yeah so if that is okay so let me see if that is a space then we need to pause the cursor because we need to fit the next word in the new line okay otherwise what we would do is we need to find the space there sure so well so if it's not a space then what we would do is if the cursor is well the cursor is the letter or equal to zero and the sentence is tr the car at this is would be cursor divided by modular sentence lens if that one is not equal to a space there you're going to minus the cursor there so that's pretty much it um so let's see so after that we are going to have the cursor so the cursor is going to be something like all of the space we have used to allocate uh to all of the space we have used to allocate the words within the sentence so here finally what we could do is we just need to return cursor divided by the sentence less so i think currently that's pretty much it so uh yeah so currently i'm thinking about whether we should plus the cursor here for this if loop so if it is so if we are encountering a empty space here um so what we would do is yeah so we need to actually say okay this is the space we have used to allocate this okay i think that should be it and then well the cursor is not equal to a uh a space there then we're going to say okay minus the cursor and then at the end it wouldn't be a so at the end it would be the space there so when it has a space we should say okay we should actually plus cursor which means we have allocated a space for this single space there um sure so let's run through this code to see how it works then hello world it works and then for the rest of that it works as well let's do a submission for it to see how it works okay so it seems like we have done with this question and that's it for this pro coding question if you have any questions regarding the solution or regarding whatever feel free to leave some comments below if you like this video please help subscribe this channel i'll see you next time thanks for watching
|
Sentence Screen Fitting
|
sentence-screen-fitting
|
Given a `rows x cols` screen and a `sentence` represented as a list of strings, return _the number of times the given sentence can be fitted on the screen_.
The order of words in the sentence must remain unchanged, and a word cannot be split into two lines. A single space must separate two consecutive words in a line.
**Example 1:**
**Input:** sentence = \[ "hello ", "world "\], rows = 2, cols = 8
**Output:** 1
**Explanation:**
hello---
world---
The character '-' signifies an empty space on the screen.
**Example 2:**
**Input:** sentence = \[ "a ", "bcd ", "e "\], rows = 3, cols = 6
**Output:** 2
**Explanation:**
a-bcd-
e-a---
bcd-e-
The character '-' signifies an empty space on the screen.
**Example 3:**
**Input:** sentence = \[ "i ", "had ", "apple ", "pie "\], rows = 4, cols = 5
**Output:** 1
**Explanation:**
i-had
apple
pie-i
had--
The character '-' signifies an empty space on the screen.
**Constraints:**
* `1 <= sentence.length <= 100`
* `1 <= sentence[i].length <= 10`
* `sentence[i]` consists of lowercase English letters.
* `1 <= rows, cols <= 2 * 104`
| null |
String,Dynamic Programming,Simulation
|
Medium
|
2082
|
201 |
hello counters I'm Marita and today I have a very cool different we have another day of Fleet Code challenge and before I solve this problem again judging from problem title I think I can guess what the problem will be about I might be wrong so but before going to Cody I'm guessing the statement and I will first explain easier version of this problem what if there was a sequence of zeros and ones and we need to efficiently answer queries give me bitwise and of some range of some interval I don't know if it will be a case but let's say so there is sequence and queries fine bitwise and of this interval then it is 0 if and only if there is at least one 0 here bitwise nth of this interval is 0 and bitwise and of this interval is 1 we are talking about this operator so how to check if something starts in some position and that somewhere how to efficiently check if it has at least 1 0 we can pre-compute something to then we can pre-compute something to then we can pre-compute something to then answer every query very fast and this will be if something starts here I will forever position remember in next 0 what of I let's say we have such an RI and next 0 of 6 of this position it will be 9 and I will compare that with nth of interval if I need to answer quickly for this interval from 6 to 7 I will check if 7 is smaller than next 0 of 6 if yes then it means that next 0 after 6 is to the right from this end of interval this is another example what about quickly answering for this big interval we will check next 0 of this like 0 of this is free so I know starting from here I can to the right and I meet first zero on the 3rd position so much earlier than this the condition I arrived earlier next zero of L this is important next zero of L must be what greater than R if we are talking about interval from L to R then bitwise end of interval is 1 because there are no zeros in the sequence and this era can be pre computed before all the queries in linear time if we go from right to the left through the Hara now I really hope that I correctly guess the statement otherwise it will be a bit stupid to have this explanation the beginning at all also here but more given the range oh I thought the house will be queries in array okay I didn't guess correctly you don't mind that even a range return the bitwise end of all numbers in this range for example let's say we have range from 5 to 7 5 is 1 0 1 then 1 0 is 6 1 is 7 I'm writing them in binary form to understand them better very position I just need to know all numbers they're all digits there are ones so what about this I hear their own ones what about just tracking the first number and the last one if there is one here let's say that first number is this the last number is that then we can find common prefix and that common prefix tells us that only those are candidates for all ones in the suffix there was zero and every position at least once because in particular yeah I'm quite sure about that if this is starting number this is ending number then in particular somewhere between them there was this thing with common prefix and then just zeros bitwise and of everything I claim is just this so find common prefix of M and n they are up two days for every bit from position 30 or 31 30 if M and this I track bitwise end of M and this bit to track if this bit is on this is true if this is different than the same in the other number then something happens I'm done I entered the common prefix so maybe break otherwise if they both have this bit then it will also be in the answer otherwise they have the same meet so I can just say answer I can or it with this assuming that it is in both those numbers this will work I will simulate this on some example and then also explain to you what I thought the problem will be and we will solve that other version together does this work I accept it so what about some simulation for example five seven maybe with bigger found and we don't need the timer anymore four five seven those numbers are really represented by in computer as 32 bits but let's say there's some number of bits at the end there is one zero one second number is the same like that my solution is iterate from most important bits so it compares those than those and so on and as long when there will be inequality like here zero and here one it will break because it will sign now from this moment nothing can be one why if this is zero and this is one I am saying that nowhere in ant bitwise and of all numbers in range there will stay end they will stay one because from this number to this one I am listing all the numbers in between in and in particular these numbers this number is in between if this is let's say 230 this is I don't know maybe 888 then there is some number in between might be 5 to 12 I'm just saying random values but there is some number here that consists of this common prefix than 1 then all the zeros and bitwise end of some numbers including this one they said everything here to zeros in dancer in the bitwise and hence after this first common mismatch first mismatch between m and n on the right everything will be 0 this is first thing the other is that there is some common prefix like here maybe this that then well the first mismatch is over there but before that every number in between them will also have the same prefix just like you know if you listed down all the numbers starting from 1785 to 1799 all the numbers in between they will have the same prefix 1786 1787 and so on I found this common prefix and in binary format of course I'm not thinking about decimal format in binary format common prefix means that ones will be there in the answer this in C++ bitwise and of the answer this in C++ bitwise and of the answer this in C++ bitwise and of number m and number that just consists of a single one like this bitwise end of this and that is just there to check if there is anything there otherwise this would be 0 if this is nonzero then I decide turn on this bit in answer you will find maybe some more detailed or just better introduction to be twice operations in my bitwise operations in C++ video on it recently almost every C++ video on it recently almost every C++ video on it recently almost every problem for almost every problem I just say watch that other video of mine and it's got like already have some useful lectures now I will quickly tell you what I thought the problem will be that may be more common in competitive programming you're given an R I like maybe 5 7 10 21 0 7 8 and so on and there will be queries and you need to quickly answer a query like give me a bitwise end of this range if maybe twice end of this range and so on and then I wanted to be smart and predict that it will be it then we need to write every number in bitwise in binary format and focus on every bit separately for every bit imagine the sequence as just an array of zeros and ones so if first number is 1 0 1 second number is 1 third one is 1 0 and so on I focus on a single bit let's say the last bit then I have sequence 1 comma 0 and writing those bits down then 0 again 1 and so on like the last digit in binary format and on this I can answer queries about ranges in constant time like I told you in with drawings to get the final complexity of pre-computation and times 32 or n times pre-computation and times 32 or n times pre-computation and times 32 or n times logarithmic value this is length of binary numbers plus for every query you do something for each bit separately so this is instead of n times Q if you just implement a brute force but this is not a problem for today apparently maybe next some next day just maybe there I am sure it is somewhere in like culture for code versus sounds quite standard so that's it for today that was quite unusual because I talked half of the video about some another random problem that you have no idea about but I hope it wasn't bad for you to watch consider liking a video subscribing to the channel if you haven't and see you tomorrow bye
|
Bitwise AND of Numbers Range
|
bitwise-and-of-numbers-range
|
Given two integers `left` and `right` that represent the range `[left, right]`, return _the bitwise AND of all numbers in this range, inclusive_.
**Example 1:**
**Input:** left = 5, right = 7
**Output:** 4
**Example 2:**
**Input:** left = 0, right = 0
**Output:** 0
**Example 3:**
**Input:** left = 1, right = 2147483647
**Output:** 0
**Constraints:**
* `0 <= left <= right <= 231 - 1`
| null |
Bit Manipulation
|
Medium
| null |
1,872 |
s tok uh problem number 8 1871 is it a patent vs. problem? Ah, in the same case of this problem, ah, now if you change the 4 types of 5 types, you will solve it by doing 5 things. Now, is there a surprise 4 meters? Like this, once or twice, with dp, first of all, from plan de dp. Schedule 1 person ah dp definition once you add it to the first foreign dpi ah ipl event ah this is the number of files from the dot to the staff woongji when there are up to 3 people xl t ah yes really Email Second child Bar Why you hit 1 to 4 Ugh 4 When you choose between Gimje and the turn will end, fur will end and the next hit you get when you use the x 5 I will define it like this. Report uh close and ddp is close tiger what should I do with you ah until uh I'm strong today I'm going to try to capture it even though the first breath was next to dl 3 4 which will be curl c ok let's decide on the top so there are cases like 2h case t1 case give d l Ah, it's absolutely impossible to decide. 5. Then and later, die. Topia tl. Do you want to get rid of the first one? 2. I'll give you a bullet like this. Oh, ah, this example. Where do I go from 10 to 10? When it became Lee Gye-seong's book, it was When it became Lee Gye-seong's book, it was When it became Lee Gye-seong's book, it was the first. The law has to be selected unconditionally, so there are more than 2, so there is a condition for 5 cases, and in particular, add the current value and set the text ah. In the chubby array, ah, this is the 1st, so you have to proceed in a format that continues to decrease by 3 one by one. Oh, one by one, you have to shorten it and ask questions in the form of just one because, for example, if the curry of the control came at an expensive price of 114, then now you can write down that 1 and select that player. That year, the National Assembly's recognition is e2 exploration, right? 1 Including write like this yes 2 because there la le um business April pleasure ah then this here per this is zero yes it's a little bit caught now two only it's neat like this 1 Koran difference Conan fur's of here again 4 xt la The file in where 2 Moreover, what is added is to send the accumulated value to 234 first, and then ah or 5 So it is very narrow. Yes, it is easy to do X-ray like this and to first like this. It's a choice, but the easy to do X-ray like this and to first like this. It's a choice, but the easy to do X-ray like this and to first like this. It's a choice, but the salary is a bit harsh and I haven't been able to get it. That's 10 lee - the phone should be black. It's false. Wait a minute. Yes, I've done it now after going through this process. Below, the comparison value is wrong. Like this - that Like this - that Like this - that 5% value. If you 5% value. If you 5% value. If you look at this here and read the problem of going to the fight, you will first choose the axe, and then the broken island will be escorted by that player, and then you will move on to the other player. So, because the difference between height and key is important, we will do ql eight - week fat. will do ql eight - week fat. will do ql eight - week fat. So if I solve it like this, uh, First, the top comes out. But the cherry is like me. The reason why the cherry comes out is, ah, at first, uh. In the case of 1-axis skis, 1-axis skis, 1-axis skis, when qna goes in first, m-sc cube cuts occur, m-sc cube cuts occur, m-sc cube cuts occur, so of course, it is a review best insert, so it is push-shop shift, ah, restaurants, etc. It so it is push-shop shift, ah, restaurants, etc. It takes as much as the maximum pen, and it takes a bit of maximum taste. There is also a crack, but when viewed as a whole, this is the biggest crack. Now, Act l 100 - 2 terrace can be Act l 100 - 2 terrace can be Act l 100 - 2 terrace can be dug up if Blythe is a thing. Therefore, this time, the preferential ride on this side is yes ah um - f yes life topeak Nepe work is percent, so Blythe is a thing. Therefore, this time, the preferential ride on this side is yes ah um - f yes life topeak Nepe work is percent, so Blythe is a thing. Therefore, this time, the preferential ride on this side is yes ah um - f yes life topeak Nepe work is percent, so this planet is 2 like this. Yes yes it will take Smarto Tayo Cook text will take yes this lies this ang win as much as misaeng So in this way the surface is once * possible because the if So in this way the surface is once * possible because the if So in this way the surface is once * possible because the if value is uh up to 5 o'clock in the era so 5 teams for this and Eyes 2 Sean El Che didn't think about it all, so I haven't thought about how I should optimize this and how I can tie it up and release it from Lee Ji-hyun. If and how I can tie it up and release it from Lee Ji-hyun. If anyone has thought about it, I would appreciate it if you could tell me about the living zombies. Also, if the tc improvement method is a bit wrong, please leave a comment and I will reflect it, edit it, and post it in the comments. So this is not the first ICA seal method, and now it is the second method. I will try to solve it with the 2.1 method. I will try to solve it with the 2.1 method, especially with 2.1. This is especially with 2.1. This is especially with 2.1. This is how to solve it when BEXCO Racer makes a request like that when you choose the iter n. In this case, you have to set it to write uh ah and do it uh quick 7 days like this, so duet customers also o 5 like this uh again that. Next time, the important thing here is writing 2. The value of dp max won will be 0, and listening m - m - m - 1 pack, writing ah f First of all, as an example, once the value comes out, the curse cove dpm - 1, why does it curse cove dpm - 1, why does it curse cove dpm - 1, why does it happen like this? Mr. HTML s said we decided this way, because we tried it like this, dpm - 2, the dpm - 2, the dpm - 2, the array itself in this state. 4 uh mrs from before and then ele th uh mr se. This is separated by a torpedo. Since there is a floating young lotto, if you select here now, it is true. If you select here, now als clr is a processor, so it has 5 advantages from - 1. Until the advantages from - 1. Until the advantages from - 1. Until the entire war breakaway island, that's how it became a sex animation, so now here, now, for now, we have to think about it, but ah, we're like this, the aspect Benji, the ideal sex spawn, what we want to see is now deeply, now it's 2002, so now it's the throne. Now, we need to search in reverse order from t20 to a, because this condition of the 2 times last students is shown, so m - is shown here, so m - is shown here, so m - is shown here, so m - 2 is - 2 is - 2 is obtained and used for handling, so the range can be set like this. And especially pin ah like this servant ah ha ah how did you set it up like this ips ipo 522 ah so far it's easy to see it as a representative child n atex special 1 2 just that rifle px ah jplus one designers dp j how It will work. Ah,this Ah,this Ah,this will be the gp, so I think the cool side of this side will probably come out. Let's see. I wrote one that I don't like, so I'll try the test case. But the expression chin comes out like this. So photo time, ah, come out with Excel. What I can't do is x because this is a flower. Even though I'm busy, I'm a slave sq. Because of the time complex Tiga on skew, it's impossible because it's revived a lot outdoors. I have to decide if this is good somehow, but before that, I'm confused for a moment. That's why the false settings of j are iPlus. I'm a little confused as to whether it's the J Plus i. So, jps i, the J Plus i, is the color right now. Let me think about it for a moment. The i-i number is set up. moment. The i-i number is set up. Where is the pie ipl, the gp that I'm trying to use? Yes, that's the computer. Up to the ith and then tips or tools 3 The fighting hand goes like this, but ah, I saw this 4 Why did you come? You have to make a choice unconditionally. 1 When you become the opposite sex ti, you can now choose the indoor tower. The first place is from iPlus on to n, so it's the same as iPlus One. I've been confused lately, but uh, it comes in 5 packs. So, heh, now, how do I optimize this? And let's do it a little less for a while. I don't know how to do that anymore, but the author says, hey, this is the key, this. To explain this, I 'll give you the 3rd screen. I really want to see the screen. Now, when I look for a job in depth, I'll think about it for a moment. I wrote down all the top 1 things, but when I look for a DP job, this is included, and now this scope itself. 3 for Tony, 5 for Sato, etc. Settings like this are shown with the selector. 233 234 235 It is impossible to select only this. Since it is possible to select only this, ah, first of all, even if you can get a party like 1234, you can get the first volume. Party members are excluded. Letterman is paid and becomes a sin this time. When you select this time in number 2, there were 300 million this time, and when you cut it, if you think about the calculation once, the side of will come out like this. If you look here, the signature is Write from e to 2 plus 3 and it ends here. Since it's over here, let's do it here and then the important thing is now the depth of 3, B. March, now we have to subtract it. edp, which is now included in the 3rd time. Then, 3 is included. So now the bp that you can have here 2 3 will now be the xx twist of this orphan. Likewise, if you cut it here and use it, ah, from the sum 0 to 2+, 3+ answer - tip 4 2+, 3+ answer - tip 4 2+, 3+ answer - tip 4 ah, and you have selected everything from here to the end. In this case, 0 will be 3455 - tpo. In this case, 0 will be 3455 - tpo. In this case, 0 will be 3455 - tpo. So what is tp at the depth we are looking for? It will be the total maximum of this. Maxim. But here, let's take a look at the dp fight. How can the dp fight be defined? If you think of it as the array itself when the depth is 3, the island from 0 to 3 and n4 n5 like this, now uh, that Murray will be given to the haerang player, where 2 Maximum Since you have to choose a4 all the way through - tp depth standing or n - tp depth standing or n - tp depth standing or n here, fight plus n4 plus 555 - tp pied, 555 - tp pied, 555 - tp pied, it will be something like this, but uh, look at the facts. Just for quick understanding, I wrote it all down like this, and this is uh. Buy 5 trillion people and then sign 5 trillion. So the DP business will fall like this, so this calculated value is 2 weeks. The calculated value is completely the same as DP life. Perfectly, so the maximum fast transaction itself is now This load, the second arm, the second sheet now comes to ten, and then these two now come to dp3 like this, so if you write it down like this, there will be no more. - dpi Also, the maxi of the dpi, - dpi Also, the maxi of the dpi, - dpi Also, the maxi of the dpi, uh, can be reduced in a generalized way. Oh, and uh 2pm - on Young's dpm A, uh 2pm - on Young's dpm A, uh 2pm - on Young's dpm A, uh huh, is it like this? uh, the transplant itself is actually uh, this navigation 2 intervention gay gra cable ordered. What I'm saying is that when m - 1n ordered. What I'm saying is that when m - 1n ordered. What I'm saying is that when m - 1n child is m - one, child is m - one, child is m - one, this means that from 0 to m only S-1 must come out. Uh, this is 4. Since it is always true, the means that from 0 to m only S-1 must come out. Uh, this is 4. Since it is always true, the means that from 0 to m only S-1 must come out. Uh, this is 4. Since it is always true, the number of 2pm is uh, zero. You can think of it in this way. ls 1 Lee Young-ji English If you are ls 1 Lee Young-ji English If you are ls 1 Lee Young-ji English If you are curious, I think you will have found the answer here. Ah, so what should I do now? As you saw earlier, you can now reduce the dp itself. dpi is conscious. I can give you a table, let's listen inn uh I can write it down in this way. 4 This is a bit complicated, so I'll give it 1000 won, so I can't find the 1st 1 window, so I ca n't get rid of the 1st window, so I have to write dpi - 1m 4, ah, have to write dpi - 1m 4, ah, have to write dpi - 1m 4, ah, a it. solves dpi If you think about it easily, you will be able to determine the timing a little more. Then, now you can set this to Tig Imsil for January. Now you can set the mowing b value. So if you write it like this, Ah, my last value. It will be 1. Especially when we want to improve the law. Then, in the first case like 1, gp ah - we have to start from 2. ah - we have to start from 2. ah - we have to start from 2. dp - because we have to make this investment. dp - because we have to make this investment. This uh child has to start from m - 2. There child has to start from m - 2. There child has to start from m - 2. There is uh m - 3. Here, the is uh m - 3. Here, the is uh m - 3. Here, the result can be obtained. So, unless you make a mistake, you idiot, the answer should come out here as well. 4 If you do this, you will get a top like this. Here, in this case, the 2-time compact ct is no longer this, but the 2-time compact ct is no longer this, but the 2-time compact ct is no longer this, but the score is a bit laggy, so it is turned on. oz is turned on, but the space complex tsh compact T is now turned on. o Even if you add it in language, you can actually get rid of this 2 3. What is important as a result of this dp itself is the a performance up reason value, so I can tell you after writing this magazine. How can I write this down? Ah, rs will be ah ep2 ah, and ah bass is now m - Why do we have this now? m - Why do we have this now? So now we are starting with FRS After. The number of S computers has now decreased significantly. Now we have S Association, so there was no S. You know, just for a moment, I'm going to cut off the video, and now - you're using your Mac to process it, but I'm - you're using your Mac to process it, but I'm processing the video recording, so I think it's holding up right now. The video is still being recorded, but my audio is different now. While watching, I am playing solo again. Now, there is definitely a problem with god. Now, I am using the audio dock for the second time. Anyway, if you look at the video on the side, I am using Feltics to give this 3. This is because this also has a space complexity of n. Since it takes up this, there is no way to kill it. In order to get rid of the method, first of all, mentor the portal. What we need is the prefix n, first of all, the pna value for initial eyes, and then the fix eye plus one that goes on strike. You need the value first. Therefore, when this is the total value, first get it. Ah, now you add msh. Then, pxi plus one. Now, how should I look at it? Pass like this. I plus one. When entering the prefix 100, you have to say that there is 100 won. The value you have now is the overseas value of Feltics. Should I set it now? So, in order to obtain m security, you should always subtract it. Because he has hair, he's on his waist - I'm on his waist - I'm on his waist - I'm going to take it out. His second ham, the third element, ka, so uh, I'm probably thinking right now. I'm thinking about how to give it now. Because of this, I'm not taking out the array eye, but I'm taking out the eye plus. Because I have to subtract the value before the 2nd start, it's rotten, and now I'm ignorant. What happens to my line now? Oh, I'm ignorant again. There isn't, and I'm starting to look for it now. Then the mother found it and it's Child Plus One. Ah, it's funny to see the recorded narration of the defendants. Yes, it feels like an interview that I interviewed on their behalf. In this way, it's on the screen now. Now the time complexity, now the space booth is also attached. Oh, it comes out like this. It comes out on the phone, and now the memory value is much larger than the one I have no use for. Compared to the bachelor, 0.1 bytes are included, but why is it 0.1 bytes are included, but why is it 0.1 bytes are included, but why is it so big? Now, I am sharing my experience with the knit code. I'm talking about it. Oh, and now it's the second time. When I make a selection from the child to the child, I select the child, and when I move on to the next step, I go to the 2nd page of my daughter's child set. I'm trying to organize it and solve it. I changed it, so I solved the 9th word and came out with the first chip. Oh, the expression is applied again. I tried really hard to explain everything, but the lacquer is all without focusing on the dp and the mrs. This is the 1 to 4 app. 6l The value is the total of the dpm minus 152. Because we made the overall selection, he selected the tpm many points, and then the tone is dynamic. Then now the next participant does what. You can't select Young's Younghee, well, you can't select anything, so the physics sum n uh, the total, ultimately, the total and the monthly value will be the dpm - won, and value will be the dpm - won, and value will be the dpm - won, and here, in order to set the value to 1 month m, first of all, let's go to the 2nd verse. If you want to mug, you have to first like it and organize it in the app Six Anal. Then, how do we set the range here? After we select the child's number, we are passing on the i-th number. After the selection is made, i-th number. After the selection is made, i-th number. After the selection is made, uh, it is handed over to the other party, so ah, you have to start from 1. First of all, you have to select two or more choices, so as if it is a choice, first two 9 and then ah, the definition of m - 1. The reason I did it is actually definition of m - 1. The reason I did it is actually definition of m - 1. The reason I did it is actually okay to have a fan, but m- okay to have a fan, but m- okay to have a fan, but m- thing is predicted here, h case, so the h case was just defined anyway, so I set it to good, up to and including mice, and then ah, let's go and define it. In order to find this kind of Diff, first define in-tuning of Max 5%, order to find this kind of Diff, first define in-tuning of Max 5%, and Max 5% and Max 5% and Max 5% is now looking for the maximum value that the other party can have. The far maximum value of the other party is just compare x plant langue dp j1. I can give it to you. What happens to dpi now? Now dp servant thinks that the child has now chosen. The fix island up to the child is now in the next order, so let's move on. So pxi plus one - expert will now be ti, and plus one - expert will now be ti, and then bass. Now, you can update it all in the year. gp health ah, now where it is deep inside it kind of pc. Because now the dp definition itself is ah, select between this child, and furthermore, select the i-th and furthermore, select the i-th and furthermore, select the i-th and pass it. That is, it is the maximum, so you can select 2, you can select the world, you can select 4, you can select 5, and you can just guess and go, so you have to keep updating the ol base like that and see everything. But, uh, this brand also becomes uh on Skier, so it becomes a square, so of course it doesn't work. Time multi ad appears. Thierry appears. Now, I'm going to hide the tone screen for a moment. This is a convenient point anyway, so now. There is a case where personal information has been exposed a little bit, so I need to pay more attention next time in the tab. So haha, I have now looked at the iPad screen more. In the case of the first dp that we have defined in this way, ah, in the case of the second dp, I'm going to explain the taste. 4 Let's say you've chosen a lot up to this point, and you've chosen this, and after the Eoyeon thing, s will be included, and then the bankrupt tank will be included, and then it will be included in the child, and now the next batter, now select. In one case, it's 3 tons of A4 or 6. When an array like this is given, 5% of it is what you can 5% of it is what you can 5% of it is what you can take. Here, the important point is that the house is ultimately made of ntp video and It's the same 5 Here, dp 2 3 is selected. More than the selected depth, do we really need to answer in 2 dimensions? There is no need to do that because this ah, here 0 is included in itself and then it is in the 3rd place. This is the result. Inwardly, 2 was stacked on the left, but here 0 1 2 3 This is the machine 1 s combined with 1 2, so it becomes more than that s, curled s3, hey s3. As a result, it is all the same, so the dp 2 3 times ntp video is the same, even if it is expensive. It's the same. Then, the dp director is also the same as the TV projectionist. It's the same as Pisarro. 9 Anyway, you can also write the dp in English and write it as an index. Print uh. Here, I probably saw it now because I don't know the general formula. If you generalize, it's the same. gp Like this, the child goes from sun 0 to child - dp mx dp eye plus one goes from sun 0 to child - dp mx dp eye plus one goes from sun 0 to child - dp mx dp eye plus one eye plus c2 guess the depth m - up to day depth m - up to day depth m - up to day a Maxim Mocha straight and dpm - 2 The painted value of the app will be us on the dp Hairu Europe page, so Now, it's the same now what do we do with the definition, now we just have to apply it, but our John side has already applied it. In fact, it has already been applied. Now, how do we convey this more? Is this dpi? From iPlus One to N, the GP card pipe, iPlus Wonder TPN, the largest value is 5% with Tikka Take. It is the value that reflects the other party's cake limit. The 5% with Tikka Take. It is the value that reflects the other party's cake limit. The 5% with Tikka Take. It is the value that reflects the other party's cake limit. The reflected value is therefore the dpi is like this now. I can rewrite the sound. Especially Hi - Pepi The thing is that it will be the maximum value, so as it hurts, I am reducing the amount of sleep in the car so that the cpi-thing can come out now from the flex eye. I the cpi-thing can come out now from the flex eye. I the cpi-thing can come out now from the flex eye. I changed it like this and it is a little more the same as before, so I understand. It'll be a bit more convenient. So dp - understand. It'll be a bit more convenient. So dp - understand. It'll be a bit more convenient. So dp - security is like that, so it's time to change. So, I applied the changes I made to that child. Now, 2, what's the initial value that needs to be the same? We need the gp work dp1 ep.12 maximum that is the minimum ep.12 maximum that is the minimum ep.12 maximum that is the minimum maximum in order to find the gp length work the p sex e is this area must be the minimum so first of all the minimum value like that 1st stage It is set. c is checked to see if 732 is present or not, and 4 is now checked like this. After checking, the rights with the firmware have been removed. Here, the way to remove the pixel is as before. If you use a site like this, you can do it in the same way. I would have talked about it. In the case of Compact City in the meantime, this can also be reduced to on, and 5 spao was not written 5 That was written incorrectly. 5 Annie, o1 spa corsten At least 5 won was rotten and written incorrectly. Now, when they gave me a motorcycle, they said it was there when I looked at the food tray, but when I saw 400,000, when I saw 400,000, when I saw 400,000, why is that so? How can I tell you this? So, when I posted this, the UN said, You guys have been trying until I reached this conclusion. Everyone, I was there, and in the middle, I thought it was okay, but as I was going through the explanation, my skills didn't reach the point where it was a bit wasteful, so I thought I'd try to explain this, but I kept repeating this several times, and then hey, I guess I should probably upload the final version. I was probably wrong. I think there are some parts, but if there is anything in the garden, please let me know in the comments and I am uploading the video in the hope that this kind of free sharing will be helpful.
|
Stone Game VIII
|
can-you-eat-your-favorite-candy-on-your-favorite-day
|
Alice and Bob take turns playing a game, with **Alice starting first**.
There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following:
1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row.
2. Add the **sum** of the **removed** stones' values to the player's score.
3. Place a **new stone**, whose value is equal to that sum, on the left side of the row.
The game stops when **only** **one** stone is left in the row.
The **score difference** between Alice and Bob is `(Alice's score - Bob's score)`. Alice's goal is to **maximize** the score difference, and Bob's goal is the **minimize** the score difference.
Given an integer array `stones` of length `n` where `stones[i]` represents the value of the `ith` stone **from the left**, return _the **score difference** between Alice and Bob if they both play **optimally**._
**Example 1:**
**Input:** stones = \[-1,2,-3,4,-5\]
**Output:** 5
**Explanation:**
- Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of
value 2 on the left. stones = \[2,-5\].
- Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on
the left. stones = \[-3\].
The difference between their scores is 2 - (-3) = 5.
**Example 2:**
**Input:** stones = \[7,-6,5,10,5,-2,-6\]
**Output:** 13
**Explanation:**
- Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a
stone of value 13 on the left. stones = \[13\].
The difference between their scores is 13 - 0 = 13.
**Example 3:**
**Input:** stones = \[-10,-12\]
**Output:** -22
**Explanation:**
- Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her
score and places a stone of value -22 on the left. stones = \[-22\].
The difference between their scores is (-22) - 0 = -22.
**Constraints:**
* `n == stones.length`
* `2 <= n <= 105`
* `-104 <= stones[i] <= 104`
|
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a smaller type plus the number of your favorite candy minus 1. The earliest possible day that you can eat your favorite candy is the total number of candies with a smaller type divided by dailyCap.
|
Array,Prefix Sum
|
Medium
| null |
16 |
hello guys I hope you are all doing well in this video I'll show you how to solve the problem lead called three sum Clauses so let's get started so the problem is that they give us an array of integers and then enter your Target and they ask you to find the three integers in the array such that the sum is closest to the Target so the Brute Force approach to solve this problem is by using three four loops and iterate throughout the array and each time we'll sum up the three numbers and we store it inside a variable so we can keep track of the closest sum to the Target but the problem with this solution is that it take off and to the power of 3 which is an efficient solution to the problem so the best way to solve this problem and the best way to reduce or solving a problem that need to sum up something an array is the two pointers technique and the idea behind the two pointer technique is initialized to pointers starting from the two ends of the array and move the two pointers toward each other's based on the occur in some and that's gonna help reduce the runtime but there is a condition that we need to apply in order to use the two pointers technique is to sort the array so let's say we have this import list an integer Target equal to one so the first thing we're going to do is to sort the array so after sorting the smallest number are at the left and all the larger number are at the right so we're going to Loop throughout the array and we're going to use the index of the for loop as a pointer so that we can have three pointers mean three numbers to sum up them then we're gonna initialize two pointers the left pointer points at the number after the I index of the for Loop and the right pointer at the last number and the array so we're gonna sum up the three numbers the first sum are equal to -3 so we check if the sum are equal to -3 so we check if the sum are equal to -3 so we check if the sum are equal to the Target if a true we return the sum so here the total are not equal to one so what we need to do here is to calculate the absolute difference between the current sum and the Target and the absolute value removes the sign of the numbers means it's gonna give us how far away that number is from the Target on the number line so after we get the result of the difference we need to store the sum inside the variable so that we can use it in the next iteration then we keep moving the pointers we need to check if the sum is less than to Target or bigger if it's smaller we move the left by one otherwise we'll reduce the right by one so here the sum is less than the target so we move the left by one and we calculate the sum of the new numbers at the three pointers so the sum here are going to be -1 and that means here are going to be -1 and that means here are going to be -1 and that means it's not equal to the Target so we need to calculate the absolute difference between the current sum and the target which is two and we compare it to the absolute difference between the previous sum and the target if it's smaller this means we found a three numbers that if we sum up them we get a value close to the Target so we change the value of the closest sum to be -1 which is the closest sum to be -1 which is the closest sum to be -1 which is the current sum then we'll repeat the same process by calculating the sum so here the sum will be 2 and we check it the sum is equal to the Target if not we calculate the absolute difference between the current sum and the Target and we compare it to the absolute difference between the previous sum and the target so here the closest sum going to be updated to the value 2. as we compare the current sum 2 to the Target one so here the target are smaller than the current sum means we need to move the right pointer to the previous number finally we're going to stop the loop because in the question details they ask us to sum up three numbers so that's why I'm gonna only use a loop that iterate throughout the array starting from the first number and ending at the second to last number so that we can get the three pointers means three numbers that's it guys finally we return the closest sum which is 2 for this input example so there is a case one will have an array that have two numbers that are the same So to avoid repeating the same combination and having the same result we can skip the number by adding a line and the code that check if the value as I index of the loop are equal to the previous value as I minus 1 index so we just continue and we don't do anything that and that's going to make the code more faster so the time complexity for the solution is often to the power of 2 or we can say it's a quadratic time complexity it's because we have two nested Loop and that iterate route array of numbers and the space complexity is of one means a constant space and that's because we are not allocating any additional memory and we are using only variables that's it guys so let's jump at Con in the solution so the first thing we're going to do is to initialize a variable called closest sum and set his value to be Infinity so this variable gonna help us to keep tracking of the sum that are close to the Target and it's also going to be the output then we sort the array by using the sort method which gonna take off and login time complexity but in the complexity analysis we're gonna drop the less significant term and we're gonna keep the most powerful one which is the quadratic time then we Loop 12 the array starting from the first number to the second last number and that each iteration we set a condition to avoid repairing the same total of our combination so if I is bigger than 0 means it's not out of the array and the value at I is equal to the value at I minus 1 we just continue to the next iteration then we initialize two punchers the left starts at the number after the I index of the for Loop and the right start at the last number and the array then we'll look throughout the array another time use by using the left and right Pointer while the left are not equal or bigger than the right pointer we sum up the three numbers at the current pointers and we check if the sum is equal to the Target if it's true we return the sum otherwise we calculate the absolute difference between the sum and the Target and we compare it to the absolute difference between the closest sum and the target if it's smaller we change the closest sum to be the current sum and we set another condition if the sum is less than the target we move the left by one position otherwise we reduce the right pointer by one and finally the end inner loop ends and we return the closest sum as a result that's it guys thanks for watching see you in the next video
|
3Sum Closest
|
3sum-closest
|
Given an integer array `nums` of length `n` and an integer `target`, find three integers in `nums` such that the sum is closest to `target`.
Return _the sum of the three integers_.
You may assume that each input would have exactly one solution.
**Example 1:**
**Input:** nums = \[-1,2,1,-4\], target = 1
**Output:** 2
**Explanation:** The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
**Example 2:**
**Input:** nums = \[0,0,0\], target = 1
**Output:** 0
**Explanation:** The sum that is closest to the target is 0. (0 + 0 + 0 = 0).
**Constraints:**
* `3 <= nums.length <= 500`
* `-1000 <= nums[i] <= 1000`
* `-104 <= target <= 104`
| null |
Array,Two Pointers,Sorting
|
Medium
|
15,259
|
1,032 |
this is uh one of the harder string search problems and here we are given a list of words beforehand and that list will not change but once we have stored that list of words and we will see how to store that once we have stored that list is fixed then we will have a bunch of queries coming to us and in each query we will have one letter let's say c in the next query we will have another letter let's say d and so on so what this query will return it should return true or false depending on whether this character is one of the words or not or this character and you can include any of the previous queries which we have made so for example the first query we have just c there is nothing before that so if c is not in the word list that we have just inserted we will return false next query is d if d is there in the word list then we return true but let's say d is not there but cd is there so we will return true next let's say e comes then we will check for if e is a word or d e is a word or c d e is a word so you are allowed to include any of the previous characters previous queries you cannot skip any of these so these should be contiguous so either just is present or if not e then look for d e if d is also not present look for c d and so on until you reach the beginning so you are allowed to include as many characters as you want so let's look at an example then it will be much more clear and it has been asked in google and facebook interviews and it's one of the harder problems so here we are creating a storage for these words so the dictionary will have just three words in this example c d f and k l and next it queries for a so there is no query before it so only possibility is to search for a so a is not present so it returns false then we have b is also not present so we will search for here we search for a here we search for b or a b so you are allowed to include previous ones so both are not present so it returns false then we have c so we search for c not present bc not present abc not present and now there is no place to go so we return false next d so d is not present so we look for cd but cd is present so cd is found and it returns true next e is not there d e is not there cd is not there similarly none of its uh prefixes including this are there so it's false now f is itself there so no need to check further as soon as we get end of a word in the storage we return true then g is not there neither fg none of these are there similarly you cannot find h g h f g h e f g h any of these i is also not there or any word uh found by one of its prefixes is also not there next l is not there but k l is there so we return true no need to check further so how can we do that so one straightaway thought would be there that we should store this in a try or a prefix tree but here you see that if we store cd so c d then f and k l in a try then we are not searching like this l k it's k l so it's fixed so here uh for example in this case we searched for l then we search for kl or let's take a negative example let's take this example so we searched for h then we searched for gh so while searching for gh we have already searched h but again we are starting from g and again we will match h then we will search fgh and then we will search efgh and in the worst case if we have let's say 100 queries already made then we will search 100 times in this try and each word will be one length to length so if n queries have been made till now then it will take n square time because searching in a query is of the order of word length and we will search for a word of length 1 word of length 2 word of length 3 4 and so on so 1 plus 2 plus 3 plus 4 plus all the way up to n if n queries have been made so this stream size keeps on growing we have to keep track of these we cannot lose these so it will be of n square so you see that query is very costly here and in fact query should be fast because this building time can be slightly on higher side since this is one time operation but query is being done again and again so it's not an efficient way to do it like that will be n square so one thing you notice is that we are looking for k l and we are currently here so what if we stored them in reverse order so instead of c d f and k l if we store them as dc f and lk just in reverse order now our job is done because we are currently here so we will start from this if l is found or not l is not there it's there but it's not end of the word so we will move up we will look for next character in the stream previous character this is k so we see whether k is there or not k is there and it's end of word so we return true uh similarly in this case let's say we are a negative example and we look for h is not there at all so we will return straight away one time if it's there let's say this cd so d was not there d is there but it's not end of the word so we just take one previous so each c child of a d or not so dc is there so we return true so worst case will be often if it goes all the way up to uh beginning and worst case and best case would be of one it may find it here again and for negative case let's say the first character itself does not match there is no child corresponding to it so it will return here only you know one for this case but if we implement it this way then it should have taken try to find h then g h f g h and so on and we would have wasted too much time so i hope this solution is very clear there is not much here it's just that based on our requirement we change the way we store in the try so we have to match from l k so word our word is in this order so this is first character second in this way we will never have to repeat the search for any of the characters so that's why we are storing in reverse order so let's write the code for this it should be easy for you if you are fluent in implementing tries so you can go through this example there are a few uh limitations given here word length can be 2 000 each word can be 2 000 so number of queries can be at max 40 000 so you see if you don't optimize the query it's guaranteed to exceed the time limit so we will need one try class here so let's implement one try class and here all the characters are lowercase english letters so it's just 26 so we can use this one the simpler version of try where we are taking array of fixed size if we had many characters let's say 128 then probably we would have used the hashmap version of try in this also you can use hash map implementation although this one is much simpler end of word is by default false and we have initialized all the children to null next we need to implement insert and also we need to implement search so uh let's say here how do we keep track of the stream so we need uh this try we will keep to store the words of the dictionary but we also need to keep track of the streams we have faced so far so first time first query j so we store a next query is a b so we should store this a b then a b c d e so we need to keep track of stream and what should be the effective way of storing it since we would search in this way from current to previous and while searching either you process the string from last to begin if you are storing in a string or it's better to store in some data structure where you can push in the beginning also so if you are using a vector pushing in the end would be cheaper but if you push in the beginning it will take off and time it has to shift everything so we can use a deck here or a list where we can insert in the beginning in constant time so we will store it in this form so we store a then b then c d since our search will start from current letter followed by previous then previous so it's better to append in the beginning so for that we will use index so that will come here in the stream checker that will be part of this so here we will have one try and one deck try for storing the words of the dictionary and take for storing the stream let's call it stream w in words so i am reversing it but you can uh handle that here also so start from s dot length minus one and decrement all the way up to zero so that's up to you whether you want to insert here or here but this try is a piece of code which should be independent of the client's concerns so uh that's why we will reverse it here it tries class should be the standard try class and it's up to the client of that code how it uses that try so that's why we are reversing it here and keeping it the standard try so reverse and w dot begin from begin till end so it's reversed now and then t dot insert w so i was talking about this instead of this you can write s dot length minus 1 you pick the character from that index and then move forward so if t children c minus a so we have 26 indices corresponding to 26 letters 0 is for a so this character minus a so if it's a it will be 0 if it's b it will be 1 if this is null so there is no branch corresponding to this character so we are inserting so we will insert it so if it's null then we create it and once created move the current trinode to that children and then we will continue until we have inserted all the characters and finally for the last character this will be pointing to the node corresponding to the last character of this string so for that end of word is equal to true so this is standard try insert implementation so we have inserted everything so this part is done next is the query so for query what we will do uh we will stream dot push front and i've already explained why we are pushing in the front so there will be slight change in the search for this case for the try we are passing a deck instead of a string and make sure to pass by reference so if we reach a case where there is no branch corresponding to this character that we are searching then we return false that means this none of the prefixes of this word is present else we continue our search and if we find end of word beforehand then we return straight away else finally we will return when we have we found all the characters of the word but none of them were end of word so ultimately we will return false and here we have already added search so let's see if this works search should not return a value okay so i have made this void it should be bull this matches here this matches so it matches with the answer so let's go ahead and submit and the solution is accepted so we are right here around 73 percent uh it has long test cases and you can see it takes a few hundred milliseconds now let's do this in java and python so if you have understood the concept and you are very comfortable with implementing the try then it should be very easy for you so the main thing is done in try itself here we are not doing anything in the stream checker class so constructed part is done so this looks to be done now we will implement the stream checker so we have initialized the two data structures and next or we can keep it outside also so here we had reversed it and then inserted so let's reverse it rw rev and this part is done finally the query part and it was also very simple we have to append in the beginning of this stream so stream dot add first and letter and this again matches so let's submit and the solution is accepted so here also it's good it's 80.5 but java it's good it's 80.5 but java it's good it's 80.5 but java solution take much less time now finally we will do it in python 3. here we cannot do character arithmetic directly so we fetch the sky value of c and a and then subtract one from the other and finally let's implement the query you and the answer matches so let's submit and the solution is accepted
|
Stream of Characters
|
satisfiability-of-equality-equations
|
Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings `words`.
For example, if `words = [ "abc ", "xyz "]` and the stream added the four characters (one by one) `'a'`, `'x'`, `'y'`, and `'z'`, your algorithm should detect that the suffix `"xyz "` of the characters `"axyz "` matches `"xyz "` from `words`.
Implement the `StreamChecker` class:
* `StreamChecker(String[] words)` Initializes the object with the strings array `words`.
* `boolean query(char letter)` Accepts a new character from the stream and returns `true` if any non-empty suffix from the stream forms a word that is in `words`.
**Example 1:**
**Input**
\[ "StreamChecker ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query ", "query "\]
\[\[\[ "cd ", "f ", "kl "\]\], \[ "a "\], \[ "b "\], \[ "c "\], \[ "d "\], \[ "e "\], \[ "f "\], \[ "g "\], \[ "h "\], \[ "i "\], \[ "j "\], \[ "k "\], \[ "l "\]\]
**Output**
\[null, false, false, false, true, false, true, false, false, false, false, false, true\]
**Explanation**
StreamChecker streamChecker = new StreamChecker(\[ "cd ", "f ", "kl "\]);
streamChecker.query( "a "); // return False
streamChecker.query( "b "); // return False
streamChecker.query( "c "); // return False
streamChecker.query( "d "); // return True, because 'cd' is in the wordlist
streamChecker.query( "e "); // return False
streamChecker.query( "f "); // return True, because 'f' is in the wordlist
streamChecker.query( "g "); // return False
streamChecker.query( "h "); // return False
streamChecker.query( "i "); // return False
streamChecker.query( "j "); // return False
streamChecker.query( "k "); // return False
streamChecker.query( "l "); // return True, because 'kl' is in the wordlist
**Constraints:**
* `1 <= words.length <= 2000`
* `1 <= words[i].length <= 200`
* `words[i]` consists of lowercase English letters.
* `letter` is a lowercase English letter.
* At most `4 * 104` calls will be made to query.
| null |
Array,String,Union Find,Graph
|
Medium
| null |
1,727 |
hello everyone i'm sean cannell so today um let's look at the new decode pro um problem one seven two seven largest sub matrix with rearrangement so we have a matrix of size and multiply n and we're allowed to re arrange as columns in any order for example we can swap column um the second column and the third column and we can get the um largest sub matrix with area and to multiply two which is four so um how to solve this problem since like for the first column you know um there are like um un column so we have an option to pick the first column then for the second column we have -1 options so it's there's so many -1 options so it's there's so many -1 options so it's there's so many combinations it's very impossible to solve this way given that a multiplier is a big number so how do we solve it okay let's take a look at so we can do this transform so original matrix is zero 011101 so we can convert it into a new matrix the value of each cell in this new matrix means um how many consecutive ones like um in such row after and in include that for example um for this cell we know there are two consecutive ones this one and this one so it's two for this cell there's three consecutive ones so it's three for this one it's two so we convert the transforms or into the matrix to this new matrix is very useful in some of our questions for each row we can sort them then for each row we can try to make the um the left top corner of my sum matrix like at this point for example let's consider the first row we started so it becomes three zero let's consider like um if we put the left top corner point of my sum matrix at this corner like what's area so three zero uh in our mind i the graph looks like this so if you if the weight is one the height is three so it's one multiplies three if the width is two the height is zero so we can just stop it then let's consider second row if we make the left top corner point of my sum matrix at this point like um what's area let's say two to one so graphing our mind looks like this if this is one height is two so is two if which is two height is 2 then area is 4. if this is 3 then height is 1 so area is 3 so the maximum area so 5 is 4. let's calculate 0 3. let's say if we place the top on the top left and corner point my sub matrix at this point which area if which is one height is one if this is two height is one so area is two so the maximum area so far is four so this is our algorithm let's start coding okay let's get the two dimensions first and yes matrix okay now let's start the transformation of this matrix three zero j is eleven and three plus so we need to go from button to top is a minus one minus if this cell is one and it's not the bottom row and we can add its value here we just in place update our original matrix plus one three right okay now let's calculate our answer okay we need to follow each um each row and try to calculate um if we place the top left corner of my some metrics into that row for the maxim area first let's start etc let's get rich service if um if it's serious then there's no meaning to determine more on this row you can just break here otherwise let's calculate which is double clutch plus one the okay let's run our program yeah so far so good okay that's it yeah thanks so for so much for watching this video
|
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
|
102 |
so the question is we are green with the tree and we need to print it by level so how I can print this tree as Elvan level Oda before moving on to this part let's first see how I went print this tree is like this to print that tree I'll use a Q Y Q because Q is a three-foot otters after because Q is a three-foot otters after because Q is a three-foot otters after first-in first-out first-in first-out first-in first-out so what I will do I will simply take a Q by the name of Q and I need a result array to store my result so I will take a cube and I will put the a root into the Q while my queue is not empty I will take it out the value you can say let's name it current will be Q dot get in the starting we will put root while my queue is not empty I will take it out one by one and I will ask if this currently the left side if this has the left tailed I will add that child to Q which is nice I will ask if this current has a right child if yes then I will add that to and at the end I will append this current to my result I so three years cone noise sm9 and 20 in myarray in my queue so now I will take out now my will become 9 I will ask for the left side load the current its note there so I will ask the right child it's not there I will simply append my 9 to the result so first I added 3 now I did 9 so 9 is out now I am at 20 so my current is now 20 I will ask if my 20 at the left side yet so I will add that to my queue now I'll ask does it have a right child story it for the left child it was the right child so yet yes it does have the right child so I added to the queue and at the end I will append that 20 to the result array now I take out 15 now my Cantor weekend 15 I will ask those 15 our left-tailed 15 I will ask those 15 our left-tailed 15 I will ask those 15 our left-tailed know verse 15 our right side now then I will simply append 15 to marriage El tari when I take out the seven now my current within seven I will ask if this current have left side no does it have a right child no then i simply append it to marriage I retire and this is my answer if I need to print it in a line in a single array but our question is a little different our question is we need to print it in this way so let's see how I can get that tree lower below so let me make the tree here 3 9 2015 7 for this also I need few things I need a result array in which I will show my result I need a queue and let's up so my Q is here and let me raise this so that I can store my result so in the starting I'll put my route to the Q output route so now my route have Mike you have three why my queue is not empty I will make a empty list and why I'm making this empty list because elementadd the same level in a different array so let me take out the size of my ari it's Q dot Q sighs and why I'm taking out this eyes to check how many element I need to put at each level so I have the cue I have an empty array I have the size when mice while my size is not equal to zero I will take out this three current equal to Q dot get and I will append this current to a so if I take a here so now my a has three and I will ask does my current have a left-tailed if candle left is not have a left-tailed if candle left is not have a left-tailed if candle left is not none yes it our child which is nine so I will put the child in the queue so let me write it down Q dot put currently left if my currently have right child I will put there to do my cue so I put it 20 and then I will reduce the size by one here my size is you and I will append a to marital day so my is this thing so I did a here now I again came here while my queue is not empty I initialize a new empty array I'd taken out the size which is 2 while my size is not zero I will take out the first element which is 9 and I will append it to a so my a will now have 9 and I will ask does that nine have a left edge no you don't have any left head does this nine ever right child no it does not have any right child to at the end I will reduce my size by one now my sizes became one and let me write it down if length of a not equal to zero I will append it so I again came here now I take out 20 so I added that 20 to a so I added 20 I will ask if this 20 have a left-tailed yes it does have I add that left-tailed yes it does have I add that left-tailed yes it does have I add that to my queue does this have a right child yes I will add that to my queue and I reduce my size and at the end I will append my a2 desert now again I will take 15 and I will follow these cells again and at the end or a will be like this and I will append that a to my result 1517 and at then I will written my result which will be T 9 2015 7 and this was what question has asked us so let's write the code before writing the code we will be using Q so let's import Q and let's start so we need au this resulting array and Q will be Q dot Q and let's check the this case wrote is none fear is simply written none let's put the root into the queue while our queue is not empty we will initialize a empty list and we will take out the size and fourth size we use queue sides while size is not equal to zero I will take out the first element and I will append that element to a and if turned out left is not done I'll simply put it to Q same way I will check the right child and I will put the right child to the queue and at the end I will reduce the size by one and if size of length a this is not equal to zero so because if it's empty there's no use to add it to the resulting array so if not then I will append it to resulting array at the end we will written down this all together let's run it so the answer is correct if you have any question please let me know in the comment section I will try my level best to help you out thank you so much for watching the video please don't forget to subscribe
|
Binary Tree Level Order Traversal
|
binary-tree-level-order-traversal
|
Given the `root` of a binary tree, return _the level order traversal of its nodes' values_. (i.e., from left to right, level by level).
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[3\],\[9,20\],\[15,7\]\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[\[1\]\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-1000 <= Node.val <= 1000`
| null |
Tree,Breadth-First Search,Binary Tree
|
Medium
|
103,107,111,314,637,764,1035
|
99 |
hey guys how's everything going this is jason in this video i'm going to solve a problem from uh elite code it's been a long time since my last video about lead code okay i hope it helps let's begin okay this is number 99 from uh recover number 99 from uh recover number 99 from uh recover binary search tree bsc we're given the root of a binary search tree where exactly two nodes of the tree were swapped by a mistake we covered the tree without changing its structure follow up a solution using linear space pretty straightforward uh i don't know what the straightforward approach is okay i could devise a constant space of solution uh let's forget about the follow-up just uh let's forget about the follow-up just uh let's forget about the follow-up just first try to solve this problem with our uh thinking so every time i meet uh the uh binary tree stuff i will first think about recursion yeah everything better could be solved by recursion and then we need to consider how to traverse the tree right for the problem here we need first target okay the first is target the swapped note so and it's a bst and bst has a character a feature of i would say the characteristic is that uh leftover is smaller than a root and the right node is bigger than the root right so if we use the in order traversal on bst leads to and ascending array right yeah this is the characteristic of all those data structures okay it says exactly two nodes of the tree were swapped so we need the first vice where it is swapped so there must be something about the swap node which is different right for our bst like this original let's first traverse with the inorder traverse to see what it is it should be one two three right now it became we do in order to traversal again it would be three to one i would say okay now see that the nodes are swapped two is two uh and one and three are swapped right okay next one next example here the original one is this is one two three four and this one would be one three two four so two and three are swapped so we can take it we if we take uh suppose there are like one two three four five six we pick up any two numbers i j and swap them it's ascending if we think of this array as a line and we swap two nodes of them the bigger one will become uh a bigger one latter one will move uh to the head right to somewhere uh before it so it will cause what the other numbers actually before it are should be smaller than it so it must be create a downward slope right for example uh if we swap the five with one which would be will be five is bigger than all the numbers before it so the all the numbers after it should be smaller right so this is a characteristic we target the first node where uh next one is bit smaller yeah this is it this is uh no target the second node this is the second node uh no the first node swap for swap okay and then the first the smaller one like the one uh okay no not one just two one here will be moved uh moved to somewhere to the somewhere after it right so it won't be smaller than the previous one right all the numbers are bigger than it so um target the next swapped node where previous one is bigger it's kind of like uh obvious that's an uh pre next one is smaller of course program is bigger right so these actually needs to leads to the consecutive the uh a continuous two array right uh next to each other but uh four three four uh one six actually if we follow these two rules we could find five and two and actually there's another one is one right four and one it's also our uh possible uh the note pair right yeah but the first one actually will be our target right because four or five it couldn't be there if five four or five is both uh if like the first one is four uh next is five then there couldn't be something bigger uh something smaller than five after it because four he's already swapped when he just swapped before the four the number must be smaller than a four right so you should it cannot be placed after five uh am i making it right yeah if we if this one is uh the target right if this one is uh a five is our target then the numbers after it will be much smaller right and the swap node will be much bigger so it's one before it will be some other bigger numbers so this one should be the first one first node and this one should be last node let's take a look at the uh an example like five two three four one six right so we find the first node is five because we found that two is more than five this is our first node and this is possible in the second node but we found another one is one smaller than f4 so this one will be the second node what if we swap it with the six let's take a look six two 3 4 5 1. again you find 6 so the first node and then we found 2 possibly the next node and next one actually we found 1 which is possibly the next node we should be the second note all right if we swap two three four again let's take a look one two four three five six we find first one four and then find the uh the next one is three is possibly the uh next node and we don't find any uh downward slope again so this is our target so this is a rule okay so we found that the characteristic we can judge uh whether they are swap nodes or not so what it is we need to keep track of the previous node and compare right okay let brief equals no initialize renewal and next first node more and second nor and for true traversal i always call create a walk method and here we will use inorder traversal so you know there's more just return okay if note has left node we walk left and then we try i handle the route okay about the intent indent sorry okay so if uh if we have proof the node is bigger than node bigger than our value it means that we find the first might find the first uh and the second node right okay so if first is no then actually we've already find found our first which will be the proof right and then we just update the second would be node right current one and after we process it we update the priv to current node and we do this recursion to the node right uh any problem what about what is wrong with this highlight uh it's not highlighting the optional uh optional option machining okay it doesn't matter here now okay walk method is done we walk with the root right yeah and then we what we do we just uh swapped the nodes right so first vowel second vowel equals second vowel first wow okay we add the semi semicolon here to avoid the syntax error let's run the code great submit great we are fast and uh what's the time and space complexity space actually we don't use the uh linear space we don't store all the nodes so it's constant space we use only three variables to hold the three nodes uh time obviously it's linear time we would uh oh the space actually yeah we have the stack problem over here so it's not constant actually the stack would cost us i would say the depth so depths of this tree yeah averagely i would say if the worst case is in the near space actually yeah and this time we traversed all the nodes once so linear time okay that's it so that's all for this problem hope it helps see you next time bye
|
Recover Binary Search Tree
|
recover-binary-search-tree
|
You are given the `root` of a binary search tree (BST), where the values of **exactly** two nodes of the tree were swapped by mistake. _Recover the tree without changing its structure_.
**Example 1:**
**Input:** root = \[1,3,null,null,2\]
**Output:** \[3,1,null,null,2\]
**Explanation:** 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid.
**Example 2:**
**Input:** root = \[3,1,4,null,null,2\]
**Output:** \[2,1,4,null,null,3\]
**Explanation:** 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid.
**Constraints:**
* The number of nodes in the tree is in the range `[2, 1000]`.
* `-231 <= Node.val <= 231 - 1`
**Follow up:** A solution using `O(n)` space is pretty straight-forward. Could you devise a constant `O(1)` space solution?
| null |
Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Medium
| null |
1,710 |
welcome to my channel so for this video we're going to analyze the daily challenge problem that is problem 1710 maximum units on a truck so for this problem here we are going to share a greedy method first i'll read through the statement of the problem and then look at one example and finally we share the short code so let's look at the statement so we are assigned to put some amount of boxes onto one truck uh here we have only one truck so we are given a 2d array called box tabs where box tab con consists of two elements so one is number of boxes and the second is number of units per box so here it explains the meaning so number of box i is the number of boxes of type i and number of units per box i is the number of units in each box of type i so we are also given an integer called a truck size which is the maximum number of boxes that can be put on the truck so we can choose any boxes to put on the truck as long as the number of boxes does not exceed the truck size so we are required to return the maximum total number of units that can be put on the truck so here is example one so the truck set is four so we put one tab zero box two type one box and one more tab two boxes so the total number of units are eight so this is example one now example two the output is 91 so we will add analyze this one shortly so let's look at the constraints for this problem so the length of the box tabs is bounded above by 1000 so this is a actually a short list so the number of boxes and number of units per box is also bonded above by 1000 and the grid are equal to one similarly the truck's size is greater or equal than one and has a upper bound ten to the power six so the last two assumptions or constraints are sort of routine so let's look at the idea here so i would say this problem is a straightforward problem the method we are going to use is a greedy method so i'm going to work quickly about example two so we um overall we want to first put the box tabs with largest or larger uh number of units per box elements so it corresponds to the second elements in the list element so for this actually we need to first sort the box tabs list according to the second component in the elements so we start from the large to small so example one is sort of special because it's already sorted if we check the second elements in each of the elements of the box tabs so for this problem so after we sort according to the second element we get this list then the truck says it's 10 so we can put a 5 of the tab 0 and the 3 of tab 1 and we have 8 then we can put 2 more of the tab 2 boxes so we get 50 plus 3 times 9 is 27 then plus 2 times 7 that is 14. so overall the return is 91. so that's the main method or idea for this problem so for this problem again i think it's very straightforward and the code itself speaks louder so let me carry out this procedure first i'm going to sort this box tabs uh i will sort in place so according to the key that is defend lambda function so the item of x i'm going to sort according to the second element but in a reverse order so in other words from large to small so once we've done this step we're ready to do the iteration so do a linear scan for that purpose first i'm going to initialize a result so the final stage of this variable is what we want to return and also in the process i want to track how many boxes are in the truck so that we can make sure it not exceed exceed the truck size so now we are ready to do the iteration so we are trying to check the inboxes and the ratio in the box tabs notice now the box tabs are is already sorted so first thing we want to do is that we check if we can add the whole of the n boxes that is if uh on chalk one plus and boxes is greater than the truck sets or not so if this were the case so we cannot add all of them so we can only add part of that so we're going to return result plus how many blocks we can add for this step so that is on the truck size minus the ones currently on the truck then for this step the ratio will be ratio now so that's the return we can directly return in this case so otherwise what we do so it means that we can add all the inboxes for this tab and therefore we can update the on track variable by inboxes and we can all we need also after the result is um the increment in uh in the units that is m boxes times the ratio so with that this part is done we're ready to return the result so that's the whole code for this problem so as i mentioned it's sort of straightforward let's check for example one yeah it passes oh this is the example two so it passes example two anyway example two is more typical than example 1 is already sorted so now let's do a check for generic case yeah it passes the generic case so that's about it for this problem so you are welcome to check out other videos in my channel and especially this problem can be regarded as a part or step in some of my videos analysis for little problem in the binary search playlist thank you very much
|
Maximum Units on a Truck
|
find-servers-that-handled-most-number-of-requests
|
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`:
* `numberOfBoxesi` is the number of boxes of type `i`.
* `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`.
You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`.
Return _the **maximum** total number of **units** that can be put on the truck._
**Example 1:**
**Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4
**Output:** 8
**Explanation:** There are:
- 1 box of the first type that contains 3 units.
- 2 boxes of the second type that contain 2 units each.
- 3 boxes of the third type that contain 1 unit each.
You can take all the boxes of the first and second types, and one box of the third type.
The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8.
**Example 2:**
**Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10
**Output:** 91
**Constraints:**
* `1 <= boxTypes.length <= 1000`
* `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000`
* `1 <= truckSize <= 106`
|
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add.
|
Array,Greedy,Heap (Priority Queue),Ordered Set
|
Hard
| null |
423 |
Hello Hi Everyone Dad Sunny Kumar From IT BHU Welcome To My Channel Court With Sunny Today I Am Going To Discuss Your Problems Will Construct Original Digit Sperm English Index Number Four To Three And Problems Of Medium Type Of List Ko Difficult Subscribe Not Been Given In The String continued after english representation of dresses miding ok what is the meaning of this subscribe and dances with subscribe The Video then subscribe to the Page if you liked The Video then tractors of all the words but if In Tourism With Sequence Of Descent And African Most Half Fuel Subscribe And Subscribe For More Video Subscribe 999 Subscribe To Talented And Must Insist And Economic Benefit Length Subscribe * Tempo Okay Sorry Benefit Length Subscribe * Tempo Okay Sorry Benefit Length Subscribe * Tempo Okay Sorry Arvind Se Paun Inch Problem Channel Subscribe Ne Twitter The Video then subscribe to the Page if you liked The Video then subscribe to subscribe and how correct is the length of the makeup 0.5 inches and for rural development solution subscribe 0.5 inches and for rural development solution subscribe 0.5 inches and for rural development solution subscribe and subscribe to subscribe our Channel Please subscribe and subscribe the Channel Please subscribe and subscribe Kare tere naam ke bina to unique identification tutu www dot pull se character meaning id would like to subscribe The Channel Please subscribe and subscribe the Video then subscribe to hua tha so let's find the frequencies of the character of district Okay you can see loot Kars Ki And Akash Vriddhi And Hindu Problem Statement In Adhik Parvar Ko The Work On Hai So Let's Start Because So Let's Get But Its Significance To Welcome To Three Times A Day You Will Not Be Given Time And Welcome To One Time To Time And Welcome To one time and I won't be Two times and won't give me to the subscribe person subscribe button dab squidoo hain let's try to find out what can be the best possible way came from ireland i 'm going for 012 21 pattern 1000 Mandal's 'm going for 012 21 pattern 1000 Mandal's 'm going for 012 21 pattern 1000 Mandal's supernova m82 dead skin more dot reduced to avoid civilian population to 10000 to check quality of mid subscribe unique identification number of vs in subscribe like this the power and strength which contains 21 540 ifik singh datas the number 90 in more to like share and Subscribe my channel subscribe kate 100 ki aapke end ok so vat vriksha apni isse zakhmon to medium defective withdrawal what is the currency of frequency subscribe to subscribe person subscribe this Video 010199 the correct unique identification is so let's find out what like presiding Speaker Previous Wave 2002 Subscribe Button More Problems Share Avoid All The Type Of Video then subscribe to the Ko subscribe The Channel Ko subscribe kare Id Quote S2 And Its Corresponding Interior Adopting Candy Crush Us Laddu 468 Loot 1843 Left 579 Subscribe Interview The Amazing subscribe The Video then subscribe to subscribe and subscirbe apne teacher operations khayal prabandhan liked The Video then subscribe to subscribe distant me pahani to hai a kiss upanishad remedy so let's friends code Video not subscribe not talking id porn phone par the walking dead to this also doubts Don't Forget To Mention In Comment Section 2 Videos And Vilas Twist Latest Video Schedules And Witchcraft Co YouTube Channel Latest Updates Thank You For Watching This Video.
|
Reconstruct Original Digits from English
|
reconstruct-original-digits-from-english
|
Given a string `s` containing an out-of-order English representation of digits `0-9`, return _the digits in **ascending** order_.
**Example 1:**
**Input:** s = "owoztneoer"
**Output:** "012"
**Example 2:**
**Input:** s = "fviefuro"
**Output:** "45"
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is one of the characters `[ "e ", "g ", "f ", "i ", "h ", "o ", "n ", "s ", "r ", "u ", "t ", "w ", "v ", "x ", "z "]`.
* `s` is **guaranteed** to be valid.
| null |
Hash Table,Math,String
|
Medium
| null |
998 |
hey everybody this is Larry this is January 20th um I'm doing lead code personal Larry challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about this prom uh usually I do I pick a random one and I did actually pick this as an RNG but then I was like oh let's solve the previous problem first so you may have seen if you were looking for it you could see the link for the first problem first and then now let's actually read this problem and actually solve this problem so let's jump right to it okay so we know what a Max tree is we have construct um what are we supposed to do what am I doing what is the difference here okay if a is empty we turn no greater we know the left is going to be construct okay the right note is huh is this like a add a value thing suppose B is a copy that oh I see oh I didn't read this part there's just so much definitions and then this is the actual problem which is that okay suppose we have so that means that you have this list I mean they don't give you the list they give you the tree and then you have this list and then now you have to try uh try to figure out oh sorry whoops this is the thing I guess so now you have these two list and you're try to figure out um but you're only given the tree of a and then now you have to try to get tree of B right okay where you have value okay huh that is an interesting problem but it also seems like it's going to be a mess to be honest but where B is the root are there multiple I'm trying to think whether I think the um the solution would be unique I don't think this is um yeah it should be deterministic because it's just based on the locations right so okay I honestly I do not have an immediate idea right now so okay so let's say we have this you have a five right well five would just go to root cuz five is bigger than all the numbers but it'll be on the left side or it'll be on the left node for that reason okay fine here you have a three so okay so the first thing to note is that um if it is smaller than and this is going to be done recursively it's smaller than the root then what happens if it's or if it's bigger than the root then well you know it just goes on the thing otherwise if it's smaller it always goes to the right side because that's how the partition works right so we always go to the right okay let's say okay uh I mean the way that I always pray about it is that let's say we have this thing and then now we insert three we have this answer but what happens when you insert say uh 4. five right when we have a 4.5 say uh 4. five right when we have a 4.5 say uh 4. five right when we have a 4.5 then now it goes so basically you keep on going to the right until you find a node that it is bigger than right and if it's bigger than then now you substitute it and then it'll be on the left side I think that's right so okay so that's not that bad but we still have to say it right so now okay so let's just say Okay so the way that I want to start this is actually by creating a sentinel value right so we have a sentinel it's going to be a tree node we have some Infinity value so that it always goes to the right side um with the rest of our algorithm so Infinity uh with none and then the right side is going to be maybe I'll write it more explicit this way I like it to write it this way instead uh it's equal to the root right and then now current is go to Sentinel um so then now what we want to do is and we only want to use the poins so okay so while current. WR is not none we might have to consider what it means to be none if it's none so we go to the right because it's on the right side if it's none then you just put it to the right okay fine right yeah that makes sense basically if you have this and you're inserting um 3.5 the 3.5 will be to the inserting um 3.5 the 3.5 will be to the inserting um 3.5 the 3.5 will be to the right of the three right yeah wait no I meant 2.5 that's what I wanted to say meant 2.5 that's what I wanted to say meant 2.5 that's what I wanted to say but if it's 3.5 then it would replace but if it's 3.5 then it would replace but if it's 3.5 then it would replace the three and then it squeeze everything else to the left yeah okay yeah so then now okay so if current. right that uh value is greater than value and these are all unique right unique and value is value unique I want to say that they're not precise about it but it probably is otherwise it would just be tricky okay so if the value is greater than that then we go to the right so in this case current is equal to current. right then we continue otherwise um I guess I don't need to continue explicity but I like to do it so that if I change the code structure a little bit it might it'll still work without thinking about okay so if it's less than then now we're done right if it's less than then we actually want to set current. right okay so previous right is equal to current. right and so that's the node and then current. right is going to be equal to a new tree node with the curent The Rue and then this current. wr. left is equal to previous right and then we can break and maybe even return actually um yeah we can actually return sen to no. uh that right otherwise current. right is none so that means that we can just set it to current. right so current. right is equal to um sent oh sent what am I doing tree no oh tree node of value uh and that's pretty much it cuz there's nothing there so you don't have to replace anything so we can actually maybe even set this is generally true so we can actually break and then maybe do this but it's a little bit awkward and also to be honest during a contest I don't like to do this just because um oh no this is right yeah um just because like there's just more things to prove I don't know but yeah then you can obviously condense this a little bit I mean you are here you follow the logic so yeah so but you can also promote this to something like this right um and yeah let's um let's give a submit hopefully I didn't miss an case and we're good uh obviously I say obviously too much but yeah for complexity though this is going to be linear time linear or constant space linear time coming from you know we have to go if it's a link list e tree you have to go through the entire link list of tree uh and space we only really have two variables right The Sentinel the current and that's it and we allocate only two extra not um and we just kind of manipulate the poters and it's in place kind of which I think is fine with this one I mean if you really want to make you can make a copy of everything it just be you do a def search or something if you know Tre traversal but uh but yeah that's what I have for this one I don't know why there are so many downloads and I guess it is a uh an interview question but uh but and I think the difficulty is about right for um for an though it is a little bit trickier and easy to get well but yeah uh that's all I have for this one let me know what you think yeah stay good stay healthy to mental health I'll see yall later and take care byebye
|
Maximum Binary Tree II
|
check-completeness-of-a-binary-tree
|
A **maximum tree** is a tree where every node has a value greater than any other value in its subtree.
You are given the `root` of a maximum binary tree and an integer `val`.
Just as in the [previous problem](https://leetcode.com/problems/maximum-binary-tree/), the given tree was constructed from a list `a` (`root = Construct(a)`) recursively with the following `Construct(a)` routine:
* If `a` is empty, return `null`.
* Otherwise, let `a[i]` be the largest element of `a`. Create a `root` node with the value `a[i]`.
* The left child of `root` will be `Construct([a[0], a[1], ..., a[i - 1]])`.
* The right child of `root` will be `Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]])`.
* Return `root`.
Note that we were not given `a` directly, only a root node `root = Construct(a)`.
Suppose `b` is a copy of `a` with the value `val` appended to it. It is guaranteed that `b` has unique values.
Return `Construct(b)`.
**Example 1:**
**Input:** root = \[4,1,3,null,null,2\], val = 5
**Output:** \[5,4,null,1,3,null,null,2\]
**Explanation:** a = \[1,4,2,3\], b = \[1,4,2,3,5\]
**Example 2:**
**Input:** root = \[5,2,4,null,1\], val = 3
**Output:** \[5,2,4,null,1,null,3\]
**Explanation:** a = \[2,1,5,4\], b = \[2,1,5,4,3\]
**Example 3:**
**Input:** root = \[5,2,3,null,1\], val = 4
**Output:** \[5,2,4,null,1,3\]
**Explanation:** a = \[2,1,5,3\], b = \[2,1,5,3,4\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `1 <= Node.val <= 100`
* All the values of the tree are **unique**.
* `1 <= val <= 100`
| null |
Tree,Breadth-First Search,Binary Tree
|
Medium
| null |
290 |
hey what's up guys Nick white here I do talk encoding stuff on Twitch in YouTube this problem is called word pattern also I do the premium Li code problems on my patreon and you could reach out to me at discord this is a word pad or an easy problem given a pattern and a string so we are given a pattern in a string STR find if string follows the same pattern here follow means a full match such that there is a bijection between a letter and pattern and a non empty word in string erster don't know what a by ejection is but we can look at the example and figure this out so we're given a pattern which is a string and then we're giving a string STR so it looks like pattern is gonna be some letters some random combination of letters and STR is gonna be words like a sentence okay so what I'm seeing here is the pattern is a BBA so dog cat dog is true because we map a two dog and B two cat so we kind of want to follow the pattern and we're in a sense that we're matching a word with a letter so that's just my first instinct is like seeing that we're matching a word to a specific letter and then we're following a pattern okay a BBA dog cat catfish so this is a different so we matched dog to a but then we see fish at the end and we're looking for a again so that's wrong pattern a this is clearly wrong it would be all the same word and pattern a BBA is false because it would be you know this is a BBA this is a so these are switched how we solve this well just based on your instinct that you see that the letters are getting mapped to words that's what we're gonna do we're gonna have a hash map and we're gonna map letters to words so we're gonna loop through the pattern first of all we're gonna split this string into a list of words so that we can like loop through each word individually so let's just do that honestly string words is equal to STR dot splits we split the sentence on spaces to get the words and yeah that's it so now one thing you want to notice is if each letter is getting mapped to a word that means that there should be the exact same length of the number of characters and pattern so the number of letters of pattern and the number of words in the words array so you could see lengths for four words l'ainte for four words and forth there's not that many variation examples but that's the truth makes sense though right so words dot length is not equal to str2 a pattern dot length sorry then we can just return false because obviously it's not going to match there's more other more words or less words than the pattern has some letters so now what we need to do is we need to create a matte hash map where we're gonna map a character to a specific word pretty easy so we'll just say type character and then word character is gonna be the key word is gonna be the value so for example a would be the key in the hash map and the value would be dog okay so we'll just call it map equals new hash map and call whatever you want now we're gonna loop through you can loop their word the lengths are the same between pattern and words so you can loop through whichever one you want I'm just gonna do words we'll get the current character current char is equal to patterned char had turned a char at I so the current character of the pattern maybe just make it make a little more sense for you guys we get your pattern so we're looping their pattern we're getting the Frontera koryn pattern so we're looping through like a BBA like looping through the characters and we want to put them into the hash map right so there's two things for hash map problems you usually want to check if something is in a hash map and if it's not you want to put it in usually so if map dot contains key current char so if the current char is already in the hash map we'll do something otherwise we're going to put it in we're gonna say map put and we're gonna put the current character and then we're gonna put the current word in the string so if we saw a we'd put dog in right away if we saw B we'd put cat in so we're gonna put words of I in the hashmap so pretty straightforward now if it contains the key well that means we already saw it right so we when we put dog in with a and cat in with B then we see cat and we already we look up we see Obie's already in there so now we want to check okay well the current word that we're on better be equal to what's in there for that letter so we gotta say okay if map dot gets current char so if the if for the if it's already in the hashmap that character better be equal to the current word that we're traversing so if it's equal it better be equal to word of i so words of i so we can do let's do this is the check if the mapping of the current character isn't equal to the current word well then that's wrong right that's wrong it has to be equal to the current word otherwise the pattern is broken right if B is set to cat and then we see B and then we see a different word than cat that's wrong they have to stay consistent be always once we set beat a cat beat always has to be cat so that's pretty much it for that and then otherwise if it's not in there then we might want to check ok well the only thing we have to do to verify is okay if map get value words of I is contains value actually I think that is the condition then we can return false so if the hashmap doesn't contain the character so if the character wasn't mapped to a word well let's check if the word is in the hashmap at any point so that we can if the words in there then it's mapped to a different character so that's already wrong so we can just return false right away and I think this method is good for that and if everything goes according to plan like that should all have gone pretty smoothly and carrot type character word to character string so I guess always making mistakes my bad and yeah it should be fine except you have to return true at the end if it's successful so I'm sorry about that I'm a loser all right there we go so you know just mess it all up all the time one more time you have this hashmap you would see a and dot a and dog right so you'd say okay a dog put that in right then we'd see B cats right we're going to with one character we're checking the current character with the current word we're traversing them both at the same time so a and dog we map it cuz neither of them are in the hashmap being cat okay that's not a B is not in the hashmap cat is not in the hashmap being cat okay it is in the hashmap so as long as it's being cat don't look good and dog as long as the same dog and we're good in this case we did a dog we put a dog in B cat we put be cut in we look up B cat it's already in there so that's fine and then we look we see A's already in there we look it up with fish Oh a isn't fish A's dog so that's incorrect so we return false so if it contains the character and it's not mapped to the correct word like if it's mapped a dog instead of fish that's bad so we got a return false that's pretty much it let me know if you guys have any questions I think it's pretty straightforward it's an easy problem and I think it's definitely ranked easy there is a little bit of discussion on you know doing things more efficiently with hashmaps so this is the same general idea but apparently when you put things into the hash map it returns an object so I would check out the discussion and see what this guy is saying about using puts who do check equality and stuff like that I don't think you have to do that I think the way that we're doing it here is good for readability and also time complexity so let me know what you guys think really appreciate everyone for watching out love you guys and I'll see you in the next one
|
Word Pattern
|
word-pattern
|
Given a `pattern` and a string `s`, find if `s` follows the same pattern.
Here **follow** means a full match, such that there is a bijection between a letter in `pattern` and a **non-empty** word in `s`.
**Example 1:**
**Input:** pattern = "abba ", s = "dog cat cat dog "
**Output:** true
**Example 2:**
**Input:** pattern = "abba ", s = "dog cat cat fish "
**Output:** false
**Example 3:**
**Input:** pattern = "aaaa ", s = "dog cat cat dog "
**Output:** false
**Constraints:**
* `1 <= pattern.length <= 300`
* `pattern` contains only lower-case English letters.
* `1 <= s.length <= 3000`
* `s` contains only lowercase English letters and spaces `' '`.
* `s` **does not contain** any leading or trailing spaces.
* All the words in `s` are separated by a **single space**.
| null |
Hash Table,String
|
Easy
|
205,291
|
129 |
hi everyone welcome back to the channel and Twitter business hourly for daily challenge problem number 129 some route to leave numbers so it's a interesting problem uh in which basically each path represents a number for example one two and one three is a path and this also represents a number so basically you have to sum up all the paths from root to Leaf node okay for example in this case we had one two three so one two is twelve one three is thirteen plus twelve is 25 so 25 is the answer similarly in this case we have four nine five four nine one four zero right so if you sum all this up you'll get one zero two six so um you know it's a really interesting problem to read but the solution is really simple so what we're going to do is we're going to use a BFS approach to solve this problem and there is the mathematical formula which you can use so what I'm going to do is I'm going to keep a variable called current sum or whatever you want to name it and we'll initialize it with zero okay and with each depth right or with each uh step I will multiply that current sum with 10 and add the current node value for example uh when we start the DFS the current sum value will be 0 right so 0 into 10 is 0 plus 1 we got 1 right we move to the next uh step on the right side we had current sum is 1 into 10 is 10 then plus 2 is 12 right so you get the uh you know the number of parts from root 2 the slightly respondent sorry the left leaves node okay similarly on the other hand the current sum was one into 10 is uh 10 plus 330. now sum this to 13 plus 12 is 50 or 25. so this is it this is what we have to do let's uh move to the code path okay and this uh I want to First Define my helper function DFS in which I will expect two values node and the current sum okay so as soon or like the base uh of course like you know if you're traversing a tree you need to check some base conditions so if node is null basically then I want to return 0. right now comes the part where I want to update the value of current sum so current will become current into 10 Plus node dot value okay and if the root has no left or let's do this if not of node dot left and not all node dot or right so basically the current pointer or the current node has no sub childrens then in that case I want to return the current we don't need to do anything else otherwise I will recursively call the DFS with node dot layer sorry no dot left and the currents are Plus node Dot right with the current sum so this solves the helper function and at the end we just have to initialize it with root and current 0 as the current sum value so this was it like this was the complete solution let's check out the test cases uh yeah so the test case has got here with some Nets of other value things and awesome so we were able to successfully clear all the test cases so yeah that was it thanks for telling guys for watching out the video and stay tuned for the upcoming ones don't forget to subscribe to the channel thank you
|
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
|
1,227 |
the solution to this problem is going to have you saying you got to be kidding me this is one two seven airplane seat assignment probability um although this problem is classified as a medium and is found within the dynamic programming tagged list uh it's not a medium and I wouldn't really consider it a dynamic programming problem at least the optimal solution um this problem is hard this problem is very difficult it requires a strong you know mathematical kind of background a strong understanding of you know uh kind of um you know induction kind of proofs right maybe a discrete math background would be extremely helpful this is just a very difficult problem and you really have to structure it appropriately if you want to find the relationship that leads to the answer um you know I spent quite a bit of time just trying to formulate uh the relationships between each of the components without being able to truly find the answer so that's something you need to consider when you're solving this problem that finding the relationship between elements and what that means will make more sense in a moment uh is crucial but with all that said let's go ahead and get right into the problem so you're given n passengers that are boarding on an airplane with exactly end seats right so there's n passengers there's N seats you know you've been on an airplane before you know you're familiar with this idea right you have a ticket probably has a seat number you go sit in your seat the first passenger has lost their ticket and picks a seat randomly but after that the rest of the passengers will take their own seat if it's still available and pick other seats randomly when they find that their seat is occupied return the probability that the last person the nth person gets his own seat okay so when you think about this problem you realize pretty quickly or intuitively that there's this cascading effect right because the first person at randomly is going to choose a seat it's possible that person chooses their own seat right and if that person chooses their own seat then we're good right if the first person a chooses their own seat at random then everyone else who does have their ticket will choose their own seat as well but if first person doesn't choose their own seat well then they're going to be in someone else's way right they're going to be taking some other individual seat and that's some other individual is going to see their seat taken so that some other individual is going to take some other person's seat and there's going to be this cascading effect right so how are we going to capture that you know within our formula and when you try to write it out usually you know you have these kind of relationships right you say like you know there's this probability that I'm gonna be in this universe where I pick my seed there's this probability that I'm going to pick this other person's seat there's this probability that picks other person C and then you can kind of Branch out like that and then if it's dynamic programming you can figure out if there's intersection of branches and kind of work back or you can you know brute force and calculate the probabilities that way right that's usually how we approach these kind of problems formally right and also intuitively it just makes sense right try to break it out into the universes of what's possible right if I take this seat then what will that mean if I take this other C what will that mean Etc right and that's what's kind of weird about this problem right because when you try to think about it you know the I'm going to walk through what I kept running into and kind of show you why this is so difficult right because you think about it in terms of trying to split it up right so if you have n people right well let's just say there's these seats right so there's these seats A B C all the way to I don't know N I guess because there's n people and then there's this first person right now this first person is what's throwing a wrench in the system because this first person doesn't have a seat so they're gonna pick one at random okay well it's possible in the best case scenario right this person that picks a seat at random actually ends up picking the seat that uh was allocated for them right so in the best possible situation with the probability of what this will occur meaning you have these end seats still right and this person ends up in their actual seat right and if this person ends up in their actual seat well then we're in good shape right because this person won't get anybody's in anybody's way so then subsequent people will also get in their seat right B will see their seat open they'll get in their seat see we'll see their person their seat open all these people will and then end will as well right so that's the ideal situation in terms of you know it's the easiest case to understand right because like if I get my own seat then everyone will get their own seat it simplifies the problem completely so that's probably where you're gonna think what you're gonna think about first but also you know what's the probability of this happening well you know I have N seats I can choose from and a is going to choose them all uniformly at random so that means there's what probability that they choose the seat well one out of n times let's use the C right just simple probability right n options I choose any of them at random the probability that I choose one of them is one out of n right so this happens with one out of n times okay but what about the other cases well in the other cases I don't choose my own C and I'm creating an issue right I don't choose my OC n minus 1 over n times right only one out of n times randomly will I choose my own C and minus one over n times I'm going to end up choosing the wrong seat right now what does that mean though in terms of what the cascading effect is right who's going to be affected well that essentially means here I chose you know I chose any of the I could have chosen selected any of these seats at random right a could be anywhere here well a could be if a is here what does that mean well that means B will have to choose a seat at random right because now B screwed B is in a bad position because I took BC but if I so that's kind of a unique case in itself as well right so that could happen with one over n and then well there's also the case where you know I take c and if I take you know cease see it over here then B will be able to sit down but then down the line right C is going to have to make a decision about what C it takes so that's what really adds a lot of complication to solving this problem right because it's not just an easy relationship like this right there's cascading effects depending on what seat I take right if I take a if a takes its seat at random then it's easy it's gravy but if a takes another seat well it depends on what seed it takes that's going to affect the relationship right if it takes c b well then C B is gonna have to do a random operation if it takes c well then B won't have to do a random operation but then C will so then you just start getting these crazy Spirals and I don't know if I still have it drawn but you know this is kind of my work uh prior that was you know leading to something that became too complicated right because I was thinking like well if a goes with a it's good right for case of four but if a goes with B well then B is going to have to make a random choice but if a goes with C well then B won't have to make a random choice but then C will if a goes instantly with d well that's a problem and we'll talk about that more but see this it starts getting spiraled out of control and it's really hard to capture the relationship of how we're actually going to solve this right so let's go back to this example so what I decided to do instead was let's just draw out a case of four and let's try to walk through it and see if that can you know lead to any intuition in terms of the nature of the solution to this problem right let's just look at a case of four and let's just walk through and see okay does this work what does this mean let's exhaust all possible things that could occur and then see if that indicates something about the nature of the solution to this problem right so this is a very time dependent kind of scenario here right because if I only have 20 minutes to solve this problem I'm probably not going to have enough time to write this out right but if I have sufficient time if I think I have sufficient time to write out the whole problem and I have nothing else to go after right I think I've tried to do it this way and it's not making sense it leads to something like this where it's all sporadic and I can't figure out what the answer is right it might be beneficial to just draw out a long example and see what kind of information that reveals right so this is kind of like a last Stitch ever right this is a last resort approach because it's time extensive but if you have the time it's not a bad idea to try it this way so I just pre-drew this out because I don't just pre-drew this out because I don't just pre-drew this out because I don't want to spend the whole video trying to draw this out but let's just say for this example right we have four people so we have n equals four right so we have n equals four people in this example now What's Happening Here Right is we have the selection of a right so a is the first person and a is going to choose at random right A's not going to intentionally choose its scene it doesn't have its ticket so the first person a second person B the second third person C the fourth person B and so on right but in this example there's just four people a wants to go in AC B wants to go on b c wants to go in c d wants to go in DC so a four things can happen right either a picks its own C a picks B at random a pick C at random or a picks D at random now let's think about what the consequences are of each of these things the first two easiest ones to understand are the red and the green um the red and the green uh lines right because if a chooses a then we're good thereafter right because if a chooses a then B isn't going to choose at random B is going to see it C open it's going to pick it C is going to see it's seed open and pick it D is gonna pick it's C and see that it's open and pick it right so this happens with one over n or let's color it to Blue that's fine so one over n in this example four right so one fourth of the time at random right because any of these actions can happen at random right uniformly a can end up here or here if a ends up just coincidentally at random in its own spot then we're good right because then everyone else will choose their seat accordingly right because only a is picking randomly everyone else is going to see their seat open and they're going to choose it the other way where this is easy to understand is well this red example right in this red example which also happens with one-fourth probability happens with one-fourth probability happens with one-fourth probability right all these things happen with one-fourth probability a is going to pick D if a picks D well we're trying to find the probability that the nth person gets its own C well a pick D so the nth person in this example is d didn't get its own C therefore D isn't going to ever be able to get its own C regardless of the rest of the orientations right just the fact that b might go in B and C might go and C and D can't go in its own seat so this problem's already done right so if a if anybody chooses the last C and it's not the last person well then the problem's over right so we don't need to extend on this example because it's already soiled right it's already broken return the probability of the end person gets his own C the nth person is never going to get his own seat in this situation so that's a big fat zero chance of it working out one-fourth zero chance of it working out one-fourth zero chance of it working out one-fourth of the time from the get-go right these of the time from the get-go right these of the time from the get-go right these yellow ones though we're not sure right because there's further kind of scenarios we need to consider and think about what does that mean for the problem well let's look at this chain here right this chain starting here and going up see if I can get this whole thing on the recording okay so in this example let's say that you know with one-fourth probability a will know with one-fourth probability a will know with one-fourth probability a will end up in B slot so what does that mean for B so B is going to walk up to its C and see that a is there so B is going to choose at randomly what to do okay so B at randomly can choose three seats you can choose a can choose C or you can choose d so he randomly selects a seat and you know in this example what you'll notice is this is something you want to look at and think about here right so this is a what's occurring here is important and if it's not clear to you now it will be later and it'll really simplify how we can build a relationship in this problem right between the components but you'll notice here that if B chooses a well then it's like a and b they just swapped with each other right so since they just swapped with each other now C can choose C and D can choose d right like a took my seat from me so if I just take his seat from him then everyone else will be able to figure it out right in this example well if B chooses C there's more to configure so we'll not worry about that next but then if B chooses D well it's the same thing as here before right if B chooses d right that's this here right if B chooses D then the problem's over because we want the probability that the N person gets its own C right so again if somebody tries to choose a seat the last C and it's not the last person that's going to cause this whole thing to fail so we don't need to keep extending the problem we just stop here right now what's the probability of these things happening well one-third for each right because B is one-third for each right because B is one-third for each right because B is going to have one-third one-third one-third right he has three options B can go to a b can go to C or B can go to D so one-third one-third one-third in this one-third one-third one-third in this one-third one-third one-third in this top right it resolves the problem because they kind of swap with one another right B to a took the C from B so then B takes the C from a then everyone else able to figure it out including the last person in this example B took the C from d is the last person so you can just nullify there you don't need to continue down that route because it's not going to lead to the solution right because D will never get its seat now because someone's already sitting in it okay now here what's happening well now C is having trouble right because now C is going to walk up and C is going to look at its seat and say B is in my seat so he's going to randomly choose a seat now if C chooses a again it works out right so again this is another thing that's weird that in a moment should make sense but what's going on here is that there's kind of a swap right but now it's kind of like a further swap right like okay a took b c b takes my C so I'll take AC and then everyone else will be able to figure it out right so now these remaining seats are open so D can take its own seat here if C decides to take DC although there's only one seat left it doesn't matter right the same thing only D can take the last C if someone else does it nullify so this becomes zero and that's this Branch let's look at this other yellow Branch it's very similar right what if a takes C well what's interesting here right is there's not multiple choices here because B is going to walk up to his seat see it's open and he's going to take it only when we get to see do we now have to reiterate and do something random right because a took CC so everyone in between a and C is going to sit in their own seat right because a took C so then when B walks up B is going to get in its own C he's gonna see it's open a only conflicted with C so now when C walks up now we have the splitting relationship we have to think about and again if C takes AC then they just swap with each other and we're good to go but if C takes d c again we have an issue and this will happen with one half probability let's try to get all the probabilities here written out one half okay and again this is a case where we start because we're trying to think about what that means for the nature of this problem so this is an N equals four you know exhaustive example and um hopefully from this we can kind of think about a few things which uh will simplify how we determine this relationship between the elements okay so the first thing you'll notice right is what's the first thing you should notice let's just sit here and think about this for a second how we're going to articulate this point to make it obvious right so you pick your seat if your seat's taken you pick a seat at random right so you pick us you try to pick your seat taken then pick it random okay that's how this works right except for the first note right the first note is going to pick it random but the observation you can make here that simplifies this problem really is well you know all these up arrows you'll notice they're all good it all leads to a good solution and why is that well if a chooses itself at random then everyone else can pick their seat Also if anyone else who's conflicted by a selects a it's going to resolve the problem going down right so you know the thing here right is when B is conflicted because a took b c B selects something at random right and there's a seat that b selects which will resolve this problem one of these seats will resolve this problem if B chooses a it instantly resolves the problem right if Beast chooses something else it could resolve the problem down the line but when B is in the scenario if it chooses a it resolves the problem right same thing in this example here when C sees that its seed is taken if C chooses a it resolves the problem okay so what I'm basically saying is for every case there exists a chair that resolves of the problem and what I mean by that is even from the beginning right at the beginning the problem is that a doesn't have a ticket but if a chooses a it resolves the problem when we get to B and B doesn't have a ticket it chooses randomly but if it chooses a it solves the problem when we get here and we're at C and C is conflicted by B but B is conflicted by a still conflicted by a if he chooses a it solves the problem so for every case when you choose randomly if you choose the chair that's causing all the problems it'll resolve all the problems and that's one of the chairs right so there's always one chair for all the chairs you can choose which resolves the issue and kind of generally what this means is well let's look at this example here okay when we have you know let's say we have x to the nodes at the first time X1 is going to select a chair randomly so if X1 chooses XX well then everybody else up into XX will choose their own C right X2 will see their seat and choose it X3 we'll see their C and choose it X4 X5 all the way up into XX if x chooses its own seat then the problem is resolved I mean sorry if XX chooses X1 then everyone else will be able to find their chair and the problem is solved but if X1 chooses some other C down this line right because all these other seats have been chosen then X1 I mean then those seats are going to have to deal with another conflict right so when we look at this first example here what I'm trying to really get at right what I'm trying to articulate which is so difficult is that this person has four seats they choose at random in one of them solves the problem this person has three seats that they choose at random and one of them solves the problem and this person has two seats they can choose from and one of them solves the problem so every single person they have n choices one of those choices solves the problem one of those choices knows out the problem and the other choices kind of push that problem down the line right this person has one choice that solves a problem one choice that causes you to never be able to solve the problem because you sit in the nth person's seat and then it has choices in the center which extend the problem out but that's true for every node right every node is the same exact relationship so even though this condition is different where B in this condition initially will check and then choose randomly at the end of the day it's the same problem B is going to choose three chairs at random one of them solves the problem here a is going to choose four chairs at random and one of them is going to solve the problem so if this is let's say let's create a recurrence relationship we'll call it f of four right F of 4 means that I'm going to have four chairs I'm gonna choose one of them at random and then see if I can get the nth person to get his own C well this problem although it's different where B is going to walk up it's the same thing it's just F of three right this is f of three because it's well B is going to choose one of these three chairs and one of them will solve the problem this one's a bit different because here B is going to choose its chair but then C is gonna have to choose one of the two remaining chairs and that's going to be F of two right so really what this is well F of four if we're thinking of this in terms of f of x is choosing X chairs where one chair solves the issue solves the problem right if we think of that as f of x well F of four is well the probability of this happening with it working out as well I either I choose the right chair right so one-fourth of the time I choose right so one-fourth of the time I choose right so one-fourth of the time I choose the right chair so I'm going to draw this more neatly and I'm going to put it uh down here I guess so you can kind of see what's going on okay so F of four is well one-fourth of the time it works is well one-fourth of the time it works is well one-fourth of the time it works out right one-fourth of the time it works right one-fourth of the time it works right one-fourth of the time it works out because I select this Branch where I put a in the right spot at random one fourth of the time it's never going to work out so that's zero times one fourth right one fourth of a time it's never going to work out because it's going to end up being zero I'm going to end up accidentally choosing that last C another fourth of the time I'm going to lead to this scenario here which is just F of 3 right it's the same problem where I have one node B where if it chooses a if it chooses one of the seats it works if it chooses any of the others it may not but if it chooses one it definitely works right the same thing forever four F4 chooses this top Branch it works otherwise we're gonna have to figure it out it's the same thing here right this is the same it's the sub problem it's a sub problem based on the same thing even though the conditions are different it's really the same scenario where you don't have your chair so you pick one at random you pick the one at random that works it works out if you don't if the problem gets extended or it fails that's the same thing here that's the it that's the point I'm really trying to articulate here is f of four and F of 3 are these scenarios are essentially the same because you're choosing a chair at random and the one that you choose that fixes it fixes the problem right so this is just F of three and this is f of two why because you've if you choose C then B is going to choose its own C and then C will have to deal with this F2 case of trying to choose two things plus one-fourth plus one-fourth plus one-fourth F of 2. okay so it seems like for any case right for any case f of n if you choose the first C it works out and that happens with one over n chance right if you choose this seat Well that happens with one of n but then the very next seat you're gonna have to consider you know branching out if you choose this seat it's going to take n over two right because what happened here right Y is n over 1 n minus two et cetera because if you choose B then the very next person is going to have to randomly select a chair to try to fix this problem if you choose C well the next person B will be able to select their chair right and then the next person when C comes up C is going to have to solve this F2 problem right so if I choose B then B is going to have to figure out and play the same game if I choose C then B will have its chair available then C will have to figure it out if I choose D then b and c will be able to figure it out because their chairs will be open and then d right if what I'm basically saying is if a chooses a you're done if a chooses B well now B is going to have the same problem of having to chooses to see it randomly if a selects c well then B will select seat B and now c will have the problem if a selects c d then d a if a selects c d then C person B will select c b because they'll see it open person c will select seat C because they'll see it open and then person D will now be the one who has to deal with the problem right so this goes all the way down and of course there's the last one of n where it doesn't work out so the recurrence relationship here right of this problem is let's write it nice and clear for the people in the back F of n equals well one over n times it works out plus 1 over n times it doesn't work out right because we're talking about probability here right one out of n times at random it's going to work out one out of n times at random I'm going to select the last personal next and it's not going to work out and then I have this relationship here where I'm going to try the N minus one person the N minus 2 the N minus 3 all the way to the F of n minus 2. or F of 2. right and you can see that here right I always go down to F of 2. there's nothing lower than F of 2 right because F of one if I only have one choice then I choose one person so you can see here that it only goes to F of two right it doesn't go below that because F of one there'll only be one choice so it doesn't make sense right I have to have at least two choices to choose from if I have one choice or zero choices then I choose nothing right I mean there's no Randomness right F of one is one okay so when we look at this I have one of n times F of n minus one plus one of n times F of n minus two right I'm just reiterating this recurrence relationship here but we could summation that as saying 1 over n times the summation of x equals 2 to n minus two of f of n minus X okay so this is the recurrent relationship of this problem this is the solution now that's why this problem is so mathematically extensive and why it's so problematic to solve because you're not going to do this typical relationship right like I did before where you're just like trying to draw lines and figure out how things are connected because you have to really think about well although the condition is different for subsequent nodes because they'll look first and they're because subsequent nodes are going to try to subsequent people are going to try to get in their own seat but if their seat taken it's really the same problem okay so this is the relationship here but then it's like well if F of n is based on previous things how does this really help me right how's this going to make my official solution more efficient well then we need to think about you know using some tweaking and some special math here to make this problem uh more concise and then try to see if we can find a solution that's not in terms of other versions of effort because now it's F's in terms of f right so I guess this could be a recurrence relationship but you know we're dealing with 10 to the 5 here in n so you know this is going to grow pretty fast so is there a way of tweaking this and finding an equation that's much simpler and faster to solve well let's take a look so usually when you saw these kind of problems and I just know this from college right we're gonna try to maybe iterate through another example of N and see if we can find a relationship between n and n plus one right since this is based off the previous things can we find the next thing and then see what that means so what would F of n plus 1 be so F of n plus one so we just replace everything that's n with n plus one now I'm going to just erase this because it's time zero right it made sense writing it out because it really articulated you know what's happening in this problem but let's not add any more terms than we need to because you're about to see this is pretty complicated so remember we're replacing everything with n plus one x equals two to n plus one minus two would be n minus 1. and I'm not going to do all the algebra here but you know just you know plug that in right I'm just adding a one so negative 2 plus 1 negative one and this would be F of n plus one minus X okay now what I want to do of course right to simplify those is I want to get rid of this summation so you know if we're going from x equals 2 to n minus 1 of this equation can we make it look like this somehow let's try to see if we can do that okay so this summation here is well for x equals 2 we have F of n plus one minus two for x equals three we have F of n plus 1 minus three and then we go all the way down to x equals n so what I'm doing here is I'm trying to draw out these examples to see if I can modify this so it looks more like this that's essentially what I'm doing right now and x equals N I have or x equals n minus 1 the last term because I want the first term and the last term to agree why did I put two here because this is this has FN minus one so this should be one right it should go to n minus two for the last example but this should start at one so I apologize okay so we started at one that would be minus one minus two n minus 1 is the last term and that would be F of n plus 1 minus n minus 1. all right so if we simplify these that means that x equals two we have F of n x equals one damn it x equals two we have F of n minus one and this is f of n minus uh n plus 1 minus n plus one would be n would be two right so n minus n 0 1 minus negative 1 2. okay so how would we rewrite this then so it's not right because we want it in the same form as the top one okay so this summation is the same as right this summation here is equivalent right if I thought about this simulation in a different way I could say well we start at if we started at x equals zero all the way to n minus two of f of x minus n or not n x minus uh n minus X right because if you did this somebody like so I found this relationship here by looking at this right so if I look at this one I say okay when X is zero we get n minus zero that's F of n x is one we get n minus one X is n minus two we get n minus two F of two so basically what I did is I formed you know using this summation I found this thing on the right and then I said okay well that's equivalent to this on the right on the left and the reason why I'm doing that is I'm trying to make it look more like this one here right so that means I can replace right I can um just make this smaller right so I can replace this summation with this summation here so that's what I'm going to do so I just copy this over and what I'm saying is this summation is equivalent to this one here right these estimations are equivalent when you just write them out right and that kind of makes sense right because all we're doing with n plus one is we're adding the F of n term so this just adds the end term to this one right but what I want to do is I want to replace this summation so what I can do in order to do that right and I learned this in differential equations which is why you know this problem is pretty difficult for someone who's not you know super mathematically aligned but what I can say is well then that means F of n plus one equals 1 over n plus one I'm going to pull one term out so that so let's pull the zero term out so that would be X of zero equals F of n minus zero which is f of n so that would be F of n Plus and then the summation just continues but now it continues from this point forward we can distribute this one Over N plus one well actually just to simplify things I'm going to multiply everything by n plus 1 right now so when you do that I kind of want this to be Standalone it's so hard to know how much to write and how much to Forget You Know so we do that this becomes one these terms go away just becomes a little nicer and we do it like this all right except now we have an N plus one term over here right so let's replace this term with this term so in order to do that we took this we moved it over what would we do to change this well we multiply everything by n all right we multiply everything by n like so then these terms this becomes a one so this is n times F of n minus 1 equals this whole thing foreign right so what I'm saying is you can replace this whole summation with n times F of n minus one apparently okay so that means over here since these are the same summations right I can replace this term with the same thing ah so now you guys see why this problem is so difficult because it's so difficult just to find the relationship and then when you find the relationship there's so much math just to get it to a point where you have a solution that's not based on you know earlier versions of itself or whatever so that means we can replace this with n times F of n minus one scare me Max n times my dog F of n minus one okay now these terms cancel and then you're just left with n plus 1 times F of n plus one equals F of n plus n times F of n all right I'll write this part out because it's the kind of the best part of this problem F of n plus one equals F of n times n Plus 1. right so I'm just factoring out this F of N and then if you notice well strangely right these two terms cancel and you have the relationship where F of n plus one equals F of n so this whole weird summation situation here you know at the end of the day is literally just itself right and I'm going to leave it like this for now because looks nice like this so well what does that mean then right like well it can't be true in all cases right because when n equals one there's only one choice so if n is less than or equal to one we just return one but if otherwise if n equals 2 it's a half so what I'm essentially getting at here which is so strange about this problem right is well F of 2 equals a half and while F of 3 is going to equal F of 2 so that means it's going to equal a half and then F of 4 is going to equal F of 3 which equals a half so it equals a half so everything's going to equal a half after two right because the next one equals the previous one with the exception of the first one right but for two it's a half because you can either choose the top or the bottom so it makes sense that it's a half right because you have two choices either you have two seats you have half probability you choose the right one and the other one can get it you have a half probability you don't choose the right one and nobody gets it like nobody gets the solution to this problem right so for f of two equals a half then F of three equals a half and four equals F so with the exception of one everything equals a half oh foreign so what's the run time in the space of this well it's pretty obvious right the time well it's constant you're just making comparison in for space well it's constant right and all that is based off of this insane relationship of looking at an example right so how do we solve this problem we looked at an example we kind of figured out what the recurrence relationship is by thinking about well it's really the same problem over and over again we kind of looked at that you know not too much I figured we'd look at this more but you know the idea here is if you choose the right chair then everyone else will choose the right chair when you choose the wrong chair everyone between you will choose the right chair until you get to you if you choose the right one then everyone thing works out if you don't choose the right one then you just extend the problem and that led us to this recurrence relationship and then we used you know some of our strong mathematical understanding you know differential equation discrete math whatever you did to kind of learn these tricks or maybe your Prodigy and you know how to do these things you know it's naturally we found that the relationship is well they're equivalent and it starts at one half and ends at one half so what I'm going to do is I really like to create cool kind of picture representations of my problems I'm going to move this all into one page this is just me wasting time right now so don't know what I'm doing or don't care you can now look at that doesn't that look cool let's get this one description all right everybody hope you have a wonderful rest of your day peace out
|
Airplane Seat Assignment Probability
|
number-of-equivalent-domino-pairs
|
`n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will:
* Take their own seat if it is still available, and
* Pick other seats randomly when they find their seat occupied
Return _the probability that the_ `nth` _person gets his own seat_.
**Example 1:**
**Input:** n = 1
**Output:** 1.00000
**Explanation:** The first person can only get the first seat.
**Example 2:**
**Input:** n = 2
**Output:** 0.50000
**Explanation:** The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).
**Constraints:**
* `1 <= n <= 105`
|
For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap.
|
Array,Hash Table,Counting
|
Easy
| null |
163 |
hello everyone and welcome to my new video today we are gonna solve another lead code exercise in this Google interview questions course this exercise is called missing ranges and here they tell us that given asserted integral array nums where the range of elements are the inclusive Branch lower and upper return its missing ranges so for example here we receive this array as an input with the lower range and the upper range so we need to return all the missing numbers that are inside this range so the thing here is that we need to take care of the range because we cannot forget to put a for example a numbers that add after our lower range if they don't appear in our array for example here they appear but they may not appear and numbers before uh the upper range the upper limit okay so that's the thing that we need to take care here so first we will create our output variable that it's at least for strings called ranges after that we will iterate through our nums array and now while we iterate through our names array is when we need to do to use sorry our lower and upper variables our limits so first we will check if the first number of our array well then Emerald the index I is bigger than the lower bound we will first we will take the two cases the case where we just need to add one number one missing number or the case when we need to add the range of numbers missing so if our first um number minus lower equals to one that means we only need to add one number so we say Okay range is that the lower bound lower but if the difference is bigger than one you know in the other case we need to add B range so we just say Okay range is at lower bound Plus Arrow Plus number before our current index and that's it and exactly the same structure for the upper bound so we need to now check if the last the number that we are currently checking well if they be here number possible we just finished traversing and at last we just need to update our lower round because we will use the lower bound to check every range that we are missing and we just update it so we say okay our lower bound is now the current a number that we are taking plus one so that the next time that we take another number we add one here and we know that range is missing okay so once we finish doing our for Loop we just need to check the last condition because we might be missing for example here we finish at 75 but we are missing all those numbers from 76 to 99. so in order to check that the last condition is if our lower bound is smaller than our upper round we need to add the whole rate okay and if our lower bound is exactly be being the upper bound so that we finished at the last number and we are lucky enough to have it similar to our upper bound we just need to add that number so we add well the lower number while we're at least over strings and that would be everything we just need to return our output variable ranges and let's test our solution and yes it's correct it has all the ranges here and I'm gonna submit it and it's accept accepted so as you can see this solution has a linear time complexity because it uses a for Loop and a linear space complexity because we use an additional data structure which is an arraylist but as you can see it's really straightforward this exercise was really easy and well thank you very much for watching this video and see you in the next one bye
|
Missing Ranges
|
missing-ranges
|
You are given an inclusive range `[lower, upper]` and a **sorted unique** integer array `nums`, where all elements are in the inclusive range.
A number `x` is considered **missing** if `x` is in the range `[lower, upper]` and `x` is not in `nums`.
Return _the **smallest sorted** list of ranges that **cover every missing number exactly**_. That is, no element of `nums` is in any of the ranges, and each missing number is in one of the ranges.
Each range `[a,b]` in the list should be output as:
* `"a->b "` if `a != b`
* `"a "` if `a == b`
**Example 1:**
**Input:** nums = \[0,1,3,50,75\], lower = 0, upper = 99
**Output:** \[ "2 ", "4->49 ", "51->74 ", "76->99 "\]
**Explanation:** The ranges are:
\[2,2\] --> "2 "
\[4,49\] --> "4->49 "
\[51,74\] --> "51->74 "
\[76,99\] --> "76->99 "
**Example 2:**
**Input:** nums = \[-1\], lower = -1, upper = -1
**Output:** \[\]
**Explanation:** There are no missing ranges since there are no missing numbers.
**Constraints:**
* `-109 <= lower <= upper <= 109`
* `0 <= nums.length <= 100`
* `lower <= nums[i] <= upper`
* All the values of `nums` are **unique**.
| null |
Array
|
Easy
|
228
|
1 |
on everyone so today we're looking at lead code number one question called twosome and i believe this is the most popular question on leap code it's also i think the most frequently asked question as well let's take a look here yeah so you can see in the last six months it's just asked everywhere and a very common question very popular question so definitely one to be very familiar with okay so we'll look at a few different approaches to solving this we'll look at a brute force approach we'll look at um another approach that could be space optimized not for this particular problem but if it was something similar and we'll look at an optimal solution so let's take a look at this prompt we're given an array of integers nums and an integer target and we want to return the indices of the two numbers that add up to that target we can assume that each input point will exactly have one solution and you may not use the same element twice you can return the answer in any order okay so here we have 2 7 11 and 15. target is 9. so we're going to return the 2 and the 7 because they add up to 9 but we're going to return the indices so it's going to be 0 and 1. here we have 2 3 4 and target is 6 so we're going to return the indices for 2 and the into c for 4 which is 1 and 2. and then here we have 3 and 3 so we do have duplicates but the target is 6 and so we're not going to return 0 and 0 we're going to return 0 and 1. okay because here in the prompt we may not use the same element twice okay so let's take a look at a couple different ways we can go about doing this okay so we have 2 7 11 and 15 so we're going to have the numbers 2 whoops okay so we're going to have the numbers 2 7 11 and 15. okay and our target here is gonna be nine so a brute force way to do this is to just do two for loops and check every number against every other number and then if they match the target we return the indices so for example we're gonna take two at the i-th and we'll check j take two at the i-th and we'll check j take two at the i-th and we'll check j does that equal 9 it does so we would return the indices here but let's say the target was um 17 right so we check 2 with 7 it does not equal j increments 2 with 11 it does not equal j increments and um 2 and 15 do equal 17 we return 0 and 3. so that's a brute force way to do it if we use that method what is our time and space complexity okay so we're not creating any new space but our time complexity would be o of n squared okay and our space complexity because we're not creating any new space we're just going to return the result value the space complexity would be o of one so we could do this in constant space but our trade-off is space but our trade-off is space but our trade-off is we're going to have quadratic time okay so now let's look at another way we could approach this input is sorted okay but if it was not sorted let's say we had uh let's say we remove these here okay 2 7 11 and 15 and let's say we had these in different order okay so we have 2 7 11 and 15. let's say we did 11 2 7 and 15 right now what we could do is we could do a sort operation we could sort this input and that would be n log n so we could sort it at a cost of n log n and then what we could do so if this is sorted we're going to get back to 2 7 11 and 15 to perform that operation it's going to cost us an n log n operation now once we have this sorted then we can use a two pointer approach and how will that work let's say we have an i variable here at the start and a j variable here at the end and now we can check do these sums does the sum of these two numbers is it greater than less than or equal to our target if it's equal then we just we know the two numbers that we need uh to find the target it's just we have to return the indices so we'll get to that in one second but let's just first figure out if these two numbers equal the target if they are greater than then what do we want to decrement j okay so if 2 and 15 plus 2 is 17 that is greater than the target we decrement from the greater side here we have two and 11 it is greater than the target we're going to decrement and then here we have two and seven the only problem is that when we sorted this our indices are all now different here we have 0 1 2 and 3 representing those respective numbers but we need to return the numbers respected to respective to the input array so if the question was not asking for indices we could get away with just sorting it and returning the actual values but because this question is asking for the indices we would not only have to sort the uh array but we'd have to make a copy of it we'd have to have we would have to have that input array in its original state we couldn't just sort it in place and then lose those in those places in the indexes now what we could do at this point is we could take two and seven and then run it again uh over the original input array find the indices and then return the indices okay so what would our time and space complexity here be so we're going to do um our worst case on time is going to be o of uh n log n because of our sort operation and our space complexity is also going to be o of n because we're going to have to copy our sorted array we can't just use the original array and do it in constant space okay so that's another way we could do this now what's the third way we could do this the most optimal way is we can use a hash okay so let's figure let's take a look at how to approach it using a hash we're going to have our input 2 7 11 and 15. we're going to have a target of 9 and now what we want to do is we have the indices here let's go ahead and put the indices here 0 1 2 and 3. we want to create a hash and we want to set this hash to the values being the keys and the indices being the values okay the values being the keys and the indices being the values so we're going to create a hash and 2 which is the value is going to map to the indices which is 0. 7 which is the value of the array is going to map to the indice which is 1. 11 which is the value is going to map to the indices which is 2. and 15 which is the value is going to map to the indices which is 3. all right now what do we want to now iterate over the array and we want to figure out what is a potential value okay and then we're gonna compare it to the hash we're gonna see if that number is in the hash so we're gonna go ahead and say okay here we're gonna have the value of two and we're gonna subtract the target from our current value so let's say we're at the ith variable here uh and we'll call this arraynums okay and so what we're going to do is we're going to create a potential key okay so we'll call this potential key and what this is going to equal to is it's going to be our target which is 9 minus our current value okay and so we subtract the target from two which is going to equal seven which is in our hash okay you can see it's right here in our hash right over here and then we are mapping it to the index so what we want to check now is if our hash has the potential key okay and the hash at potential key is not at the current index because remember we cannot look at the same numbers so that's another thing that we can't do so we have to also check if our hash at potential key is not our iaf index okay and if it passes that then all we have to do is return a duple with our iath index and our hash at potential key the value at that hash key okay so let's just kind of go over this slowly one more time just so it's clear we're going to come here at the ith index and we're going to go ahead and subtract our total or target from our current value which is 2 okay nums at i is going to equal 2 right here this target 9 minus two is going to equal seven and that's going to be our potential key what we did beforehand is we went and put all the values and mapped them to the keys okay so now we're checking does this potential key exist in the hash if that 7 exists in the hash we know that we have reached our target okay and now we just have to make sure that this potential key is not checking itself it's not the we're not doing uh it's not seven and seven it's not checking itself and that's all we're doing here is making sure that potential key does not equal i where we're at the ith index the current index and if that is true then we're just returning the ith index which is zero and the value of the hash at the potential key which is one okay so let's go ahead and jump into the code okay so first what we want to do is we want to create a hash okay and then we want to go ahead and set the hash and map it to the indices so we'll just do one for loop here okay and now we can go ahead and get our value so we can say let val equal nums at index i and now we're going to set the value to the index okay the hash key is going to be the value and we're going to set that to the index so just like we did right here that's all we're doing we're just creating a hash and then the value of each one of those nums is going to be set to its respective key okay now we're going to do another pass through this and now what are we doing we are going to get the potential key and check if it is in the hash and that potential key is not at the current if element so let's go ahead and create let potential equals target minus nums at i okay and if hash at potential key and hash at potential key does not equal i then just go ahead and return the duple return i and hash at potential key okay let's run that and we're good okay so now what is the time and space complexity using this method well we're making one pass through the array to create the hash and then we're making another pass through the array to find the potential key and check to see if that is in the hash okay so our time complexity here is going to be o of n okay because we're only making two passes through the array we could even optimize it just to make one pass but it's not going to change the big o so now what about our space complexity well we have to create that hash that is relative to the size of the input okay so it's a linear relation so our space complexity here is going to be o of n okay so we can get an optimized solution here of o of n time and o of n space if we want constant space then we have to trade off on time and you know the first strategy that we looked at using two for loops we could do this with o of uh um o of n squared time and then constant space uh the middle solution using n log n sorting it that would actually be worse on space and still be linear on time because we'd have to make a copy of the array so this would be the most optimal solution for this particular problem we could get o of n time and o of n space okay so that is lead code number one the classic problem two sum highly suggest to be very familiar with all the variations and all the variations on how to solve this problem because as you can see it shows up all the time so it's a good one to know okay so i hope you enjoyed it and i will see you guys on the next one
|
Two Sum
|
two-sum
|
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_.
You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice.
You can return the answer in any order.
**Example 1:**
**Input:** nums = \[2,7,11,15\], target = 9
**Output:** \[0,1\]
**Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\].
**Example 2:**
**Input:** nums = \[3,2,4\], target = 6
**Output:** \[1,2\]
**Example 3:**
**Input:** nums = \[3,3\], target = 6
**Output:** \[0,1\]
**Constraints:**
* `2 <= nums.length <= 104`
* `-109 <= nums[i] <= 109`
* `-109 <= target <= 109`
* **Only one valid answer exists.**
**Follow-up:** Can you come up with an algorithm that is less than `O(n2)` time complexity?
|
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
|
Array,Hash Table
|
Easy
|
15,18,167,170,560,653,1083,1798,1830,2116,2133,2320
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.