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
216
Raj Welcome back to my channel Laga luck making person delivery question video such mistakes messenger this suggestion or gold solve question number 2016 combination consent off beat increase note subscribe The Channel Please subscribe and related videos problem got well respect yes but Like this you have not appeared and order problems setting new problem in which were given to input procession of questions boss 7 and left forces of water list number one to 9 left click subscribe number 123 subscribe And subscribe The Amazing Subscribe Want to know that in which FIR numbers of other numbers 1214 Kasam Vikram shrink 793 combination in your exam question from number 90 number two to two all my problems and see that you can edit few solutions walnut then that Bigg Boss and this particular Question Study Combination To Which Question Subscribe Button Click Heer Voor Sent Missile Range From One To Subscribe List 2 F 2 2019 Sudhir And Hair Politics Customer Number Of Views Subscribe Loot Subscribe To Sudhar Se Saaf Right You Okay What Do You Want To Tell The Tracking So Subscribe Take One Number Don't See The Total Number Of Numerous It's Simple So Let's See How You Do First Here Select Ward Number 16 Selected Not To Select Reddy Number 19 Number Subscribe Now Number One Of the number of the number subscribe my channel do n't forget to subscribe that noilet the second number 200 g * hair that noilet the second number 200 g * hair that noilet the second number 200 g * hair soft of the collective responsibility handed over now on the scam end side click subscribe button number one two three and subscribe To Key Value It Is The Meaning Of I Request What You Want But This Side Of - Of I Request What You Want But This Side Of - Of I Request What You Want But This Side Of - Is Equal To How Much They Give But How Will You Know It Back To The Self I Am The Number Three Lucky Number 19 Number One Two Three Key Sukh Samridhi Ko Seven Hair And Size Wells Shri Vikas K Recovery And Magic 1969 Chilli Powder Coriander Powder Cumin Powder Sonth Do A Relationship With Colored In This Competition In No Impression In Way To Numbers And Subscribe Our Output But Not The Mirror Work Phone Number To The Volume to back to the 1251 more hai to 1285 no veer vinod ko subscribe similar 69 finally Bigg Boss 212 ki suryagrahan ko wala game na with one with selected to front sunao with silver 2183 select number three layer and not 3193 total number of versus finger To subscribe The Channel press the subscribe button Range Number 4404 subscribe to the Page if you liked The Video then subscribe to the Page Reminder Share Improve Total Number in the Best Ji Ko Shuddh Ki Birthday Sameer Wild Discovery Channel Subscribe Button Back to the Real State End This Time With No Entry Zone subscribe The Channel Please subscribe and subscribe the Video then subscribe to the Page 200 Words for the Backtracking Algorithm Voice gravity of wave gold in the left for all its values ​​in the mid-1960s with me to the difference between the Subscribe From What Does A I Lay Crucified Default Office Were Not Been Written A Little Kids To Result Subscribe Our Channel Subscribe To-Do List To-Do List To-Do List Setting On Tomorrow 9:00 AM Guys West Indies Tutorial Tomorrow 9:00 AM Guys West Indies Tutorial Tomorrow 9:00 AM Guys West Indies Tutorial Relation Or Starting From Some Cases Starting From One In The going forward a combination someone in this game will start from two and will take all the information from two students of starting position dano person tak liye wali and what is the from this what is the meaning of 200 degrees it will ask the customs to the robbers Brush of subscribe to this website template image well this condition agraja film data pir world.so main young are list aaj hum in for 10th na this condition adherence and returns to form as third standard size and the size of the temperature subscribe button more equal To 9 Inch Plus A View To Start From One To Request 9 And Free From Video subscribe and subscribe the Channel That This Taken Into Consideration Is Held In The Years Back To And This Next Element Servi Is The First Number To And Number List 105 Result Tenth Which Exactly To Abhinav Plus One That The Volume Of K Rooms Have Been That Economy Mein Bolti Hoon Sab - I Have Economy Mein Bolti Hoon Sab - I Have Economy Mein Bolti Hoon Sab - I Have A Time In The West R Time Held On Second Number 90 Simply Remove Result Subscribe To I India And Vectra Functions Doc This Computer Anxiety Shool Field Result List With A What Do You Do To Relax Homes Single Withered Template Image Good Night Stroll Hai Next This Is Early Morning Calling Specification Result 10th Class 10 Notes Hee To-Do List Subscribe That Hrithik Will Come Which Will Stress Hormone Test Cases for Little Kids subscribe and subscribe the subscribe Video subscribe comment and subscribe the Friend Hai Ki Soch For Watching Bye
Combination Sum III
combination-sum-iii
Find all valid combinations of `k` numbers that sum up to `n` such that the following conditions are true: * Only numbers `1` through `9` are used. * Each number is used **at most once**. Return _a list of all possible valid combinations_. The list must not contain the same combination twice, and the combinations may be returned in any order. **Example 1:** **Input:** k = 3, n = 7 **Output:** \[\[1,2,4\]\] **Explanation:** 1 + 2 + 4 = 7 There are no other valid combinations. **Example 2:** **Input:** k = 3, n = 9 **Output:** \[\[1,2,6\],\[1,3,5\],\[2,3,4\]\] **Explanation:** 1 + 2 + 6 = 9 1 + 3 + 5 = 9 2 + 3 + 4 = 9 There are no other valid combinations. **Example 3:** **Input:** k = 4, n = 1 **Output:** \[\] **Explanation:** There are no valid combinations. Using 4 different numbers in the range \[1,9\], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination. **Constraints:** * `2 <= k <= 9` * `1 <= n <= 60`
null
Array,Backtracking
Medium
39
1,820
hello everyone let's take a look at the code 1820 maximum number of accepted invitations and it's a lot question let's take a look at this problem first the problem is there are m employees and young angers in class attending an upcoming party and we are given a multiply an integer matrix grid where grid ij is either zero or one if grid ij is one that means on the ice boy can invite the juice girl to the party a bird can invite at most one girl and a girl can accept at most one invitation from boy so we need to retain the maximum possible number of accepting invitations okay so there are two examples you can take some time to use the examples and the constraint is mn is between 1 2 and 200 and let's take a look at some hints here the first thing is um we can see that the problem can be represented as a directed graph with an edge from each point to the curve he invited second thing is that we need to choose a set of edge such that no two source points in graph have an edge with same endpoint yet since one girl can be accepted like by one boy and one worker like choose at most one girl for three inches this problem is maximum bipartite matching in graph okay so let's take a look at how to solve this problem okay i will use the second example so uh i just write this graph to represent relations so um b1 has two edges which is a g1 and g3 b2 the second board has only one edge which is g1 the slipper has only one edge which is just three the fourth ball has three edges which is just one two three okay so this is graph representation this is a matrix representation okay and i need some um variables for example girls which means um like for the girls with index cereal um like which boy assigned to and like uh at first all girls are available they are not being like invited by any voice so it's negative one for example if g1 is simulated by b1 then the index will become zero here if g2 is invited by b4 this index will become three and match is our answer we want to get the maximum match here okay so we just follow every ball here for b1 we want to find a girl to match b1 then we just follow all the girls at first with it with g1 and v1 has an edge and g1 is available so we just match p1 with g1 so this becomes zero and match becomes one okay next we'll try to find the girl for b2 then we do the same we just follow all girls we start with g1 b2 and g1 has an edge so we try to ascend g1 to b1 now we make g1 p2 g1 then we try to find the new curve for p1 since previously g1 was connected with p1 so we need to find a new curve for v1 and it's very similar which just follows all the girls and we find that 2 3 and b 1 has an edge and q 3 is available so we assign g 3 to b 1. okay so we assigned two three to b one then we update all girls so for g one it matches p two so the index is one for g three it's matched b one so the index is 0 here and match becomes 2 now for b3 we try to assign choose 3 to b3 since it's only one edge if we assign g3 to p3 we know that and this 3 was assigned to b1 then we tried to find the b1 new girl and we just iterate out girls and the g1 and the b1 has an edge so we assign g1 to b1 in this case but g1 was also assigned to b2 so we try to find a new girl for b2 but we cannot find any available girls for b2 so if we add b 3 here we cannot increase our match so it's you useless to add b3 so match is still two next b4 okay we try to do before g1 we try to assign g1 to b4 but g1 was assigned to b2 so we try to find the new match for b2 but there's no other edge so we cannot do b4 g1 someone try to do b4 g2 yes it's fine since g2 is available so b4 and q2 is match then we update the girls and match okay so we get our final answer three okay let's take a look at the implementation so we have a curse vector here and we have an integer match finally we just written match in this for loop which is for all words for each boy we try to add it to our answer so we try to find a girl for you versus for you but we also want to make previous boys that have girls still have girls if we can add you then we can just increase our match okay now let's take a look what this function is for this bipartite function we try to find the new curve matches you so we just follow out girls here yeah if uh if this boy and girl and does not have a connection we just continue if this girl has been visited we just continue otherwise we try to match this curve v to this point u so we set save to true and if this curvy is available we can just assign this board to v right otherwise if it's not available we try to assign this curve to this port but this girl was previously assigned to a boy so we finally sport and we try to find this boy a new match so we need to recursive call here so in simple case this square v is available we can just assign it then return true means we find a new curve for you and we can also increase our match or if cisco is not available we assign c square to this point and for the previous board attached to this curve we try to find it a new party so there are two cases here okay let's take a look at like how to interpret this code like i just keeps matched here for the previous example b1 g3 b2 g1 b4 g2 now imagine that we're adding new board b5 if b5 has a neighbor g4 that's not assigned it's very simple we can increase our match we find the new graph for e5 otherwise let's say um for this p5 it occupies choose3 but g3 was assigned to b1 previously so we find a new curve for b1 we find b1 have a neighbor g4 and g4 is available so in this case we can also increase our match or like there's another case like b1 try to occupy g3 so we'll try to find the b1 a new match then we try to assign g2 to b1 in this case we try to find it before a new match then we find b4 has enabled g4 and g4 is available so in all these cases we can increase our match okay that's it see you next time
Maximum Number of Accepted Invitations
number-of-ways-to-reconstruct-a-tree
There are `m` boys and `n` girls in a class attending an upcoming party. You are given an `m x n` integer matrix `grid`, where `grid[i][j]` equals `0` or `1`. If `grid[i][j] == 1`, then that means the `ith` boy can invite the `jth` girl to the party. A boy can invite at most **one girl**, and a girl can accept at most **one invitation** from a boy. Return _the **maximum** possible number of accepted invitations._ **Example 1:** **Input:** grid = \[\[1,1,1\], \[1,0,1\], \[0,0,1\]\] **Output:** 3 **Explanation:** The invitations are sent as follows: - The 1st boy invites the 2nd girl. - The 2nd boy invites the 1st girl. - The 3rd boy invites the 3rd girl. **Example 2:** **Input:** grid = \[\[1,0,1,0\], \[1,0,0,0\], \[0,0,1,0\], \[1,1,1,0\]\] **Output:** 3 **Explanation:** The invitations are sent as follows: -The 1st boy invites the 3rd girl. -The 2nd boy invites the 1st girl. -The 3rd boy invites no one. -The 4th boy invites the 2nd girl. **Constraints:** * `grid.length == m` * `grid[i].length == n` * `1 <= m, n <= 200` * `grid[i][j]` is either `0` or `1`.
Think inductively. The first step is to get the root. Obviously, the root should be in pairs with all the nodes. If there isn't exactly one such node, then there are 0 ways. The number of pairs involving a node must be less than or equal to that number of its parent. Actually, if it's equal, then there is not exactly 1 way, because they can be swapped. Recursively, given a set of nodes, get the node with the most pairs, then this must be a root and have no parents in the current set of nodes.
Tree,Graph,Topological Sort
Hard
2306
505
hey what's up guys uh this is strong here again so let's take a look at lead code 505 the maze number two uh i believe you guys must have already seen the maze number one right so this one is pretty similar but actually it's not that similar the description is the same but you know the output is different so this time you know basically uh there's a ball in the maze right and then the ball can go through the empty spaces by rolling uh into four directions but it won't stop rolling until it hits a wall okay and then when the ball stops it could choose the next direction okay now you're given like this m times n maze and the starting point starting position of a ball and a destination position and then you need to return the shortest distance for the ball just to stop at the destination right if the ball cannot stop at destination return minus one so the distance is the number of space empty spaces traveled by the ball from the starting start position okay and you may assume the borders of the maze are all was right so that's why so here for example this one right the ball starts from here and then and the destination or the gate is it is this one and the answer is 12. and why is that because you know so the ball roll i go to here first right and then from here it go down from here it go to left right and then you go down again then go to right and then go down and then go right so this is the optimal path this bar can reach to the destination right and the total distance is what we have one right one plus one here we have three and then we have going we have one and then we have three then we have two and then we have two right so this is what two five six nine 2 5 6 9 11 13 12. uh oh here yeah this is this one this should be two this one is two that's why the total is twelve right okay cool and so if you guys remember the uh the maze one the original maze problem you know for the original maze problem it just asks you if this ball can reach this uh this destination or not it doesn't ask you the mid the smallest distance to reach it right and yeah okay so here's another example here so for this one you know the answer will be minus one because here's the destination but no since the ball can only stop while it hits the wall as you guys can see you know so the ball will never stop at here because you know no matter if the ball is rolling in this direction or in this direction you know it can only pass this destination but it will never stop at it that's why the answer is it's minus one okay and cool so since this one i asked us to find the shortest distance you know we cannot uh use the uh there are basically the basic the dfs or bfs to explore uh all the possible routes right and then we also maintain like a visited nodes because that will that mean that may not lead us the optimal solution right and why is that because let's say you know the ball move here and then here right so when the ball is here it has like two options it can either go right or go left yeah because you know this one has already been visited that's why the block will only go right and left but the optimal solution is go left because if you go right and then you go to left the total distance will be bigger okay that's why you know we need to use another like algorithm okay and so if you guys know there's a uh this uh diecastro algorithm basically the texture algorithm can help us to calculate the minimum distance in uh in a graph right in the weighted graph between any written any this uh any uh two notes right so it and it's a perfect fit for this problem because you know for this problem you know from here from the starting point to the ending point that's the two nodes in the graph and from the starting point we can have different like edges right so and we can also have like different nodes so the nodes will be the other stopping point for example this is also like a node this is also a node here it's also a node right and between those kind of nodes they're like there's like kind of like the weight on this edge right so the weight would simply be the distance in this case and we're getting the minimum like the total distance between these two nodes right so if we can model this problem into a digester problem then the rest should be pretty straightforward right where we just need to use the uh the dextro problem template which is the uh the while loop right the bfs or dfs plus the priority queue okay and yeah then let's start coding so for those who don't know the dinosaur problem i think you can just search online there are a bunch of other like uh videos or articles that can give you the very detailed explanation about why the textual problem works so long story short right you know we define like m times n distance so where the m is the maze and the n is the uh of the maze zero so we define like two dimensional distance here you know at the beginning everything will be the max size okay and then for n this so this two dimensional uh list stores the minimum distance between the two nodes okay and we also gonna be maintaining like the priority queue so the product queue the key for the product here will be so the key for the product queue will be the basically the distance to this current location right which will be the starting from zero start one so this the key will be the distance right the current distance and then the in and the coordinates i and j and if there are like multiple paths that can reach to this i and j you know we could have different like a distance right and then that's why we use the product queue because if we sort if we create a maintain the key in this way you know the first one right so the first one will always be the smallest distance to the current uh to the current direction to the current not current location because you know if this one is i and j right so this one is i and j if we have a multiple root can lead to this one right now we always obviously want to use that you know the total cost so this uh this i j means that you know from the starting point right this is a starting point from the starting point to the current to the i and the j node right where is the uh some coordinates in this graph right and what's gonna what is the distance right to from the starting point to this current one right you know if there are like multiple paths that can lead to this uh inj here you know for example if this one right basically you know we might have different we may have multiple uh entry points or added items in this priority queue for the same ing and every time we'll pick the smallest one because we want to get the shortest distance right that's why we use the particular to get the short the we always process the smallest distance from the prodigy so that we can make sure we'll always find the uh the smallest distance from the starting point to any i to any ij location and after that we're also going to be updating the distance because we'll be using this distance the two-dimensional list here to the two-dimensional list here to the two-dimensional list here to maintain what is the current uh minimum distance from the starting point to this uh to this inj uh position and then every time when we find us a smaller or like a shorter distance path we update that and that's the basic idea of the directional problem or dexter algorithm and okay so here we need a base case right so the base case is the start and destination it's going to be a start of zero and start off of one it's going to be zero right so obviously you know the starting point and itself has a distance of zero and for the priority queue you know we have zero at the beginning and then we're also going to be maintaining like a visited set right and then uh four directions right so this is standard thing one zero one minus one zero minus one right so while the product queue is not empty right so we have a current distance right and then we have iron j we pop it from the prodigy keep pop prodiq and then we only insert into the visited set whenever we pop it out from the priority queue okay so this is important because you know that's the only that's the time we can be sure you know we have picked the correct distance for this i and j add inj okay and then we're gonna try different edges right so and the edges here or the neighbors for the current node will be eroding into four directions right and so we have four d in directions and then the new i gonna be i and new j will be j right and a new distance okay we'll be starting from zero and the basic will try to roll in four directions right so basically while this one is nu i plus d0 and the new j is also in the range of n right d1 for this one right and the maze animates new i plus d0 and the new j plus d1 is equal to zero right so we keep rolling until we hit the wall right then we increase the new i and new j and then we also increase the distance okay so after the while loop the bar stopped right stopped rolling and then we simply we need to check the uh if the new iron new j first if has not been vegetated before right and the distance right and the current distance plus the new distance is smaller than the distance of new i and new j right this part is all like uh what part of the dashboard problem uh dax algorithm right then we push it into the product queue right with the uh with the new smaller distance for the current for this new i and new j and then don't forget to update this one the destination gonna be new i new j equals to this oops this one okay yeah so that's it so basically after the while loop here you know we will have a distance that can tell us you know the shortest distance from the starting position to all of the other nodes in this graph and then we can simply return right the distance of the destination zero and destination one right oh this one's too long okay zero and that's destination one right but you know don't forget we also need to handle this minus one case so what would be the minus one scenario uh okay obviously you know if we never if we will never be able to reach the uh the destination so the value for this destination in the distance uh array or two-dimensional to the array uh array or two-dimensional to the array uh array or two-dimensional to the array will be remain to the system max size right as long as we have there's a way we can reach that you know this one will definitely be updated with a much smaller value right that's why you know we only return this one if this one is smaller than system dot my size no otherwise minus one okay keep oh he push that's it yep so there you go right it works um so the time complexity for draw i think it's d i am times n times log m times n yeah i think this is the one because you know the worst case scenario will uh will be inserting everything into the uh in the priority queue right that's why the worst case for now for the particle is this one and we'll be inserting for each of the uh the node will be using this particular right so i think that's it this one it's pretty interesting problem you know as long as you can realize that you know this one you know every time when you guys say this kind of shortest the shortest distance uh always try and you can see it could be a like a graph related problem and then you're also asking you're asked to get the shortest distance and then definitely try the darkest show algorithm it's pretty useful and it's not that difficult to remember and to implement right cool i think i'll stop here and thank you for watching this video guys and stay tuned see you guys soon bye
The Maze II
the-maze-ii
There is a ball in a `maze` with empty spaces (represented as `0`) and walls (represented as `1`). The ball can go through the empty spaces by rolling **up, down, left or right**, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction. Given the `m x n` `maze`, the ball's `start` position and the `destination`, where `start = [startrow, startcol]` and `destination = [destinationrow, destinationcol]`, return _the shortest **distance** for the ball to stop at the destination_. If the ball cannot stop at `destination`, return `-1`. The **distance** is the number of **empty spaces** traveled by the ball from the start position (excluded) to the destination (included). You may assume that **the borders of the maze are all walls** (see examples). **Example 1:** **Input:** maze = \[\[0,0,1,0,0\],\[0,0,0,0,0\],\[0,0,0,1,0\],\[1,1,0,1,1\],\[0,0,0,0,0\]\], start = \[0,4\], destination = \[4,4\] **Output:** 12 **Explanation:** One possible way is : left -> down -> left -> down -> right -> down -> right. The length of the path is 1 + 1 + 3 + 1 + 2 + 2 + 2 = 12. **Example 2:** **Input:** maze = \[\[0,0,1,0,0\],\[0,0,0,0,0\],\[0,0,0,1,0\],\[1,1,0,1,1\],\[0,0,0,0,0\]\], start = \[0,4\], destination = \[3,2\] **Output:** -1 **Explanation:** There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there. **Example 3:** **Input:** maze = \[\[0,0,0,0,0\],\[1,1,0,0,1\],\[0,0,0,0,0\],\[0,1,0,0,1\],\[0,1,0,0,0\]\], start = \[4,3\], destination = \[0,1\] **Output:** -1 **Constraints:** * `m == maze.length` * `n == maze[i].length` * `1 <= m, n <= 100` * `maze[i][j]` is `0` or `1`. * `start.length == 2` * `destination.length == 2` * `0 <= startrow, destinationrow < m` * `0 <= startcol, destinationcol < n` * Both the ball and the destination exist in an empty space, and they will not be in the same position initially. * The maze contains **at least 2 empty spaces**.
null
Depth-First Search,Breadth-First Search,Graph,Heap (Priority Queue),Shortest Path
Medium
490,499
127
what's up everyone today we're going to go over word letter first we'll look at the input and the output then we'll look at the diagram to understand the approach now for the code i'll be linking it down below in the description and finally we'll go over the complexities the input is going to be two words and a list of words so this is going to be our begin word and this is going to be our n word and the output is going to be an integer our job is to go from this word and transform it till it finally ends up as that one using the words in the list so what's a transformation if we go from one word to another word by changing one character so hit becomes hot because i changed to o so let's look at how we get the answer five for this example we go from hit to hot becomes dot because the h becomes a d dot becomes dog because t becomes a g and dog becomes cog which is our n word because d becomes a c now you observe something like words which look like nodes and this transformation which looks like an edge so we have ourselves a graph and because we want the distance from the origin to the end we're gonna go for layer focused bfs if you guys didn't see my video about the difference between a layer focused and connection focused bfs i'll link it down below feel free to take a look so how are neighbors actually generated we know that a word and its neighbor are nodes and the relationship between them is an edge the way we generate neighbors is by going letter and letter in the given word let's say h i t is our word so first is going to be h and we swap it out for alphabets that we have so a i t b i t c i t d i t all the way to z i t now if a neighbor exists in the word list we are going to add it to the queue and add it to the visited set otherwise if our neighbor is actually the begin word we are going to skip it so once we're done with hit we go to the i right so h a t h b t h c t h o t and we see that h o t is in the actual list so we add it to the q and we add it to the visit itself finally we wrap it up with t same way hia hiv all the way to hic now let's look at the actual big picture and go from start here's the overall diagram of our problem now that we understand how a neighbor is formed let's begin with our first word hit so hit is going to generate its neighbors first we take the letter h and we swap it up for the 26 letters in the alphabet so ait bit all the way to zit right and we swap it out ajt hbt etc then we actually hit h-o-t because then we actually hit h-o-t because then we actually hit h-o-t because h-o-t is a letter in our list h-o-t is a letter in our list h-o-t is a letter in our list now we found one more thing and we can put it in the queue once again we go from h and we generate its neighbors aot bot cot etc next we go dot because that's a valid letter sorry valid word in our list and we can put it in the queue and it's going to be another layer in our word letter similarly we check it out for letter d we swap out the different neighbors for letter o we swap out the neighbors and for letter t we swap out the neighbors until we hit d o g finally we swap out the letters so aog bog and c audrey and we hit our n word so our word ladder in this case is going to be one two three four five the time complexity is going to be of n because in the worst case we might have to go through the entire given list and the space complexity is going to be of n times m squared because we can go through the entire list and store up to m squared potential neighbors n is going to be the length of the list and m is going to be the length of the words okay so that's how you solve word letter if you like the video please thumbs up and if you want to see more don't forget
Word Ladder
word-ladder
A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that: * Every adjacent pair of words differs by a single letter. * Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`. * `sk == endWord` Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return _the **number of words** in the **shortest transformation sequence** from_ `beginWord` _to_ `endWord`_, or_ `0` _if no such sequence exists._ **Example 1:** **Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\] **Output:** 5 **Explanation:** One shortest transformation sequence is "hit " -> "hot " -> "dot " -> "dog " -> cog ", which is 5 words long. **Example 2:** **Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\] **Output:** 0 **Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence. **Constraints:** * `1 <= beginWord.length <= 10` * `endWord.length == beginWord.length` * `1 <= wordList.length <= 5000` * `wordList[i].length == beginWord.length` * `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters. * `beginWord != endWord` * All the words in `wordList` are **unique**.
null
Hash Table,String,Breadth-First Search
Hard
126,433
54
hey what's up guys I like white here I do tech and coding stuff on twitch and YouTube I do all the lead code and a current solutions playlist for both of them so check this out I just do all the problems so this one's called spiral matrix I wonder if any of you guys have heard of it before it's a medium problem trying to do some more medium ones given a matrix of n by n elements meaning rows by columns return all elements of the matrix and spiral order this is really popular a traversal through a 2d array this is something you need to know this is something I've been trying I've wanted to know for a while it's not even that hard it's just like when I first saw it I was intimidated but it's basically doing a traversal where you would you know print so you would let's start at zero for example we would go you know one two three six nine eight seven four you know and then you'd move inwards the spiral moves in war itself obviously so how do we do this well just indices basically you just loop through and you just use indices I was kind of like at first I was like oh my god this looks hard dude spiral traversal but really you're just going from the beginning column to the end column from the beginning row to the end row from the end column to the beginning column then from the beginning or the end row to the beginning row and what we're gonna do to actually accomplish this is we're gonna have boundaries we're gonna kind of have pointer we're gonna have counters that are keeping track of the you know beginning row in the ending row in the beginning column in the ending column and as we traverse we're gonna traverse this whole row at first right one two three then we're gonna move the boundary for the beginning row up one two this row now because we've already traversed this row we're never gonna do it again so we just keep moving that boundary the end column will move inwards the beginning column move inwards is a smaller example but you know maybe if we could find a bigger even this one's bad you know we would Traverse down here and then we'd move the column end here and then we true you know so we've moved these boundaries and let's just implement it and you'll see as we go so we actually we have to do given a M by n elements return them in spiral order so we actually have to store these in a new list of integers you can call whatever you want the I read I saw the solution so I'm just gonna use that one it's called the res not his solution I saw one in a discussion that was pretty good so if matrix dot length is equal to 0 we'll just return that right we're gonna return nothing the matrix line 0 we're just going to return we didn't reverse anything so we'll just return 0 then we're gonna have our boundaries I was talking about right so the beginning we row is going to be set to 0 the ending row is gonna be set to the length of rows minus 1 because we're going to be using indices so matrix doubling minus 1 right that's the number of rows except minus 1 for the indices like I'm saying beginning column is going to be 0 and column n is going to be matrix of 0 dot length this is pretty standard if you know about 2d arrays you should be able to understand this it's just you know these are gonna be our boundaries and then we'll have our main loop is going to be well begin row begin is less than or equal to row end and column again it's less than or equal to column n if you don't know about if you're getting confused already I'd recommend go checking out just 2d arrays in general looping through them using two for loops or something like that first okay but if you're not if you are paying attention now this is gonna be probably the most important part and how we're organizing this right so this is probably my favorite organization I've seen out of all of these solutions so far we have these boundaries and then what we're gonna do is first we're starting at 0 right that's our coordinate that we're gonna start at and we're gonna move right and then we're gonna move down and then we're gonna move left and then we're gonna move up so if we're moving right we're gonna just have a bunch of and these are just four loops so we're gonna have four loops that consistently move within these boundaries right so we're gonna have is set to grow begin column begin right because we're going columns right we're go one two three we're get work we're traversing the first row but what we're actually doing is accessing column indices right because these are column values okay so we're gonna be going from the column value indices zero to the ending column that was indices of two zero one two so we're going from column begin to column and less than or equal to because we counted for the indices up there right and then what we're gonna do is as we traverse we're going to add it to our output array which is res so add matrix of and right now what we're doing is we're only you we're only traversing the first row right so we're gonna be traversing row begin and then what we're changing is the column indices so I is going to be in this you know eyes taking place to calm and when we traverse the whole first row this is where it's a little switch you have to kind of adjust your mind to this is you go you iterate down this whole row so we're gonna do is move the row begin boundary we're gonna increment it because we've already done everything on that first row we don't need it anymore we got to move our boundary upwards I was explaining that earlier second loop and then we're gonna you know we're going from row begin because we're starting at here we're starting at the end of column boundary and going from the beginning row boundary to the end row boundary okay so while row is begin Y is less than or equal to row and I plus so we're looping there and then we're going to do res dot add matrix of I is in the row work because we're changing row positions now retro indices now and the column is going to be the ending column value write the ending column boundary because we're at the very ending column boundary right now and now that we've iterated through all of the ending boundary of the column boundary we can be chromatic column end subtract one this is gone so no more are we going to be looping through this or this all we have left is this little square here and this is now the last column boundary and then this is the beginning row boundary this is the ending row boundary etc it would be better if we had you know this isn't much better for an example to explain but now here's something else that you have to consider guys is now that we've changed these values in our loop relies on row begin being less than or equal to row end and column begin being less than or equal to comment we have to keep we have to do checks because we did change these values so we don't want to mess up in our last two for loops so while row begin is less than or equal to row end we have to do a check now then we can do our second two loops so this time we're gonna be going right we went down and now we want to go left we're gonna be going from the ending column boundary so column end well I is greater than or equal to column begin because we're going from the ending column to the beginning column I - - and column to the beginning column I - - and column to the beginning column I - - and we have to decrement right because we're at a higher value than the value we want to get to then what we're gonna do res dot add matrix of row end because we're in the final but row boundary now we're at the ending row boundary row end because that's all the row values and then pi is going to be the column index right and then after this well what are we gonna do we have now gone through the whole bottom row so we can push back on that row end boundary right row n can be decremented we've already iterated through this whole last row we can move up row end is now in the middle here and then we have to do the check once again while column begin I mean if combien is less than or equal to column and then we're gonna loop through into I is equal to we're going up now so I is going to be equal to row n because we're at the ending row and we want to get up to the beginning Rho is equal to Rho end well eyes great for I greater than or equal to Rho begin I plus no I - - right weird to Rho begin I plus no I - - right weird to Rho begin I plus no I - - right weird e commenting cuz we're at a higher value than the one we want to get to her at a higher row than the one we want to get to wanna get back up we're gonna do res dot ad matrix of this time it is I in the row value whatever your eye is set to so that's I set to row then you put I in the Rose index and then this is going to be were at the beginning column right this is the beginning column this is the ending column so or the beginning column so we're gonna use a column begin and we just iterated through all of the beginning column so what we're gonna do is we're gonna do column begin plus move that boundary forward so as you can see we're looping around in a spiral and then moving these boundaries inward so on a bigger square it would be easier to demonstrate here but the boundaries keep moving inward until we iterate through all of the elements and we will every time we're adding them into this list of integers and then right at the end all we have to do is return this list of integers hopefully this works cuz I have been having a little bit of trouble here there we go first try we run time one millisecond as you can see I had a little bit of trouble when I was practicing so yeah this is really good we have to be aware of change these if statements I guess that's really important in the boundaries once you get this concept I think it's pretty easy it wasn't that bad it does look kind of like a lot of code at first but it's really not that bad and I think it's pretty cool it's actually like a fun problem also highly recommend these like chocolate almond things dude it's like cocoa powdered almonds super grab all of them this is a long video but you know thank you guys for watching hopefully you like this one you know try and do some more medium ones I know I've been slacking and put in some easy ones but I've had a lot of technical interviews lately so sorry about that and this is preparing me dude I'm telling you it's for sure so let me know we gots thing please check out my other videos and thank you for watching see ya
Spiral Matrix
spiral-matrix
Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[1,2,3,6,9,8,7,4,5\] **Example 2:** **Input:** matrix = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\]\] **Output:** \[1,2,3,4,8,12,11,10,9,5,6,7\] **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 10` * `-100 <= matrix[i][j] <= 100`
Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row. Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not.
Array,Matrix,Simulation
Medium
59,921
153
so welcome back to a new video and today we're going to do question 153 find minimum and rotates 300 Ras so pose an array of length n it's just sorted in ascending order is rotated between one and N times for example the right nums of one through seven might become this so we can see that these two arrays are the same as this but the only difference is that this is a rotated four times is relatively seven times and down here they say you must write an algorithm that runs in big old login that should be a hint that this question has to be done in bio binary search white if you don't know how binary search works I recommend no before this so go watch a different YouTube video of binary search and come back so an example one we have enough so if you already know how binary search so we're gonna grab the left index zero in the right index which would be for it and we'll add them 4 divided by two and find the middle index so let's just say that the middle index equals 2 which will be 5. if 5 is less than the right index which is two we want to move the middle index we want to move the left index past the middle because since we're looking for the lowest number will always be in between will always be below the right index if it's less than the middle so since 5 is less than two the left index will move from index 0 to index three and I'm going to find the middle again and if the left index is less than the right index will now equal the left index and if the left and right index both equals to the same number that much means that we got the lowest number so let's make the left and right index which would be zero and length of and we can do a while loop the wild left and right we're doing this because we don't want these two um past each other then we want to get the middle index X left right four divided by two and if not of index in the middle is greater than all right so like as we can see here the middle is greater than the index drive we want to change the left index so it will be left equals middle plus one out the right equal so in this case it would be basically if this was still left and if left is less than two or at the middle lesson two then the right index will now equal this and if these two new matters we roll with return numbed up index left India that should work for all cases oh my bad if right equal to the middle not mistake ended there we should work it out and like I said if a question ever asks you to do it and walk event that should be an instant hit to doing binary switch way and yeah um I hope this helped I'm gonna go take a nap now bye
Find Minimum in Rotated Sorted Array
find-minimum-in-rotated-sorted-array
Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,2,4,5,6,7]` might become: * `[4,5,6,7,0,1,2]` if it was rotated `4` times. * `[0,1,2,4,5,6,7]` if it was rotated `7` times. Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`. Given the sorted rotated array `nums` of **unique** elements, return _the minimum element of this array_. You must write an algorithm that runs in `O(log n) time.` **Example 1:** **Input:** nums = \[3,4,5,1,2\] **Output:** 1 **Explanation:** The original array was \[1,2,3,4,5\] rotated 3 times. **Example 2:** **Input:** nums = \[4,5,6,7,0,1,2\] **Output:** 0 **Explanation:** The original array was \[0,1,2,4,5,6,7\] and it was rotated 4 times. **Example 3:** **Input:** nums = \[11,13,15,17\] **Output:** 11 **Explanation:** The original array was \[11,13,15,17\] and it was rotated 4 times. **Constraints:** * `n == nums.length` * `1 <= n <= 5000` * `-5000 <= nums[i] <= 5000` * All the integers of `nums` are **unique**. * `nums` is sorted and rotated between `1` and `n` times.
Array was originally in ascending order. Now that the array is rotated, there would be a point in the array where there is a small deflection from the increasing sequence. eg. The array would be something like [4, 5, 6, 7, 0, 1, 2]. You can divide the search space into two and see which direction to go. Can you think of an algorithm which has O(logN) search complexity? All the elements to the left of inflection point > first element of the array. All the elements to the right of inflection point < first element of the array.
Array,Binary Search
Medium
33,154
337
hey everyone welcome back and let's write some more neat code today so today let's solve house robber three i know i solved house robber one before i skipped house robber two for now i might come back to it at some point but i really like house robber three so i'm gonna solve it today so we are given so we're given a binary tree in this case and you can read the story about the thief who just wants to maximize their profit basically and each of these nodes in the tree represents a house let's say and the restriction is we want to rob the maximum amount from this tree the only restriction is if we rob this node right the root node then we're not allowed to rob any adjacent nodes notice how we have two adjacent nodes right basically this one's children right so if we rob this we're not allowed to rob these two right but we're definitely allowed to rob these two because they're not adjacent by adjacent we basically mean that there's an edge connecting them right so since there's no edge connecting this three with this three we can rob both of them and we can also rob this one we can't rob these two if we rob it like this we get a profit of seven now what's our other choice well if we skip this house right we don't rob this house we're definitely allowed to rob this and we're definitely allowed to rob this but then we can't rob these two children right so then we get a profit of five clearly the other way with a profit of seven is the greatest so that's the way we're going to rob it you can see that's what they explained to us in the explanation so our output is going to be seven that's the max amount we can rob without robbing adjacent houses now let's look at a different example now with the solution to this problem you can really get bogged down in like the details of okay if i rob this then i gotta skip these two right and i'm allowed to rob this and there's a lot of ways to brute force this problem there's a lot of ways to have conditions and edge cases but let's look at look let's look at a simple way to analyze this problem basically we have two cases right one case is where we include the root so i'm gonna call that case with root so we have two cases one is with root so basically we're trying to rob the max amount from this tree one case is we include the root so we're definitely including this root now how does that affect the way we can rob the rest of the tree basically it tells us we have to skip this node and we have to skip this note we have no other restrictions those are the only restrictions if we decide that we want to include this root so that's one way we can rob it right one case is we include this root and that affects how we can rob the rest of the tree the second case we have is without the root so that's our second and last case we only have two cases so the case means that we are gonna rob the max amount from this tree where we definitely do not include this node we're skipping this node what how does that affect the way we can rob the rest of the tree well there's no restrictions now right we can just take the max amount from this tree and the max amount from this true we're not required to skip these two nodes anymore right we have no restrictions now we can decide to skip this node right we can decide to skip it or we can keep it or we can skip it right we have no restrictions there are some cases where even though we skipped this node we might still want to skip this node to maximize the profit because look at this is a hundred i can either rob this house and skip this or i can rob this house and skip that right but the main thing is when we go without the root where we do not include this root we are in charge we have we can make those choices with that being said the solution to this problem is a depth first search solution which runs o of end time meaning we only have to visit every single node at most one time right so that's pretty efficient but the only difficulty is that there are going to be some modifications we have to make to this step for search specifically that we for each node here right we're going to be returning a pair of values right we're going to be returning two values right and those two values are going to be for let's say this subtree what's the max profit we can get with the root including this node what's the max profit we can get without the root basically not including this node right and so we're going to be returning that pair of values up and up until we get to the root where then we will basically have our result right we'll have once we get to the root we'll have two values a and b one that has the max we can get with the root one that has the max we can get without the root and then we're basically going to return the maximum of these two values right whatever happens to be the scenario where we can rob the maximum amount that's going to be the result that we return and we can do that in linear time so first we're going to start at the root like any other depth first search we want our pair of values right but before we can get that we're going to call debt for search on the left child right and of course debt for search on the right child this is going to be post order traversal basically so let's run debt for search on here to do that we need to run debt for search on its children right now you can see that the right child is null right it's empty so what's going to be the maximum we can rob with and without root for a null tree well just zero right that's pretty basic right for an empty tree we can't rob anything it's going to be zero okay so let's look at this node now right the another base case now it doesn't have any children right so we can say that those are zero as well so but that's not so important because this is basically the base case as well right so what's going to be the max we can rob including this node including this 100 right that's the first value remember so that's going to be a hundred in our pair right if we include this and then you know we don't have any subtrees we can get a hundred now what's the max we can do without this node if we decide not to rob from here well we'd get zero now there's probably not any reason we'd want to do that but this is important so now we have the pair of values from here that we're going to return up to this node and we have the pair of values from here that we're going to return up to this node as well okay so next let's look at this node right so now we've called our way up back to this node so we want the pair of values for this node so first let's get with root how can we compute that well we're going to take this value right so with root for that node 20 right we're going to take its own value right so 20 plus we want the maximum from its left subtree right but not including the 100 right because remember if we rob this 20 right we're not allowed to rob its direct child so what's the max we can rob from this subtree where we don't include 100 well you can see that value is right here right remember the second value represents without root so that value is just zero so we add zero exact the exact same is true for its right sub tree which is just an empty sub tree right so zero right we're taking the value 20 and adding the maximum from its left and right subtree where they do not include the roots meaning they do not include the direct children so we total this up and we just get 20 right so that makes sense right when you look at the picture so we're going to put a 20 here because when you take a look at this entire subtree right if we included this node 20 the max we could rob then is 20 because we're not allowed to rob any of its children basically what's the max we could do without the root meaning if we decided not to include this 20 what's the max we could do then well to do that so basically where we're not including this node so we cannot add it we just want to look at its left and right subtrees and get the maximum of those so from its left we want to get the max of the pair right pair left so whatever the left returned and we want to add it with the max that the right returned right so it's a little messy but this is basically what we're doing right the max of the left and the max to the right so now what is the max of the left subtree what's the maximum we could possibly rob from here well that value is right here right a hundred we want to take the max of both of these this one is zero so we're going to take a hundred and what about the right subtree well that's just an empty sub tree so the only thing we can get from that is zero so basically when you total this up you get a hundred what that means is we can put a hundred here for the second value because for this node right for this entire sub tree what we're trying to say is if we do not include the root without the root we don't include this 20 what's the max we could rob from this entire tree well it's only a hundred right okay so now basically what we've done is we've gotten these two so now that we've computed basically what we wanted for this tree we're almost ready to handle the root case which we want to do but let's start with this right sub tree first right so we want to compute a pair of values for here right but to do that let's look at its children so it's left subtree's empty what that's going to end up returning is just a pair of zero what about its right subtree well we're going to do the same thing we did before if we decide to include this root clearly we don't have any subtrees so the max we could get with that so the first value in the pair is going to be 1 right with root is going to be 1. without the root if we do not include this root what's the max we could rob from this subtree well it would be 0 right because it doesn't even have any children so now let's call back up recursively to this node four so what's the max we could rob with the root if we decided to rob this four well then we're not allowed to rob either of its children and it doesn't have any nodes below its children so the max we could rob doing that would be 4 with the root is going to be 4 without the root so if we decided not to rob this node we want to get the max of its left which is 0 and the max of its right which is 1 add those together we get one and so basically without the root the case where we do not rob this node is gonna be one okay so now we're finally ready to handle the root case right we're finally ready to handle what the max we could rob with and without the root node because we have this part and we have this part so how do we compute with root okay with root means we're including this node right so we're going to take 3 plus right so we're including this node and then we want the maximum of the left subtree not including 20 right but luckily for us we already computed that in this value right so the max of the left subtree without including its direct left child is a hundred right so that's the left portion right what we're saying is we're robbing this skipping this and then robbing this 100 right okay great now we want the max of the right subtree right not including this four luckily for us that value is stored right here right that value is going to be returned back up to here that's how we get how we're gonna get it in the code so that's a one right so we're adding a one to here and what that basically means is we're robbing this three skipping this node and then robbing this one which we're allowed to do right because there's nothing connecting those nodes so basically the total with the root three is going to be 104 so that's the first value that goes in our pair now technically we also need to make sure that this is the greatest value so we're going to compute the max without the root right the max value we can get when we do not include this three so basically we're not allowed to compute we're not allowed to rob this three so we want the max that we can get from the left tree without any restrictions right which what we're going to do is take a look at this pair of values what's the max of them it's not 20 the max is a hundred right so then to our result we're gonna take a hundred right now we want the same thing from the right subtree right there's no restrictions right so we're taking a look at this pair of values four and one which one of them is greater well it's four right so basically what i'm saying is even though we skipped this node the root node we're also skipping this because if we skip this it allows us to rob this node where we're also going to be robbing this and skipping this one so i'm taking a hundred and four and adding them together i'm getting a hundred and four so i'm going to put 104 over here so look how both of these values are 104 what that tells us is if we include the root with the root there's a way we can the max we can rob is 104 right and what does that look like it's this plus this right and the second value tells us if we don't include the root without the root we can still get 104 a different way we take this 100 rabbit and rob this four right so that's kind of weird there's two different ways to get the same result but either way we know that the maximum we can rob from this entire tree is going to be 104 so that's the result that we can return with that being said now let me show you what the code looks like and it's not too difficult because we know that this is just a modified depth first search so i'm going to define a depth first search function nested inside of this function even though i probably don't need to do that but what i'm going to do is remember this is going to return a pair of values what that pair is going to be is with root right the max we can rob with the root and the max we can rob without the root okay so great with any depth first search we want to start with the base case so if the root is null what are we going to decide to return with an empty tree you can't rob anything so for the entire pair i'm going to say 0. otherwise now i'm going to do our recursive call right i'm going to run the max we can rob on the left subtree so i'm going to call depth for search on root dot left it's going to return a pair of values i'm going to put that in left pair i'm going to do the exact same thing with the right subtree so in right pair i'm going to store the result of the max we can rob from the right subtree it's going to be a pair of values with root and without root of the left subtree and right subtree so now i want to return the max we can rob with root and without root right where we're currently at right where we're at the node that we're currently traversing so first i have to compute this pair before i can return it now how can i compute with root well since we're including the root we know at least one value is root.val at least one value is root.val at least one value is root.val and what other values are we going to add well we're going to take the left pair and get the second value from it and the right pair and get the second value from it why are we getting the second value at index one well when you look at what this function is returning it's returning two values with root and without root remember if we include the root value we're not allowed to include the root value of the left and right subtree so we're getting the max we can do without those two nodes okay great now the only thing left for us to do is compute without the root so in this case we're not allowed to include this root.val so i'm allowed to include this root.val so i'm allowed to include this root.val so i'm going to delete that and so since we're not including the root value there's no restrictions on what we can get from the left and right subtree so what i want is a max we can rob from the left sub tree it could be either of the values in the pair so i'm just going to take the maximum of the left pair it could be the value with the root it could be the value without the root we don't know so i'm not going to make any guesses i'm just going to take the maximum of that pair and i'm going to do the exact same thing with the right pair so i'm going to take the max of the right pair this computation is actually giving us what the max we can rob without the current node that we're at it's as easy as this and the reason it's so easy right i'm making it look easy is because we modified our depth first search not to return one value but it's returning a pair of values that's really the key here we're returning two values that makes it so easy for us so now we're actually done with our function we computed these two values and returned these two values now all we have to do is call our depth first search function passing in the root right but we know even this step for search call is going to return two values and we want the max of those two values because we want the max that we can rob from this tree so once i compute that max then all i have to do is return it we're returning a single value here so when you take a look it's a very efficient algorithm there are other ways to solve this with dynamic programming and stuff but they all actually have the same time complexity big o of n so i think that this solution is the easiest there's no need to over complicate a problem like this with like dynamic programming techniques so i think just doing the depth first search way is the best it's super efficient and it's hopefully understandable so i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon
House Robber III
house-robber-iii
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called `root`. Besides the `root`, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if **two directly-linked houses were broken into on the same night**. Given the `root` of the binary tree, return _the maximum amount of money the thief can rob **without alerting the police**_. **Example 1:** **Input:** root = \[3,2,3,null,3,null,1\] **Output:** 7 **Explanation:** Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. **Example 2:** **Input:** root = \[3,4,5,1,3,null,1\] **Output:** 9 **Explanation:** Maximum amount of money the thief can rob = 4 + 5 = 9. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `0 <= Node.val <= 104`
null
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Medium
198,213
35
Hello friends welcome back to the PM sof Solutions in this session basically we are going to solve lead code problem number 35 search insert position so let's move to the dashboard and let's try to understand the problem statement basically the statement says that given a sorted array of distinct integers and a Target value return the index of the target is found if not return the index where it would be if it were inserted in order and you must write an algorithm with big go login runtime complexity so here is example it is an sorted areay of distinct integers and uh here is a target value and because Target value appears at index two so the output is two to achieve Big O login runtime complexity we can use the binary search algorithm basically uh in this algorithm we are going to use two pointers left and right and uh which is going to represent the range where the target value might be present and in each iteration um the middle element which will be the mid is uh compared with the target value and the search range is updated accordingly and if the Target is found the index uh is going to return if the target is not found then left pointer represents the correct insertion positions so basically this algorithm has a uh big of Logan runtime complexity so since the search spaces is hared in each iteration of the while loop so I'm going to provide you the algorithm um o is indirectly the twoos so after getting the todos you have to pause the session and try to implement this so here is your complete algorithm or todos so pause the session try to implement the code so now let's implement the code also first of all we have to initialize left and right pointers so for that I'm going to uh create two variables left and right and parall we will going to assign the value also so uh left value will be zero and right value will be going to the last index of the list so for that we will going to get the list length and uh in length we will going to do minus one so we have created two variables left and right and as well as we have also assigned the values parall after assigning the left and right pointers we will going to implement the binary search Loop so while left is less than or equal to right after implementing the binary search Loop Next Step says that calculate the middle index so for that we are going to create one variable mid and we will going to assign the value of left plus we have to find uh the middle index so that's why I'm going to subract the left value from the right so right minus left and uh at the end we need to divide by two so we need an integer value so that's why we are going to use double for Slash and we are going to divide by two so we have find we have calculated the middle index after getting the middle index next step is to check if the middle element is equal to the Target so for that we will going to use if else so if num which is the list so num middle index is equal to Target value if Target is found then simply we have to return the index so return mid the middle element is less than the target then we have to do something else so for that we will going to use l if nums mid is less than Target so we have to update the left pointer so for that uh left is equal to Mid + one and uh finally we need to implement like as a if the middle element is greater than the target then we have to update the right pointer so for that we are going to use else block and if the middle element greater than we have to update the right pointer so right is equal to Mid minus 1 and finally if the target is not found then we have to return the left pointer as the insertion position so for that uh simply we can return the return left value yeah so this is the complete implementation of your code let's try to run this code and check that it's working properly or not now you can see that we are getting error so list indices must be integer or slices yeah you can see we have created variable name with mid and we have passed Min so that's why it's giving error we have to correct this and parently uh if you have uh noticed then we have also put it here wrong variable name you can see there is a Target and we have put it Target so we have to correct this also and let's try to run this code again and now you can see that all cases has been passed or accepted if you face any error then you have to Simply read the error statement you will find the answer within the error statement so according to that correct your code and uh rerun your code it will work properly so let's uh try to submit this code and check that it's submitted or not it's accepted or not so now you can see that code has been accepted or submitted successfully so if you have any query regarding this search insert position program implementation or anything related to programming so you have to put your query in the comment section as well as you can also put your queries on Instagram page as well as you can connect with us through the telegram so whenever we will get your query we will try to solve your query as soon as possible so that's it for today and uh see you in the next session with a new problem till then keep practicing keep learning and take care bye-bye
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[1,3,5,6\], target = 5 **Output:** 2 **Example 2:** **Input:** nums = \[1,3,5,6\], target = 2 **Output:** 1 **Example 3:** **Input:** nums = \[1,3,5,6\], target = 7 **Output:** 4 **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` contains **distinct** values sorted in **ascending** order. * `-104 <= target <= 104`
null
Array,Binary Search
Easy
278
76
Hello friends, welcome to the new video, question number 76 is a late code minimum window something hot level question, which category will the question be in, then it is written here that Vegetable 2.1 String and Vegetable 2.1 String and Vegetable 2.1 String and Sliding Window question is this question, you people will find it on the internet, the name is Window Spring. This has been asked in Google and Directory. Let's start editing the given string. Friends, you have given it to us. What do you have to do? Finder Minimum Invoice which will contain all the character city in complexity on9. Complexity should be your oven. Basically it is said in the question. If your spelling is correct, you have to search all the characters inside the rings and you have to specify the minimum window in which all the three characters are coming, then you will see that in ABCD Manager, highlighted, there is a window in which all the three characters are coming, but You can get a small window like BMC, this is a small window inside which all the three characters are there, so you have to return the smallest window and the skin inside it, you have to return it like BMC and it is written in the question that this time In this note, true window, you have to return an empty string for basic and it is said that there will always be one unique minimum window in this, you will get one window in every case and if not, you have to return a parenting, then a little detail of this. Let us understand in the minimum window sub Singh, in this question friend Singh dad, there is a lion like this and there is a print inside the trinity with three characters which are once, V is 1 and C is once, so we have to get these three characters in this above. You have to search in the team within the rings and if you do not find then the return of this question is tight ring then you will return antising but if you find all three ABNC once in the search then you have to find ac wind toe. Inside the window ABRC, you should get all three and you should get all three once because in the string below, all three are once. Okay, so they have to see orange at once. How many times have the operations been heavy once and was once and In this trick above, what kind of window am I seeing in which ABC three are found, so what I have to do is to cut this window and I will return this trick to this one, okay but the question is, it is said that you should point the minimum window. So let us search some more windows in which we get all three ABCs, then there can also be a window like this in which you can get all three ABCs, then you can cut this setting also and return it, okay, this can be possible as per And there can be more possible answers in which all three ABCs are found in one, in this window also ABRC all three are coming and once we get the list of all three, then we can return this window also. Next window can be one window, it can also be this window seems to be the smallest and it is ABC in minutes, all three are a possible answer, this can also be and what we have to return, we have to point the minimum window in which ABC If all three are coming then our answer will be BANC, this spring we will return and this trick is for lens, so basically I compared the length and saw which spring was the shortest in which all three ABC were coming. You must have understood what to do in this question, so let's start our spring, you have to search this ABC from BBC and I told you that you also have to see Off Clans, that is one more friends, Kitna MB Kitna Bar Hai, C Kitna Bar Hai. If C was there again then you have to search twice. Inside that window, what will be the first step and in the court also the first step will be this. If we have to save these three characters somewhere then I will save in the table. I will do it and inside the code, our key value tree is from this, inside the S map, we can use it in this also, so how will we save it in the table, first of all we will select the character one, friends, you are seeing it once, then you beauty. Will come between Congress, yours is once, will pick up the CV, I am getting it once, so basically I will save the account of these three by making a single loop, which characters are there how many times and how many times I have to find this window dirty, okay one Let us give a small example and try to understand how we will search and I would like to tell that this question is based on a sliding window technique. If you have never done sliding window questions before then I would recommend it. Now you can stop this video. You can search in youtube, first you can understand the basic what sliding window technique can be and what it is and you will get very good videos and after that you can continue this video because in this question I am not explaining the basics. Those who want to use sliding window or butter, we will use sliding window. Okay, so we have a frill, let's assume that there is some string like this and in this sting, we have to search this NDMC. One more time, friends, it is Bikapur once. Have pure sequence is also once okay so the first character string gas is mine so I'm going to do if this is inside my table I see it juice my table so I'm going to update my table. I will give that I have found it and I will zero it in the account okay and we will move ahead a little bit before moving ahead we also have to see that we are searching they are doing Trinity and the string is ok which is the length so basically I You have to search the window, but in that window, the total number of off-car actors' account is as total number of off-car actors' account is as total number of off-car actors' account is as soon as possible, B is once, C is once, then I will make the account variable, it will become free as soon as it travels, meaning equal to the length of the fix. Once this is done, I will understand that I have found all the characters I had to search and all the other characters I had to search, so in that case the account will be free, then we will stop our window, then I will save account one in an account variable. Now let's move ahead a little bit and this time we will see that we have got this again, so we will go to our table and notice in the table that the one account has already become zero, now you do not need just one, already you You have added SA but you will update in your table that if one extra has been used then what will you do in the account? You will close the one negative i.e. you have close the one negative i.e. you have close the one negative i.e. you have used one extra but you have not noticed that there is no change in the account variable. Why will we do it because we have already got one, now this one is negative and I am you, we have used extra, so after reading this negative, I will not update my account on the barrier because I appoint extra which I did not need now. Coming to this and we are getting extra, so this time in our table or in this, we will make this one account - two, which means that this one account - two, which means that this one account - two, which means that you have got extra twice and your account variable will not change anything because your account will go into negative. So now they will read it that do n't increment the account variable thank you now I you have done one in play store that you wanted once and you have done one account once so that's 121 is your one go next Next is our seed, now we will go to the table of B, bank account is one, we can use it, so in the table, first of all, we will update the account of K to zero and make our account very welcome to, this means we have two. Characters have been found, we are searching total three because string is tk length and account variable is our two, so now I will not complete my window, let's move ahead a little bit and this time our character is c, so you will see in the table. If the account is Khandav-One then account is Khandav-One then account is Khandav-One then you can add C, then after adding it in the table, you will update the CO to zero and account will be corrected to those who have patience, then at this point you have got a window which There is one account inside, one bank account and one Sita account, so you have got a window, so consider this as a big example and take it as a big allegation, this example has also been given to us in the list court. So to understand the technique, I would like to tell you that in this we are going to use two points and the first point A is because there are 2 points because it will pass the left country route, it will hit the right boundary and we will make our window by using both the point A. If we maintain then we will name the first pointer as Start and the second point A which is I will make you notice that when you move in the loop then the second point A will automatically be like that or but the job is the left point which will be the start point, you can throw it aside or Then we will move after seeing some conditions but will keep moving with your look at the ride point, will pick 11 characters, will keep on processing and using these two points, we are going to create our window and we have stored ABC in the table is visible to you. Now how will you use these for inter? First of all, both the points are hitting your hair, so you have got this and you have gone to your table, there was one account, which means we have only one need, this is what we needed once. So what we did was we used one and made its account multiple in our table. Okay and let me tell you, we made the account variable off and made the account variable our one that once you have used one and it is like the account variable is free. It will go right there and you will understand that you have found the window. Okay, so we are going to find all the windows and how will we save the smallest window and we will see that slowly first you move a little bit, then the start point will be yours. The first position was seduced and your loot which is moving forward, now the side of your window is two but the next character in the window was D, eat and gordy, you searched in your table, I did not find you, that means Duggee. We don't have internet so we can just simple move ahead and there is any option. Now your character is that you saw in the table that you are not sleepy then neither will you update the table. Measurement will update the account variables. Now you will move ahead now. You saw and chapter is 20. Now you saw in your table that there is one account in the table also, it means that the bank you need is one, so what you will do is update the table, make 200 in the table and we will use the middle account. We will change the variable to two, okay but we have not got our window yet because the size of the window should be which is the length of the stuffing clay which is three, so what we will do is we will move a little bit and this time our character is gone, right? So, if he adds juice to the table, what will we do, there is no need to update this table, there is no use of this thing, so we move forward to the right boundary of our window which is running from our loot. Now we will go ahead one by one, now our character is C, now you will see that we will go to the table and search and you will see that the learned hour is one, so it means that you have C as blue, then what will you do to get the account of C in the table. Will grow and you will free the account variable and update it first and like law travel is free so we can say that you have got your first window and in this window we are also getting all three characters BMC so now we What will we do now, we cannot return to this window, basically what we have to do is that we have to point to the smallest window, the minimum window inside which all three characters are at their peak, so we find a first window and we know where the left boundary of this window starts. And we have made the length of this window and further you may get more windows, so what we are going to do is that we will create a variable of length in which we will keep comparing the length of all the windows and we will save the window which has the shortest length. We will do this and we will save the starting point of the left boundary of that length, that is, where the small part is starting from. This will be done in two memorials in a very easy way, all the windows will come, everyone will have the length, everyone will have the start point. You will save the point with the smallest window and at the end of this question you know where the start is from and what is the length, so now you can cut that prince later and apply all the fitting functions. In the end, Sab Singh will organize the function, start points will be there and lunch will be given, our shooting was BANC, which I had seen earlier, Meena and I were getting a small amount and we will return it, but now we have all the windows, now we only need the lens. To compare, this is the first time we will save it in length and save its start boundary. Further if we get a shorter length, we will override this length and save it at the start point. If we get a shorter length then we will save that length. If you override it, we will set it, save its start pointer and these two variables in fact last, if you have to cut the spring then we will do it later. Okay, now let's move ahead a little and now what to do, we have got the first window. So now we will break our window, how to break it, I have an account in my window, that means I was getting all the three characters, so now I will free the left boundary of my window and move it in the leg boundary until one eligible character is outside my window. It doesn't go away, meaning if I remove my window in some way like this, then mine got removed, so I made one of the tables back to one, I did that because now I have got only one need again and I made it one. That not only one will come to us again, it has come out, so now update the table again, okay and what you are about to do is that you will reduce the account that you have because in your window, you are just two character children which is this So you have removed your account, now you will have to update that account and why are you updating it? First of all, you will look in the table. In the table, you will see that one of your accounts is positive, which means you have back it. Put in the table, if it is positive, it means one of your accounts has come positive and your success has gone out of the window, then what will you do, will you return your account to 2, okay and like you get this account 312, now again You will search your window right boundary and we will search again to find ac wind in which abc we get all three ok now you notice in your window it has come out only b and c so now again we will check undefined So we will make right pointer on this and you will see the character is gone, it is not in your table, that means you are not searching, so do not do anything, in this case, now keep moving forward, now your character is given DAV is not in your table, this lamp. If you were not searching for the character then we will move ahead. We have come on Eid. This is not in your table. If you are not searching then we will move ahead. Now you see the character has also arrived and your character is also one in the table. Juice does, but you saw that it has zero in the countable, which means that if you have taken as much as you need in the window, then the account in between will turn negative in the table and your account variable will see that its account has become negative. This means that all the information you need is already in the window, then your account variable will not increase its size. The account will become Pattu. Ajay Maken will remain tap two. This next character of ours is this, you will go to the table, you will search, one, you You will see that there is one account, which means you still do not have one, so what will you do, you will reduce one account in the table. Now your account variable will see that it has not gone negative. There is one account, which means you have corrected the usage and you will not have just one. Had it been negative then you would have used your extra but if it is 2030 then your account will get marital treatment and I told you that as soon as your account is equal to the length of your 303 meaning job district then it means you get all three characters. If the actress has got it as many times as required, then you have got a 1 second window in which all three ABCs are there. We will compare the length of this window with the previous length and you will see that earlier the length was shorter, so we will consume it. If we get it, we would check and its start boundary, Love Country, is also of use less, so we will consume it too. Now what are we going to do, now you have to look a little carefully. Now you have got your Windows, so now you We will move the left boundary and from the window, you will select a character which will be an eligible character and this window will be completed, after that you can start the process of searching the window again, so we are going to do the same, I will do Malefic Moon. My character is given which does not add juice to the table, so in the table I am not going to increase the account again, so I move ahead. If the character and the character also do not make any difference, then I move ahead because it is not in the table, because in the table we have to move ahead again. The ingredients that have to be done from the account because we will take out any eligible character so that the window month becomes incomplete and we search our window again but you notice that these three characters are still in your window so now what are you doing? While you are trying to complete your window, somehow a character slips out and your window gets completed so that you can search again but in this process you might have objected, in this process your lunch is also getting reduced meaning. It was found in our window. Now we are moving ahead to complete the window. But it is still taken and on this I have found the length also short. So in this process you will keep comparing the length also. If the length is found less. So we will override Abu Salem, we will save the smaller line and save its start point. We only need these two valleys to find the answer at the end. Okay, now what do I do? I move my window further. I am here and this time my character has also come and we will see that ours is also inside the table and there is an even better joke quote - If we are useless then first of all quote - If we are useless then first of all quote - If we are useless then first of all use the account and we will give you a bigger condom and like you will also account. Even if you give it bigger - I am sure of it 101 but the one who has patience in your account will - I am sure of it 101 but the one who has patience in your account will - I am sure of it 101 but the one who has patience in your account will see that it is still your V. The fun that you had increased B, you had also used your extra, now you had balanced it, so it is as if it is greater than zero. Only then can you accept that one of your characters has been removed. If my account becomes one, then I would accept that one of mine has also been removed. Even if it is still zero, my account already exists, which is fine inside my window. You can also see that I am also ready and whatever we had withdrawn and increased the account, this was also extra inside the table, so there will be no change in the account and in this case the window you see is a little. It is getting smaller and is eligible, then what will you do, we will compare the length of that window, now what will you do, you have come on Eid, this is not within your table, Taylor, you will move your left boundary, this and this time too. We will compare our length because this window is your eligible. Okay, now our character has learned, so you will give C. If C is in the table and the learned account is there, then we will remove C and will give the learned account in the table. First let's remove C and increase it in Sita container. Learned that the word has increased in constable. You will see that it has become greater than zero, then your account variable will understand that an eligible character has gone out and your window has become ineligible, then you The account is yours, we will change it to 2 and from here we will search our window again. To search the window, we will have to face right. Again, we are right but the character is our N and you will see that this end character is not in our table. If we are not sleepy then we will keep getting up on the right. Ride entry will be ours. Next character is C so you will search in the table. C is your exit. Learn account is one, meaning we need one lesson, so this is the one we are going to use. And we will make Sita 100 in our table and as learned account will be zero and it will be used then our account variable will also be incremented and become free like account bevel is free then you get an eligible window then compare the length. Take and compare and see, the younger sister is fine, save her left boundary start pointer, just save these two, now you must have noticed that you have reached the last character on the right side, that means now we stop here. We will have to go to the right and we cannot have this attachment. We cannot search any more windows to the right. This is the end of the right, so is this our last eligible window in which all the three characters ABC come or can we find some other window? We had seen earlier that as soon as an eligible toe was found, we used to repeat our process, we used to free the left side, take out one eligible character and make the window ineligible and what happened with that, our length kept decreasing in this. And we used to get some eligible windows, so this time also we are going to do something like this time we have character and I, so I will search the character in the table and if there is no other character, then we will face on the right side, we are looking for such a character which Our window will become ineligible but as you have seen the length has reduced, another eligible window has been found which has all the three characters inside it, so now we have got another length, we will compare our length and we are on the right because DB is our table. If it is not in the table then we can get in the mood for the ride. The window that we have is still eligible. All three characters are also there in it. Now your character is there which is not in the table so you can get in the mood in the right. Now your character is also there but Your window is eligible because it contains all three ABCs, so in this case we will compare the length and also compare the start point, is this the smallest window or not and we are going to do this, now we are going to remove the middle. We will remove the bay and enlarge the account in the middle of the table and your account variable will become a task because your window has become ineligible, so you have compared all the windows and you have also seen which one is in the middle. The window is the smallest, go to that window, take its length as well and you have saved the start pointer which was on the left and right of that small window, so now by writing the function of a substring in the last, there is a single line code to your spring. Can cut and can return the small setting which has all three characters inside it. So now let's come to the chord. Let's see how to code it. Before coming to the court, he quickly adds complexity and allied. Two in the list suggestions. Approaches are given. We have discussed approach one which is a basic sliding window approach, so what can be its time complexity. Scientists of S Plus TV will have such an artist rings length that if your straight is fine then it will go and in this there will be more of the year. In this year's sp might and visiting every element posting gas stove, in this year's case you can visit all the element of singh gas twice, once from left for inter, once from ride point fear pace complexity your ko be fool spst Maybe the size of your window in this of the year is fine, it can be equal to this. The second approach is given here and the quarter sliding window. In this approach, we create a filter like this and this project is useful now when the shooting you are searching for is Springsteen. The size of what you are searching is way too small, the length of settings means the string is much smaller than the sin gas, then we can create a fielder list and the size of the filter will be much less than this, so basically this is what you do in daily life. Complexity will be that stupid to * size filter list plus TV and this * size filter list plus TV and this * size filter list plus TV and this only use full Justin Ok size is very less and in that case your complexity will be reduced a little bit from the earlier approach so now let's come to the code let's start coding We have given the acting S in which we have to search and in the example, I assumed that all the three characters are ABC, we were searching it inside the settings and we were taking out all the eligible windows in which all the three characters are A B. NC, in the smallest window, we have saved the length and start point on its left boundary and in the last, using the length and start point, we can cut as many lions as we can in the smallest window and return, so let's start. First of all, let us analyze some things like string has 570 cashew lens in it, then you will not be able to search and your spring gas is smaller than your creation, even then you will not be able to search, so in both these cases we MT Singh is going to return, so I will return, we will write and stitch, okay, now let's move ahead, what will happen if we have made a table, we have taken Simti, let's say ABCD, so we have made a tablet and how to make it, we are also in this. We can use this because it has key values, so the market key will be the character and in the value we can store the account, so let's create it in this and it will be of type, first our character will be or and Value can be typed in our interior. Okay, let's give it a map reward. Add new. Now let's write in it. Okay, so in this we have to process Springsteen and this is where you have to fill the stable. How will you fill each one? After doing this, you have to process the character, I will write the three words inside the lion, I am okay, now one by one we can process the character, so first of all I will check that it is already contained, the thing of content is and If this character is already in the map then you have to increase its account, okay then I will output this , this , this , whatever account is there, will increase the account and if this character is not already in the map, then we will enter it and its account. Let's do one, okay, so in this way our table has failed, now we have to move ahead and now we have to search in our lion gas, we come across some variables, first of all we have to create an account variable which is account if you see our three. If it was done, then we would have understood that we have got the window, so we have to create an account variable, one, you have to create a start pointer, which will be your start point, which will come after hitting the leg boundary, one, you have to create one, you have to calculate the length bar, then you have to calculate the minimum balance. We will create it with the name, in this we will check the minimum balance and at the beginning we will change it to the maximum value. In this, we will save the length of our smallest window and the problem we will get is the last point of that window, where is it starting from. I Namdev, the left point of the window with minimum length, let's name it as Minimum Left and we will have to create a person and I think our work will be done. Now we have to process our spring gas and as we have done. I had seen in the diagrams that we are going to do something similar, first I would have written it once plus, then you saw that it was the right boundary, this one of ours will do the loop, your start point was here but the one that has come here is our right boundary. Keep searching either the right boundary of ours will take care of the loot and the left boundary we will shift according to which is our start point, I have told that this is ok so what to do now we will see all the tractors one by one. We will check the character, are those characters inside our table, basically if they are in this match, then I will write it at once, we will check with the content key and whatever character is coming, we will keep checking first. If that character is in your table, then you If you want to reduce the account of a character, then basically you will say that you have found a character in the window, if you want to reduce his account, then I will write once how to reduce the account of that character. First, we will work out the process for the already existing account of that character. And in that account here we make minus one. Okay, so it will be something like this that whatever character we got, then in the table we made minus one of that character, whatever account was there, eat this line which I selected whatever account was there, we took it out and called 1 in it. Okay - what we had to do after doing one. Okay - what we had to do after doing one. Okay - what we had to do after doing one. Now you have to see that your for example character was in the table. If his account was one then his The account would have become zero. If his account was negative, then you can use it in one window, but you will not use this account in your window. If you have got an eligible character, then we have to see that in the table - the account see that in the table - the account see that in the table - the account should not go negative. Write a condition ' should not go negative. Write a condition ' should not go negative. Write a condition ' Laptop Not Gate', in this you have to check Laptop Not Gate', in this you have to check how much is left of this character in the table and its account and Greater Coriander will run till equal to zero. If Greater Than is equal to zero and you have subtracted from the table. If you have used that character, then you will give a big one to the account variable, you will say that you have found an eligible character, whatever is your window, now you were looking for three eligible characters, then you will do plus here and you will get one. It is okay and this process will continue to happen, but when you get all three, whatever is our spring, here towards our skin, which is your Singh, Meena and BNC, Meena, so we were thinking that we will get 3. Our account should be three in length, but if our spring was double ABCD, then we would see that the account should be four, like if it was four, then we would think that we have got an eligible window in which this character is, so what should we do here? We have to compare the account, when your account will be free, if 30 is our ABC then you will understand that you have got an eligible window, here we have got the eligible window, so now what do we have to do, first, whatever is the meaning of this window. Loosening happens, we have to save its length and after that we have to move the left boundary of that window, then we have to remove one character from it until this window becomes ineligible, then this process will run again and then we will check the balance. How can we set the length, so basically I can write the condition that if your minimum length was, we had made a video, this is the minimum length, we have to store the entire length in it, if it is increased then it will be of the size of your window, the window will be on the side. Your height don't have stopped was the left front and if you do plus one then you will get the size of a set up window so you that if the length is bigger than this then this time you will come inside this loop and reset your window of the window. You will set the size, that's it can be anything of yours, it can be fiber, it can be wind office six, then you will set your minimum length to Ireland, next time it will save the loop length only when for example this Six is ​​the length, next time when will you example this Six is ​​the length, next time when will you example this Six is ​​the length, next time when will you get length 6, will you get five or four? Then we will come inside this look that every time we have to see the small window to see which window will be smaller and the start point of this window is saved in the minimum left. I will do it, I had made minimum light and variable, I had saved the left boob battery in it and by using both of them, we can later cut this trick of ours. Okay, so we came to an eligible window, in that we have saved the length. Now If we have to remove our character then the character and how to remove it, then I write the condition to remove it, then you will have to first check in the map whether this character on the left side of yours is eligible for you or not because Now you will start moving your boundary from the left side. Okay, so which character of yours on the left does this dot character hit because the start is our left front. If it is in your table then you have found an eligible character. If it is not in the table then You will keep increasing the start point and keep making the window smaller. For example, if we are not able to find that character, then we will keep making our left ventricle smaller. This white look will still work because it is still available in your account. Then you will come inside, then you will find that the length of the trees is less than your length, you are not getting the window ghee, then again you will not get the character, then you will keep increasing the cut, you will keep reducing your left boundary, but this time also you will get the character, there is the missile. To get out of that, we will make our window ineligible, so how will you make it ineligible? First of all, you have to reduce this account back. We saw that in the table, we had incremented and reduced this account. Okay, so first increment the table. This is done only to increase the amount. Whatever character you have got in the festival, you have to return to your hair. The first position was the first position which was your life battery. If you increase the account of the character you have got there, then how will you create his account first? We will also have to find out the account. To find out, I will have to extract his account from the table itself and finally, I will give him a bigger account, so in this way I will increase his account. Now I will reduce this account variable of mine so that My window becomes ineligible and we go out of our form. You must have noticed that there was a case like this in your table, this was his account was negative, so what does negative mean, it means that you have used two extras, so anytime. When it comes, first you will balance it, enlarge it to minus one, then if another one comes, then you will enlarge it to zero, then go now, your extra apps have gone out of the window, now it comes for the third time, then you will increment the office contact, meaning. Now Ajay Eligible, this which was valid has come out from your window. Now you will reduce your account variable and make the window ineligible, then you will have to write a little condition in it. Face if your account in your map has this value. Let's take whatever account you have, it has to be bigger than your zero, only then what you have to do is in that case you will reduce this account variable of yours and as soon as this work is done, we will come out of our wild form of account - - You will do this, you will come out of the files in this manner account - - You will do this, you will come out of the files in this manner account - - You will do this, you will come out of the files in this manner and after that again we are searching here, the account will become free, again you will get another window of three, then you will come in this loop, then in this way, I have written the condition for coming out, the length for each time. So now we just have to return, so finally what we have to return is that we have this length, this is the minimum window, this is the length, so we have to cut our screen, so I write all the fittings and Josh was the start pointer in it. I had set it in medium left, so we will write its left boundary wall and we have to take its length from where to where we have to cut, then from this position till your total length i.e. position till your total length i.e. position till your total length i.e. you have to cut till there, then this is the window for that. If you can cut the string very easily then this will be our final answer and there is a condition in this you also have to see that if you do not get any window then your minimum length will not be updated. If you never come in this condition then There will be minimum length of the interiors and max rally, then you can write in such a way that if your minimum length is more than the length of your spring, basically we never got any length of ours, if we did not get the balance then that In case also we can return, we test and in this way our answer is done, once we compile the code and check that some compilers are done, first of all this bracket is added extra, remove it and you will see. This form should be this short and what we did in a logic like we got a character so we incremented our account variable so this is our this should be inside the brackets when you get a character then this is you increment the account and Please tell me if you have found an eligible character, then it should be within the condition. Once we run it, we see that it is fine and we are getting accepted. Once we submit it, we see that the code is also submitted and you are watching me and my channel. You can support me with a small donation so that I can continue making videos for you guys. You will find the donation link in the about section of the channel or in the first comment of every video. You can go to the about section of my channel and get this Google shadow access. You can see the video of which interview questions I made, this list of questions I made, this category, you can do voice search, channel related news, which video is coming next, you will get all the updates by watching this video. Thank you very much Lord ji for reducing the loot to half now
Minimum Window Substring
minimum-window-substring
Given two strings `s` and `t` of lengths `m` and `n` respectively, return _the **minimum window**_ **_substring_** _of_ `s` _such that every character in_ `t` _(**including duplicates**) is included in the window_. If there is no such substring, return _the empty string_ `" "`. The testcases will be generated such that the answer is **unique**. **Example 1:** **Input:** s = "ADOBECODEBANC ", t = "ABC " **Output:** "BANC " **Explanation:** The minimum window substring "BANC " includes 'A', 'B', and 'C' from string t. **Example 2:** **Input:** s = "a ", t = "a " **Output:** "a " **Explanation:** The entire string s is the minimum window. **Example 3:** **Input:** s = "a ", t = "aa " **Output:** " " **Explanation:** Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return empty string. **Constraints:** * `m == s.length` * `n == t.length` * `1 <= m, n <= 105` * `s` and `t` consist of uppercase and lowercase English letters. **Follow up:** Could you find an algorithm that runs in `O(m + n)` time?
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach. L ------------------------ R , Suppose this is the window that contains all characters of T         L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T When the window is no longer valid, start expanding again using the right pointer.
Hash Table,String,Sliding Window
Hard
30,209,239,567,632,727
1,094
Hello Hi Everyone Welcome To My Channel It's All The Problem Car Pulling So You Are Driving Option 28 Capacity MP Seats In Delhi Available For Passengers Dual Only Drives It Is It Can Not Turn Around And Drive Back So Give Only Strips Where Tips And Icon Are In Things Starting locations from first number of centers and third tips and location contains information of condition this trick handed over number option just must be picked up and location topic dam up from the name of the location of governors of kilometers from vehicles through these people it is possible To pick up and drop of all passengers for all subscribe on do superintendent landing 878 series overlapping trips so every like will have maximum capacity of total person like two plus three five wickets maxis floor accept document all the person hands free account complete destroyers return forms similarly This capacity for this example increases 250 between can transform dear all the passengers sweet bjp president rule in directions develop subscribe skating 50 per cent and subscribe button and that foreign example for under stand and soon total third tips fibroid graph like this from its a to 7 This is to 7 bf2 on board like a person in the recent trip from 30 to this is the point sammati se zee tv channel from this subscribe to i is over had 2000 worshiping and behave maximum level per cent and power bank and physical qualities of will Have Been So They Can Transfer Dam Remedies 10 Per Cent Will Get Out While The Person Will Not Difficult Subscribe 100G Thursday Subscribe To 102 I Let Seedhi Considerably Problem Solve Maximum Trips Can We Shades 3338 Reviews And E Coordinator Line Number Operation Passenger Set Max India Particular Tips 120 And A Starting And Ending Kilometers Mexico Tent House Should Give Something Is Pay For 2nd Feel Every Position At Every Kilometer Maximum And How Many Percentage In Which Is The Widen It's A Trip In Strips Take A Trip Every Five Retreat In This for the trip kilometer starting from 0001 between start location and most electrification twist refill will take maximum 10 kilometers from 0 to 10 after every place will be default here fall on channel subscribe our kilometer subscribe every time 2009 subscribe soft 02923 lo mil gayi this end Modifications Or Have Been Like This Way More Than 4 People Nuvve Are Placid In Return For The Time Complexity 2006 Subscribe Complexity Of Eggs Subscribe New Delhi Species So Hai But Someone Carefully Right Nau Hindi First Audition That Tweet Also Field Agri Kilometer And Avoid Going But See Carefully Need Not Only Dasha Dip Like and Subscribe and subscribe The Channel 100 From This Is to Three Rs 500 Is Account Only Person Scheduled Time Deposit Cutting Flash Lights of Spain West Indies 10 Vikram Like This and Will Check the Year at This point the person will get 9 votes - point the person will get 9 votes - point the person will get 9 votes - similar this point se point plus three for the point - egg - 380 take only this for the point - egg - 380 take only this for the point - egg - 380 take only this point servi se 10 1023 liye subscribe three letter this in the solar light se z3 plus minus 2009 hai so what will oo Will start after reading this all the year and getting basically a co meeting this number operations in this person will travel from government capacity to total capacity like first wilson factory for Vikram and administrative district comes 0 continuous voice zero given this any and every moment of mirch One Is Capacity Voltage Change Between Zero Means Pitch Indicator V Shape Dipper Organization The Time Back Kilometer Point Mode On The Capacity So Let's Previous Improvements For Implementation Will Take Care Of Time On That Asaram B Saf 20 Capacity 2019 Width Roll Trypsin Triplet City In Strips End Time Stamp Of Starting Point Of Which Puberty 90 Chief End Point Will Subscribe Must For Inter Time Table Number In More A Man Will Travel From Capacity - Man Will Travel From Capacity - Man Will Travel From Capacity - Equal To Number Panel Soch Every Point Of Ephesus That Chapters From City Lens That Is Point Of Butterfly The Problem limit Dravid and show members of currently so let's come pilot code &amp;c pilot code &amp;c pilot code &amp;c 's uniqueness 's uniqueness 's uniqueness is or co disgusting compile late compiler is development of which they are not deputy chief vintage cars number Ronit Roy 1500 that this compile and upgraded to translate samriddhi code that And accepted to know what is the time complexity of dissolution pure time complexity of dissolution is like share and chief scanning between strips don't like open channels pe 2018 201 simran 90 and complexity of 60 Video Channel thanks for watching Question On
Car Pooling
matrix-cells-in-distance-order
There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west). You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them up and drop them off are `fromi` and `toi` respectively. The locations are given as the number of kilometers due east from the car's initial location. Return `true` _if it is possible to pick up and drop off all passengers for all the given trips, or_ `false` _otherwise_. **Example 1:** **Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 4 **Output:** false **Example 2:** **Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 5 **Output:** true **Constraints:** * `1 <= trips.length <= 1000` * `trips[i].length == 3` * `1 <= numPassengersi <= 100` * `0 <= fromi < toi <= 1000` * `1 <= capacity <= 105`
null
Array,Math,Geometry,Sorting,Matrix
Easy
2304
1,582
hello hi guys good morning subji I hope that you guys are doing good this special positions in a binary Matrix now although it's an easy problem and I was thinking not to take this problem but the concept basically the followup which we're going to see is exactly what we saw in this hard question a few months back maximum strictly increasing cells in a matrix and it has been asked by Google quite frequently in last 6 months that's the only and only reason why I'm picking up this problem which is the easy problem but still the concept basically the followup which you're going to see is exactly what is being applied in this particular hard problem now you can see how important is that problem itself good let's quickly go and see what the problem says it just says that um we are having a m cross n binary Matrix M binary as in 0 and one we have to return the number of special positions in a matrix now how they Define the special position a position I comma J is called a special if that specific I cell is one and all other elements in the row I and column J which means if this I want as a special cell in that column and in that row everyone else should be a zero so that special that cell will be a special cell now I just have to figure out the count of all the special cells as you can see in this it is a special cell as if we go in this Row in this column everyone is zero if we see this in this column in this row everyone is zero it's also a special cell if you see this column this row also zero so this is a special cell so count of special cell is three now the simple approach which comes in our mind is we want to figure out if this cell is a special cell this so basically the simple brue Force approach which comes in our mind is we will go on to every cell now I'm standing at this cell specific cell I need to know if this is a special cell or not so first condition is that its value should be one that is first condition second condition is its row value all the values in its row apart from him should be zero all the values in its column apart from him should be a zero so if I'm standing at this cell specifically first condition was verified that okay it's a value of one I'll go on to all of its row values which means in a specific row all the values it should be a zero then let's say if this would have been a one so I will go onto this and this portion to see if it is a zero if it is a case then I'll go on to all the column values and we'll have to verify that everyone should be a zero if yes then this is a special cell but in this case you will see that in the column itting encountered a one so for sure this is not a special set and thus you will say that okay move on to the next cell and verify if it a special cell or not with this fact in worst case what you will do let's imagine that you have every cell as a one so for every cell you will be end up going and verifying okay if I'm at this cell it can it's a potential candidate so I'll go on to all of its rows and all of its columns in this specific Row in the specific column I'll go on and check if all the values are zero if yes then I will actually go on and deep dive into and say that okay this is a special cell so what you saw firstly I'll go on to every of the cells which is M into n cells now for every cell I'll go on to this specific column which is of size M or I'll go onto and basically I'll go onto this specific row so basically for every cell I'm just going on to one row and one column that's it again that is not M multiplication because it is one row and one column for every row not every column it is one row and one column that's it for this cell just one row and one column m n that's it so that's the reason the time complexity of this approach which we saw the simp simple FR Force approach will be o of M into n and multip O of M plus n space will be nothing but o of one because we are not using any extra space we are just going onto every cell and verifying for that specific row and column if that is valid or not so ultimately the same which I did in the code also again um apologies for not writing the code on Terminal because my like this hand I got on accident so my this hand is not working properly so I have to write very slowly with the these three fingers only like these three fingers I like my other two fingers are kind of not working right now because of some muscle issues it's phys theapy going on but still uh so yeah that's like we cannot code right now uh very fast so it will take a lot of time if I just write the same code on the code editor but yeah no worries uh the code is simply as that we'll go on to every row and column now for every row I first have to check if that specific cell is a one or not if that is not simply continue if that is a one then I will go on to all of my that specific okay if this was a matrix for us right we know that we going to we go on to all of our rows and columns okay let's say I am at this specific row comma column right now I will go on to all of my this columns like for this column I go into all the cells so I just say I know my Ral to 0 to r equal to M and this is the column value is same column and column so I'll go on to all this cells in this column and similarly I'll go on to all these cells in this specific row saying Cal to 0 to c equal to n and for sure row value is same row and row so I'll go on to all of these row values and we'll check that all the values should be a zero if it is a one and for sure I will not count this spefic it will for sure be one apart from him apart from the cell which I'm going to actually take as the main element apart from him if any other value is a one please mark as false because it is not good else and in the same case uh when we are trating on a row for that specific row if any of these cell apart from him is actually one again Market is false now simply uh if ultimately it's still a good which means everyone is a 0 then for sure say good and increase the answer by one and that's how you simply of M into n m plus n time capity and o space of o one you'll simply solve it now comes an interesting part that how you going to follow up and figure out what's the most optimal approach now just if you just go back you will go onto every cell that is for sure you will go on to every cell because for sure you have to figure out if that cell is a good cell or not now why this element was required this element was only and only required just to know if I have some one value in the entire row or not if I have some one value in the entire column or not apart from this yeah apart from this main cell if I have any one value apart from this value if I have any other one value in this entire column or not right so ultimately my aim was to all to only get a 0 right but my what I was trying to find out if I had something as one in the entire row or column or not right so your ultimate task was to just find out if there is something apart from zero or not right so why not simply take the sum of this specific row and simply take the sum of this specific column as simple as that I'll take the sum it will come as two I'll take the sum it will come as three now with the fact that if I take the sum of the specific row it will come as one the sum of this specific column it will come as one now if the sum of basically if I just take the sum of rows and columns so I'll just take the sum in this side for every row it is for every Row for every row this the sum is here it will be a one as simple as that and same for every column I will have a sum Now by why you took the sum because ultimately if you remembered my main task is just to figure out if I have something which is like I just want ultimately all zeros if I have something more than zero for sure the sum will be more than one so I can just go and verify that bro one thing here the sum is one which means that this particular cell and for sure first check will be if this L has a value of one if yes then just check the sum of this specific row which you can get from one of this precomputation which you will precompute the sum of this specific column which you again you will precompute if that is both one and one bro you find a good cell now in this case you will see that the cell although the value was one here that's great now you'll go and check the sum that's two check the sum that's three ah if it is other than one then for sure I would have encountered any other one values in this row or columns and thus sorry uh that would not work and ultimately I would say that just pass off so what you did you rather than going on to all these cells in the row and column you just precomputed the sum so that in just over of one time you can figure out if that cell is one but the row and column if that is all zeros or not with just simply a sum of the row and columns now ultimately you will ask what's the complexity of time or the time complexity for this it's as simple as that you will go on to every cell now you also you will also do pre-computation right yeah I'll do some pre-computation right yeah I'll do some pre-computation right yeah I'll do some pre-computation for that pre-computation pre-computation for that pre-computation pre-computation for that pre-computation part I will simply do one thing I will go on to all of my CS like I just want row sum right I just want row sum so this is the row sum this is a row sum I'll just keep it here and I also want the column sum this is now this I want the column sum I'll just keep the column sum so it will be two it will be zero it will be one so just this pre computation will be needed which will be a o of M into end time when this pre-computation will be done when this pre-computation will be done when this pre-computation will be done now I will just simply go and for every cell which is a one I'll just go and verify again now when I was referring that hard question which I referred uh wait I'll show you this hard question in this hard question exactly and see that's a standard trick for Matrix if you can pre-compute the row and column you can pre-compute the row and column you can pre-compute the row and column values that will help you a lot in this pre-computation of row and column this pre-computation of row and column this pre-computation of row and column values will be the trick to actually Sol it in the most optimal time and it's actually a hard question but yeah with this simple trick it will be solved very easily now uh when I am at a matrix okay uh in O of M to end time I go on to every of my cells and with this pre-computed values I will know if that pre-computed values I will know if that pre-computed values I will know if that specific cell basically the row count and column count if it's one I'm good if it is not simply move on to next cell so and but you will s you will see that with this the space has increased like you will have to use the entire columns and rows right you will have to keep somewhere these values so space has for sure increased which is actually o of M plus n but in the industry they can be caveat between space and time but it is always recommended that if you can reduce time and increase space that is okay so this is a better approach than the previous approach allthough space has increased but not that much because time has decreased by quite buy quite a lot of amount cool uh we'll quickly see the code it's again uh pretty simple firstly as I showed you I have I will have to precompute something what was that row and column so I just make a row and column Matrix basically row and column cells oh rows as in just a array so I make a row and column as a as one of my uh arrays just to keep track of these values right here it's just two ARS row and column that's it now I just simply go on to all of my elements in The Matrix and we'll simply just have a check okay if that is a one then simply increase your row and column for that specific I so if that is one I'll say my row of I increase it by one if that is a one simp simply say my row of I increase it by one if that's a one simply say column of that specific J increase it by one and as you will encounter here just saying column of J will increase it by two and with this you will simply go and build this entire row array and this entire column array right now when this portion is entirely done you have now your row array and column array built now when you have your row and column array built now simply tra on the entire Matrix again now when you entire Matrix first have a quick check if that specific values are one and also its row and column count should also be a one if all three conditions satisfy with this being the primary condition and these are the conditions to just have a check if that row and column count are all zeros this is for that now if that is the case then you are very good simply increase your answer if that's the case you are very good and simply increase your answer uh yeah simply give the answer and simply return the answer and again time capacity will be o of M into n plus o of M into n because you'll see o of M into n for this and O of M into n for this so it will be ultimately o of M into n Only and space will be actually of M plus n because you will see that you are using this m and this n for row and columns so yeah with this you will quickly you will be easily able to solve this and again uh do try this hard question although if you are stuck you can just search for this problem name maximum strictly increasing cells in a matrix by irth you will still found this question Cool again byebye
Special Positions in a Binary Matrix
design-browser-history
Given an `m x n` binary matrix `mat`, return _the number of special positions in_ `mat`_._ A position `(i, j)` is called **special** if `mat[i][j] == 1` and all other elements in row `i` and column `j` are `0` (rows and columns are **0-indexed**). **Example 1:** **Input:** mat = \[\[1,0,0\],\[0,0,1\],\[1,0,0\]\] **Output:** 1 **Explanation:** (1, 2) is a special position because mat\[1\]\[2\] == 1 and all other elements in row 1 and column 2 are 0. **Example 2:** **Input:** mat = \[\[1,0,0\],\[0,1,0\],\[0,0,1\]\] **Output:** 3 **Explanation:** (0, 0), (1, 1) and (2, 2) are special positions. **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 100` * `mat[i][j]` is either `0` or `1`.
Use two stack one for back history and one for forward history and simulate the functions. Can you do faster by using different data structure ?
Array,Linked List,Stack,Design,Doubly-Linked List,Data Stream
Medium
null
784
foreign letter case permutation and it's uh simple you can say simple backtracking problem you're given a string s and we have to transform every letter individually to be lowercase or uppercase to create another string we return a list of possible strings we could create and of all possible streams that we can create and we return the output in any order so we don't have to sort it's in any order it's acceptable the constraints are that the string length is from 1 to 12 and the string consists of English letters uppercase English letters so lowercase and uppercase and also digits so in this example we have A1 B2 so the first run that we can generate is basically just the same we don't do anything the second one is that we do the uppercase B and third one is we do the uppercase a and then in the last we do the uppercase for both the letters that we have inside the initial string for the second example there's only one letter so the digits remain the same we can either go with an option of having the lowercase z or the uppercase X so there are only two options how do we actually generate the all the uh all the permutations all the combinations that we can have with the initial strength so basically with the backtracking problems we will always start uh from our base function and we will have some helper function that we will be calling recursively uh over the input the initial string or the array or whatever we have and we will be gradually generating uh the output and we will have a base case so a few things are important base case in our case the base case will be when we reach a string that we have generated that's of the same length as the initial strength because we know that we have transformed some of the letters some of them we might not and maybe in the last case we have never we haven't touched any letters so we just want to for any strings that is unacceptable acceptable transformation of the initial string we will have it the base case is that we have the same length now the second thing that's important to backtracking is the decision making process so for decisions we can basically we only have two decisions so we can either do an uppercase or lowercase letter for the digits we basically uh just uh propagate down to the recursion tree because the digits cannot be transformed so those are cases now we will go through the example and also in the helper function we always uh do we always pass as parameter some um some important information so for example in this case we will pass our uh initial word or the string that we are trying to generate another versions of we will send the current index the starting this will be zero we will send value that we are generating right now so in this case it will be just an array of characters and then we will send the result we always send the result that we will from the mean function return as the final output and in the result we will be just basically once we hit that base case we will be putting the uh the current value that we generated inside the result uh the word is basically just our we always have to send the set of candidates the set of candidate that we can use for the generation purposes now if we go to the to our initial string the root of the we will just Mark the like this imaginary root of the recursion tree in the first uh our first base case when we call the helper function we will have a letter A so we can do the decision either to uh use uh the lowercase a or the uppercase a and we are using the index 0 to fetch the first character in the initial string so because it's uh a we can do these two uh these two options and we will increment the index one once we so we will do the first we will do the left recursion subtree and in this case we are now looking at the second character which in our case is one so basically when we next time when we call the helper function we will have only one option in this case it will be one and we will then again increment our indexed two so it's now pointing to B old while we are doing this we are putting the characters that we have selected in inside the current path of the recursion tree inside our array of characters so we chose a we chose one then we have two options we can either go with P lowercase or B uppercase let's say we always Traverse through the left tree and we basically put B in the character array next we will go to the will increase the index to 3 and we are pointing now to the last candidate to the last layer in our initial word which is two and we cannot transform it so basically two will be this next time we call the helper function the index will be four so that's our base case the index is equal to the length of the word and we don't have any more characters so uh basically we have to put the current array of characters we have to form string and put it in our result so the first string will be basically be a one B two we will do basically the same when you are done with that we will return from the uh from our last school of the uh recursion um of the helper function we will go to B and because we don't have anything else here in the tree we will go again back uh to here and each time you basically discarding the elements that we have passed in the recursion tree so we will discard uh two and we will discard B um because we just covered them all but next when we hit number one we will go to the right subtree or the right node and in this case it will be uh the uppercase B so in this case and also we are because we are traversing the through the recursion stack the index will change so it will reduce from four three to two and uh we will be again looking at the uh at the B candidate inside our uh initial word and in this case because we already had the left three as lowercase b in the right uh node we have the uppercase B and we will basically do the same in the next iteration so we will overwrite basically this B and the two will remain the same and this when we will again hit the base case and we will have to add the A1 but now uppercase B two and basically we will do the same for a we will go up the recursion tree when we are done with all the sub trees uh and uh basically when we are done with the first left node we will Traverse then again through the uh right node but now starting with the uppercase a so we will get different uh versions of the initial string and basically when you are done with all of the options we will return to the main function and so we'll be stop calling the helper function and from the main function we will just return the result because we are passing it by reference it's okay just to return it as the result from our main function now the for the time and space complexity we basically for the space complexity we are uh we only have the this array of characters that we are passing through and it's changing and it's of the length it's proportional to the size of the to the length of the initial word now for the time complexity we will basically have uh how we how do we calculate it we basically have two options so our breadth our width of the recursion tree you can say is two it's a maximum two and the depth of it is we go as far as the uh as we have candidates and in our case it will be the total number of candidates will be the length of the word so in this case it will be four and we can also put n because that's more generalized and so we know basically that we will be doing this n times so the time complexity will be 2 to the end now for every leaf if node we will do some computation in this case we are just copying over the array of characters to a string we are transforming this array of characters to a string which can be uh well depending on the program language it can be uh the linear operation uh that's linear in proportional to the size of the character of array which in our case is n so we will have to add this additional multiplier n or it can be constant so in that case we will have only two to the end but because we are we will be using Java to solve this it will be two uh to the end times the multiplier and for the time complexity we'll start by declaring first our result which will be just a list of strings that you'll return uh after that after we have generated them and then we will call our helper function which will be defined just in a moment and we will pass the initial index which is zero and for the current value that we are generating it will be the fault value it will be an array of the characters of the same length as the input that we got and the next parameter that we will send will be the actual num set of candidates which in our case is basically just a word that we have the string that we have so we will pass S as our third parameter and for the last parameter we'll just send the result and we are sending by reference so the things that we add inside the helper function will be visible inside the main function so we can basically just return the result now to the main part of this problem we will Define the helper fashion as we said we are passing the index as the first parameter and how we are traversing the um the recursion tree this index will be changing it will be incrementing or decrementing Basin based on which direction we are going in the recursion tree current word will be our current and generation that we are um current word that we are trying to generate the word will be set of the candidates it will not change and the list will be uh the list of strings in the three uh that we will be in injecting the words that we are generating so first we will have our best base case and our base case is when we have an index that's of the same length as our set of candidates we are out of the Kennedy so we basically just can add the current string that we have formed inside the current word characters over a to do this in Java we will just call the new string Constructor and we will add it to the list of strings then we will basically just to the return so we can stop the traversal through the recursion tree so we are basically going back now uh for the regular case we will get the character at the current index and you will basically check if the current character is uh digit if it's digit we know that we cannot do anything we will call we will propagate to the we'll go to the next level of our recursion Tree by calling our helper function cursively but in a more interesting scenario where we have a character we will have two options we will first uh do a lowercase of the character and we will call our helper function cursively and then we will retract we will do the back backtracking we will overwrite the character at uh so in the previous scenario it was uh this is basically a left node it was a lowercase now in this case it's a uppercase and we are going back uh we are still going down to the recursion tree by calling to helper function cursively
Letter Case Permutation
insert-into-a-binary-search-tree
Given a string `s`, you can transform every letter individually to be lowercase or uppercase to create another string. Return _a list of all possible strings we could create_. Return the output in **any order**. **Example 1:** **Input:** s = "a1b2 " **Output:** \[ "a1b2 ", "a1B2 ", "A1b2 ", "A1B2 "\] **Example 2:** **Input:** s = "3z4 " **Output:** \[ "3z4 ", "3Z4 "\] **Constraints:** * `1 <= s.length <= 12` * `s` consists of lowercase English letters, uppercase English letters, and digits.
null
Tree,Binary Search Tree,Binary Tree
Medium
783
172
welcome to the coding interview problem factorial drilling zeros you are given an integer n return the number of trillion zeroed in n factorial the constraint to this problem is that you have to solve this problem in logarithmic time complexity how we can solve this problem first let me ask you a question in what situation will you get a trolling zero post this video right here and think about it when you are done come back to the video we will get a trailing zero whenever we multiply a non-zero number by 10 if we a non-zero number by 10 if we a non-zero number by 10 if we multiply this number 1 by 10 then we will get 1 trillion 0 if we multiply this number 2 by 10 then we see that we get one trailing zero if we multiply the number one by ten two times then we get two trillion zero if we multiply the number two by ten two times then we get two trailing zero so what we have understood we understood that when we multiply a number by 10 only then we get a trailing zero if we multiply a number by 10 times then you will get 10 trillion 0's since 10 is made up of multiplying 2 by 5 so another way to get a traveling 0 is to multiply a non-zero number by 2 and 5. a non-zero number by 2 and 5. a non-zero number by 2 and 5. so to count the number of trailing zeros we need to figure out how many times we multiply two by five here we see we multiply two by five once so we have here one trailing zero and here how many times we multiply this two by five twice so here we have two trillion zeros now let's take a look at factorial of five the factorial of five one times two times three times four times five that's equivalent to one hundred twenty in the factorial of five we see that we have only one trailing zero now our goal is to find how many times we multiply 2 by 5 if we rewrite this then we see that here we multiply 2 by 5 once so we have here only one 0 since we have multiplied two by five once there is one trailing zero instead of keeping track number of twos and fives we really just need to keep track of the number of fives this is because in any factorial calculation there are always just going to be more multiples of two than five here you see we have three multiples of two and only one multiples of five so if we can find the number of multiples of five then we can get trailing zero for factorial of a number let's take a look at another example for better understanding for factorial of 10 we have 1 times 2 times 3 times 4 times 5 times 6 times 7 times 8 times 9 times 10 and that's equivalent to this number and in this number we see we have 2 trailing zero if we rewrite this then we get like this so here we see that we have one two three four five six seven eight total eight multiples of 2 but we have only 2 multiples of so if we can find the total multiples of 5 then we can have the answer here we see we multiply 2 by 5 twice here and here so we have here two trailing zero our goal is to find the number of multiples of five two appears in this factorial eight times and five appears only twice so we can get the number of telling zeros by calculating the number of multiples of five if we are given factorial of 25 then we have to find the multiples of five right to get the number of tailing zeros here we have five numbers that multiples of five and this 25 contains two five if we write this again then you get one times five two times five three times five four times five here we see total multiples of five is six so in the factorial of 25 we have six trailing zero now our goal is to find how many times we multiply the number by 5. now let's see how we can find that first we're going to declare a function traveling zeros that takes an integer number as input then we're gonna initialize a variable count equals to zero this variable will hold our answer then we're going to run a loop well n is greater than 0 then we're going to divide in by 5 then we're going to add that to our count variable then we're going to return the count and this is the pseudo code to solve this problem first sake of understanding if you are given the number 5 we know that the factorial of 5 is 120 so we have here only one trailing zero now if we divide this number by 5 then we're left with 1 and then we're going to add that 1 to this count variable so count became 1 for next iteration of this while loop number is greater than zero but in divided one is zero so it will add zero to this count so it remain as it is one and for the next iteration we see n equals to zero and zero is not greater than zero we are into this while loop will just return this one and this is how we can solve this problem and this solution takes big of log five base in where n is the given number and this is the time complexity for this problem and this is five based log okay and it will takes constant space complexity since we're just using one variable count all right guys hope this concept was clear if you have any question if you have any suggestion latest though thanks for watching this video
Factorial Trailing Zeroes
factorial-trailing-zeroes
Given an integer `n`, return _the number of trailing zeroes in_ `n!`. Note that `n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1`. **Example 1:** **Input:** n = 3 **Output:** 0 **Explanation:** 3! = 6, no trailing zero. **Example 2:** **Input:** n = 5 **Output:** 1 **Explanation:** 5! = 120, one trailing zero. **Example 3:** **Input:** n = 0 **Output:** 0 **Constraints:** * `0 <= n <= 104` **Follow up:** Could you write a solution that works in logarithmic time complexity?
null
Math
Medium
233,809,2222
1,588
Hello Hi Guys So Today Will Be Going To Discuss This Problem Far From Its Good Bye Weekly Contents Problem Name Sum Of All Subs Problem Kuch Nahin Hai Means And Us Me Jitan Bhi Na Nikal Like Hum Subscribe To Us 143 Like Share And Subscribe If you can, then that balance is spent all morning 1234 12345 like subscribe Video subscribe If you want to take out their time in the working committee, then its Swiss stomach is disgusting. The size of subscribe is and inside that, the size of one subscribe is off and then another subscribe and 100 grams. Now generate 200 phone numbers in the morning, how many will be there at max and half inch and * now we will run * * * * * half inch and * now we will run * * * * * half inch and * now we will run * * * * * * we will take it and put a plate on it, now * we will take it and put a plate on it, now * we will take it and put a plate on it, now even a little thank you from that number. You can reduce like subscribe and subscribe to that and this can be one because FD this concept factum delegate arrange them in one time complexity so let's what are subscription and how can we use them and to remove all this from central to ward no-1 Constantine ok so lets central to ward no-1 Constantine ok so lets central to ward no-1 Constantine ok so lets come to and 400 separately increase to right 114 to 15 to zor chahiye tu chahiye to possible 2065 subscribe our YouTube Channel Apne 272 plus 5302 1000 k sorry it's ok Chhotu support khudne toh to Plus 5768 stand in the morning that so how can we bring it in the oven we can bring this test using training started from training to other 1253 subscribe disposition to hear someone from his position of the if not subscribed till here then subscribe from here Had come then here is okay from here till here what is it so oneplus 5 275 12th personal leave from here till here okay so you and also that we follow behind because we are asking that from here till here Till here, till here in Assam, from here to here, subscribe, okay, then we can use that, there is nothing to find Tehsil Pua Rains, we are here But took out this tree 1425 way witch nothing but 157 12581 572 sure 1234 intact someone needs two to four oaths time know that and till separation number comes holiday was difficult for him now I will have to do some value - right meaning I just want this will have to do some value - right meaning I just want this will have to do some value - right meaning I just want this Survey - If you want to do then I will get this question Survey - If you want to do then I will get this question Survey - If you want to do then I will get this question Okay now requests for wearing nothing but the difference between tits If one has all this and this is all I want to show this question then nothing will happen This even survey - this one Side difference between two even survey - this one Side difference between two even survey - this one Side difference between two rupees 100, if this steam rice is the time from beginning to end, then if I do this in this water this morning, then I will get all this wonderful stuff from edit that my ko from zero to now If you understand from the loudest till then it is simple to yoga, I have to clean my stomach and return, Hrithik is hidden, I have to return Bijawar right, it is bad luck as if we have only this one, if I romance with Totka from one, then till. Ransom should be in that in the interval kuch nahi karna hai tu tak submit tak kasam kya hai celebs mere ko lekar delhi tak samjhe to one se pehle ki value karni hai right so 17 - one witch six suppresses previous committee from - one witch six suppresses previous committee from - one witch six suppresses previous committee from LPR is nothing but fixed position R - 6th LPR is nothing but fixed position R - 6th LPR is nothing but fixed position R - 6th position is also mentioned because then we need white today because we need Alto K10 so I have to do 17 training of 100 then we have to include simran of Alto 800 okay or in problems so now we do not have to do anything we have to generate all the chords in this length And we have to do this again and again that it is the time of Alwar, so what can we do now that the bulb is lit from zero to the end of each other, now if I am already on one position one is the element then Separately, 142 53 Soumik, now I am in this position, so now I have to learn something right, you are on the seats, this is already and you are taking the length, so I will add to it, so I have got a three size pilot saver. Now I will fold it in this, you will see the file and you will get it in the morning. Current element was IS, Limit was Begusarai, Online survey on this strike, I should find some jewelery in it, always keep adding to it, I will make a joint in the decoration again and again. All those other lenses in the morning in which this eye is included, okay so let's in this case one will be then 152 then one will be 4253 so these are three possibilities online pinpointed then what will I do I will increment the eye then the previous report is 251 This point will be a reminder, disconnect the phone, it will be 1253, it will be ok, sleep, now I have got a plus in it, as if Sachin has returned with a plus, as if I have brought a plus, which is not done in the morning, okay, then I have to run the loop in these square offs. And in this, we click on the bar, we have to use, okay, so it's good, that's so normal, next one wavelength first prize for fiction and field mother, you will value the first plate, okay from two one to 100 plus subscribe Na chanak tiffin if the answer is hundred point is quite him loud plus okay point question Adhir Vikas it cost us 250 plus to the scientific now Scotland and okay so inter equal to two now we just have to keep in mind that l minus one our Like from the eyes between these and because we have a condition that is jayya means if i0 is then zero - 151 if I access the negative tree is then zero - 151 if I access the negative tree is then zero - 151 if I access the negative tree us then it will be placed in the run time so here I have put a small check that and minus One our zero two end in between yoga camp us runtime error fashion same fruit - - - - 121 normally error fashion same fruit - - - - 121 normally error fashion same fruit - - - - 121 normally benefit white shroud we can digital because she will bind ginger let's do 180 okay interviews nothing but it's for Swaraj Se Bhi Answer Request You Answer Plus B - A School Plus B - A School Plus B - A School Ki Swami Vyas Return Karna Hai Return A Answer Ok Harendra Loan Repayment Electronic Shoot Software 366 Marte Hain I Fail So Thanks For Watching This Will See You In Next Video Playback
Sum of All Odd Length Subarrays
sum-of-all-odd-length-subarrays
Given an array of positive integers `arr`, return _the sum of all possible **odd-length subarrays** of_ `arr`. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** arr = \[1,4,2,5,3\] **Output:** 58 **Explanation:** The odd-length subarrays of arr and their sums are: \[1\] = 1 \[4\] = 4 \[2\] = 2 \[5\] = 5 \[3\] = 3 \[1,4,2\] = 7 \[4,2,5\] = 11 \[2,5,3\] = 10 \[1,4,2,5,3\] = 15 If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58 **Example 2:** **Input:** arr = \[1,2\] **Output:** 3 **Explanation:** There are only 2 subarrays of odd length, \[1\] and \[2\]. Their sum is 3. **Example 3:** **Input:** arr = \[10,11,12\] **Output:** 66 **Constraints:** * `1 <= arr.length <= 100` * `1 <= arr[i] <= 1000` **Follow up:** Could you solve this problem in O(n) time complexity?
null
null
Easy
null
95
hey guys let's take a look at number 95 unique binary search tree so trees - unique binary search tree so trees - unique binary search tree so trees - we're given an integer please generate all structurally unique bsts well actually this is a follow-up of problem actually this is a follow-up of problem actually this is a follow-up of problem of 96 and I've already done that before please so to my channel for 96 unique binary search trees there it's specifically a same problem but that problem only requires to return the account of the binary trees but here we need to generate all the real trees right so Wow please search on my channel for that detailed explanation there I'll just start on writing on the code writing the code the basic idea is that for a number of n if we want to generate the binary search tree we need to first determine the roots if we determine the roots root we if we have chosen the root we can separate the problem into left part and the right part it's different strengths different numbers right and then that could be done in to iterate iteratively and we can just then combine these to a left part and right part and add and get the permutation of each of the trees and generate a new tree and push into the result right yeah let's say the for number n for each time we generate to the binary search tree there's a pick a number there so it's generated a range of number with a start and the end right so I'll say the generate is a recursion function will start and end and then the results of this of the binary search trees are kept our stored in this result just as what did before in 96 will choose the route start ok now we're picking number it might be one it might be two maybe three so the problem becomes the left part would be left list with trees because it's a bunch of tree it would be what it will be generator right generate start from start - I - right generate start from start - I - right generate start from start - I - water right cost right trees it would be a generator 8i plus one and right and now we get the left part and the right part like for three of a tree here we get the trees of one and two or three and then we combine them so for each LED tree that node left node in left trees for that off not in my bad for LEDs right node of right trees we will create a new tree so the new tree will be node needle root would be new tree node i right so it's I and then roots left will be left no good try to pee right now and then we could push this roots into the result and finally how would this end well if like if starts is bigger than end result will push just return new array and if start is start then it will be a tree of start new or newer so it's ok it's just like this and then we can return generate one and I'm not sure it is right it should be if something is wrong it must be in this the ending cases right tree is not eatable right trees oh we forgot to return my bad if return results yeah it seems that I've done this problem like five months ago expected empty oh it's Noah so it should be empty my bed if you be I think issue it's right you should return nor the problem becomes if we imp to zero you should be none if it's zero because we start with zero and then add zero well it says start from one all right integer give in hmm that is nasty yeah equals zero return empty Wow once again we need to fully understand what the input either is about it or not yeah we're accepted and maybe it's not that bad and about the time complexity please refer to my lat last video about 96 actually we're using these is for loop here and so it's very complicated about time because it's related to Catala let's say we want this is alright but it's oh and for just each and well it's a shame it should be just Catalan so the time complexity would be Catalan and the space will be Katalin and this is my guess it's might be wrong man I'm not sure I'm not I don't think they're interviewers were asking us to detect the right time complexity here fridge yeah we will use yeah so that's all for this problem hope it helps see you next time bye
Unique Binary Search Trees II
unique-binary-search-trees-ii
Given an integer `n`, return _all the structurally unique **BST'**s (binary search trees), which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. Return the answer in **any order**. **Example 1:** **Input:** n = 3 **Output:** \[\[1,null,2,null,3\],\[1,null,3,2\],\[2,1,3\],\[3,1,null,null,2\],\[3,2,null,1\]\] **Example 2:** **Input:** n = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= n <= 8`
null
Dynamic Programming,Backtracking,Tree,Binary Search Tree,Binary Tree
Medium
96,241
977
Hello guys welcome change sid question of cotton in this question Thursday must subscribe a video subscribe problem subscribe to Shri Ram Complexity of this College of Law and World Peace Complexity 2017 Rajdhani Express Middle School Kids submit button Vinod given link problem subscribe Video then subscribe to subscribe and subscribe the that today medical unit to howrah two variables left android 1.8 diner ten variables left android 1.8 diner ten variables left android 1.8 diner ten point to 0.2 point witch will be positive veer point to 0.2 point witch will be positive veer e will ut lt tej din question right now he will take place for value labs Subscribe To Candy Crush Mental Pointer Variable In This Part Is No The Amazing Divine And Gorgeous Welcome 90 Degree Mandi Right Index And Also Degree Mandi Point Of Vintage And This Point Amazon Middle Thursday Subscribe To Video That A
Squares of a Sorted Array
distinct-subsequences-ii
Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_. **Example 1:** **Input:** nums = \[-4,-1,0,3,10\] **Output:** \[0,1,9,16,100\] **Explanation:** After squaring, the array becomes \[16,1,0,9,100\]. After sorting, it becomes \[0,1,9,16,100\]. **Example 2:** **Input:** nums = \[-7,-3,2,3,11\] **Output:** \[4,9,9,49,121\] **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in **non-decreasing** order. **Follow up:** Squaring each element and sorting the new array is very trivial, could you find an `O(n)` solution using a different approach?
null
String,Dynamic Programming
Hard
2115
89
hello so today we are doing this problem called gray code as practice for the video explanation of a gray code that I put up just before this it would be very useful to watch that one first and then watch this one after it and so this problem is a direct application of that and so it just says that definition of the gray code which we'll look at which is a binary numeral system where every two successive values differ only by one bit and here we get an integer end which represents basically the total number of bits in the code that they want and we want to print the sequence and the sequence must begin with zero and so for two these are the bits each differ by one and the result should be this and for zero there is just zero so this is a direct application for that one and so I'm just going to put as a first solution the one explained in that video which if you want to know why it you just need to look at that video but that one is just you need to um so the way to solve that is just construct a list first like this then after that we need to go through for n we need to go through all two to the power of n combinations as we saw in that explanation that's the number of that's that so we can that's the number of combinations in a gray code of n bits so we can either do it this way to the power of n or we can also do it like this is the same thing and then we can just add the current sequence and that just by ignoring the they're currently ignoring the bits the binary representation with the binary representation shifted to the left so basically taking in the binary representation taking the bit at one position and the one to the left that's basically what we are doing here and exhorting those two that gets us the one that gets us the value for the gray coat and we can just return this at the end and that's pretty much all there is to it in terms of time complexity here the time complexity is of 2 to the power of n because that's how many time how many times were on the for loop and in terms of space complexity this is just Oh fun so next we'll look at a different solution that uses also another formula from the previous video explanation about the gray codes to solve this ok so the second solution one of the things we looked at in that video explanation about the gray code was a recursive formula that defines the gray code sequence for value N and so we said that it's so L 1 is 0 and 1 and also we can augment this by saying for L 0 is just 0 as the problem said and then L n is just concatenate 0 with the previous sequence and n minus 1 and add to that 1 as a first value concatenated with the previous sequence reversed right so that's what we came up with when we said that the way to get the gray code sequence was to take n equal to 1 is just a 0 and 1 and here you could add an equal to 0 it's just a 0 and then for n equal to 2 just take the previous values of 0 and 1 and reflect them right just take 0 into 1 here and then reflect them so kind of using a mirror or something so you get one first and then 0 and the first part which is the previous sequence not reverse it is just put 0 in front of them the second one which is the previous sequence reverse it just put 1 value in front of them and the same thing we did for n equal to 3 we took the and equal to2 sequence which is this entire thing and we just put it here in blue in and then we rested so one zero one fell after that and then 0 1 then 0 and then the first ones we put 0 which is the one in light blue here in front of them and the mirrored one I will put 1 in front of them and so that's the direct application of this formula and we can just take this and convert it in to use it as a recursive function right and so that's what we will be doing and so to do that we can just say get the result for gray code of n minus 1 as a recursive arm operation and then just construct our result by doing basically a zero plus s for every s in the previous result right and then add to that one concatenated to the reversal previous sequence which would be just for as far as in the reversal previous sequence which will be just reversing us right and then once we get all of this we can return them and then we will get them as strings so I'll get them like in this format right and so in Python we can convert that into binary using just int with the string representation of the binary and to saying its base to get the number so that we can return 0 1 3 2 and those numbers basically yeah so it's a direct application of the recursive formula here and so let's write it and type it into lead code we will use our base case for our recursive function would be for n equal to 0 the value is just a 0 for n equal to 1 it will be 0 and 1 okay so let's type that ok so let's type the same formula so for n equal to zero which is our base case we need to just return 0 right so that's just returned it's just the bit 0 right and then for n equal to 1 we said it's zero in the one right so we are going to just return them in a string format of binary so like for zero it will be four in equal to 4 it would be like this and then I just need the helper here for my recursive function you don't see why in a moment and then now I can do so this is n equal to 1 so now these are our base cases now let's do the recursive call which is just getting the previous sequence so this one here would be L n minus 1 in the formula and this here is at 1 and this here is 0 and here we will need for the helper to get the previous sequence so n minus 1 and then we can just do the same thing we said in the formula which is concatenate 0 with an N minus 1 and then concatenate and 1 with the reversal previous sequence right and so that would be doing like doing it like this so we'll need to concatenate 0 with every element of the previous sequence and then add to that concatenating 1 to the reflected portion of the sequence which is just the previous sequence reversal right so we will concatenate put 1 in front of those so for us in the reversal previous sequence right and now that we have that we can call that function here but this will return to us if I print this you could see where it returns so you can see it prints them in bits right so we need them to be converted to integers as I said in the explanation and so that would mean what we'll do here is we'll return each one of them were converted into an end so let's call these s in that and convert s to forest right and basically this here will convert any binary sequence English in a string format into a number into an integer so if we run this there is return okay I'll submit okay so that passes in terms of time complexity here at the time complexity here we do at most and calls right because every time would adjust by one and so the time complexity here would be so it would be just open right and then for the space complexity we are using your curtain here so it's a it's not a recursive and so we will need to use the stack and so that would mean here we would have ov and also so it's likely but in terms of time complexity but we pay a cost with the space complexity here yeah so that's it for this video thanks for watching and see you next time bye
Gray Code
gray-code
An **n-bit gray code sequence** is a sequence of `2n` integers where: * Every integer is in the **inclusive** range `[0, 2n - 1]`, * The first integer is `0`, * An integer appears **no more than once** in the sequence, * The binary representation of every pair of **adjacent** integers differs by **exactly one bit**, and * The binary representation of the **first** and **last** integers differs by **exactly one bit**. Given an integer `n`, return _any valid **n-bit gray code sequence**_. **Example 1:** **Input:** n = 2 **Output:** \[0,1,3,2\] **Explanation:** The binary representation of \[0,1,3,2\] is \[00,01,11,10\]. - 00 and 01 differ by one bit - 01 and 11 differ by one bit - 11 and 10 differ by one bit - 10 and 00 differ by one bit \[0,2,3,1\] is also a valid gray code sequence, whose binary representation is \[00,10,11,01\]. - 00 and 10 differ by one bit - 10 and 11 differ by one bit - 11 and 01 differ by one bit - 01 and 00 differ by one bit **Example 2:** **Input:** n = 1 **Output:** \[0,1\] **Constraints:** * `1 <= n <= 16`
null
Math,Backtracking,Bit Manipulation
Medium
717
60
today we will see one fun problem it's called permutation sequence so we know that if we have n digits we can indistinct digits we can arrange them in n factorial ways so this in fact comes from that only so if we have three digits let's say blue denotes one red is two and green is three so we can arrange them in three factorial ways and what is 3 factorial it's 3 times 2 times 1 similarly 4 factorial will be 4 times 3 times 2 times 1 so this is 6 this is 24 so in it factorial can be obtained if you know the factorial of n minus 1 just multiplied with n so you see this term is common here so it's equal to 4 times 3 factorial so now here the problem is that you don't have to list the factorials but instead you will be given one number like this 3 here so you are given 3 and you are asked that what is the fourth number in this arrangement so let's assume that they are arranged in ascending order so first you will write 1 2 3 then 1 3 2 then we can only write two possibilities starting with 1 followed by 2 3 or 3 2 similarly next will be 2 and next smallest is you make the most significant bit as small as possible so here 1 was fixed so we added 2 first then 3 2 here 2 is fixed so smallest will be 1 followed by 3 then 3 1 so fourth one will be here so we will just return this value that is 2 3 1 if we are asked that n is 3 and we have to return fourth value so let's see how to solve it so let's see a bigger example here n is four so there will be 24 possibilities and we are asked about ninth number in this arrangement in ascending order so here we know that here first digit is fixed first digit is 1 so we will be left with first digit is 1 we will be left with 2 3 &amp; 4 so how many ways are left with 2 3 &amp; 4 so how many ways are left with 2 3 &amp; 4 so how many ways are there to arrange these 3 factorial so overall we have 4 factorial that is 24 but if we fix one digit we are left with 6 possibilities and you will see if you look at these three digits these will be the all 6 possible arrangements of 2 3 &amp; the all 6 possible arrangements of 2 3 &amp; the all 6 possible arrangements of 2 3 &amp; 4 similarly here 2 is fixed so these are again 6 so if you know the factorial from 1 to n that is 1 to 6 and it's 24 and you are asked lets in 9th then you know that first digit cannot be 1 we are keeping it sorted since it's more than 6 every digit starting with every date there are n minus 1 factorial arrangement similarly starting with 2 there will be n minus 1 factorial arrangements so we know that 6 numbers have already occurred starting with 1 and those are the smallest 6 so we see varies our value its 9th and next 6 will occur starting with 2 so till here we have 6 numbers till 2 we have 12 numbers so our number lies between 6 and 12 so we have to first task is to find what is the first digit so we know that it's less than 12 so up to 12 and more than 6 it will start from 2 so this we have figured out now we will subtract so it's starting with 6 we know that it will lie in this range since 6 is here and 7 to 12 is here this is 1 to 6 seven to 12 13 to 18 and 19 to 24 these are the four ranges for four digits and our nine lies here so we fixed the first digit to now within this range what is the position of ninth so subtract all the values before it so six start before starting with two there are six numbers so subtract six from nine so our new K becomes nine minus six or three that is we want to find the third digit in this group and what is this group first digit is fixed so we are left with one less d and the digits are 1 3 &amp; 4 so write all and the digits are 1 3 &amp; 4 so write all and the digits are 1 3 &amp; 4 so write all the permutations of 1 3 &amp; 4 which are the permutations of 1 3 &amp; 4 which are the permutations of 1 3 &amp; 4 which are here and find the third digit third number in sorted order so our earlier problem was n was 4 K was 9 so 4 9 reduces to 3 now again we will see that we have three digits and it's factorial will be 1 2 &amp; 6 six ways it's factorial will be 1 2 &amp; 6 six ways it's factorial will be 1 2 &amp; 6 six ways of arranging them so if we have to fix one digit how many ways other digits can be arranged so go one step back just like this one so each digit will occur two times so let's write it 1 3 4 1 4 3 then 3 1 4 3 4 1 then 4 1 3 4 3 1 so we know that we have to find the third digit so we know that 1 2 lies here 3 2 4 lies here and 5 to 6 lies here so our problem is smaller here so where will 3 lie so 3 will lie in this range which is starting with three so we know that next digit is 3 so we now fix 3 so we have 2 followed by 3 and we are left with we remove it from the list of digits or layer it was one two three four with six two so we removed it and these are sorted so they will still remain sorted if we remove something from in between now three is fixed so we remove it now our digits are one and four so we know that they can be arranged in just two ways one fourth and four one and here we have to subtract this previous reign just like we subtracted 6 from here so we will be left with one so this reduces further two to one so two digits that is one and four and find the first one in them so what is the first one in them so 2/3 is what is the first one in them so 2/3 is what is the first one in them so 2/3 is fixed we have 1 4 so it will be 1 4 &amp; 4 fixed we have 1 4 so it will be 1 4 &amp; 4 fixed we have 1 4 so it will be 1 4 &amp; 4 1 so the first one is this one so add it so this is the result 2 3 1 4 so how we will do it let's write the code then it will be even more clear so let's keep all the factorials and all the digits in a vector fact and its size will be N and let's initialize with 1 since 1 factorial is 1 we can start from 2 and we know that this formula holds so what is n factorial is n times n minus 1 times n minus 2 times all the way up to 3 to 1 and this thing is n minus 1 factorial so n factorial is n times n minus 1 factorial so if we know n minus 1 factorial it's a one operation to calculate n at factorial if we know this if we have already calculated this so we start from 1 factorial 1 is 1 then we can start from 2 I equal to 2 to n so fact 2 will be so before calculating any value we already know the previous value since we have initialized with 1 and starting from 2 equal to F 1 x 2 and in general it will be F I equal to fi minus 1 times I so this way we will calculate all the factorials beforehand so that we don't need to repeat similarly we will also keep track of needs and now let's calculate the factorials so our factorials are not calculated now what we will do all we have to return it in the string form so let's create one empty string then while result size is less than n minus 1 we will do something what we will do and why I have kept 1 less than the required size what will be the size of result it will hold all the end its so it's eye size will be exactly in and this will exit when the size becomes n minus 1 that is 1 less and why we are doing this let's see in a minute finally we will return a result but before that let's fill it here so we have to find how many repetitions are there starting with each digit so for that we went to one position max second last position in this factorial this is what we saw here so if we have four digits each digit starting with each we will have six values similarly when we have three digits starting with each digit we will have two values so we go we pick this again last one so it's let's call it repeat number of times numbers are repeated starting with a fixed value fact the fact lot size last index is size minus one we need say minus 2 which is the second last so that's why we kept n minus 1 otherwise this will become invalid so for this we will additionally add a condition in the end that if result dot size is less than that then a result plus equal to 2 string digits zero so digit will digits and results are in sync so once we add a digit to a result we delete it from the digits vector similarly we update the factorial so if result size is n minus 1 then number of digits will be 1 only so we have to just append that date so this is the number of times each number will each digits will be repeated starting with a given value so we have to find what is the next digit that we have to fix so we are finding the range here so let us call it next digit so it's K divided by digits so here let's see the example when we are finding the ninth number 9th what is the number at 9th position which is this one so we have to see how many digits have passed let's say it was not 9 but let's say 12 13 14 15 let's say we wanted 15 element so we know that starting with 1 6 with 6 numbers are there starting with 2 6 numbers are there so in essence we are adding 6 until we exceed this K 15 so we added 6 still less than 15 again I had 6 still less than 15 again at 6 now it overshoots so we take one step back so how many times we have added 6 two times that means first and second digit are done we are in the third digit range so that's how we are calculating in which range it will lie so that is next digit and here there is a correction it should be minus 1 why let's again look at the example so if it's 15 what will wait 15 divided by 6 is 2 point something so it will be 2 so at index 2 what value will be there 0 1 2 so at index 2 30 that is 3 so we are in the range starting with three range and which is correct for three I have taken a new example to make it more general so we have come here but let's say we needed twelfth number so twelve y six will again be two so we will not take third digit that is three it's not in the third digit range but it's still in the two digit ring just the last one so what we will do k minus 1 divided by repeat so it will be 11 by or so if it's exactly divisible then we go one step back that is not third number but second number only last one of this so that's why we do K minus one to get rid of that border education are you so this will give us the index of digit to fix which will be appended to result from the available digits so this is the next week and next let's append it to result digits next digit so if there is some confusion here try to run through this example do a dry run write on a piece of paper that once this line is executed what is the value of result what is the value of repeat what is the value of the next digit and so on and what is the new K so it should be very clear and now what we need to do we need to delete this from the digits this digit is fixed appended to result so get rid of this digit occurring at this position next to it so we will do digits dot it is digit not begin which is the I traitor to the first element we add to it next digit so die traitor advances by next digit positions and removes this digit which we just included here and also our or digits size is one less so our factorial will also be one less so here we will remove the last one since we have one less digit so we have n minus 1 factorial ways of arranging them so we have to keep till n minus one only and not NS one so pop back it will remove the last one and next so once we know that we are in this range so here what we did once we know that we are in this range starting with two we subtract everything before it all the multiples of six so if we are here again we subtract two times six so that we know that in this range now we have to find the third one so for that we have to take modulo six whatever is the repeat size so new K is K modulo repeat and if it perfectly divides the edge case that I talked about let's say we wanted 12th number then we know that it's the last digit off in this one so in this case we will append this two and now with the remaining we know that we it's on the last one so it will be the largest number starting with two so starting with two we are arranging one three and four so smallest one will be 1 3 4 next one will be 3 1 4 or not it will be 1 4 3 we have to keep the most significant bit as small as possible in the beginning so 143 and similarly last one will be 2 is fixed so 4 3 1 the largest one starting with two so - we had appended starting with two so - we had appended starting with two so - we had appended so whatever is remaining digits and remaining digits are always in sorted order we started with 1 2 3 4 then we inserted 1 so we removed this so they are still sorted let's in next digit is 3 so we will insert it and remove it so still the remaining digits will be sorted since we are removing from in between so their ordering is not disturbed so what we have to do whatever the remaining digits start from end appended move to next previous appended again move to previous until you reach the first one and you stop so this is the condition here if K so if this case happens it will automatically amend append the remaining our digits and this result size will automatically become n so this condition will not be executed but let's say this did not happen and this loop exited because of result now holded n minus 1 values so we will come here and append large digit that is remaining and return it now let us run it into n vector it should be repeat not need that's why we kept repeat here it works Oh our answer is wrong here so let check why is it so we are getting all once it should not happen since we remove the digits once we appended to yield so we are not updating the digits so we have started initialized with 1 so everything is 1 so only 1 is present we should have added here also digits y equal to I plus 1 so first one will be a 1 next one should be 2 and here we are starting from 1 so due to zero-based indexing again I am so due to zero-based indexing again I am so due to zero-based indexing again I am adding plus 1 and this should also be I plus 1 so effect or real of one is one for next for 2 it should be 2 times 1 so let's run it again and this time it works so let's check the other example which is for 9 so this is also correct next let's take a case like for eight so it should be last digit of 2 so 2 4 3 1 2 1 4 3 ok he miscalculated so this is also correct so let's submit and the solution is accepted and here you see that we are right here the 100% and most of the right here the 100% and most of the right here the 100% and most of the people are here only so it takes zero millisecond so it's good in Java similarly you can replace these vectors with lists and do accordingly I will write it in Python we can write in one line so initialize with 1 times n similarly digits is 1 times n and get rid of this for I in range 1 to n minus 1 so this should remain as it is and here it's very simple to access the second last element just use negative index and here it's steer to convert append a digit or number to a string and here we will use pop it takes the position so next is the position pop at that position then we have to remove the last element so we can use slice and remove the last one and then this is valid so the solution is also accepted
Permutation Sequence
permutation-sequence
The set `[1, 2, 3, ..., n]` contains a total of `n!` unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for `n = 3`: 1. `"123 "` 2. `"132 "` 3. `"213 "` 4. `"231 "` 5. `"312 "` 6. `"321 "` Given `n` and `k`, return the `kth` permutation sequence. **Example 1:** **Input:** n = 3, k = 3 **Output:** "213" **Example 2:** **Input:** n = 4, k = 9 **Output:** "2314" **Example 3:** **Input:** n = 3, k = 1 **Output:** "123" **Constraints:** * `1 <= n <= 9` * `1 <= k <= n!`
null
Math,Recursion
Hard
31,46
261
hey guys it's offie1 here and today we're going to be solving graph Valley tree in this problem we're given n number of nodes that are labeled from 0 to n minus one so we're always going to be starting from node 0 and I think that's important to know and we're also giving a list of undirected edges and they want us to write a function to check whether these edges make up a valid tree so what is a valid tree while a tree has two properties and one it has no cycle and two it is connected so what do these mean exactly well no cycle that's pretty straightforward let's say we have three nodes we have a node up there node here and a node here this would be considered having no cycle because if we Traverse the tree we'll never end up in a loop but if we add an edge here if we start from here and to visit his neighbors we'll go down here and if you visit this guy's neighbors we'll go here and then eventually we end up back here and we end up in an infinite Loop so that's what having no cycle would mean this edge here cannot exist okay so what does connected mean well let's say we still had this tree here this is a valid tree well let's say we had one extra node just out here by itself this would mean that the tree is not connected and that would be an invalid tree however if you added an edge here this will still be a valid tree also I forgot to mention this undirected edges just means that the edges point to both ends so there's no specific direction that it's going to so we can go from this note to this node and also from this node to this node so here we've drawn the example from the problem and also I've written the ballot tree conditions so let's see if these edges give us a valid tree so first we have our edges zero to one so we're going to have zero and we're going to have our one note here and because it's an undirected graph the edge goes to both ends so we can go from one to zero and zero to one but I'm just going to draw them as a straight line just to keep it simple so our next Edge is going to be zero to two so we can draw a two note here and we can connect that to zero then we have zero three so now we're going to have a three note here and then our last Edge is going to be one to four so we're going to have a four node that is connected to one so just by looking at this let's see if you can see if it's a balanced tree while it is connected because every single node is connected to something and there are no side Cycles so as you can see we can go from zero to one and one to four and there's no Loop there if you go from zero to two no Loop and zero to three there's no Loop but if we had an edge right here connecting four to three then it would be a loop and this commission would not be met so it wouldn't be a valid Tree in that point also let's say we had a note 5 over here just by itself then it also wouldn't be a valid tree because this 5 is not conducted to any of these nodes over here so this can show not be met at that point so to meet this condition here we should be able to Traverse the tree and go through every single node just by starting at this point here or any point really since it's an undirected graph but let's just say we start at zero because that's the easiest one so if you can visit every node starting from zero then that means the graph is not connected so again if we had an extra note over here we would never be able to visit this node starting from zero because it's not connected to three so we can say if all nodes weren't visited then we can return false because it wouldn't be a valid tree and now where it gets tricky it's a second condition here because if you remember these are undirected meaning that we can go from one to zero and zero to one so let's say we start at zero and then we visit one well from one we're going to visit all the neighbors so we would visit four and we would visit zero and we will see that we already visited zero so we would think this is a cycle but that will be false so we have to take care of this somehow well that's actually not too hard all you have to do is keep track of whatever node we came from and not visit that node so what I mean is let's start from zero again let's say we go to one so if we're at one now we're gonna visit four and we're gonna see that zero is our parent so we don't want to visit that one again so what we can say down here is if our neighbor is our parent then we don't want to visit it so we can say don't visit or in other words we can say that if our neighbor is not our parent then we do want to visit okay but now how do we actually keep track of whether we have a cycle or not well this visit function here is actually going to be our DFS call and in our DFS call we're going to Mark our nodes as visited and the way we're going to keep track of that is by using a hash set so for example when we visit node 0 we're going to make a hash set and we're going to store our node 0 in there because that means we already visited it and then at that point we visit the neighbors so now we go to one and then one we would add it to our hash set and then we go to one's neighbors first we check if zero is the parent and it would be so we don't visit that and then we go to four or it's not on our hash set so we would add that and then we can see that four only has one neighbor and that's apparent so we would not visit that and then we pop back up to zero and we visit the next neighbor so now we would be visiting two and two is not on our hash set so we would add that in there and two has no neighbors so we pop back up to zero and then we would go to three and three is not on our hash set yet so we can add that so we can mark it as visited and at this point our DFS call is done because we would only do DFS or the node 0. and we already visited all of Zero's neighbors so that means there's nothing else to do and then at this point we would just return true that it is a valid tree and just to show you how the cycle detection Works let's draw an edge here and let's say that we're at three and we visit our neighbors from three so we will check zero but that's our parent so now I'll go to visit four and we see that four is in our hash set meaning that we already visited it at some point so that means this is a loop here and as you can see it is we can go from three to four to one to zero to three and then back to four so at that point we return false because it would be a cycle our time complexity for this algorithm would be o of V plus e where V is the number of nodes and E is the number of edges and our spaces are going to be the same thing so we're going to have o of V plus e because we need to store the graph the reason the time is O of V plus e is because we have to make the graph and Traverse it so now let's get into the code so to start I'm going to break up the problem into four different parts so first we're going to make the graph then we're going to populate the graph then we're going to do our DFS call where we check if it's a cycle and then we're going to call our DFS function so let's start first let's make the graph and to do that we just have to initialize and empty hashmap and then from here we can populate the hash map with every node so for I in range of n then we can do graph map at the key I is equal to an empty array for now because it could have multiple neighbors so that's why we're using an array next we're going to populate the graph and the way we're going to populate It Is by going through the edges so we're going to do for parent and child in edges we're just going to append these to the arrays so we're going to do graph map at the key pair it and then append the child to it and we're going to do the same thing but backwards because it's an undirectional graph so graph map at child and we're going to append the parent so at this point our graph is populated and now we can just call our DFS and like I said we're only going to call our DFS for the zero node so we're going to do if is cycle that's what I'm going to call it four zero and we can say the parent for this one is just zero it doesn't really matter where you put there as long as it's not an actual node you can put negative one if you want but I'm just going to use zero so if it is a cycle then that means it's not a valid graph so we return false okay so now all we need to do is Define our DFS function and before we do that we want to have a set to Mark our note just visited so we're going to have visited and it's going to be an empty set to begin with and then we're going to Define our DFS function so Define is cycle because we're looking for Cycles and we're going to pass in a child and a parent from here the DFS function can be broken down into three separate parts so if the first one is going to be our check conditions second is going to be our Mark is visited and the last is going to be called DFS okay so now we can start defining our function and the first thing we want to do is check conditions so what's our condition going to be well we know that if a node is in our visited set and we visit it again then that means we're in a loop so we can say if our child is in our visited set we can just return true because that means there's a cycle and then if it's not in our visited set then we can just add it to it so we can say visited dot add we're going to add our child and then from here we want to visit all the neighbors for the child node so we want to do for every neighbor in our map for the key are of a child then we want to check if our neighbor is equal to our parent then that means we don't want to visit that because that would give us a false positive so we can just skip this for Loop if it is our neighbor and then next we can just run our DFS for our neighbor so we can do if is cycle for our neighbor node and now our child becomes apparent if that returns true then that means there is a cycle for the neighbor which means there's a cycle in the whole graph which means it's not valid so we can just return true here and then if you make it past this for Loop then that means there is no cycle so we can just return false and then at the end here if there is no cycle we can return if n is equal to the length of our visited set because our visited set should have every single node and N tells us how many nodes there are so these two should be equal and this should work so as you can see this code is pretty efficient and now I'll go through the code manually so here I've drawn another example and I've made the graph already here just to save some time so the part for this is complete and properly in the graph is also complete so now if we look at our node 0 and our hash map we see that the neighbor is one and that's correct and then for one the neighbors are 0 2 3 and 4 so that's correct as well and as you can see we have a cycle here that we should be able to detect with this code so now let's see so we're going to have our initial visited set which is empty and to mark them as visited I'm just going to check them off just to take some space so now we're going to call our DFS function so we're going to start at node zero so we see that node 0 is not on our visited set yet so we're going to mark it as true so I'm going to check that off and now we want to visit every neighbor for zero and the only neighbor is one so now we go to one we haven't visited one yet so we can just Mark that as visited now and then we're gonna call DFS for all the names in one so our first name is going to be zero but as we know zero is the parent so it meets this condition so we skip the for Loop for that and now we go to the next neighbor which is two and for two is not our parent so we're gonna do this if statement here and we're gonna do our recursive call so we're going to do is cycle for our neighbor which is two and our child was currently one so now our child is equal to two and our parent is one well let's see is our child visited yet no so the market is visited and then we go through every neighbor in two the first neighbor is going to be one and we see that's our parent so we can just skip the for Loop for that and then our next neighbor is going to be three so now we check if three gives us a cycle so our neighbor is going to be three and our child is going to be two so now we check if three is in our visited set and it's not it'll be Market is visited and then we go through every neighbor in three and our first neighbor is going to be two but two is our parents so we can just skip the for Loop for that and now we are at one so now we see if one gives the cycle so now our is cycle function is going to be one for the neighbor and three for the child so let's replace this one and then three and now we check if our child has been visited yet and it has because we have this green check mark here and at this point would return true for this function we'll return true here and that gives us a true statement here for this if statement and then for the overall function we return a false meaning there is a cycle and that is correct if this video helped in any way please leave a like And subscribe thanks for watching and I'll see you in the next video
Graph Valid Tree
graph-valid-tree
You have a graph of `n` nodes labeled from `0` to `n - 1`. You are given an integer n and a list of `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edge between nodes `ai` and `bi` in the graph. Return `true` _if the edges of the given graph make up a valid tree, and_ `false` _otherwise_. **Example 1:** **Input:** n = 5, edges = \[\[0,1\],\[0,2\],\[0,3\],\[1,4\]\] **Output:** true **Example 2:** **Input:** n = 5, edges = \[\[0,1\],\[1,2\],\[2,3\],\[1,3\],\[1,4\]\] **Output:** false **Constraints:** * `1 <= n <= 2000` * `0 <= edges.length <= 5000` * `edges[i].length == 2` * `0 <= ai, bi < n` * `ai != bi` * There are no self-loops or repeated edges.
Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return? Is this case a valid tree? According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”
Depth-First Search,Breadth-First Search,Union Find,Graph
Medium
207,323,871
791
um hello so today we are going to do this problem which is part of Le code da challenge custom sort string so basically we get two strings we get order and we get string s and all characters in order are unique um and they were sorted in a custom order and what we want is to sort s in the same order as the string order okay um so basically what that means is if a string let's say if B occurs before a in order then we want to sort s so that b also occurs before a that's essentially what it means now two things s can contain a letter that doesn't exist in order so that like d and in that case we just need to put it at the end of the string for our sorting like we did here the other thing is you could have multiple occurences in s you can't have it in order but you can have it in s so you can have a maybe three b's and then c d for example now in this case for the Sorting you would have c b a c b three times and then a two times and then d right and then C D right so basically if you have the same letter as long as you respect the order when the character occurs you can put all the same occurrences together now you could also have a in a it can be a b a right CD in that case what we would do also is CB a c CB a d right so that's just a clarification there now if you look at the constant uh the string itself is not too big uh s is 200 and the order uh length is 26 because we have only lower case English letters so definitely an OV Square solution an OV lagin solution should work um so let's think how we can do this um well we just need to sort but when we are sorting we need to make sure let's go for example here okay so let's say we have this order string and then we have this is order and then we have S which would be this okay so let's write down just the indices here so here 0 one two these are the indices okay so basically what this means is for every letters in s we need to just sort by the indices right because if since C has an index that is smaller than a c has to be before a and since B has an index smaller than a it has to be before a in the sort right so if we sort by this here for example and of course we ignore D because it's not in the order for now um then what would get well C is the smallest in the indices so put C first B is the next smallest a is the next smallest so we have this and then we can add whatever is not in order at the end and that's exactly what we have so that's the key idea basically sort by index sort s by index in order then add up um add up uh characters that are not in order but there is another way to do this for characters that are not in order how do we just add them to the end well it doesn't matter the order they are in so let's say we have x w why it doesn't matter the order we add these in any order would be valid since they are not in order and the problem here says return any permutation that satisfies the custom order so what this means basically is we can just give them all the same um index the same basically index in terms of this here and then have them um be sorted in basically whatever order we don't care um and so what index do we need to give them well we don't want to give them any index that is smaller than index of something that occurs in order because that then that will mess up the order but we can give them anything at the end so we can just give them the length of order so the last basically like three which doesn't exist here so they will always be at the end okay and that's pretty much to the idea here so let's C it up so what we need is um we need to let's call our function custom order right and so it gets character C what's the order well we said we want to get the index of the character if the character is in order if not we want to give it as an as a an index the length of the order okay and then we can just sort s using this custom order right and now this will give us a list and so we will need to join it with just empty string to get a B to get a back a string so we can just do something like this okay and that should be it so if we on this submit it looks good okay now another way we can do this is if you don't want to do the index function which is oen uh to make the to make this function of one what you can do is use a map from the character to the index in order so let's say order map order index let's call it and let's have the character map to the index for this in the enumeration of order okay now in this case what do how do we get the index well we can just say order index and get um we can get C right but get also has a default so if it's not in our map like this then we can return a default value and so that's what we can do here we can return this as default if it's not there so like this okay uh looks like there's a problem let's see oh this needs to be defined okay looks good um now this function is actually pretty simple so we can just add it here as a Lambda so we can do Lambda C like that get rid of this and this should be it submit and that passes okay now in terms of time complexity this is of this is all of n uh of the length of order let's call that o of n um and this here if we call M the length of s this would be so this is actually will end up being constant because order is up to 26 only okay so this is constant this is O of n Lin let's actually consider n the length of s so this is over Lin this look up here is constant so this is over l again um and the joint is over so overall this is over lag in time and constant space um not constant space because we are using this extra array so open space um but overall time is over laging so can we do something that is not over L something maybe of n uh solution we actually can so let's see how we can do it so what we can do is we can first just get the count counter of occurrences in s okay so what that means is something like we would have for S equal to this we would have an occurrence of s which would just say how many times each character occurs so a one time B one time c one time d one time okay now how do we get these to be in the order in the same order as the string order well we can actually just create a string uh let's call just a list of the characters and we can just go through order okay and we can check if this character so this would be will go through order in the order it is in so it goes through C first B then a then for each of these we check how many occurrences it has in this occurrence and for the number of that it's there we just add that to our list so for example here we will add the occurrence of s for that character we will add it the number of time it Ur So for example let's say if it was two here we will add it would add eight two times and we do this in the order in the custom order and so for example here we'll add C first we how many times it see occurs just once let's add it so it would be sorted just by the way we are constructing it would be sorted in the same order as the string order okay now once we do that we used it so we set it to zero why do we do this well because remember the D here which is not in order we want that the we want only those that are not in order to still remain with a count so that we can add them again so first we process those in order and then we process those that are not and how do you do that well since we put those in order here at equal to zero it's whatever is remaining in occurrence of s and so we can just go through those so we can just go through every string in and we can just add it now for those that are not in s not in the occurrence anymore that's because we set them to zero so this will be zero so we don't need to care they won't be added again and now this contains the list and we can just join it like here and return it okay so that's the idea here just keep track of the counter go through order in its just in its one by one and add as the characters occur in this string and then for the remaining ones that we haven't added yet because they were not here we just add them yeah um so let's put that back up here um and now we can just join this like that it should work let's run um looks like we have a problem because this is not valid um yeah we also need to Define the occurrence which would be just um the counter of s okay and we can submit and this passes okay um yeah so that's pretty much it for this problem thanks for watching and see you on the next one bye
Custom Sort String
split-bst
You are given two strings order and s. All the characters of `order` are **unique** and were sorted in some custom order previously. Permute the characters of `s` so that they match the order that `order` was sorted. More specifically, if a character `x` occurs before a character `y` in `order`, then `x` should occur before `y` in the permuted string. Return _any permutation of_ `s` _that satisfies this property_. **Example 1:** **Input:** order = "cba ", s = "abcd " **Output:** "cbad " **Explanation:** "a ", "b ", "c " appear in order, so the order of "a ", "b ", "c " should be "c ", "b ", and "a ". Since "d " does not appear in order, it can be at any position in the returned string. "dcba ", "cdba ", "cbda " are also valid outputs. **Example 2:** **Input:** order = "cbafg ", s = "abcd " **Output:** "cbad " **Constraints:** * `1 <= order.length <= 26` * `1 <= s.length <= 200` * `order` and `s` consist of lowercase English letters. * All the characters of `order` are **unique**.
Use recursion. If root.val <= V, you split root.right into two halves, then join it's left half back on root.right.
Tree,Binary Search Tree,Recursion,Binary Tree
Medium
450
498
Loot Time Se Absolutely Challenge Squashed Traversal Difficult Question Remedy Christmas Who Made Clear Hai 100 Subscribe Now To Receive New Updates Element Amazing Click Subscribe Button And Click Subscribe Button On This Side That Sudhir Gautam Se Is Ayub Returned To Meet Again Have And Using Department Research Now Highlighted The Truth And Kollam Sir Sudheer Vats And Bigger Call Centers In The Midst Travels Through Subscribe 560 Knowledge CPI(M) Travels Through Subscribe 560 Knowledge CPI(M) Travels Through Subscribe 560 Knowledge CPI(M) Midding Vinoba Subscribe Button Shravan Ko To You - - Shravan Ko To You - - Shravan Ko To You - - Diner Production Row - - Column Plus Diner Production Row - - Column Plus Diner Production Row - - Column Plus Request You Are Giving Of Urinating Volume Decrease Do And Wherever You Get No Money Do Subscribe Plus And Minus 200 Column - - This What They Want Right Now 200 Column - - This What They Want Right Now 200 Column - - This What They Want Right Now Algorithm President and Tennis Academy Ne to Take Care of But That in the Boundaries Here and Her Soul Will Win Co-operative Law and Her Soul Will Win Co-operative Law and Her Soul Will Win Co-operative Law Secretary According The algorithm in this award is discussed with respect to download wave fighting subscribe button new cars adb school number 90 that it has no case and want to give a new ringtone new events with name transport1 and two corner cases fog will simply user will create new arm rest in it Answer And 13 Number First Mission Also Answer Bollywood Exactly To The Number First Meter Centimeter Chart Means And Came Into One Should Define Two Variables Row And Column For Effecting The Video then I Want A Place That Right Side Reaction Is Difficult-2 M*N I C Plus Is Difficult-2 M*N I C Plus Is Difficult-2 M*N I C Plus Is Plus And Tennis Of I Request To The Element Art Reason Ruk Volume Index Send According To Dengue 10 On Fuel Checkpoint Ro Plus To Olympic Champion To In Cases Equal 2018 Minute Even You Want You Can Do China I Sump That Sleep Upwards That Laterite Soil and Updates Rome of Means - - Column Plus Rome of Means - - Column Plus Rome of Means - - Column Plus A Slightly Gauri Shankar Them Know What Does It Means That Film Is Equal To The Effigy Blast Column Day Yearly Guddu Pimental And Otherwise System Gang Will Increase In The Column Plus Otherwise Will Obey His Logic Pro X Minus Plus And Bells What Do It Is The Case Main Pot Song Ki Neend Download Par Ho Download That Faraday Boundary Condition Vaikunth Ki Rohit Ko Sudhar Last Row In The Words They Do Feeling's Monday Column Ki A Press Latest Post Column In What Will do these quintillion apps download means a pro plus call - - the a pro plus call - - the a pro plus call - - the final simply return paper answer key mein aaye ho time uthakar kya chale mein jo front arm ki i think it monitor matching and was last updated on hain akshar dead over time complexity of Algorithm You Are Travels Singh Faujdar Limit Points Suzy Time Complexity Word Equal To An Airplane Mode Of Came Into And What Is Peace Complexity And Game Same Ecological Using And If This Singh Anil Minta Narayan Prem Sai Is So Difficult Is Ball Se Thanks For Watching Video
Diagonal Traverse
diagonal-traverse
Given an `m x n` matrix `mat`, return _an array of all the elements of the array in a diagonal order_. **Example 1:** **Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[1,2,4,7,5,3,6,8,9\] **Example 2:** **Input:** mat = \[\[1,2\],\[3,4\]\] **Output:** \[1,2,3,4\] **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 104` * `1 <= m * n <= 104` * `-105 <= mat[i][j] <= 105`
null
Array,Matrix,Simulation
Medium
2197
1,769
hello everybody today we will focus on solving the lead code problem 1769 minimum number of operations to move all balls to each box and you can read the question from here but i try to explain that question with the illustration i made some drawing here we are given binary string the length of the string give us the number of the boxes and the numbers or the numbers of the string give us that whether that box has ball or not let's look at the example our binary string is one zero the length of the string is three because of that we have the three boxes the first index is one box number one has one ball second index is one box number has one ball the third index is or the third character is zero the third box don't uh doesn't have any ball and the quest the problem is that we need to just calculate the minimum operation to bring the books for balls for each boxes what's mean that it's mean that let's start from box number one and we are inside the box number one and we'll bring the ball from the other boxes and like that to bring and actually i first of all before this i would like to explain the operation what's the mean of the operation means that to bring one ball from or from one box to the other one for instance if you want to bring this ball box num forum box number two to box number one we need one operation yeah and uh what's to make some illustration or to explain better let's start from box number one we will bring the other box we will bring the balls from the other boxes firstly we to bring the ball from box number two we need one operation box number three don't have any ball because of that we type here one same for box number two box number three don't have any ball box number one has one ball to bring that ball to box number two we need one operation and we are inside the third box right now to bring that ball from box number two we need one operation and to bring the ball from box number one we need two operation one and one totally three operation and we need to return our result as a list yeah that's the explanation and how did i solve that problem i have used the brute force method and yeah firstly i have checked that whether which boxes i am right now and if the boxes um if the box or if the box has ball or not and after that if the box has ball i subtracted the indexes for instance currently i'm the at the first or the box number one the index number is zero and to bring that box from uh to bring the ball from box number two i have a hair mixer only subtraction actually that um the first box index zero the second box index is one uh minus 0 is 1 and it shows us the number of the operation we type the code actually then we can look that as i said i have used the brute force methods firstly i have to find the list empty list so i am at least quarters and i mean i made the first iteration for i in range land boxes second iteration for j in range boxes here i have a condition as i said i uh took i checked that what uh which box i am right now and the second condition is that whether that box has ball or not um and if i is not equal to j and sorry and boxes j is not equal to zero and then new value plus is equal to subtractions i appends new file and at the end of the outer loop return empty list i think everything is okay right and let's submit that yeah it has been accepted i would like to emphasize one more time here i check that which box i am right now because i don't consider the balls which i'm in right now and here i check that whether the box has ball or not if the box don't uh doesn't have ball then i don't need to consider that box also here actually i calculate the operations indexes i make some i subtract instead indexes and i sum up all of the indexes and at the end of the first loop i append that to my empty list at the end of the other loop i am i return that list to the uh the response actually yeah um i hope that you understood the problem and thank you very much for your watching this video if you have any problem please comment bye
Minimum Number of Operations to Move All Balls to Each Box
get-maximum-in-generated-array
You have `n` boxes. You are given a binary string `boxes` of length `n`, where `boxes[i]` is `'0'` if the `ith` box is **empty**, and `'1'` if it contains **one** ball. In one operation, you can move **one** ball from a box to an adjacent box. Box `i` is adjacent to box `j` if `abs(i - j) == 1`. Note that after doing so, there may be more than one ball in some boxes. Return an array `answer` of size `n`, where `answer[i]` is the **minimum** number of operations needed to move all the balls to the `ith` box. Each `answer[i]` is calculated considering the **initial** state of the boxes. **Example 1:** **Input:** boxes = "110 " **Output:** \[1,1,3\] **Explanation:** The answer for each box is as follows: 1) First box: you will have to move one ball from the second box to the first box in one operation. 2) Second box: you will have to move one ball from the first box to the second box in one operation. 3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation. **Example 2:** **Input:** boxes = "001011 " **Output:** \[11,8,5,4,3,4\] **Constraints:** * `n == boxes.length` * `1 <= n <= 2000` * `boxes[i]` is either `'0'` or `'1'`.
Try generating the array. Make sure not to fall in the base case of 0.
Array,Dynamic Programming,Simulation
Easy
null
1,318
I'm back with another problem from lead curve the number thirteen eighteen minimum flips to make or B equal to C so we are given with three numbers a and B a B and C so the problem is a are B equal to C so that is what we need to carry out and we need to identify how many bits that we need to change so essentially let's try to understand an or operation right so our operation is like this so if a bit is one from one number and another bit is also from one another number right so then it will be 1 and the second case is if either of them is one from one number right the R is one again so right so these are the operations where we get 1 so if you have both numbers or both bits are 1 which get 1 or any of the numbers is 1 we get 1 but if both numbers are 0 right then only we get a 0 all right so that's that is essentially the our operation so in the given example right so the given example 2 6 &amp; 5 right so the given example 2 6 &amp; 5 right so the given example 2 6 &amp; 5 if we convert to into binary that is 0 1 0 and the second one number B 0 1 0 so C is 0 1 so that is 5 right so essentially if you do an hour operations between NZ it is expecting C but how many bits we need to change the question how many flips that we need to make so we need to do a kind of reverse engineering so in the last bit there is least significant bit right in see it is one but in a and B they are zeros so from our logic right if in order to get a 1 it can be any of those bits can be 1 right so right now these two bits are 0 we could flip either one or two of them to be one but since we are looking for a minimum number of literate so this is the minimum number of flips so it's enough for us to flip one bit or one of them basically so here we could change this bit to one that's what is shown here that is this one we are only working on the least significant bit right now right so that means the flip count is one now if we go to the second that is second least significant bit right so both of them are once but we are expecting as 0 from our definition of our if we want to get a 0 right both number should be zeros right so in this case since both are 1 we can't get a 0 with that so we need to flip both bits so that means for if you flip 1 to 0 the count of flips is 2 and if you flip this one also to the 0 the count of flips becomes 3 so for this significant bit if we change to 1 and this significant bit we change to so total number of flips are 3 now as of now and for this 0 or 1 its 1 so we don't need to change any bits 0 or 0 so we don't change any bits so for this problem right when a is equal to B is equal to 6 C is equal to 5 the number of bits that we need to change or flip are 3 right so it goes so it's a simple problem let's go look at the logic how you're going to solve it so the first thing what we are going to do is convert the numbers into binary just like in our example right two is converted into binary that became zero one zero B is six that can become 0 1 0 C is 5 0 1 0 so we first convert them into binary the second step that we need to do is we need to make sure the length of the converted numbers are same for example if you convert to write to do binary the actual is 2 is equal to 1 0 in binary right but whereas 5 is equal to 1 0 1 right and whereas 6 is equal to 1 right so this is how it is actually but they are not of equal length for this purpose what we are going to do is we are going to make them equal in length so what we can do it just prepend 0 here right so even if you put 0 the value still remains the same so we can prepend any number of zeros so that way we can make the same length right so now there are same length just like as shown in the example so here he has to added one more extra 0 which is not required at least for this case if one of the number was like 8 right let's say if this was Kate right 8 is 1 0 so in this case right to make all of them of same length we should put a 0 here and a 0 here now all of them are similar so essentially what we're trying to say is make them same whatever the numbers that you get a B and C after you convert them - binary and then by comparing the - binary and then by comparing the - binary and then by comparing the number see in each bit right for each Briton see compare the bits in a and B if both of them are once and if your answer bit is also wonder we don't need to change anything but if the both of them are wants thought your answer bit is zero just like we saw in the previous case right so here both of them are ones but we are expecting a zero in that case there are two flips needed so that's what we did so likewise we will have to continue from the for each bit position so once we do that we will need to calculate the number of flips let's go look at the core so here these are essentially converting a B and C into the binary format so once we put the binary format right into a1 b1 and c1 these are strings basically what we're going to do is calculate the max length right calculate the max length with this once we know the max length we need to add the extra zeros for each of these numbers right so 4 from the max length subtract the length of the a1 and a prepend that many zeros right for b1 also prepend that many zeros / co for b1 also prepend that many zeros / co for b1 also prepend that many zeros / co and also prevent that many zeros so in the previous example that what we saw is 0 is it 0 is essentially 1 0 right and 5 is 1 0 1 4 8 is 1 so the left here is for the length here is 3 for the length here is 2 so here for - the length here is 2 so here for - the length here is 2 so here for - the maximum of 2 3 &amp; 4 is the maximum of 2 3 &amp; 4 is the maximum of 2 3 &amp; 4 is the maximum of 2 3 &amp; 4 is 4 right now what we are going to &amp; 4 is 4 right now what we are going to &amp; 4 is 4 right now what we are going to do is for number 2 we are going to do two zeros prepared so that's what we are one tonight this will become 0 and this will there is no need to append anything so this is 4 and 4 that will happen to 0 that means that's it so now they're all of equal lengths so that is what we are doing here I wrote a simple prepend zeros special function which does the same thing basically right so now while going from each bit location right so we'll have to compare each bit location and or it and compare with the answer so that's what this Court will do it so we are going from the first index tilde max length that is a in our example it is 4 right maximum so if at all see that is C the answer bit is 1 and both of them are zeros that is when we need to flip there are only two cases where we need to flip so there's this is one case if we are expecting a one but both the bits in a and B are 0 that is when you need to flip at least to one of the bed right because as for the our definition if any of those bits are one you get the answer one so we are going to increment the defect by one that is one first case and the second case is if you are expecting see the vacancy is 0 and if any of them are wrong right that is another case right because to get a 0 you need both bits to be zeros right so if at all each bit is 1 we need to up we need to increase the count dick bits if B's bit is also 1 we need to increase it so likewise we calculate the diff it's and then finally we increase the index so we go from zero at index 1 2 3 4 and so on finally once we end the numbers right we return the debits so basically this is a simple logic that we are doing this is an accepted solution basically ok thanks for watching viewers we'll come back with another video very soon thank you please subscribe and share among your friends if you like this video thank you
Minimum Flips to Make a OR b Equal to c
tournament-winners
Given 3 positives numbers `a`, `b` and `c`. Return the minimum flips required in some bits of `a` and `b` to make ( `a` OR `b` == `c` ). (bitwise OR operation). Flip operation consists of change **any** single bit 1 to 0 or change the bit 0 to 1 in their binary representation. **Example 1:** **Input:** a = 2, b = 6, c = 5 **Output:** 3 **Explanation:** After flips a = 1 , b = 4 , c = 5 such that (`a` OR `b` == `c`) **Example 2:** **Input:** a = 4, b = 2, c = 7 **Output:** 1 **Example 3:** **Input:** a = 1, b = 2, c = 3 **Output:** 0 **Constraints:** * `1 <= a <= 10^9` * `1 <= b <= 10^9` * `1 <= c <= 10^9`
null
Database
Hard
null
133
hi friends welcome to today's video on our graph series I am chimney a software engineer at Microsoft Dublin Ireland today we'll be solving another medium question from leadco titled clone graph I'll start by reading the question pointing out exactly what the question requires from us I would then explain my proposed solution using a studio code so you can implement this solution using any language of your choice and get the same results also I'll implement this solution in JavaScript and explain the time and space complexity of the solution all right let's get started the question reads giving a reference of a node in a connected undirected graph return a deep copy clone of the graph each node in the graph contains a value int and a list of its neighbors test case formats for Simplicity each note's value is the same as the notes index for example the first node with value one the second node with value 2 and so on the graph is represented in the test case using an adjacency list is a collection of on ordered lists used to represent a finite graph each list describes the set of neighbors of a node in the graph the given node will always be the first node with value one you must return the copy of the given node as a reference to the cloned graph constraints the number of notes in the graph is in the range of 0 to 100. one less than or equal to no dot value less than or equal to 100. note that value is unique for each node there are no repeated edges and no self Loops in the graph is connected and all nodes can be visited starting from the given node all right as the title suggests the question can be easily identified as a graph problem and it's important to note from the given constraints that the graph is connected which means that you can visit all nodes From Any Given node and the graph is also undirected which means that the edges indicate a two-way means that the edges indicate a two-way means that the edges indicate a two-way relationship to learn more about this check out my video on graph data structure in this question we are given a class representing a node in a graph the class contains the notes value which is an integer and its neighbors which is a list of all its edges that is a list of all its adjacent nodes similar to our previous video titled or path from source to Target we also do not need to create an adjacency list since the given node is an instance of the class that contains the notes value and a list of all its adjacent nodes and each adjacent node is also an instance of a colors containing the notes value and a list of all its adjacent nodes making the creation of an adjacency list redundant if you want to learn more about adjacency lists and how they are created please check out my video on graph data structure the question requires us to create the graph and we can achieve this by simply traversing the graph and at each node create a copy of this node and save the node and its copy as key and value respectively in a map we will use recursion to solve this problem you can use breakfast search if you wish understanding graph traversal is crucial for solving any graph algorithm problem and I cannot emphasize this enough check out my video on graph traversal where I provided a detailed explanation on depth for search breakfast search and recursion so solving this using Studio code given that our function takes a node as inputs the first thing we will do is to check if this node is null and if it is null we will return null because null is a clone of null next we will create a map to store the newly created node copies using the old notes as keys and the new notes as values this will allow us to retrieve any cloned node from the map with constant time complexity we then create our recursive function taking an input of current node in the recursive function we will check if the current node has been created in the map if it has been created we exit the function else we create a clone of this node by instantiating a node class with the current notes value and assign it to a variable clone node then set this newly created clone node as the value of the current node in the map let's assign the neighbor list of this current node to a variable neighbors and look through these Neighbors on each level we will call our recursive function on it after the recursive function has run for the current level we can be sure that a clone of it would exist in the map since the recursive function creates a clone of a node if it does not exist yet so at this point we can retrieve this clone copy of the neighbor node from the map and assign it to a variable clone level now we will push this clone level into the neighbors list of the Clone node we just finished defining our recursive function the next thing is for us to call this recursive function with the given node and finally at the end of the function we return the value retrieved from the map using the given node as the key as this will be the cloned version of the given node great let's implement this in JavaScript I will now delete the studio code the first thing is if the given node is null return null creates map to store our cloned nodes Define our recursive function if the node already exists in map return else create a clone of the current node and assign it to a variable clone node set the current node in the map with the cloned node as its value assign the current notes neighbors to a variable Neighbors use a for Loop to Loop through these levels call the recursive function on each level retrieve the clone of this neighbor from the map and push it into the neighbors list of the Clone node call the recursive function with the given node and finally return the value of the given node in the map let's run and submit the code great job let's talk about the time and space complexity of the solution the time complexity of our solution is O of n plus e where n is the number of nodes in the graph and E is the number of edges this is because the function uses a depth for such algorithm to Traverse the graph which visits each node and each Edge exactly once the space complexity of our solution is also o of n plus e because it uses a map to keep track of the cloned notes and their corresponding original notes which takes up o of n space the recursive function also uses the call stack to keep track of the nodes being visited which takes up all of e space since there can be at most irrecursive calls on the stack at any time overall this solution has a time and space complexity of O of n plus e thank you for watching till the end if this video was helpful please give it a thumbs up and hit the Subscribe button to see more videos like this in the future if you want me to solve any specific graph problem leave me a comment in the comment section and I will add it to my list of videos to create thanks again for sticking to the end see you in my next video bye
Clone Graph
clone-graph
Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph. Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph. Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors. class Node { public int val; public List neighbors; } **Test case format:** For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list. **An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph. The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph. **Example 1:** **Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\] **Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\] **Explanation:** There are 4 nodes in the graph. 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). **Example 2:** **Input:** adjList = \[\[\]\] **Output:** \[\[\]\] **Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors. **Example 3:** **Input:** adjList = \[\] **Output:** \[\] **Explanation:** This an empty graph, it does not have any nodes. **Constraints:** * The number of nodes in the graph is in the range `[0, 100]`. * `1 <= Node.val <= 100` * `Node.val` is unique for each node. * There are no repeated edges and no self-loops in the graph. * The Graph is connected and all nodes can be visited starting from the given node.
null
Hash Table,Depth-First Search,Breadth-First Search,Graph
Medium
138,1624,1634
390
cool 29 League in amination game there is a list of sordid integers from 1 to n starting from left to right we moved the first number and every other number until you reach the end after this we please repeat the previous step again but this time from right to left we move the rightmost number and every other number from the remaining numbers you can keep the stuffed again alternating left to right and right to leaven to a single number remains fine to last number that remains on a list of length n uh ok like this is well kind of think a little bit because I feel like there's some what is N and I wish they tell you and then maybe it's slightly easier though I imagine it's not and square out and squares and log n right like if you just simulate this you know be n log n because you only have log n steps is that fast enough for this and I think that's my question then I get is fast for it instead of like less than human I don't know like a hundred thousand something way he moves all the art numbers and we or the power of two's for whatever reason it's not true I think right now I mean I definitely could write the proof for us I don't know if it's fast enough anyway but just try to see if I could think about a cuter way let's say there's a ten ended and ten you would remove ten six to instead of four and eight so the parity is a little different so we could do the math so you don't give it that you don't have to necessarily look the backwards just do the parity based on the number of array elements on the second world whether it in a maze the first element where the side Phuket is anything when this is done mark n so that is it really necessary to do more than simulation I was just a little bit of a mistake just give me the bounce I guess that's why and so but it stands being clever word that we could to mmm sex maybe hour so you'd ever don't have any heart numbers okay so I mean you can think about it as I think you could do a bitwise on this one actually so you could doing login maybe don't hold me do that one yet so okay so first of all we remove all the bits or all the possible numbers where the white mode number is zero oh sorry the rightmost digit right most digit is 1 which means just another way of saying if it's odd so ok last you go to you and then I'm just finding it I'm I don't think this is to what I'm doing but I'm just kind of writing my darts out in code form and then if there are odd numbers of numbers love there are numbers of number left and we actually move the last bit and there's even number numbers left we move every second number which is so then the second pit has to be zero expired we'd lose it then the third one you remove that again with the last bit of thing okay and the second most abundant is a little tricky for me goodbye I said was I prefer so I gave all you even numbers so yeah turned so yup that it's the easy bit wise thing to you go out well just start the second digit has to be one good enough it's like a mutual what's ten that's time but if tide state and we would have get him laid all the ones where them okay I think I have some idea but I feel like I sure yeah so that's a view you may want to add so we divide everything by two so just one two three four really except for now we have to decide whether we skip the first one or not to get the first one so okay if it's given number then stitch it has to be zero okay so then that and then now you move kind of cancer yeah okay I think I've died here I don't know if I could explain it very well but then if this is five no one but because it's hard you remove all the ones so you know that the second digit has to be yeah then you know the second it has to be 1 this is the case then the second it has to be easier you know now then the second it has to be 1 well if 5 is here then the second digit has to be 0 ok so ok I think I have some idea yeah well playing around with another first okay so well that's it I'm skip it and see if digit is even then we just take away order once word I so then I'm is the last digit is 3 okay then and we don't do anything really you just go to the next digit okay fine not very good have to do more stuff but do nothing for now for parsing else it is in wonder advance what even well even I'm aware you go backwards and then now it matters where let's call this brown actually confuse myself because confusion it's hard otherwise is because if the mathematical version okay backwards is if it's otherwise I guess if and go back to this even if it's even you then the last digit is also a zero so one two five no yeah then it's a one this is such a mess okay so it's a bun then could well have been that digit otherwise nothing happened together so you is that good don't worry about it I'll print some stuff up not copied about it but okay which means 101 in the one digit if and only if I'm I don't take the case where there's only one number left so let's see maybe what an annoying file there's nothing interesting about it I think like nothing I wear a good ad like we've made algorithmically interesting is just not a good checking my cases what it is it's just like I feel like this like weird like I'd might not percent certain things in the right way that's - just things in the right way that's - just things in the right way that's - just now 9 is a good case though you're like okay so first rate so the last teacher has to be zero that's binary that has to be zero this means the second-to-last be zero this means the second-to-last be zero this means the second-to-last teacher has to be we know what I'm saying anymore has to be one and then the last entry has to be zero now the drastic it has to be okay because that this is the case and we wanted and we want to keep the coin so passage it is one okay and now we go to the third digit where it is 0-1 responding so they actually get suing one messed up town pretend you eliminate or the odd ones wait well the died one time the last if anyone said you may be up to do some another coin flip okay maybe that's why I got confused I don't see just Stinson always be alternating so you maybe you have to keep track of and then it keeps the bond because it is the first number you know that's I but then I that's not uh not technically out anymore just that the third digit is thought it's you know but I'm and it's just work stuff to keep track of how it isn't medium maybe there's a easy an explanation and I'm just like doing it's silly or yeah you just put for us yeah at the end just brute force can tell me just tell me guys just put force and I've been like waiting all this time for no reason but I know that the first ticket is zero in step one because it's based off the last one so I am not articulating that much with this project problem because there's a lot of just me thinking about it at the time but articulate it's just how do I know that this is still in there then it could be snowing one but then the first ticket is zero instead of one because we do too if this is ten and we have five numbers then what happens then you have ten and $100 which I guess in that have ten and $100 which I guess in that have ten and $100 which I guess in that case which means this guys have fallen late you know this is divided by four ready and it eliminates the first one but in this case the first the last digit would be one and not zero so I feel like the problem is also like I feel like I'm just gonna end up like guessing it and seeing the works I think that's why I don't like this farm at all and that's a pretty intuitive way that I'm just not thinking about it - it's tough you always will look the - it's tough you always will look the - it's tough you always will look the first one how do we know what's in it well okay because if the last one is an odd number and you have already eliminated some kind of there's like some kind of mathematical induction thing that I'm not like doing it right yeah I mean it definitely is a loggin thing but have them have to be in powers or like yeah it has to be in powers of two which is why we you know have some blog entry but it matters where whether you're taking the first one or not sorry I'm taking it well at all but yeah there's definitely some parity thing that I feel like I have to kind of keep track of that we obtained the more okay well he says another number if they cut a little bit sense what is too small and then a flash for look you want to dip it see what my mother mad things should be why yeah but I think the tricky thing is that like if you look at n is equal to 10 and you actually get something completely different yeah I mean that's what I'm trying to do it's just that it's very annoying to get it right and that's essentially what I do with the my two here yeah but in some like order to kind of I don't know maybe I should I prove foster a little bit in the sense that I should have looked at more example but I mean I have some sort of that idea I just don't know how to get it condemned a20 what are my states if I did that I print out stuff I wonder nine move out three or four knowing that the first one the second digit is could be a one time is my third ball not counting right round cuz maybe this is and maybe another way to think about it is whether the first number has a zero one and then eliminate all the ones that are the same as the first number so okay first I'm going oh that's actually somehow the first sorry and in the second world well you know that the first number has of one good and we don't eliminate it I think there's some like state project thing that so that first that's the first ball to first come always have a one no just in this case yes I see were the only because being eliminated so if pass one we and I need to use the bathroom memory of it so this is the first we're in the second where first number who have C that's not true Oh man is just important I think one thing that maybe should have done I could still do it's kind of like the brute force solution and then kind of generate and then just to kind of help me visualize just a little bit more I feel like I don't need anymore but I think that's what I could have done a little bit but here if it's even number on it there's only matters on maybe I need to take these two together and figure out what that means like take them in set of two oh my math is not strong enough for this but myself backwards all right I think it's I think I'm gonna buy track it's just that I don't know about keeping track of enough states or even my states are correct I think there's some kind of like you could probably do this to some kind of finite state automata each bread let's step back a second okay two four six eight essentially how do we keep track of what's next we already know that's just one in two no matter which way you go is that right eight well this case we have 1 2 3 eighth floor so you two and four so yeah if I have 1 in 2 or 0 and 1 mmm or interesting maybe just have to turn the best one and 3 and 2 is just 2 at 1 it's not interesting I feel like this is similar to and I'd really like I'm thinking about it in like that pyramid quality there's true that for any two adjacent entries they only different about the last bit so they here's some when I got back I was just my mind is not really up okay guys time making excuses that I okay express it come on now okay first of all use okay so this is good maybe ish I figure we need this later and then the first well now the first number will have one bit so this actually doesn't it's not true the only thing that could flip is if the odd the round number is okay so if it's an art world we either then we kind of flip it and all right not Venice then it's odd then we kill the first digit so we don't fit so it was even then before every maybe and it just went really fast so just like mo I was going to make a snarky comment about just like a lot of other things but maybe it's a little too big because the first is Silla it's just no longer gig now this is right and not the end part we were just two numbers start first stage when I say well yeah my brother standing this way could you get rid of this first ticket there's something weird thing that I need to do here okay that way you're going tell you won't happen now that's a given by it is it see you then ready eliminates I'm completing a few things as well yeah the first one so first let's zero and you keep the pit look I just try overage how nice I love it okay how you don't keep the pit for Adwords if heartworms will you check this for some reason it's I and we get rid of the first cut my first pet the first but it's co2 okay what the service time we need one I just even made him say and the number of items this year and then we get rid of side some odd items that we get rid of the first one and it let's see Leoben numbers tend to carry out of second digit not for us and when status yeah maybe this is a mess I got me thinking only in terms of this input so it doesn't mean anything to me yeah not surprised I doesn't work for the other ones mm-hmm what's hoping well not gonna take requests anyway no it's good but these ones are always a little look like these also in general someone has like a random like oh yeah this is how you think about a farm and then the form becomes way easier and the coding is like you know 20 lines of code so it's just like silly all right sometimes even real life you're forced to do work on something that you know necessary agree with also maybe my earnest you don't always you know make down having that point you out of thing yeah just answer what's the answer for 10 oh yeah three six and then you eliminate to 6/10 it was for a and I need to make 6/10 it was for a and I need to make 6/10 it was for a and I need to make four is eight okay I didn't inside that five just not always got to in this case no I like I just got it too in this case and I need to you so it's still gently now fashionable know that point is actually what I just said what's wrong because why there's always going to push you because you start at the parity bit you always remove the bigger of the half so no that's true okay it's just which one see it was not given a number in it oh cool this one and five and now we want to get them made the first number which has a one bit and your one eight two numbers of Tula it's true that the first digit as I won I need like one more check on the last bit and if no easy way to see what happened my other toys maybe there's a way I can we indexed use in a way that I could figure it out can i yes people were saying some of similar didn't I anticipate this farm coming to no because now I kind of way use the bathroom I feel like I'm close that the idea is similar ish great like they're not that many come other possible ways to do this but boy am i strong that's think what's my answer is I need to take a look real quick I think I'm just not adding maybe I'm just not adding the last bit in a way because I think that's what a couple of zeros on some power to stuff okay yeah so maybe I'm just maybe I'm close I'm just missing like one more check I don't know so I think I'm off by eight and every one of these so there's something like one more chance I'm actually closed okay come on so okay so I'm close or closer even though it's hard to believe because I'm still I'm wedding less than the line of code a minute and some of these are just decoration statements but okay I'm close so mm can I represent this in a slightly different way and I don't even think so Kay thank you brother just keep track of the first number because it essentially and then down fixed hours I'm looking at bit by bit which is fun it's not this is like an extra one but I don't have and maybe I just check it first don't get six volt so in the first of all never okay move another way think about it as keeping track of the first number instead of the first bit what that work but essentially you add to pick and you eliminate the first number it's not good and then mm-hmm don't worry about that and then mm-hmm don't worry about that and then mm-hmm don't worry about that you know so close like some weird stuff I'm missing PI one bit this is close actually to be honest it's about yourself which there's a little bit okay wonderfully snow their riches were yeah and what I need to use the rest okay but uh okay the first well you may know them because we know that's cool you know that's still known to the sphere above one number left out really long time okay that's the one type issues but now I buy juice now and we still have one still in the middle first okay maybe I just need to think about okay to say first number is another one so we eliminate the furnace then first yes you go to her oh I'd be - nothing oh I'd be - nothing oh I'd be - nothing no event is art and we remove the first character even its event and we do not know that's even maybe I forgot don't die in the first place kind of count the petal a bit the other way let's see if I fix myself I mean yay oh no I feel about this I mean there's a cup of vegetable here I think what I mean that was that took 15 minutes I think I got a little stuck on the bid counting a little bit but I think I didn't kind of say it explicitly but in my mind I think I shifted my mind a little bit and that was kind of how I thought about it I think yeah I got stuck on a bit kind of like trying to do some thing with counting bits and I don't maybe I was very close to a state machine type thing and I think you I could have probably still made it work I just kind of maybe have to keep track of everything but I think one thing I realized was maybe we just keep track of the first number since inrease because in some sense the first number it's going to be its home actually is similar to the pre-med poem that we had earlier to the pre-med poem that we had earlier to the pre-med poem that we had earlier where at the end when we have one number then your first number is your answer right that's how I got eventually started to think about that so I start up one and then the second thing was thinking that for each row you know the difference between adjacent elements I starts at one and then it doubles to two and then forward so forth no matter what so and then I asked myself well in that case if you eliminate the first element that means you just added by you know two to the all power in this case is ma the number of round power away and that's it and in that sense that would have made the problem very easier and hmm and I kind of took way too long for a medium I don't know Mike I've done better I think what I got stuck for a while I think that's kind of I mean sometimes that's a trap that uh well I definitely get into our others similar but in terms of just thinking about it for myself I'd ever again do a thing where I get to local minima local Maximus where like I'm like oh I'm so close I just have to change this one thing maybe but then I never found that one thing where I think about looted to this earlier where you've get the white way of looking about it is a lot easier and my second way of visualizing this was much cleaner and I wish I kind of got into it but I just didn't think about it enough I was stuck in there uh you know that little that help instead of going for the answer and that took a while I mean I would say maybe on an interview if I get stuck like that probably an interviewer would probably nudge me a little bit in the right way and hopefully that in that case it doesn't take another hour but uh but this is so I don't know how I feel about this one so maybe I just don't have a good of pain about this it's a little tricky to think about but if you had the right kind of mindset it's easy but I don't know if I could good like and this feels like one of those qualms to be frank we're like you know I didn't see it today I see it tomorrow and I just kind of like ah yeah this is obvious haha but like and that's what I mean by a little bit of like I don't know like it's a little like a brain teaser you think we're like I don't know but uh yeah so I mean you would not see me give these kind of interview bombs but I don't know if I would expect to see this I think you like if I see the stand well then I won't attack I mean I were able to dice now see how it goes I don't know if I would have definitely let's talk a little bit and it don't have much confidence and as I predicted the final code is like ten lines of code it's just way tricky ten lines of code but to be frank knowing the answer now saying about that tricky it's just like I don't know I feel like it maybe uh I don't know if this is one of those cases where like in a weird way because I have you know did a lot of toys and my two to shared of you will that I was trying to do I'm like doing bitwise things maybe I'll try a little idea but as soon as I kind of got to like fake idea and maybe like a like someone whom it's not as kind of in the reeds in the leaf code maybe they could have kind of easier because it's more obvious to them the right approach because it in some way is like I mean and like there's no heavy machinery in this it's just understanding binary numbers which I think you can figure out I mean I don't know maybe that's it but that's not any easier part so I don't know if I would expect to see this but if I do it is what it is but I don't like this as a while for me anyway and maybe that's just pious but uh yeah I could explain it again and try but I think so actually my we're Road names uh well I mean this could be wrong and it's more straightforward its data so I think so if you look at the rounds here on example so each adjacent number is always going to be just two to the I for some power i right I think that's I mean I think that's you know we've been people have been talking about it I think the chance so I think that part is it's understandable though I think there's a little bit like flaming and that we always eliminate where the doubter is to dipose one but Purdue it before that for you to row like in the first row that Delta is one was like remote the others too third one 2004 and the last one to doubt it well it's just there's only one element right so that you know parts of two so in that case you just keep the foot in track of the first number away and then for each you similarly whether you remove the first number and that's it but in you know weird way and then just file through what that means which means well for every alternating steps where you go left away what in their terminology left your way you always eliminate the first number right and when you always eliminate the first number then you just add two next you add the Delta of that well which in this case on the first wall is just plus one right and well we don't really need the first were if I'm given rows or the roads where you look back you don't need them in the first world the first element so I keep saying anymore when that well you don't you limited the first element then you just keep the same element so you don't there's no adding here placing it is when these things are not true but yeah so then you just keep the first element because in this case they're in the next row the first element is still two and then in the next row you made the first of all again keep saying oh sorry you eliminate the first element again so you know that the doubter are always gonna be four in this well so you add forward to it so you have six left and now you have only one element so you return it is that okay I mean it's such a like once someone show you the thing is like it's I feel like it's so much easier and even looking at the code it's not clear to be honest like you have to like a dad kind of but I think I would say if you want to practice this a little bit or like kind of think about it just think about what it means to just keep track of the first element and then once you and yet to think forward a little bit but let's just say you know start with one because that's the entire sequence keep track of the first element of that world and then follow through what that implies and like what happens when you determinate the first element well it's just the next element and then there's some states around that I think that's a Hopi that went okay because let's say you have two four six eight ten we just don't need the other possibility for like ten then you would eliminate the first number and you know that the next number it's four then you keep four and four is your first big number or your next first number and make
Elimination Game
elimination-game
You have a list `arr` of all integers in the range `[1, n]` sorted in a strictly increasing order. Apply the following algorithm on `arr`: * Starting from left to right, remove the first number and every other number afterward until you reach the end of the list. * Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers. * Keep repeating the steps again, alternating left to right and right to left, until a single number remains. Given the integer `n`, return _the last number that remains in_ `arr`. **Example 1:** **Input:** n = 9 **Output:** 6 **Explanation:** arr = \[1, 2, 3, 4, 5, 6, 7, 8, 9\] arr = \[2, 4, 6, 8\] arr = \[2, 6\] arr = \[6\] **Example 2:** **Input:** n = 1 **Output:** 1 **Constraints:** * `1 <= n <= 109`
null
Math
Medium
null
1,802
hello guys welcome back to my YouTube channel and this is day 9 of June delete code Challenge and our today's question is a maximum value at a given index and a bounded array so let me explain you the problem statement first uh so uh you are given three positive enter integers and index and maximum uh you want to construct an array nums and that satisfy the following conditions so we will be having uh these three integers uh n that is uh like the total number of element that should be that should contain in an array then index and this maximum sum so uh this like we have to uh make an array such that we have to make an array of size n so this is this will be of size n that is nothing but 4 and what we have to do we have to put the elements in this array such that any two consecutive elements should not have difference more than one like you can put one here then the difference is zero and you can put one two so uh in this case difference is one but you cannot put like this here one and here three because in that case the difference will be two so it should not be this it should be uh it should be one or less than one so and this is maximum sum like some sum is what if you are putting values here so if you are putting values let's say in this case 1 2 then again two and then one like in like this if I am putting values in this array so the maximum sum is what six here so the maximum the elements uh that you are putting in the array should not uh exceed uh maximum sum so like the values can be uh can be six or it should be less than six if you are summing up the all the elements of the array so you have to so I think the question is clear now uh they are giving us n that is nothing but the uh total elements in the array and we have to put the elements in the array such that any two consecutive elements should not have a difference more than one it can the difference can be between two elements should can be one or zero and we have to put only positive elements and they are giving one index is what this is like in this example this is two so zero one and two so in this place that is nothing but index that is given we have to maximize the value of num we have to maximize the value of this index so what we have to do we have to maximize the value of this index such that all the conditions should be followed what conditions consecutive elements value should not differ more than one it the difference between two values can be one or zero we have to put only positive values and the sum of all the elements should cannot exceed the maximum value that is 6 in this case so uh what we can do uh let's uh see what we can do in this case so uh we know the size is 4 I am making array of size 4. I can put one everywhere this is one case that I can this is one thing I can think of so I know uh like at this point index 2 this is index 2 I have to maximize the value here this is 0 this is one and this is two I have to maximize the value here and it should not exceed 6. so uh what I can do uh this is one now I can I put two here let's see I can put 2 here because in this case difference is 1 and here also difference is one between this between index 2 and 3 and 1 and 2 yes 2 can be put can I put three here let's check if I am putting 3 here then the difference is becoming 2 in this case and 2 also in this case so this is not possible and uh if I put uh 2 here let's say to uh to check like if I put 2 here to uh satisfy this condition the difference between two integers should not exceed one it's it can be one it can be zero so in this case if I sum up two plus one three plus three six and six plus two is eight so this is uh exceeding six so the maximum it is crossing maximum seven so we cannot put three here so in this case we checked like 2 is something that we have that like one we can put and two we can put and then three We cannot put so the maximum value that we can put is 2 in this case so uh let's see how we can approach this problem so uh we have given three things and that is I told you that is uh size of the array then index the particular index where we have to maximize the value and maximum that is uh that will be given to us and the values of the element the sum of the values of the element should not exceed this maximum sum value so uh how we can approach this let's see that I know uh the value of this index in this case the size of the array is 4. okay at this index one this is one nice this is zero this is one this is two this is three so at this place one we have to maximize the value so how we can maximize the value like what can be the search space like what value I can put like I have checked one I have checked for two and then I have checked four three it is not working so till what point it can go till the maximum sum right guys I can put 6 and rest of them I can put 0 but the condition will not satisfy that is other thing but the lower value that it can get is one and highest value it can obtain is 6. so can I treat this as a search space yes I can treat this as a search space this is the low point and this is the high point and if this is lower this is high I can what I can do binary search how I can do binary search I have this search space and I can get one value let's suppose I am getting 3 in first case if I do penal such like 1 plus 6 by 2 that is nothing but 7 by 2 and 7 by 2 is nothing but 3. so I will check for three can three be placed here if three can be placed here I will check for greater value then I will go and check in the right space and if 3 cannot be placed I will check in the left search space so this is becoming finances problem in this situation in this case this is a binary search problem so what I have explained you till now you can treat one as a lower space like you can put one in minimum case and you can put six and that will be your high point so this is your low and this is your high and every time you will be calculating your midpoint and if this midpoint can be put here I will explain how we I will be checking the uh like condition if it can be placed or not placed so if this can be placed here we will check for greater value we will go right and if this cannot be played cannot be placed if like three cannot be placed here then we will check for lower values we will go left so this is the intuition and approach that we will be using so let's see uh actually uh the kind of pseudo code what we will be using so what we will doing we will be doing binary search here okay so how we'll be doing binary search we will find the mid is what it is nothing but your lower plus higher by 2. by 2R we can also write like this right shift then I will check if is possible like is possible if this value can be put if this value can be achieved I will check to the right to the greater value I will go right else I will go left so how I can check like how I can check uh this value can be put here simple like if they are saying 3 we have to check for three for example so I will put 3 here and here I will put 2 and like if we are 3 I will just like I will just uh decrease one value every time three then two here then one here like this is how I will be putting the value because I know the difference can be one or zero so I will just decrease the value in the left or right like if this is the target index so I will put the mid value directly here and in the left and in the right I will put decreased value decremented value like if this is three I will put two here if one more index will be here would be here I will put one year but this is not in this case so I will put only two in the left and in the right I will push if this is three I will put 2 here then one here and if one more index will be here I cannot put 0 because only positive will use I can put so I will put 1 in this case so what I will do after putting values you have like you have seen that if for this value I have to check I will put decremented value in the left and in the right also why we are putting decremental value because the difference can be one or zero so I am putting decremented value every time and if this will be one more place here so I will be putting one not zero while we are not putting 0 because we can put only positive values so after putting values once you have done with that you will be calculating the sum and if this sum is less than or equal to your maximum sum you can say yes this value can be put here and if it is satisfying for this then we can check for higher values or greater values like this we can go right and check for greater values but the problem we can we will face here we will face if we put values one by one because the N can be very large see here the n can be 10 to the power minus 9 so we cannot go and put values to every index and we cannot count the values for every index like the counting values for every index in this case so if the values are if the number of elements are very high so we cannot count the it will give tle time limit exceeded so what we can do see we know if we in the mathematics like if you are familiar with Magnetic mathematics you can do easily so let me rub this then I will explain Okay so let's see how we can actually uh count the values so if I wanted to know what is the sum of values till 5 if I wanted to know if till 5 I wanted to know let's suppose I wanted to know what is the sum of values till 5. okay till 5 I wanted to know what is the sum of values so the formula is nothing but n cross n Plus 1. by 2 so that is what 5 into 6 by 2 this is what two three so six so this will be fifteen and if you count one to five one two three four five this is what five plus four nine plus three that is 11 and 11 plus 3 that is 14. sorry pi plus 4 that is 9 plus 3 12 and 12 plus 3 that is fifteen so this is how we can uh like we can get the sum of N natural numbers n cross n plus 1 by 2. if I like if I want to get the sum of starting five values I can get by this so for any value we can get so how this can help in this problem like if I have 3 here suppose so I know if I have 3 here I can directly use this formula how I can use this is nothing but n cross n plus 1 so 4 by 2. so this will be what two twos are four so this will be 6 and I know if this is three year I will put in decremented value in the left so I will put 2 here and one here and if you will do the sum so one plus two is three and three plus three is six so this is how I can find the sum of values and in this case I need not to put values I can directly find the sum so if so in the right how I will be getting like in the right it is not 1 here 1 is not there so how I can get that let's see that edge case also like uh like what I am telling you is let's rub this okay so uh yeah see the edge cases now like I have told you we can use binary search I have told you we can check and then and according to the condition we can proceed but how we will do the sum of values because that will be giving you tle see this is the main funder of this problem like if I have three here let's suppose this is your index what index 0 1 2 3 4 these index you have in your array and the I know in the left I will put decremented values like two and one in the right also I will put decremental values 2 1 then this is the index I so I will calculate the sum till here 0 to I and then I plus 1 to this last index I plus 1 to n minus 1 how I can get I have this formula n cross n minus n plus 1 by 2 with this I can get easily if I want to get the sum till here I can get easily by putting 3 cross 4 by 2 that is nothing but this will be 2 so 3 into 2 that is 6 easy but this is not that easy let's see the edge cases what can be H case is let me show you if I have 3 here let's suppose and I have only uh let's suppose I have only uh what I can say I have only uh let's suppose instead of like this if this is the condition then what I can do I have to put 3 2 1 and I cannot put 0 so I will put again one so in this case how I can find the sum till I have told you first of all we will find the sum till I and then we will find I plus 1 to n minus 1 so see in the left how we can find the sum so if the values like we will check the two things we will check like required left what is required left that is actually how much values I can have in the left if I have mid value this like if I have here 3 I can have three values like that will be in the sequence like one two three that like the sum that we are calculating is like this sum that we were calculating that is six in four three we are checking so this is for three two one till one to that point how many values are there that will be your mid value that you are passing here so required left is what your mid value like for these values I am calculating the sum so this is what your required value so this is 3 in this case like I can have if I have three only if I have only three elements then this formula works this is like this is only you need to check what is the sum and one thing we will calculate that is or that is what have left I think have left I have used uh yes have left I have used the variable so it will be like convenient for you to understand later have left is what how many we have in actually so we will check like here these are four values that are in the left so I am telling four values I have in the left or 4 and only for three values I can calculate the sum so what I will do is I will calculate I will check like how many uh like for how many values you can give me the sum I will I'm saying for three values only so what is the sum that is six like this one plus two plus three that is six and then I will check how many values are in the left I am saying four values are in the left so what I will do I will again find the sum of this remaining value how will I find I will do sum of have left minus required left that is one only I will say only so only one value is left so I will just add this value like how many ones are in the in this here like if I have three ones here so what will say like I can like required left is three but have left is what in this case one two three four like not four this is three years so I will directly what add 3 in this case but let's suppose this is not there only this one is there so what I will do I will just like whatever one is extra like just add the extra ones nothing you have to do after calculating these values by formula just add up this these extra ones so like see another uh s case what can be another Edge case like uh you can have what you can have this condition also like if you have uh let's suppose array and you have three here okay you have three here and this is your index two let's suppose this is one uh this is let's put zero and this is one that this is the case then you can have two here but when you will be calculating like the sum with your formula okay with your formula this will give six because it will including one also here so in this case what we will do after calculating this sum you have to what you have to do you have to just you just have to check how many values are remaining like you have calculated uh what required left is what the values that I can that I am calculating with the formula that is 3 like the formula the value that I am getting with the formula that is of three values and what I have actually have left is for tier 2 in this case so like one element is remaining so for that I will again calculate like with the formula I will calculate I will check like what is remaining I will just subtract through from that so this will be what 6 minus one so this will be 5 so I hope you are getting it like this uh like this like what I am seeing is with the formula like with this formula you can get the values but if this is like if this is three year then this formula will give value till 1 so you have to extract this one and if this is like a it let me uh conclude it quickly over time trying to convey the point is if you have three here and you have only uh one in a one value in the left so in this case when you will calculate this will give value till this one and you don't have this one in this case so you have to discard this one and in case you have what you have like three here then you have extra ones in case you have extra ones so you have to add this extra one I am saying whether it is in the left or whether it is in the right and let's suppose you have value in the zeroth index only if you have the value you have to that you have to check is that zero syntax only you can directly add this value nothing to do so I hope you are getting it let's see the code to give you more clarity so uh what I am doing is let's see from this max value function as I told you we are setting up the search space whatever we are doing we are declaring the search space poor binary search this is our step one then we are nothing we are just doing binary search easy binary search and we are finding the mid value you can do also here by two but like sometimes it get it gets doubled that's why I'm doing the slideshift one this is also the same then I am checking if this wall if this value that I have calculated is possible to put if yes I will put I will store in the answer and I will check for the greater values like if 2 is possible to put I will check for three okay and if this is not possible I will check for lower values because if 2 is not possible I am sure the greater values for greater value definitely it will not possible so for lower values only I can check I hope this is clear then we will just do let me remove this I have like I have put this for uh debugging so let's see this function is possible what this is doing uh in is possible we are checking like how many values can be in the left so I if I have this array okay if I have this array and if I have three here I will say I can have required left value as 3 by 3 because I can have 2 here and I can have one here then I will check have left is what if this is index like 2 then I will say index plus values for like if this is index 2 so then have left will be 3 so I am saying like three values are in the left for that we have to calculate the sum in the left and then we have to tell so this is this if the uh this is index 0 like if for index 0 we have to check we can directly put the value here and we can directly add in the sum like if we want to check uh like on the index 0 can 3 be put so we can directly put 3 and add in the sum like uh this is the like if any particular index we have to check so we will just what we are doing in this function we are checking the sum in the left and sum in the right like 0 to I have told you and then I plus 1 to n minus 1. this is we are doing here so if this is on index 0 we can directly uh sum the value if the values are much for example if this is three this is 2 and then we have like add up values so what we will do we will just calculate the value with our formula like that n into n minus n into n plus 1 by 2 I have told you this and left over additional ones we will just directly add and if this is not the case is like this if you have 3 and 2 only and the formula is giving value for one also so we will just calculate the value and we will subtract this remaining one so this will calculate 6 and we will just subtract one so this will give 5 like this so this is for the left 0 to I and then we can we are doing the same thing 4 index plus 1 to n minus 1 you will do in your notebook you will get it so in the last you will check if the sum that we have calculated to 0 to n minus 1 if that is not exceeding maximum sum if that is less than or equal to maximum sum I will say yes it is possible to put a particular value at a particular index and yes you can check for greater values now this is how we will be doing I hope my Approach is clear to you if you have any doubt you can ask me in the comment I like sometimes it is not getting into your head just uh Watch the watch this video one once or twice you will get it do the dry run in the copy and this formula you will get it once you will do in your copy notebook and if you have understood please like this video and you can also subscribe to my channel for such for more such content I will be putting more daily lead code Challenge videos and contest Solutions so thank you for watching foreign
Maximum Value at a Given Index in a Bounded Array
number-of-students-unable-to-eat-lunch
You are given three positive integers: `n`, `index`, and `maxSum`. You want to construct an array `nums` (**0-indexed**) that satisfies the following conditions: * `nums.length == n` * `nums[i]` is a **positive** integer where `0 <= i < n`. * `abs(nums[i] - nums[i+1]) <= 1` where `0 <= i < n-1`. * The sum of all the elements of `nums` does not exceed `maxSum`. * `nums[index]` is **maximized**. Return `nums[index]` _of the constructed array_. Note that `abs(x)` equals `x` if `x >= 0`, and `-x` otherwise. **Example 1:** **Input:** n = 4, index = 2, maxSum = 6 **Output:** 2 **Explanation:** nums = \[1,2,**2**,1\] is one array that satisfies all the conditions. There are no arrays that satisfy all the conditions and have nums\[2\] == 3, so 2 is the maximum nums\[2\]. **Example 2:** **Input:** n = 6, index = 1, maxSum = 10 **Output:** 3 **Constraints:** * `1 <= n <= maxSum <= 109` * `0 <= index < n`
Simulate the given in the statement Calculate those who will eat instead of those who will not.
Array,Stack,Queue,Simulation
Easy
2195
1,578
Hello hello everyone welcome to my channel its all cheat code problem minimum relation cost to is repeating letters for giving his fears and worries of increased cost of you its cost auditing also character of india has written a minimum of relations dare not do it letter next Two Years I Noticed That You Will Delivery Subscribe Example Don't forget to subscribe and subscribe Quiz-13 Absolutely Only Boys Is Not Only Three Quiz-13 Absolutely Only Boys Is Not Only Three Quiz-13 Absolutely Only Boys Is Not Only Three Minimum Costs To Avoid Oily Hair Oil Subscribe Now To Receive New Updates From A Minimum Of Eggs Subscribe From Being Considered So Let's Group Of The Character Mirch Coat And Have To Delete A Minus One Character Solid Only Single Electronics Dedicated Of Be Id M Id To Delete All - Dedicated Of Be Id M Id To Delete All - Dedicated Of Be Id M Id To Delete All - 110 Minimum Will First Total Cost Maximum Subscribe Plus App Is Between this total and the maximum office three stand fennel force substrate maximum from tenth witch will Vikram Seth - 10m special Vikram Seth - 10m special Vikram Seth - 10m special 100 remove into effect from witch the consider for this 420 hair 753001 left over 500 cost video Shyam Singh Dhindsa again from this point to subscribe to SUBSCRIBE AND SUBSCRIBE GROUP THANKS DRYER VITAMIN A AND D GROUP MAX AND FINAL ANSWER WHICH NEED TO RETURN SWITCH FROM SOM WILL GET RID FROM PHYSICAL SE ZINC AND NOT LOSE WITHOUT VOLTE PLUS EGG WILL START FROM SOFTWARE WILL CHECK 500 AND THE BEST CARAT THE CURRENT IS Not Equal To Subscribe My Channel Do n't Forget To Subscribe Group From Thee Inki CNN Today I Am Getting Disconnected From Character In This Update Subscribe Character Add G Group Me Obscene Daughter The Marks Of Karan Maxis Group Muslim President Amit Bade Ribbon More Share Like Subscribe And Also Like and Subscribe To the Scientists at What is the Time Complexity of Dissolution Soldiers Are Treating All the Character Hindi Streaming All the Element Egg White Safed Tea Spoon Please Subscribe Like and Subscribe My Channel Thank You for Watching
Minimum Time to Make Rope Colorful
apples-oranges
Alice has `n` balloons arranged on a rope. You are given a **0-indexed** string `colors` where `colors[i]` is the color of the `ith` balloon. Alice wants the rope to be **colorful**. She does not want **two consecutive balloons** to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it **colorful**. You are given a **0-indexed** integer array `neededTime` where `neededTime[i]` is the time (in seconds) that Bob needs to remove the `ith` balloon from the rope. Return _the **minimum time** Bob needs to make the rope **colorful**_. **Example 1:** **Input:** colors = "abaac ", neededTime = \[1,2,3,4,5\] **Output:** 3 **Explanation:** In the above image, 'a' is blue, 'b' is red, and 'c' is green. Bob can remove the blue balloon at index 2. This takes 3 seconds. There are no longer two consecutive balloons of the same color. Total time = 3. **Example 2:** **Input:** colors = "abc ", neededTime = \[1,2,3\] **Output:** 0 **Explanation:** The rope is already colorful. Bob does not need to remove any balloons from the rope. **Example 3:** **Input:** colors = "aabaa ", neededTime = \[1,2,3,4,1\] **Output:** 2 **Explanation:** Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove. There are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2. **Constraints:** * `n == colors.length == neededTime.length` * `1 <= n <= 105` * `1 <= neededTime[i] <= 104` * `colors` contains only lowercase English letters.
null
Database
Medium
null
1,290
Hello Hi Everyone Welcome To My Channel Today Jab Bigg Boss The November Recording Challenge And Problems Convert Binary Number In English To Interest In This Problem Governor Bane Representation Of Number Wise Notes Of December 19 201 Subscribe Representation Of Decimal Number Of This And 1000 Number Into Decimal Subscribe 10 2010 From Every Bit Brightness Increase Dev 225 12512 Sudhir And Of All Subscribe Number 181 Song Vinod Is Withdrawal List Sid And Use This 554 Solution You Can Hold Number 10 From Multiple Alternative Medicine A Product Of Who Is Equal To The Number Plus App New Delhi From the Start Flat to Start Poems Multiply Factor Every Step Factor You Changed into Multiple Too Subscribe Indian Space for Tourists Can Withdraw Subscribe To That UC Davis Fall Dish Representation So Let's Initially Our Decimal Number 205 Multiple 102 Annelida The First Woman In Multiple items with two a plus b value within second middle in this life is whole with two plus debate on the third wishes open country-foreign vikram samvat 1232 open country-foreign vikram samvat 1232 open country-foreign vikram samvat 1232 plus 12510 into two our video subscribe and subscribe the Channel number 90 into two plus debit ago That * Plaster Bit That * Plaster Bit That * Plaster Bit A B * Hold Y2 A B * Hold Y2 A B * Hold Y2 Juice 10 Drop C Dynasty York List Narrate Vacancy Difficult Times For Add To The Power To Plus B Into Power Plus Seervi It's Improvement O's Travel Code Bindh Available Nam Net To December Decimal Numbers And Will Reduce List Will Not End With First To Start To Last Apr 9 2010 Whatever Number Decimal Number Also Constructed From The Vine Representation In Na Ling Left Side Compiled And This Booklet Prosperity Code That And Accepts There Time Complexity Of Dissolution And You Can See Midning Processing all the notes subscribe for related which are I safe try to notify solution hit the like button subscribe for more mod videos thanks for watching
Convert Binary Number in a Linked List to Integer
make-array-strictly-increasing
Given `head` which is a reference node to a singly-linked list. The value of each node in the linked list is either `0` or `1`. The linked list holds the binary representation of a number. Return the _decimal value_ of the number in the linked list. The **most significant bit** is at the head of the linked list. **Example 1:** **Input:** head = \[1,0,1\] **Output:** 5 **Explanation:** (101) in base 2 = (5) in base 10 **Example 2:** **Input:** head = \[0\] **Output:** 0 **Constraints:** * The Linked List is not empty. * Number of nodes will not exceed `30`. * Each node's value is either `0` or `1`.
Use dynamic programming. The state would be the index in arr1 and the index of the previous element in arr2 after sorting it and removing duplicates.
Array,Binary Search,Dynamic Programming
Hard
null
274
Hello Guys Welcome Back To Decades And This Video Will See The Question Tax Problem Wishes From List Code 11:00 Of Problem Wishes From List Code 11:00 Of Problem Wishes From List Code 11:00 Of The Great Challenge So Let's Know Problem Statement In This Problem Veer Website This Negative Energy Resources To Function To Compute The Richest Definition Of Do Subscribe and the subscribe now to receive values ​​of maximum familiar with this problem values ​​of maximum familiar with this problem values ​​of maximum familiar with this problem not familiar with my video and audio problem no problem the difference between set the stations for each and every paper will be given in ascending order notification sir given in ascending order rachyou is to Solve this problem in login time for bison problem will not have to give its request to the hindi of this is the difference between the problem solve video solve this problem in this after 10 minutes and subscribe to The Amazing for other videos Description Me Bank Complexity The Time Complexity Vishwasham Plus Shopping Sorting Will Be Taking And Log In Time And For Watching C Applied Research Limited Login Otherwise And Linnaeus Varishvi Can So This Is The Internet Solution Will Provide You My Solution For Brain Research In The Code Link Below Description Will Also You Can Watch That In Order To Understand If You Are For Watching My Video Nurses
H-Index
h-index
Given an array of integers `citations` where `citations[i]` is the number of citations a researcher received for their `ith` paper, return _the researcher's h-index_. According to the [definition of h-index on Wikipedia](https://en.wikipedia.org/wiki/H-index): The h-index is defined as the maximum value of `h` such that the given researcher has published at least `h` papers that have each been cited at least `h` times. **Example 1:** **Input:** citations = \[3,0,6,1,5\] **Output:** 3 **Explanation:** \[3,0,6,1,5\] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. **Example 2:** **Input:** citations = \[1,3,1\] **Output:** 1 **Constraints:** * `n == citations.length` * `1 <= n <= 5000` * `0 <= citations[i] <= 1000`
An easy approach is to sort the array first. What are the possible values of h-index? A faster approach is to use extra space.
Array,Sorting,Counting Sort
Medium
275
1,981
hey everybody this is larry this is me going with q2 of the weekly contest 255 minimize the difference between target and chosen elements hit the like button hit the subscribe button join me on discord especially if you came here right after the contest because then we can talk about this thing and people do talk about these problems right after the contest so it's super uh fun but yeah um okay so this one what is the thing first thing that i look at first thing i think about is maybe some sort of dynamic programming and like some sort of binary search and dynamic programming i thought about maybe heaps you know like bounding the number in some way and then i look at the constraints i said okay so the target is less than 800 right so then the question for me was is there a way to change the target um to use target in some way right um and that's basically the idea that i have here um so again when i was trying to solve this problem during the contest i was trying to figure out if i could do some heap and only care about some numbers but then you may have a last row where you know you bring everything back so i didn't think it would work and you only care about certain things but yeah so as soon as i saw the target i said okay let's do the math right um and i pull my calculator which you can't see on screen but i wrote okay 800 oops times 70 what is that's 3.9 million uh maybe that's good enough 3.9 million uh maybe that's good enough 3.9 million uh maybe that's good enough so that was basically my logic um yeah uh and even though in python it's a little bit sketch actually to be honest because fine is super slow but anyway so the idea i have here is breaking into cases right um i don't know what the best recommended way is and maybe we can do some code review afterwards because i'm curious but this is the way that i did it but basically there are only two cases right um or two possible cases one is that the smallest or the closest number is smaller than target and then the other case is the smallest number is bigger than target okay duh um but for me that's how i broke it down right so i go okay what is let's say we sum up the smallest number in each row what do we get well if we sum up the smallest number in each row then we have two cases right if we sum up the smallest number in each row if the total is greater than target that means that you're not going to get any closer right does that kind of make sense because if you're small if you take the smallest number in every row and it's and you sum it and it's already bigger than target you're not going to get any smaller number because that's just the way it is right um because it's not possible to get smaller because also because there's no negative numbers though i don't know if that matters um it's just that there's no possible way i mean negative numbers do matter in that they're all uh makes things a little bit more complicated but okay i put emphasis on this part because it is important to know to understand for the next part that okay so let's say then in the other case smallest is smaller than target but what does that mean right because all the numbers are at least one and 70. that means that let's say our constraints are rows is equal to 70 columns is equal to 70 right and target is equal to 800 right what does that mean and you can actually tweak around just a little bit but i'm just gonna you know um let's say you can even use zero it doesn't matter because but i wanted to use zero for illustration because it's easier to kind of visualize then that means that our smallest total or total smallest maybe it's equivalent is equal to zero right i know that this is one and sub zero but bear with me a second that means that there exists a solution um or an answer where um delta is equal to 800 right does that make sense i don't know why i just take some my computer is a little bit slow is it frozen just like the uh i think my q my browser is frozen so yeah 800 right because that what does this mean that means that if um that means that answer has to be between 0 and 1600 right all right i got to get a new browser sorry friends um but yeah does this make sense because if the reason is because if there is a possible sum at 1601 say um this is already further away right i don't know why this computer i need to maybe get an upgrade sorry friends uh i'm trying to type it out for y'all okay there we go um okay hope that makes sense so that means that the answer has to be between 0 and 1600 so then now this allows me to do a dynamic programming on each row and that's basically the idea i have here so upper means upper bound i set it equal to target times two because again the answer has to be from zero to you could make a tighter bound but i didn't want to do the math um and zero is the better answer right i don't know why that's outcome okay so then here now this is the rest of the code and it is dynamic programming on uh on the fact that okay so the previous row we look at every possibility right what i mean this is just a basically look at each 12 previous well previous x is true if the there is a possible sum to x and again uh sorry friends my computer is really acting up weird okay this is now another so previous x is true if there was possible sum to x in the previous row okay and then the dynamic programming hopefully now makes sense which is that for each row um and i sort it just to make it a little bit maybe faster you don't even need this um it makes a little bit faster because then i can uh do this break but you actually probably don't need this it's just that in python i'm always making optimizations two viewers but yeah so if the previous vote has a sum in the index then now for each item in row we then item plus the index is uh it's a possible sum so we set that it goes to true and then now at the very end we set the previous equal to possible and then at the very end of that after we process all the row again we set best it goes to target minus smallest though that should be another thing anyway as a possible answer and then we just go through every index and if it's possible then we look at the absolute difference between index and target and then that's your answer um yeah that's basically the idea and this is dynamic programming of course this is going to be o of r here uh this is going to be o of target times 2 which is our target and of course this is o of c i use r and c instead of n and m because n m is confusing so of course this is just three for loops so in the worst case this is going to be o of r times c times t for target time and in terms of space this is just o of um of c oh no sorry of t it's all t space because each row we have t times two space right um and then here we yeah that's pretty much the answer i mean i don't know um yeah so that's the answer for space and that's the answer for time and again if you plug in the numbers 70 times 1600 is good enough so that's why i said this is good enough um yeah that's all i have for this one let me know what you think um this is a really tricky one finding uh i think this observation is tricky i have i will admit that i've i don't know if i've seen a similar problem before but i have used this technique before which is why i was able to come over relatively quickly did it in about six seven minutes maybe i think i did a lot of i guess it was eight minutes but i did a lot of testing to double check um that's why it was a little bit slower but because i wasn't quite sure about the running time because i find it slow uh anyway that's all i have for this one you can watch me solve it during the contest next very weird problem but okay choose one see what 70 by 70. hmm so that should be okay so i wonder if i should do this in another language but oh um a different target fast enough it just times out i'll be really sad pretty sure that's fast enough in most languages hey uh yeah thanks for watching hit the like button here to subscribe and join me in discord hope y'all have a good rest of the week stay good stay healthy and to good mental health i'll see you later bye
Minimize the Difference Between Target and Chosen Elements
maximum-transaction-each-day
You are given an `m x n` integer matrix `mat` and an integer `target`. Choose one integer from **each row** in the matrix such that the **absolute difference** between `target` and the **sum** of the chosen elements is **minimized**. Return _the **minimum absolute difference**_. The **absolute difference** between two numbers `a` and `b` is the absolute value of `a - b`. **Example 1:** **Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\], target = 13 **Output:** 0 **Explanation:** One possible choice is to: - Choose 1 from the first row. - Choose 5 from the second row. - Choose 7 from the third row. The sum of the chosen elements is 13, which equals the target, so the absolute difference is 0. **Example 2:** **Input:** mat = \[\[1\],\[2\],\[3\]\], target = 100 **Output:** 94 **Explanation:** The best possible choice is to: - Choose 1 from the first row. - Choose 2 from the second row. - Choose 3 from the third row. The sum of the chosen elements is 6, and the absolute difference is 94. **Example 3:** **Input:** mat = \[\[1,2,9,8,7\]\], target = 6 **Output:** 1 **Explanation:** The best choice is to choose 7 from the first row. The absolute difference is 1. **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 70` * `1 <= mat[i][j] <= 70` * `1 <= target <= 800`
null
Database
Medium
null
230
You guys don't know about Loot or about your suji so friend this is the platform which repairs you old track if you are a working professional or you are a student here but what do you mean these days there is a lot of There are so many hot websites in one movie that you are afraid of losing a job. The cheese seller says if you like this vegetable, she is becoming a student, mix that and York Women Before Going Abroad, then you get CR and you get another one. You have a job in a factory, you have a toilet, this computer and you have your own job system, how do you sit for noodles at that time, what is the thread, if you apply on your side then it is far away 2 p.m. Paying money for the meeting in 2 p.m. Paying money for the meeting in 2 p.m. Paying money for the meeting in starting What you should do is to read that it is a difficult job, you have to pay for it and white dress, you will get it on this website, then I will definitely provide you the services, you will check that in New York and by going to this, you will get the link in the description here. But he will add it, okay, then I will request you to do this and here and there are many friends, many contacts are there to spread those points and violence, who were participants of the party in the questions of very high gravity, in the recent times, so if you Ameer Vasundhara In the future also, when everyone comes with questions, I will update the video there. Okay, so you guys, in June 2012, what is how cutting, I told you that you have to take a job, Mitthu used Europe as money starting, if you What will you do, then I will tell you what to do after you and what you can do by offering blood and flowers, okay and this little and many keys of your skin remain there, you, your partner, I will give you one and a half penis whenever someone else asks before this. And now after that here you will see what I will do now, I will update it and add it in the spoon description for them, okay so that is the correct charge given, Anush voice of small and medium did pay to loot means I will meet with us that this is so You will get the third here in this form, something like this, if you have this from here, first of all you have to describe which one means in the school, see, first of all, the limit for subscription will be the smallest, meaning 5 minutes, meaning this small, something small in the whole world. Which element is this thing? It is a request to all that they are free in its WhatsApp more to hai hot video and this amendment to the Pune festival is fine, so we take their second place here, this is the back that Mr. Kunwar Vyaghra became the fix here so far in this World Cup, first of all what happened, second is medium to third is 3G in the video, here we have to form them, okay and what is pimple and what is not, like I am not maintaining this for you and 125 27 28 2011 9825 that is 411 Now I will call it sauce that there is only two so to visit this video dedicated to the smallest cement and fold like this Which one is after that so pass on its subscribe button so I then I will refund you, I got the retail price, it is okay, the question has been asked in the exam from here, now see, we will try it, so we have to take any hinged inverter here, meaning we have taken out the treatment of trimming it, so we type here, what is the benefit of the tree that we have. It is BSP, it is not buying, it is not mandatory, meanwhile, this is true till the limit increase search tree minute, so what is the property of BSP that your which is like this and it is inverter, it is dry, it is okay. It is its inverter. It is okay, it is okay, tell me how much you are fine, it is good to do this trick on this side and how to look from how you take it from, take it, re -ray and from that of that By going to the link on that ns1, on the vagina, go to that and run it, okay 11, so this can be done, second, if that friend, you have to do it without express, that is why you have to do Wizcraft without taking extra space, how will you do this business, how will you do it? Life gets spoiled by boarding here, car service is tax free, tax is on life status, there is acid and you can get something here, we will do this, we will work in Niketan, till the time we work as journalists, they will work in inverters in this winter. Are going to convert but movie will not be inverter because we know that we have to stay in sodium balance in inverter we will see that we will get total of so where click in half cooked involvement in mudder do trial inverter privacy do phone point 19 that your you and control Where should I find my friend, I am worried like people will follow you, your mobile will be hacked, okay if it is not safe to go, then first of all, I will make one of my own in Dubai, to maintain the intake, get the intention to induce, second one. Question will have to be done in this lineage traffic point result. If you take interview then call from here, call two, do not return that come in your index record 204 and resultant value to the robbers soon that the one who understands them will be the result value of water point. A more comprehensive form of this point, if you return the purpose of the drain, then do that, rob Ajay of 2018's 1 minute school admission, oh yes, if it comes, mind it's record is broken, the limit is that and here, whenever You come in the inverter, increase it for your work, print the notification, it is good, ₹ 10, what is the value of your index, get notification, it is good, ₹ 10, what is the value of your index, get notification, it is good, ₹ 10, what is the value of your index, get up, it is done, the only difference is that in the central top, there are two fruits only on the back and from here, the returns of the day are like this. If not, then go to the primary fuel filter and ponds for your dry fruits. Go to this. Laptop is coming, you have to go to the right, so before that, do some work in that minute. Okay, now let's keep watching. One happened. So it should not be done at all or any comments should be made or it should be an assignment. Okay, I am passing it this way. 10:30 am. Look at the country. It's good, okay, I will submit it. It was done at that time. Please make it non-half . it's two
Kth Smallest Element in a BST
kth-smallest-element-in-a-bst
Given the `root` of a binary search tree, and an integer `k`, return _the_ `kth` _smallest value (**1-indexed**) of all the values of the nodes in the tree_. **Example 1:** **Input:** root = \[3,1,4,null,2\], k = 1 **Output:** 1 **Example 2:** **Input:** root = \[5,3,6,2,4,null,null,1\], k = 3 **Output:** 3 **Constraints:** * The number of nodes in the tree is `n`. * `1 <= k <= n <= 104` * `0 <= Node.val <= 104` **Follow up:** If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
Try to utilize the property of a BST. Try in-order traversal. (Credits to @chan13) What if you could modify the BST node's structure? The optimal runtime complexity is O(height of BST).
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
94,671
1,095
hello everyone welcome to this LOD daily where we are going to go through find in Mountain array which is a problem where you receive as input an array of integer and a Target you're supposed to find the first occurrence of the Target in the mountain array so uh in this problem we have a couple of conent the first is that you don't have all of all the element at the beginning you but you do have some method that you can use to get a specific element in the array and the second thing is that you have a limit on the number of request you can perform on the array so um that being said how are we going to organize ourself to solve it before solving it we need to understand what is it have some example and um try to come up with an approach that will help us to solve the problem so before diving into it if you're New Year here is AG here you are solving L Cod daily uring solution so if you're interested in any of those topic don't hesitate to subscribe do not miss what we doing here so let's start so like we said we have an array which is a mountain array is basically an array which is like which is separate into two part I would say we have an ascending part and an descending part so a mountain AR will always behave like this right he will climb and it will go down like this is an example of mountain array so uh and then you have a given Target that you're supposed to search and you're supposed to search the target into your Mountain array and return the first occurrence of that Target what does that mean that means if the target is maybe this element if this value is the same here you should return this one if the target is here you should return this one right so uh to validate if what we are thinking about is exactly what we are supposed to do that mean sing in an array an element it look easy right let us do something easy to just validate that so what we are going to do is that we are going to initialize our index to zero that mean the first element and then we are going to say while we are not at the end of the array let us take the element compare it to the Target and if it's equal to the Target return so this is what we are trying to do so we are looping from left to right and if we find a Target we return the target basically if you have two target the first one will be fine first so let us submit this and see um so if we do so we are going to see that okay it is working that means we are correct about the fact that what we need to do is just about sing an element in an array but just that we have Conant here the first con I just mentioned you can't make more than 100 call and then if you have an array of 100 element basically even this approach will help you to AC the result with less than 100 call because the AR has just 100 element but here is not the case here your array can go up to 10^ 4 so here your array can go up to 10^ 4 so here your array can go up to 10^ 4 so this will not help you to pass all the solution now you know what you're supposed to do you know what is block you from passing all the solution and now you should think of an approach that will help you to cross this bounding of 10 power 4 and then since we have an array which is actually increasing and an array which is actually decreasing we should think of binary search and before thinking of binary search we need to evaluate is binary search actually enough to solve this problem so uh we know that binary search actually solving the problem is Big of log of n so the question is what is the number of call we can have with log of um with log of n given this input so you can compute it easily by just say uh you can just compute it log of 10^ 4 ID by oh no equal to this of 10^ 4 ID by oh no equal to this of 10^ 4 ID by oh no equal to this divided by log of 2 this is the number of call that you expect to have with an input 10 power 4 so average 14 call okay nice we have an average of 14 call so if you use a binary search we are going to have the result into average 14 call which is actually less than 100 which is nice which is something we want but we know that binary call can be binary search can be applied on an array which is in a sorted array right but our Mountain array is not sort how can we organize our to make it s so uh basically we have an arrow which is climbing and going down so we have two part of the array which are actually Sol so what we can do is that we can divide our array into two and then take the first part which is s apply the binary s in need search for the element and go to the second part apply again the binary search and search for the element and if the element is not found in the first and the second one then we return minus one so basically that will be our goal here to separate the AR into two AR we need to find the pick element so the first thing we are going to do is find the peak element the second thing is sarch into the first array the last thing into sech in the second array and we are going to return the result at the end and then you may ask yourself by doing all those operation are we still in the are we still going to perform less than 100 request and the answer is yes because we are going to search the peak using binary search which is average 14 we are going to search to the left using binary search which is average 14 and we are going to search to the right using binary which is also average 14 which give you um 40 something 42 now uh you are going to say that it's a little bit above the 42 request but it's still less than 100 request so we are 100% sure that with request so we are 100% sure that with request so we are 100% sure that with that approach we can indeed find ourself in the boundary and have the result now the next thing is how to find the pig so for us to search the pig we are going to uh use a binary search and then what we are going to have is something like this we are going to have a starting point here which is the first element of our array and we are going to have an ending point here which is the last element of our array and basically what we going to do is that we are going to find the middle of this element and then in the first case will be here and what we are going to say is that if that middle is actually less than the element just after him that means the pi is in the subar greater than um the middle the temporary pink otherwise that means the p is actually in the left array so if in the first case the temporary Peak that means the middle is actually less than the element plus one that means this one can be shift to the P plus one right and otherwise that means the first element can be shift to the peak right so that's what we are going to implement here our approach now will be we going to find the PE we going to say okay while we haven't me why the end is not equal to the start we take the pick as the middle element that means the start plus the different divid by two and we are going to check if the peak the mountain peak is actually less than the mountain PE + one then we are than the mountain PE + one then we are than the mountain PE + one then we are going to say the start will move to p + going to say the start will move to p + going to say the start will move to p + one is exactly what I just explained here now you understand why I was saying that you have more than 42 requ because here you are calling for the PE and you are calling for the pe+ one so basically are calling for the pe+ one so basically are calling for the pe+ one so basically you can say that your session Pi is actually 2 * log of N and the session actually 2 * log of N and the session actually 2 * log of N and the session ascending will be log of N and in the same will be log of n this is actually 4 time log of n which is still uh something acceptable right so this is something we can go with without um being afraid of falling into out of boundary so uh let us continue with our pick function we are able to have the pick with this approach and then um at the end the pick will take the start so at the end basically the pick is the start the end will be equal to the start so the P can take the start or the end now that you have the PE you need to perform the search so this is literally uh the binary search that we did yesterday and the day before yesterday we apply binary search on no yesterday we use build in binary search the day before yesterday we use a modifi binary search so this is definitely the week of binary search uh check out the previous video if you want to know more about binary search but uh in binary search you definitely search an element into a sorted array given that you know the element right so what we are doing here is the binary search we take we Define a midle element we get that element we compare the element to the Target that we are searching if it's equal then beam we have it we return if it's not equal then we move then we perform a check if it's not equal we are going to check it's actually the element let me take this so you understand better let's say we are searching an element here and then um let's say we have this element is actually one this element is six this element is 18 this element is 20 and this element is maybe let me 40 this element is actually 50 right so what you're doing is that let's say we are saring for six we searching for six for instance if you're searching an element in a binary search in a b in a binary way you are going to define the first the starting point the first element and the ending point here so you have the ending point here and then you are going to define the middle in this case the first middle will be this and the idea is that you're going to compare this middle to the element that you're searching let's say we are searching for six for instance you're going to say okay is six actually greater or equal is six actually equal to the middle Element no it's not actually to the middle element so we don't return it we are going to check okay is actually 6 less than the middle element yes it's less if it's less so you just move this end pointer to the position Target minus one if it's not the case if you were searching maybe for 14 you will see that it's actually the middle element uh less than the search element yes if it's less now you are going to instead move this one forward so basically the idea is always to kind of split the array into two sub array uh by saying that okay the array is s if I'm searching for this element which is not at the position that I was thinking it was what part of the ARR is my element is it the upper bound or the lower bound because each of the iteration will actually split your input into two so either be in the array consisting from the middle to the end or from the middle to the zero so each iteration is going to split spit that is what make it to be log of n so by doing so you are able to have uh the result in case it exist if it doesn't exist you're going to twist you're going to move left right until you find that your both indexes the start and the end are actually equal in that Cas that means the array doesn't exist if it doesn't exist you're going to search in the second part now searching in the second part is basically the same but just that the check is actually different right since you actually in a descending array you're just going to say if the current element is actually greater than the target instead of updating the end you're actually updating the start because the AR is actually descending and at the end if you don't have the answer here that means it is not in the first array it's not in the second array so it doesn't exist we return minus one so this was my Approach of solving this I hope you do enjoy it uh let us R and see what it gave you see it's actually perform well so this is what we have you see we have 0 millisecond it's actually performing pretty great we have all test cases green so this one my P of Serv this I hope you do enjoy feele to leave me any comment I'll be really happy to interact with you regarding this see you on the next videoo
Find in Mountain Array
two-city-scheduling
_(This problem is an **interactive problem**.)_ You may recall that an array `arr` is a **mountain array** if and only if: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `mountainArr`, return the **minimum** `index` such that `mountainArr.get(index) == target`. If such an `index` does not exist, return `-1`. **You cannot access the mountain array directly.** You may only access the array using a `MountainArray` interface: * `MountainArray.get(k)` returns the element of the array at index `k` (0-indexed). * `MountainArray.length()` returns the length of the array. Submissions making more than `100` calls to `MountainArray.get` will be judged _Wrong Answer_. Also, any solutions that attempt to circumvent the judge will result in disqualification. **Example 1:** **Input:** array = \[1,2,3,4,5,3,1\], target = 3 **Output:** 2 **Explanation:** 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2. **Example 2:** **Input:** array = \[0,1,2,4,2,1\], target = 3 **Output:** -1 **Explanation:** 3 does not exist in `the array,` so we return -1. **Constraints:** * `3 <= mountain_arr.length() <= 104` * `0 <= target <= 109` * `0 <= mountain_arr.get(index) <= 109`
null
Array,Greedy,Sorting
Medium
null
922
hello welcome to the channel i'm here to do my 100 legal challenge today we have lit code 922 sort away by parity 2 so given an array a of non-negative 2 so given an array a of non-negative 2 so given an array a of non-negative integers half of them are odd and the half of them are even sort the array so that where the a i is odd and whether a i is even it's confusing but yeah so now you can take a look at this example so when the index is zero so it's even so this number of this location should be even so now we can see this is even 0 1 2 so this integer supposed to be an even number but now in here index of one as odd but here's even number so the result should be replaced this mismatch and then you will come out with a correct order so that is the example and the order of this is fine when they fulfill this condition here so the solution for this one you can either create a new memory stack or array and then keep store sorting them and when you find even number put to even index and odd number and put it on index that will come up with solution but it's using extra memory but we can use two pointer pointed to the even which is um zero one pointed to one the odd index so we find which one is valid if the current zero is a valid number and we jump we keep searching and until we find the in invalid position for odd and then we find it for even then we can replace them and then we keep searching to the end of the array then it will come up after sorting uh the mismatch position then we come up with a right order so we first let's take a look at this we will have in even equal to zero and in r equal to 1 so we have a while loop even less than a dot length and on less than a dot link so now we have this and what we need to do next is keep searching for the mismatched position while even first less than a dot link and a even mod to equal to zero that mean even should equal to two if they are in the right position then we jump two step for the next even position while odd less than a dot link and a r could be as an odd number then r should be skipped so now this fulfill and what we can do is double check even it's less than a dot length and odd less than a dot lane then that means they are still in the array that waiting for uh exchange then we can exchange them by taking tam equal to a even and a even equal to a r and a are equal to 10 so now switch it we can move even pointer for two more and odd move two step four and until the while loop is done and then the array should be in place now we just return a for the result now let's run this code and it looks good for the test and now that's it for this question and if you have more questions please comment below and i will see you in the next video bye
Sort Array By Parity II
possible-bipartition
Given an array of integers `nums`, half of the integers in `nums` are **odd**, and the other half are **even**. Sort the array so that whenever `nums[i]` is odd, `i` is **odd**, and whenever `nums[i]` is even, `i` is **even**. Return _any answer array that satisfies this condition_. **Example 1:** **Input:** nums = \[4,2,5,7\] **Output:** \[4,5,2,7\] **Explanation:** \[4,7,2,5\], \[2,5,4,7\], \[2,7,4,5\] would also have been accepted. **Example 2:** **Input:** nums = \[2,3\] **Output:** \[2,3\] **Constraints:** * `2 <= nums.length <= 2 * 104` * `nums.length` is even. * Half of the integers in `nums` are even. * `0 <= nums[i] <= 1000` **Follow Up:** Could you solve it in-place?
null
Depth-First Search,Breadth-First Search,Union Find,Graph
Medium
null
1,359
Loot to control valid point delivery obscene means you are appointed then it means 230 delivery will be tied to-do list like disgusting 2.23 2.23 2.23 question on drum logic under is yes to very simple subscribe ko tum and this song MP3 subscribe my channel subscribe no If done then you can subscribe this is your minus plus okay so this will go ka UN - 151 - so this will go ka UN - 151 - so this will go ka UN - 151 - subscribe okay so this for everyone - Subscribe to the channel - Subscribe to the channel - Subscribe to the channel and in it the mission Flight for - 123 For that you used to live as a reader for D3 Life is okay so every for every end means only here P one two three let's go behind here okay so all you have to do is this one long Long Jhaal This is absolutely fine so subscribe this video channel and subscribe thank you Jhaal
Count All Valid Pickup and Delivery Options
circular-permutation-in-binary-representation
Given `n` orders, each order consist in pickup and delivery services. Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). Since the answer may be too large, return it modulo 10^9 + 7. **Example 1:** **Input:** n = 1 **Output:** 1 **Explanation:** Unique order (P1, D1), Delivery 1 always is after of Pickup 1. **Example 2:** **Input:** n = 2 **Output:** 6 **Explanation:** All possible orders: (P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1). This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2. **Example 3:** **Input:** n = 3 **Output:** 90 **Constraints:** * `1 <= n <= 500` Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that : p\[0\] = start, p\[i\] and p\[i+1\] differ by only one bit for all 0 <= i < 2^n - 1.
Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start.
Math,Backtracking,Bit Manipulation
Medium
null
1,043
hey everyone today we'll be solving lead code 1043 partition array for maximum sum it's a very important question and has been ask in Amazon Adobe and Facebook let's have a look on the problem statement in this problem we are given an integer array a r partition the array into sub arrays of length at most K okay after partitioning each subarray has their value changed to become the maximum value of the subarray okay it is saying that we will be given an array and we have to partition these array okay let's say uh whatever partition you are making let's say I have partition in this form and the constraint we have to keep in mind that every partition should not exceed their length from this K so here the first partition is having one element Two element and one element each for rest of the partitions so every partition is having a value or length less than K so all partitions are valid now if I try to partition this array again and if I partition the form like this first three element in the first partition and then four element in the second partition if I do this kind of partitioning the first partition is having three elements and second partition are having four element which is more than K so this is not a valid partition and as per the problem statement we have to partition this array such that every partition is having a length less than equal to K so let's say I'm doing this 2 so all the elements are valid and after partitioning what is going to happen is that in this array every element let's say one will be converted to the maximum value of its partition so maximum value of this partition is 15 so one will be converted to 15 and 15 will also be converted to 15 7 will be converted to maximum value of its partition this partition which is N 9 is already maximum and from this partition maximum value is five so two will be converted to five and five is already five 10 is only one element in the partition so 10 will remain the same so sum of this partition is going to be 30 + 18 + 20 that is 68 50 and 68 okay 30 + 18 + 20 that is 68 50 and 68 okay 30 + 18 + 20 that is 68 50 and 68 okay so 68 is the sum 68 will be the answer if I partition in this form this is a candidate to our answer not the actual answer so one possibility is something like this and if I try to partition it again let's say now we will use our mind to maximize this answer so let's say if I partition something like this array and here 10 I'm seeing the maximum value if I partition like this here I did three partition of this array and every partition is having a length less than equal to K three elements in one partition one element in second partition and three element in second partition so from the first partition the values of all three elements will be changed to maximum value which is 15 from the second partition maximum value is 9 already from the third partition maximum value is 10 so all three values will be converted to 10 and 10 if I make sum of all of these values it will come to 45 + 9 + 3 10 to 45 + 9 + 3 10 to 45 + 9 + 3 10 30 75 + 9 which is 30 75 + 9 which is 30 75 + 9 which is 84 in 84 is more than 68 which I previously calculated using this partitions so now 84 is our candidate answer we will consider 84 and we will be checking all the partition and whatever like sum is going to be maximum that is a valid partition and we have to return this value this 84 and I see that we cannot have any partition better than this because here the maxim value 15 Maxim value is 10 and we cannot extend partition more than three so 84 sum of this array after this conversion is going to be maximum and also they are saying that written the largest sum of the given array after partitioning and test cases are generated such that answer fits in 32bit iner okay we don't have to worry about the Overflow and all we'll just keep on calculating the sum okay now the problem statement is clear to you so in the as the problem statement we are G we will be given an array and a value K and we have to partition this array in such a way that resultant array sum is maximized and the resultant array will be uh array will be formed from these element the maximum of this partition is 15 into 3 so sum from first partition is 15 into 3 from second partition it is 9 from third partition it is 10 into 3 so some of these values are my array sum and that array sum should be maximized now I hope that problem statement is clear to you and we are also given constraints that array dot length is already only 500 not more than that now we have to build our approach to solve this problem here what we have to do is we are given an complete array and from this array we have to find the maximum answer such that the every partition we can make is of size 3 maximum okay so our array is going to start from this and we have to solve this way let's say if I have to look up any small problem let's say I consider only these four elements so the uh like problem statement will become 9 2 5 and 10 but the partition side will remain the same so here what we have to calculate is partition this array in such a way that every partition is not exceeding the uh length of three and we have to maximize the sum so this problem statement is almost similar to this problem statement just the input array is getting smaller okay so we can say that this is a sub problem to our bigger problem this is our sub problem and this is our biggest problem that we have to solve this whole array what do we understand using a SL sub problem that we are having a sub problem and if we have a look further let's say we are solving this array only 5 and 10 with Partition equal to three this is another Sub sub problem and least at the least we have 10 as a array and K is equal to 3 so we are uh getting sub problem in such a way that at some instant we are left with no array and k equal to 3 What is the maximum sum we can get zero as a maximum sum so here we are having a load of sub problems and we are solving the sub problems using recursion from the bigger problem if we have to solve a smaller problem and we'll keep on doing a Sol smaller problem and then in that in the end we are getting a terminating case or Edge case so this is nothing what a than a recursion so we are we will be trying to solve this function using recursion okay now let's try to understand how we will be Sol solving it using recursion let's say I have some kind of helper function where it is getting a solution and some Global variable let's say this is this array and this K value so I'm what I'm passing to my solution is idx is what the starting index of element from which I have to start solving so here the indexes are 0 1 2 3 4 5 6 and this is my bigger problem that starting from zero till the end I'm considering this whole array with k equal to 3 value okay so if I make a call to the solution function with index equal to0 this is the biggest problem I'm having and in the smaller case how I'm going to break this problem if we are starting with zero we have three possibility either we consider one in our first partition and we'll keep on doing the recursion with the rest of the array or we have second possibili considering first two element in our partition one where let's say partition one is and the other possibility is that partition one is having 1 and 15 so we took one as a only single element in the partition one or two elements in the partition one or if we consider three element in the partition one it will look like this partition one is having one or 115 or 1157 if I take four element in the partition one but here it will violate the K value because K value is three so it means we can have maximum three element in our part in any partition so here in this case we are not going to consider P P1 as a 115 79 the first scenario is that we are considering one as our first partition and then we will make a recursion call that we believe that our solution function is Will get answer to the rest of the array and I will just going to I'm just going to solve this only and the other possibility is if I try to solve this array 1 and 15 I will call I will uh take help of my helper function that I started with Index this and after index plus two onwards you have to solve I will just solve this much problem okay and third possibility is that I'm considering 15 and 7 and then asking my helper function to like uh to give me solution this index onwards which is idx + 3 if I'm solving onwards which is idx + 3 if I'm solving onwards which is idx + 3 if I'm solving this I will get answer from solution index + 1 solve it plus helper function index + 1 solve it plus helper function index + 1 solve it plus helper function will get you answer of index plus 2 onward Sol helper function will give you answer plus so sorry answer of index plus 3 onwards and you have to solve this why we are solving is three only three blocks because currently at every step we can have a partition of three size only and here so you have to solve only one partition one possible partition first partition that is partition one and partition one itself can be of three type because K value is three now to now try to analyze our partition partitioning if I partition from here my answer array will going to have one here and here this will be filled by recursion okay if I'm part partitioning against this value our first partition is going to have 15 two times and the rest of the thing will come from recursion helper for function now if I partition from here because maximum allowed partition size is three in that case my 15 will be considered three times because every element of any partition one can be replaced with the maximum element of that partition so 15 will be considered three times Plus Solution from my helper function so my sum of uh the array can will be 15 into three times 15 into 3 45 Plus Solution and further coal so I can make three coals here for K = 1 k = 2 K make three coals here for K = 1 k = 2 K make three coals here for K = 1 k = 2 K = 3 so you can say size equal to 1 2 3 = 3 so you can say size equal to 1 2 3 = 3 so you can say size equal to 1 2 3 or just ignore that so if K = to or just ignore that so if K = to or just ignore that so if K = to 1 I will be partitioning from here if k equal to 2 I will be partitioning from here and if K is equal to three that is size of the partition is three I'm going to partition equal partition from here so we have three possibilities if I'm uh and what I'm going to do is from this array in X = to 0 and from is from this array in X = to 0 and from is from this array in X = to 0 and from the answer of this function can have three possibilities so maximum possibility from this I will be taking as my answer so answer is equal to maximum of these three and these are my sub problems I'm going to call using recursion so for the one for the first one the sum is equal to 1 + solution one the sum is equal to 1 + solution one the sum is equal to 1 + solution whatever the solution we will get here in this case 15 into 2 30 plus helper function result here in this case first partition will give me 45 plus answer from helper function okay now what we have done so far is we have we are done with our first partition and answer for my first partition the maximum of these three value will serve my answer so in this way we are going to approach in the recursion form and what is the terminating case of the recursion let's say uh after doing keep on after keep on doing partitioning I'm getting an empty array or you can say my index is going out of bound greater than equal to n in that case whatever value of K it is the maximum sum we can get is zero as we do not have any element how do I get the sum so this is going to be our terminating case if index greater than equal to n return zero okay now we have to consider one more aspect which is whether we are getting these sub problem overlapped or not okay let's say here we made Call of solution of one because it was first index here I made Call of solution of three now from solution of one if I consider three elements if I further consider three elements in this partition let's say like this 1 2 3 4 so it will make further call to some Value Plus Solution of four right and from here if I make if I consider only one element because at every step we are considering either one element Two element or three element so let's say from this function we are considering three element or from this function we are considering only one element so from solution three will further make call to solution 4 because I only consider one element so here what we will do what we'll do is we are uh doing a recursion in this form coming here solving solution 4 and then we are doing a load of thing and after some time we are coming here and doing the like processing of solution 4 again it means we are going to have overlapping sub problems so these solution four and these solution 4 is getting processed multiple times it means that my solution function against the value of index should be cached somewhere that is if I'm solving solution 4 I'm getting some result and if I again time to solve solution 4 I should get the result from cach a not directly processing it if I do not process it from cach a so it will be n ra to power K uh about the time complexity being exponential what I'm going to do is I will be memorizing this solution I hope now here it is clear to you that first of all I tried to solve it using recursion and then we figured out that we are having overlapping sub problems and we need to do the memorization we have to cachier the answer and what is the what should be our cached like key idx value can be my key and in the constraint we have given that uh index size that array size is till 500 so if I take a array of 501 that is sufficient to store my answer and once we have did the recursion with memorization what is going to be our time complexity so the time complexity will be become order of n into K after memorization and what about the space complexity is nothing just uh the array I'm using to store my like cache then that would that will be order of n space complexity is order of n so this is the time and space complexity of approach so here we concluded our question using recursion with memorization that is topown approach using DP now we can code this out let's try to tackle this problem using recursion with memorization so first of all let's write the recursion for that uh for that let's uh let me take a solution function where I will be just passing the index and what should be the starting value of index zero and what we have to return is I will just directly return the value of the solution function okay now what this code represent is that this solution helper function will give me answer of this array where value of K is um as it is like given to us and this solution will be the solution of in uh array starting from zero index that is the biggest problem and here I'm not going to pass these parameters uh in with the within the like function call I'm keeping it globally so integer n to store the length of the answer integer array to store this array integer K to store the K value and here what I can do is this Dot N is equal to a DOT length a this dot a is equal to given array this do K is equal to K now my Global variables are organized and I can use these variables in my Global function now let's try to write our main function main U heart of the code which is solution function and it is going to return the an integer that is my answer to the biggest problem solution here integer index what is what was my terminating case that uh when there is no element left in the array that is if index is greater than equal to n we can return zero if index is greater than equal to n that is no element left in the array maximum on maximum sum of that array we can get is zero okay that's clear to us and now what I will do is I will try all the partition of K size from size 1 2 3 so let's say for that write a loop of K times I equal to 0 i l than k i ++ okay now here I will try to use all ++ okay now here I will try to use all ++ okay now here I will try to use all the partition of K size as well as I will have to check whether I + idx is will have to check whether I + idx is will have to check whether I + idx is not exceeding the limit it should be less than n this is a corner case here what I have to do is first of all I need to know what sum value the first partition is going to contribute for that I need to track the maximum of the current partition that maximum of the current partition I will keep on calculating while doing the iteration not every time so let's say it maximum equal to math dot minimum underscore value okay now maximum element of this partition is maximum equal to math do maximum so far and array of idx plus I okay this partition is starting from idx and I is the increment in that partition so first element of this partition is going to be idx plus 0 then idx + 1 idx + idx + 1 idx + idx + 1 idx + 2 and maximum I will be getting as I'm as I will be parti uh iterating through the partition from left to right okay now we uh this Loop will be called three times as per our first example in the first partition let's say I'm partitioning over one and then getting answer from this solution so I will also need to capture a variable result to Sol my result let's also keep it minimum value math do minimum value and what is the result I will get every time result is equal to first of all we have to maximize our result comma the value we will write here what value should we write the sum from current partition length let's say currently we have uh captured this first two element so how do we get some of these this partition only the maximum value we have captured so far into the current partition size what is current partition size I + 1 if I equal to 0 it means size I + 1 if I equal to 0 it means size I + 1 if I equal to 0 it means current partition size is 1 plus the solution helper function will give me result of the rest of the array solution where I will be passing index + solution where I will be passing index + solution where I will be passing index + I + 1 okay now have a look on the example one if we consider this as a first partition the helper function will get me result of this array index is zero I is also 0 + array index is zero I is also 0 + array index is zero I is also 0 + 1 index plus I + 1 if I consider this as 1 index plus I + 1 if I consider this as 1 index plus I + 1 if I consider this as a first partition I will get I will ask my helper function to get me answer of this subarray starting with index one okay in this way we have captured our result and ultimately what we have to return is nothing just a result now let's try to submit this problem if uh okay I'm running over sample test cases here I got some error we should not put semic colum here running it again over sample test cases okay so this is my recursion function recursion approach where it is going exponential every time it is going making creating three more calls if I submit the problem it is definitely going to give me tle let's try okay I got tle so we have to memorize our solution and in my solution function I'm only passing one variable which is index so if you are not if it is not clear to you that what we have to memorize just the variables among solution function we have to memorize so we have only one variable index what can be the value of this Index this index value can be from 0o to this array length minus one 0 to n minus one that is the DP array we can use can be of same size as array integer ARR DP so DP array is equal to new integer of size n so every value of index can be stored in this DP array and before returning from this function I'm going to store it against the index my first call my top down uh recursions first call which is the biggest problem is starting with index0 so DP of 0 is going to give me the answer that we are directly returning from the solution and before processing after processing we are storing our result and before processing we have to check whether we have already soled it or not and also we our elements are starting with zero okay let's say if we have all the elements are zero in that case we NE unnecessarily are going to make a further call so we will keep it a rapper class integer so that I can check whether it is not null or not DP of in if it is not clear to you can comment down below I will make uh I will try to explain you further we will check if DP of idx is not equal to null it means we have cached this value if this value is already cached we can directly return it return DP of idx else we will do the processing and then we will store our answer DP of idx equal to result okay now I think memorization is done submitting again whether we don't have any compilation error okay sample test cases are passed successfully submitting the problem it got submitted successfully hope you understood the problem now we will have a look on the bottom up approach hey everyone uh this is our second approach where we'll be using bottom up dynamic programming or you can say tabulation method to solve our problem so before that you have to understand what is dynamic but what is bottom up approach in the top down approach we saw that we have a bigger problem uh that is a complete array we have to solve and to solve this complete array what we did is we want solution of this and we the solution of this we can get is solving some part of this array and then we will further make a call to helper function that get me answer of this from the bigger problem we are moving to a small problem okay for value of k equal to 3 but here in this case in the bottom of approach we are we have a tendency in a different manner like first of all we will be solving a smaller problem first that is what is a smaller problem so 1 15 7 this is a smaller problem to this problem it means that if we have to solve this bigger problem it means we have already solved all of its smaller problem so first of all you have to understand what is the smallest problem here smallest problem is that we have only one element in the array or you can say we don't have any element in the array if we do not have any element in the array the answer of that input is zero if it do not have any element in the array and you have to partition in it in the size of K and you have to give me the maximum value of the array sum you can get that is zero it's clear to us visible to us so after that a small problem is this one considering only one element if we have to partition this array only how do we partition considering one in the partition and then if we are considering one in the partition we have one plus rest of the input which is smaller problem that is no element from that we are getting zero sum so if we have only one we are getting sum as one now let's say now our further bigger problem is 1 and 15 for one I have already stored that for a problem where the arrays like this we have a maximum answer is one now we have a array where we have two element 1 and 15 so for the 15 we have to do the partition how many ways you can do the partition as for the value of k is K value is three it means we can have at most three element in the partition let's say first of all we I took only one element that is only 15 in this way what is the answer 15 plus the answer of smaller problem what is the smaller problem answer of this one array but that smaller problem answer is already stored here that is 1 so 15 + 1 16 is going to be the so 15 + 1 16 is going to be the so 15 + 1 16 is going to be the answer okay and what are the other possibilities to do the partition the second possibility to do the partition is partition from here if I partition from here what is going to be the value I'm considering these two element in that partition 15 into 2 that is 30 because both the items will be converted to the maximum element of that partition so 30 plus smaller problem what is the smaller problem we don't have any element in the array that is zero we'll get so 30 is the answer if we have an array where we have two element 1 and 15 so till 15 answer would be 30 and this we can store in our DP array I hope that is clear to you now let's say uh again we have one more element 1 15 and 7 so this is my bigger problem if we are moving to the bigger problem it means you have already solved a smaller problem so for this 1 I know the answer 11 15 if that is the array we know the answer the maximum answer we can get is 30 now for this 115 and 7 we have to know the answer maximum answer we can get we have three possible ways to do the partition if I partition from here I won't un of this sub problem if I partition from here I want answer of this partition this a problem where I don't have any element so let's say for the partition one the possible candidate to our answer is 7 plus answer so far is 30 which is 37 if I partition from here let say this is second partition 15 into 7 which is these two element in the in this part current partition it means both of our element will be replaced with the maximum one is 15 so 30 from this partition plus smaller problem which is one only so for this one I know the answer from my DP array which is one 30 + 1 which is 31 so if the partition 30 + 1 which is 31 so if the partition 30 + 1 which is 31 so if the partition is this that is partition three I have 1 15 and 7 in one partition so as sum from this partition will be 15 3 are 45 plus sum from Sol problem which is zero so maximum value is 45 it means from 1 15 if I have this array the maximum value I can get is 45 so 45 will be stored here so in this way we are going to use our approach to fill this table and it is a 2d 1D array one day array of similar size we can have as array and we can fill this array in this manner so if I if we keep on filling this array so ultimately at the last index we are going to have answer of this complete array that maximum sum we can get after making partition from this array is going to be stored at this position okay I hope that is clear to you let's do one more iteration 11579 1 15 7 9 so this is my array and D P I have filled so far is 1 30 45 and 9 we have to fill okay this is a current problem we have to solve so we will see how many partition we can make so first of all I can make this partition let's say this call it partition one or you can say this partition two where 7even and 99 is one partition or this is partition three where 15 7 and N are in this partition so as this is clear to you I'm let me just check whether store the answer of partition 3 is going to be 45 plus 1 that is 46 okay so for the partition two what is the value the 30 from Sub sub problem plus from this partition 7 and 9 that is 16 46 now for the partition one problem from uh answer from sub problem is 45 and from this partition itself it is 9 so 45 + 9 is partition itself it is 9 so 45 + 9 is partition itself it is 9 so 45 + 9 is 64 so this is giving me the maximum value it means the partition one is a good partition and the maximum value I can achieve so far is 64 okay so in this way you are going to fill the table so first of all taking a DP array of same size and then for every index I will go J for the J index K times in the left side firstly I'm considering one element uh like for every value of I will I considering like so how we are going to solve this problem 1 15 7 9 for every element for every value of I it means from I we have to capture the value of this subarray it means we will go to the left so first of all we will go to the left as per the value of K if k equal to three we will considering consider one element starting with uh I and then two elements starting with I three elements starting with I in the left direction that is our J variable will go in the left side and from uh if we are going out of bound we can directly return zero that is for the empty array the result is zero okay so for every index I will move my pointer J to the left side for to like to check the possibility of K element in the part in that partition will if I will keep one element in that partition or I will keep Two element in that partition I will k key element in that partition in this way I will capture the value of that partition and will and I will use my previously solved sub problem value that is uh this memorization value okay now let's try to write the code for this in that case we will get it will be more clear to us and also let's try to solve the time comp time and space complexity for this what is the time complexity I'm moving my j i value from 0 to n minus1 so that is I is going n times n iteration of I and for J can have ma Max K iterations so the time complexity will be n into K and what is the space complexity would be order of n similar to the complexity we are getting in top down approach let's start writing the bottom up approach for this problem here first of all let's capture the size of this array and then I will take a DP array of same size new integer of N and now I will keep my I pointer from starting of the starting element of this array till the last element of this array that is from I = to 0 to I less than n i ++ 0 to I less than n i ++ 0 to I less than n i ++ okay that's clear to us it means that we have to solve the problem ending at I index so for I equal to0 it means we are trying to solve the problem where we have only one element I equal to 0 that is for one it means from starting from this I will move to the left side using my J pointer so for that let me just write another loop in i j equal to I and J minus so what should be the value of J at the last time at the at uh at most to the left uh we can move only K times to the left so it should be J greater than IUS K if the value of I equal to 4 so we will move the JP pointer till IUS K okay that is fine and we will also check whether the J is not going out of bound so for that I will keep J greater than equal to zer and here as the J is decreasing J minus okay that is clear to you and now key uh while capturing the partition we will keep track of the maximum value and the result as per our top down approach int maximum integer dot minimum value and in result is equal to integer dot minimum value so to capture the maximum value is equal to math do maximum value and the element at that J index so array of J okay maximum element is captured now let's capture the result so result is equal to math do maximum of result comma size uh sorry sum from that current partition so current partition length is i - J + 1 partition length is going is i - J + 1 partition length is going is i - J + 1 partition length is going from I to J including both so that's why + one and we should make multiply this + one and we should make multiply this + one and we should make multiply this with the maximum element of that partition DP of J minus I because till J that is that element is considered in the current element okay now we also need to see that J - 1 is not going out need to see that J - 1 is not going out need to see that J - 1 is not going out of bound okay so for that if the J is going out of bound it means from that array our answer should be zero because there is no element in it so we can put a condition where J minus 1 is greater than equal to Z or you can say J greater than Z if J greater than 0 then we can use it this otherwise we are good to use zero so this condition is important it means that uh if I'm at one I have considered one from the remaining ele remaining uh array the DP of uh where the DP of J minus 1 I have to calculate but it does not exist I will get zero okay now what I will do is I will be storing this result so this is the maximum among all the partitions at ending at I index so this result I can store in DP of I that is equal to result so maximum answer I can get till I index is this result so this is smaller problem and then keep we'll keep on solving bigger problem using smaller problems okay I hope the problem is fine let's try to submit our sample test cases missing return statement and what we have to return is in the end we can directly return DP of n minus one DP of n minus1 is storing answer from for whole array okay sample test cases are passed submitting the problem it got submitted successfully hope you understood the problem thank you guys
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
78
hello welcome to my channel and today we have leeco 78 subsets so given an integer array numbers of unique elements return all possible subsets and the solution set must not contain duplicate subset so we turn the solution in any order so now example one two three we have all the combination uh in this case style is zero i mean the empty array and then you can put individual one only one digit we have three two digits we have three and three digits only have one combination uh this is uh for one two three array but in this order it's hard to see but now i rearrange this one in this order so it's much better to see so now we have an empty array and this big outside array is output so we first put this empty array in this um output array first and then we try putting in an integer now we have the order in one two three so we put one in there first and until we put um enough until we get to the last digit so now we have one and this is array become the ray currently become one and put it to this output array and then we put another one next one is two put it in this array the current array right now is one and two so still not reaching to the end of the array yet and we'll put three in there and then now three will put it into the i mean this one two three put it to the output and reaches to the end of the array now one needs to be changed you will go back there and change one and then we'll put i mean actually two now two is not reaching to the end of the array yet but three is the end of the array so we move three now we have one two for the current array so after two there's still one digit which is three so we place two by three to become one three and three is the end of the um array then we remove that one so now we have one and it's really reaching the end of the array already so now update one become two and we do the same process and now you have the output so i and then we can take a look at the code and then you sell explain so list of list is a template we'll make that one first as outputs equal to new arraylist so also we turn the output and in between we will have a helper function or we can do backtrack i'll use helper right here that put in the nums output starting from zero which is the index and a new temporary array this okay so helper functions have all the things that get inputted the important thing is how to write a helper function so let's see we have the type numbers and we have a list of lists or output i also have integer index i also have a list of integer called current list so now this is all the uh type for the input the construction is done um first thing first uh we'll put the current array that start with empty array we put that into output new array list that take in the current this it's kind of different from python that's how java did that and that's first thing and you have the current keep track of all the current state and next thing we will look through everything after the index is equal to index i less than the another array which is num and now this is the mid part that we need to modify the current array current list we add um because we have index right now oh actually we have i right now so we will put nums i in there and after you put one in there and then look through everything after that and do the recursion of the helper function that taking is num output index plus one but it started from next index because you cannot repeat one and one then we have index plus one and the current is the current that after adding the num i then we done for here so after you loop through the num i in the current one and we will move it remove uh no it's current the size minus the last one of the current uh list after you for example if you add one in here the um the one will be the first number that in this current list and then we'll do everything after the current list and three so after the one is done and we will move the one and then put two in there because index will be plus i will be plus one and then we put two as a leading number in this current on this then that's it for this backtracking num problem let's see if it's working or not hmm um okay this is i think if there's anything wrong let's see i plus one uh nums minus oh here shouldn't be at n minus one okay cool and that's it for this question that's nice it's bit 64 it's not bad so if you have any question please comment below and i will get back to you as soon as possible and i will see you next time bye
Subsets
subsets
Given an integer array `nums` of **unique** elements, return _all possible_ _subsets_ _(the power set)_. The solution set **must not** contain duplicate subsets. Return the solution in **any order**. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** \[\[\],\[1\],\[2\],\[1,2\],\[3\],\[1,3\],\[2,3\],\[1,2,3\]\] **Example 2:** **Input:** nums = \[0\] **Output:** \[\[\],\[0\]\] **Constraints:** * `1 <= nums.length <= 10` * `-10 <= nums[i] <= 10` * All the numbers of `nums` are **unique**.
null
Array,Backtracking,Bit Manipulation
Medium
90,320,800,2109,2170
1,845
hello everyone and welcome to yet another daily challenge from lead code so this challenge is set reservation manager it says to design a system that manages the reservation state of N seats that are numbered from 1 to n implement the seat manager class a seat manager Constructor seat manager initializes a seat manager object that will manage N seats numbered from 1 to n all seats are initially available okay uh in reserve features the smallest number unreserve seat reserves it and returns it number void unreserve with integer seat number unreserve the seat with the given seat number so we can check over here it initializes this thing reserves it so one is reserve two is reserve when we call on reserve two is popped out makes sense so looking at the constraints so it's 10 to^ constraints so it's 10 to^ constraints so it's 10 to^ 5 so seat number is less equal to n which is obvious for each call to reserve it is guaranteed that there will be at least one unreserved seat for each call okay to unreserve it's guaranteed that seat number will be resered which should be the case at most 10 to^ five calls in the case at most 10 to^ five calls in the case at most 10 to^ five calls in the total will be made to reserve un Reserve okay oh makes sense it's it is pretty straightforward then so while jumping into code one thing we need to remember is we need to suggest the minimum the least seat to reserve and to unreserve they just provide a seat number so that's find for us so for Reserve we need to provide the Le seat so we can say we can have an appropriate seat for such use case stores minimum or least seat number which could be allocated so life would be super easy when we are having just reserves going on that means I can just suggest seat one then seat 2 seat 3 seat 4 but that's not a case once uh seat one seat2 C3 C4 is assigned and post which we can see that cat 2 is unreserved next thing I cannot suggest seat 5 I need to suggest C two C2 over here so that is one reason that we cannot just rely upon the appropriate seats uh appropriate seat number so we need to have one mechanism to know that unreserved seats so what are the unreserved seats which are having which we are having so we can say that unreserved seeds uh is a set of priority Q is a priority Q why priority Q uh so that when whensoever we are pulling this out any element out we are certain that the first element is the minimum element and by default the priority Cube within Java is mhip so we do not need to worry about any other implementation over here we can just go ahead and we can say that unreserved seats is equal to new priority q and the appropriate seat initially is one why one as the counting starts from one for seats and if for any other the reason we see that n is less than or equal to zero uh as number of seats starts from one and there should not be any other seat numbers less than or equal to zero then this needs this is an invalid case and we need to throw uh through new exception over here invalid number of seats commenting this out because uh uncommenting would throw an exception as we need to add the method signature and adding the method signature would lead to an compiler error so keeping it as it is now here we see that if the unreserved seat is empty seats which means our life is very simple and there is no unreserved seat it means we can just go ahead and iterate go and suggest the APT seat as this is incrementally the least numbered seat okay so now we are just returning return app seat and we having an increment operation as well post which we have return so it's a postf increment but for some cases let's suppose we do not have this empty so we are just go going and saying return unreserved seeds do poll you're polling this out and we are suggesting that take this seat for you which is obviously minimum and now we are unreserved so let's first check whether this function is complete or not uh we have and reses complete and this so there is one case over here we can add here apt seat is equal to max number of Max seats that would be a better choice of wordings so what I'm saying trying to say over here is if appropriate seat is equal to Max seats so in no possible way is greater than Max seats then in no possible way we are allowed uh to have to return this seat you're getting this point if the chairs are only 10 and we are saying a guest to sit on a chair number 11 this is not a valid case so in such case we are throwing new exception saying seats overflow or seats are less this would make sense seats are less and for such cases we take ahead a new variable known as int Max seats and we are marking this final so that we don't want to change it uh in the coming time and Max seats is equal to n so this is the case for us now so and I think this is completed now well now for unreserved thing unres method we see that seat number should be valid that means seat number should be greater than zero us and it should be less than seat Max seat sorry less than or equal to Max seats then only it is valid else uh if it is less than or if it is greater than Max seats then it's not a valid case and we need to throw in such cases an exception through new except over here uh stating that invalid seat number to unreserve deserve okay my bad spelling mistakes yep and return null in such case just to stay consistent with compiler anyways the compiler is consistent even if I didn't throw anything but still uh now we are sure that the seat number is fully valid so we just go ahead and push uh offer this to our unreserved seats uh okay we have unreserve seats completed we have Reserve method completed and we have Constructor completed let's run this well it shows the prominent compiler error stating it is null so null return is not allowed when it in case of void so this return statement well it's accepted uh as a first test case okay let's check for others as well sure it is accepted solution uh so this was about seat reservation manager do let me down know down within the comments uh what are your thoughts upon this explanation that was from my side thank you no
Seat Reservation Manager
largest-submatrix-with-rearrangements
Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`. Implement the `SeatManager` class: * `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available. * `int reserve()` Fetches the **smallest-numbered** unreserved seat, reserves it, and returns its number. * `void unreserve(int seatNumber)` Unreserves the seat with the given `seatNumber`. **Example 1:** **Input** \[ "SeatManager ", "reserve ", "reserve ", "unreserve ", "reserve ", "reserve ", "reserve ", "reserve ", "unreserve "\] \[\[5\], \[\], \[\], \[2\], \[\], \[\], \[\], \[\], \[5\]\] **Output** \[null, 1, 2, null, 2, 3, 4, 5, null\] **Explanation** SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats. seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1. seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2. seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are \[2,3,4,5\]. seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2. seatManager.reserve(); // The available seats are \[3,4,5\], so return the lowest of them, which is 3. seatManager.reserve(); // The available seats are \[4,5\], so return the lowest of them, which is 4. seatManager.reserve(); // The only available seat is seat 5, so return 5. seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are \[5\]. **Constraints:** * `1 <= n <= 105` * `1 <= seatNumber <= n` * For each call to `reserve`, it is guaranteed that there will be at least one unreserved seat. * For each call to `unreserve`, it is guaranteed that `seatNumber` will be reserved. * At most `105` calls **in total** will be made to `reserve` and `unreserve`.
For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix.
Array,Greedy,Sorting,Matrix
Medium
695
472
hey guys in this video i'm going to walk through is the code number 472 concatenated words so we are given an array of strings uh words without duplicates and we need to return all the concatenate verb in the given list of words so a concatenated word is defined as a string that is comprised entirely at least of two shorter other words in a given array so let's talk another example here so uh we can't the cat cats dog cat etc can see so the output required is cats dog cats so because cats dog cats can be concatenated or comprised by cats and dog and cats which can be fine in the original list and also dog cats dog can be concatenated by dog cat and dog and these three sub words can be found on in the original list as well so we have a another one is a red cat dog cat so red cat dog cat all this word can be found in the original list so i think this is a little bit more simple example as you can see uh cat dog so this word can be separated by the two smaller words which is cat and dog so this problem was asked by amazon so amazon's crazy about this question so let's take a look at how can we solve this problem um first we have a set word set which is converting the original list to a set which is takes a little bit less time to look up and then we have a function called good word so basically we loop it through all the index uh from one all the way to the length of the um the in the length of the word minus one because the range does not return the last index and then we have a prefix and suffix so prefix is everything before the index including the word add that index and suffix is everything after and if the prefix is in the word set and if the suffix is in the word set or if the suffix can be pushed back to this function so it's a recursive uh function and then we return a true and at the end if this is a good word we have planned we append it to the answer and at the end we return the answer and this function uh logically it works well and by concept but it's a bit slow uh it's gonna run out time for legal validation because as you can see a lot of uh for example for this example in here um a lot of repetitive work going on in here so that's why uh this is not the most efficient solution and we can optimize based on that how can we do that and i have written a slightly better uh functions called check basically the same as the last one good words but the enhancement is that we use a dynamic programming so we use a memorization dictionary to keep track of um all the intermediate steps so we don't repeat our work so let's take a look at it so we still have the prefix and suffix and um if the prefix yes this part is very similar to what we had before however the enhancement is that we have the memorization dictionary so if the given word is already in the memorization dictionary and then we don't do the rest we just directly look up that dictionary and then return it and also another enhancement is that if the lens or the word is only one we don't do we don't need to do the rest because there's no way to well you know um there's no way to another word that is concatenated for that word and um and uh when we write this a memorization dictionary after we check it before we return the function we also save the result to the memorized dictionary so and this one will be for the future use so let's run it as you can see it passed all the tests uh for term complexity-wise uh for term complexity-wise uh for term complexity-wise uh imagine if uh the list is all different words and none of the words in the set can be uh concatenated and by any other word in the set in that case that will be the worst case scenario that means we have to uh look through the entire for loop still entire case so the time complexity will be o of k times n so k being the longest the length of the longest word and end me being the number word that will be the worst case scenario and for um space complexity we're going to be b over n because we have the memorization dictionary also the word 7 here so that's so much for my solution i hope this is helpful if it does please like and subscribe that would be huge support thank you so much for watching and i will see you in the next video thank you
Concatenated Words
concatenated-words
Given an array of strings `words` (**without duplicates**), return _all the **concatenated words** in the given list of_ `words`. A **concatenated word** is defined as a string that is comprised entirely of at least two shorter words (not necesssarily distinct) in the given array. **Example 1:** **Input:** words = \[ "cat ", "cats ", "catsdogcats ", "dog ", "dogcatsdog ", "hippopotamuses ", "rat ", "ratcatdogcat "\] **Output:** \[ "catsdogcats ", "dogcatsdog ", "ratcatdogcat "\] **Explanation:** "catsdogcats " can be concatenated by "cats ", "dog " and "cats "; "dogcatsdog " can be concatenated by "dog ", "cats " and "dog "; "ratcatdogcat " can be concatenated by "rat ", "cat ", "dog " and "cat ". **Example 2:** **Input:** words = \[ "cat ", "dog ", "catdog "\] **Output:** \[ "catdog "\] **Constraints:** * `1 <= words.length <= 104` * `1 <= words[i].length <= 30` * `words[i]` consists of only lowercase English letters. * All the strings of `words` are **unique**. * `1 <= sum(words[i].length) <= 105`
null
Array,String,Dynamic Programming,Depth-First Search,Trie
Hard
140
7
okay we should what's up guys Nick here we're doing some moral eco problems too if you don't know I do live coding and tech stuff on twitch and YouTube so check that out in the description we're doing number seven reverse integer we're gonna be doing the Java implementation and I'm gonna explain it to you so give it a 32-bit signed integer basically it a 32-bit signed integer basically it a 32-bit signed integer basically what we're gonna do and this is you take an integer well they give you an integer in this method it's called reverse and well guess what you reverse it right so if you have one two three you want three two one and if you have negative one two three one negative three two one if you have one twenty one two one okay so not too bad and you have to be in the boundaries of the lowest integer and the highest integer which is you know 32-bit signed integer range so how know 32-bit signed integer range so how know 32-bit signed integer range so how are we gonna do this how do you were reverse an integer you know that's that was you know that was confusing to me to like turn it into a string and then you know go back and you know make a new string and return it well no there's actually a way to do it that's actually a little bit clever so all you have to do is let's make our new integer called the reversed this is the one we're gonna return and create as the reverse version right so if X is one two three we're gonna want reversed to be equal to three to one in the long run so that's what we're gonna try to accomplish here I'm gonna make a pop variable for now and how we're gonna do this is we're going to go backwards we're basically going to traverse the integer into you know number by number backwards meaning you know if it's one two three we're gonna go three two one and you know we're gonna put the 3 in there the 2 into there and then the 1 into there right basically how you would do with strings when you do like a reverse you know iteration back where it's not a string or whatever but I shouldn't be too bad so all we have to do really write here is we're gonna set pop is equal to X percent of 10 and basically the percent symbol is a remainder so it does X divided by 10 and takes the remainder of that so 1 2 3 divided by 10 is actually 12 point and with a remainder of 3 right so that the pop is always going to be the last digit right three so what we're gonna want to do in the end is just gonna add that to reverse so pop is that and then we're gonna divide by ten to you know continue decreasing the size as we go of X so if it's one two three divided by ten is it going to be equal to twelve right so we'll get the last element three and will basically pull it off and then X will now be that it'll be stripped of its last element and we'll just throw the last element into reversed and that's really the whole problem I mean I don't know how much more I can explain of it I don't know if I did a good job you can let me know in the comments below if I did a good job of explaining it but all you have to do is reverse x 10 + pop and then return is reverse x 10 + pop and then return is reverse x 10 + pop and then return reversed right return our reverse number shouldn't be too bad and you'll see that the test case works so 1 2 3 becomes 3 2 1 not too complicated the only thing when you submit is we have to be aware of those boundaries on the Lee code problem I'm sure it's not that big of a deal I mean I don't know when you'll come and do you know the specific situation but just for this problem we will account for these boundaries so all we have to do is check if reverse is less than integer dot max value or if reversed is equal to integer sorry integer max value and pop is greater than 7 then we would want to return zero right and also we want to do a check if reversed is less than or greater than integer.min value right because or integer.min value right because or integer.min value right because or reversed i might have these backwards actually now that I'm writing it sorry about that we'll switch in a second value and pop is less than negative eight I think we return 0 I'm pretty sure these are backwards now that I'm looking at it but let me just submit sorry once yeah illegal start of expression what oh sorry yeah guys oh my gosh have to look at my keyboard when I type or something like didn't go too well output is yes so what happened is these are just backwards sorry about that because you know obviously if the reverse integer is greater than the max value that's going to be wrong actually sorry divided by 10 you have to make sure it's divided by 10 because everyone runs into problems you know just because I'm making these videos you know obviously I could redo the video and you see the runtime success thirty two point nine six percent not amazing if we got rid of the pop variable and you know did something else it might be faster but everyone makes mistakes oh I'm doing this like live long make the video so I think it's more realistic like to just leave this in obviously I could redo the video and write that correctly the next time but you might see errors like this when you're doing it so it's better to see these live and actually see people experiencing problems and fixing them so the only thing is that reversed is obviously can't be greater than integer dot max value because there's a max value set boundary set into Java so can't be greater so I don't know why I would write you would have to write great or not in less than obviously so we make sure that it's in these boundaries and that's you know pretty much it so thank you guys for watching I hope you kind of understood what I said I know I'm not I couldn't explain good at explaining these but I'm gonna keep going I'm sure the hundredth problem in I'll get a lot better at explaining these so that's about it hope you learned something thank you guys for watching see ya
Reverse Integer
reverse-integer
Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`. **Assume the environment does not allow you to store 64-bit integers (signed or unsigned).** **Example 1:** **Input:** x = 123 **Output:** 321 **Example 2:** **Input:** x = -123 **Output:** -321 **Example 3:** **Input:** x = 120 **Output:** 21 **Constraints:** * `-231 <= x <= 231 - 1`
null
Math
Medium
8,190,2238
952
cool 9:52 largest component size by cool 9:52 largest component size by cool 9:52 largest component size by common factor come in a non empty array of unique positive integers a consider the following graph to a length nodes and nodes labeled is observed to a sub n minus 1 there is an edge from a sub I and a sub J if and only if a sub I and a sub J share a common factor greater than 1 we turn the size of the largest connected component in the graph okay what does that mean okay I mean this is a good practice for me I think immediately when you see stuff like connected components you should think about stuff like Union fine or something like that or DFS I think I mean let's look at the end and we'll kind determine two issues okay so anything 20,000 is a two issues okay so anything 20,000 is a two issues okay so anything 20,000 is a little bit tricky of course a lot of the standard connected components our whims are gonna be we plus Yi but Yi can be up to Yi can be we square away and in this case I can certain the PE I mean this is just GCD so they could all like be part of the same component and then you have a full graph way because you can note that everything is transitive in this case if well that's not true hang on yeah I guess not well it's not necessary transitive but for connected components you like there is some transitive closure in this so in that case it doesn't really matter but that also means that yeah so that hmm yeah the naive algorithm is going to be a and square for that reason for like but any connected components so the kind of better way to kind of think about it is kind of figure out the graph in a better way and I think thinking about this and it may be to some hints I think immediately when I look at compacta grade and one my mind jumps to you know GCD again which is something that we talked about earlier but maybe I think for each number we just calculate or as factors like to the prime factorization and then for each number kind of so I think they're kind of Quan quoted easy a naive way to think about it's kind of having each node and they try to get you to think that way with the pretty pictures is that each node is the number but I think actually what you want to do is that you just notice a prime factor so like for example I think the way I want to think about it and this one I could do in Java since people keep on the question John but maybe not maybe a good explanation but well this number so for prime factorization is 2 or 2 times 2 if you want to be 2 3 15 is 3 5 is 3 and 7 oh sorry 5 and 7 right so for that it means that yeah what you want to do is that for each of these numbers is actually an edge in this case well two inches by two but six is an edge between 2 and 3 15 is an edge between 3 and 5 35 is an edge between five and seven right so now you connect them together and I think that should be good enough to kind of yeah and then you kind of maybe do a final loop at the end to kind of count out how many in each component and then you can we could do a union fighting for each number and all the factorizations I think what is two so the math that I would do it I'm doing this on a calculator but I can babble showing you what I'm gonna do on a calculator to find out the upper bound of the number of primes or a number of notes yeah number of primes I that most applied to under 20,000 so that most applied to under 20,000 so that most applied to under 20,000 so then we can kind of do the math on that yeah and probably like the biggest H maybe like 2 times 3 times 5 times 7 times 11 and so forth way so let's see what that he goes tuna I'm putting on my calculator basically the number of primes such that it's less than 20,000 primes such that it's less than 20,000 primes such that it's less than 20,000 so actually this is already greater than 20,000 so that means that the biggest 20,000 so that means that the biggest 20,000 so that means that the biggest number you could have it well it's roughly just five different times in this case oops what is this you go to my calculator so in this case this is you go to okay mm I mean I guess that's not that point but what was I gonna say about this Oh anyway that was actually not in point but what that means is that in this case do it this number 23 10 creates 5 square 5 choose 2 edges right which is 10 edges 15 edges so this will create 15 edges on a graph and but that also means that each number at most can have 15 edges time and this with 20,000 numbers yeah time and this with 20,000 numbers yeah time and this with 20,000 numbers yeah 15 edges each on each number and for 20,000 umbers this means it's about 20,000 umbers this means it's about 20,000 umbers this means it's about 300,000 so 300,000 is the number of 300,000 so 300,000 is the number of 300,000 so 300,000 is the number of edges right so now we can do the traditional repose you think because we know that well we as you go - I don't know that well we as you go - I don't know that well we as you go - I don't know it goes up to try it a little like number of primes there's more than 20,000 so that's just a half of them so 20,000 so that's just a half of them so 20,000 so that's just a half of them so like all right you can look that out but so let's say ten thousand plus three hundred thousand which is the dominating number and then we can count do it that first search and then go back and just do the count on whether they believe in the same thing right so now we could do it Union fine and yeah cool all right actually I am gonna do in Python just because I've been practicing to practice Union finds to be honest because like I couldn't do this in depth first search in Java very quickly but I do want to practice a little bit on Union fine something that I was a little weaker I know I should have done so yeah so in this case that's to do we want to do is sip yeah okay so yeah let's just do a fine of X is equal to exist not equal to X 10 okay and then Union is just it's just too naive Union so X is equal to two numbers yeah I'll just find of why I didn't say the same really they should be the same after Pat compression the Dean of the Union find operators and now for you to number for X and a let's actually have a prime factorization with teen so what's there okay so for y and range from 2 to X apply doing those smaller than that ok I should use about why was it y is equal to while that's why is them extent X then if X mod y 0 damage is a factor then will be so less if this is a fact can we have a duplicate number is any money the only 20,000 maybe you can money the only 20,000 maybe you can money the only 20,000 maybe you can actually pretty calculate all the numbers maybe even 100,000 that's not a numbers maybe even 100,000 that's not a numbers maybe even 100,000 that's not a big deal but anyway yeah if X is if this mod stand that's well let's insert y for assemble append Y and then Wow X Y Z so we do that yeah the French Way oh right yeah and then if X is greater than 1 then we just append X and this is a little bit you know and this will always be primes because if it was not if Y is not a prime then it would have I need to increment that would make things easier and you can do the math of like fYI secretly yeah make sure dad's odd numbers but it's kind of same logical to surf maybe I yeah but it's the same magic as if we're you know if Y is not primed and then to plan them but before that would have already monitored to say well or something like that or the fact of it yeah and then now for X in a what are we willing to for X and a oh yeah so now we get all the factors of prime factor of X and then oh we have to set up this and I find the next plaintiff appears to parent which is the union-find parent which is the union-find parent which is the union-find parent that's what I call it there are other ways to go about it and it's actually and I was a little bit wall in my mouth but by the way it's roughly right this is actually a hundred thousand I think I said so maybe some of these changed numbers slightly there should be okay and it's you go to actually 100 well this is and there's just another max number say and this is equal to say a hundred thousand okay now we can do for each pair that's Union them for f1 in factors actually don't I was going to say you could do pairs but just by definition you could also just witch McCoy Union with the first number so I think that's fine actually numbers let's find a union between F and in fact the it's like to do this actually sorry then it doesn't do it move itself what so that's just Mary name things a little bit better you know I know wash okay so so yeah so actually this is I mean I didn't say that as part of my fingers there 15 edges but Josh you know because of Dirk it is a connected component you only need two four edges so this is actually given way faster because there's only five or six which is like you know okay that much faster already okay so this will kind of give us all the connected components and then now we have to figure out there to count the biggest component how do we do that well I guess it yeah I think we just take for number X in a we just add a count I'm just fine see using a collection and let's actually use collections County and then X in a do you want it okay so we increment which we call the first fine of the first factor I mean there's a as long as you take any factor doesn't really matter but actually let me catch that so I don't have to calculate a prime factor again because all you need is one factor so I'm put down and look up table X is negative factors of civil okay and then now we only need to look up of X and then we do it Union fine on that to get the Union fine parent and then we increment time and then now we just have to find the max after values maybe that's good enough we'll see you okay I think idea why scissors oh it just should be okay implementations always older than it a little bit but we'll see okay you'll be nice if you told me to answer okay uh other in the edge cases I determine a surprise one do i do anything smart with one that's me and duplicate numbers in general public I feel like I'm gonna dateable conferred on this one okay well Oh cuz one doesn't have a point okay fine and that's why I test them down so that's good so would that cause any issues mm okay the only other kind of thing is that I don't do any small union but I have compression so shear okay let's just submit it let's see where that goes because I shall have a solution that mixes both of them okay cool Wow I'm very slow on this one so maybe there is a faster way to do this I mean I guess I could optimize the prime factor I could have done was go as if it's kind of running tight on the timing down so I mean you should I don't care about timing but this one's a little bit slower than I would like my memory usage less than a hundred okay I remember usage is actually great I guess that's what I mean I guess that's the trade-off what I mean I guess that's the trade-off what I mean I guess that's the trade-off people PI have a say for a lookup table for the primes where I just do not sign up my memories great but yeah and then that's it I think there's some stuff that could be optimized nowhere but I think this is also one of those problems where at least for LICO specific it's no weird because you can actually have a global value and you cash a lot of these things so that on multiple tests you take advantage of the prime factor being already calculated for you and stuff like that which is the little bit dubious versus like each particular case so they give almost like a pre-processing cost or something pre-processing cost or something pre-processing cost or something that you use all the time but uh that said and I applied the need to do this I could just have kept track along the way so maybe that could be slightly faster but that point is probably not likely to be the reason I think the Union fine is why maybe I could be a little bit better about the path compression but I like doing this in a more balanced way so that the path compression is slightly faster but to a nine seconds I don't know yeah but overall if you're following from the beginning to the end and then I'm you know I'm gonna try to explain again but the idea is that uh and I love that I hope that they try to fool you but like these this graph thing when like you know you century what I did and probably it's the solution even though there might be some optimization needed or maybe that's why I use channel but yeah so they do expect each node to be like drawn a graph like this but what I did as we mentioned before was I take the prime factorization of each of the numbers and then connect and connect the primes that are in the number instead and Wow and it didn't seem like I needed every bit of that speed up though I guess I could have just cashed this if I was a little bit smarter about it but oh yeah oh boy not bad interesting palm I don't I end up taking I took about twenty minutes I think I spent a good amount of time describing the problem dough so I don't feel that bad what I want to say about his father I think on this farm again is very Maffei so I wouldn't necessarily expect this to be honor to be on an interview there are components that are actually critical to an interview notably connected components is a big thing I see connected components a lot in general both sides know you could do it a couple of ways you can do it that for circulatory and breadth-first search you circulatory and breadth-first search you circulatory and breadth-first search you can do it in union climb just know it I mean do you have to know it so if that part of the problem is way no worthy but I would say that stuff about why this is non-trivial and also like an S you have non-trivial and also like an S you have non-trivial and also like an S you have experience probably not something that you'll be taught about it's not very quickly I mean it's not impossibly hard it's just you know you have 45 minutes to do with programming interview that's the little bit I want to kind of get into but it's a code for smile but yeah but overall a fun prom and then 15 minutes which is or 20 minute ish give or take which is something that I'm happy about and there are some optimizations for like pre calculating which I did not take a Fanny job but uh yeah like yeah if you're studying for interviews I would not necessarily use this one and as you feel like a very strong in math already planner and I would but the connected components product I said is worth practicing but it's a competitive programming form this is like a an a good heart I would say a good ish heart for normal people form but quite like an average ish compared to programming problem so I dig it and it's good practice I actually really enjoyed kind of change you know learning to master the way and I captain Tom Brady maybe I should have done it safe but anyway cool that's what I have for this Palmer let me take a look at this solution real quick okay so your script in you know D I don't know what it is disjoined it just joined said Union or something I on there but uh unions fine is what I you should call but few always call different things these days oh this is witch McCoy yeah and yeah okay I mean I feel like they really so duh there which McCoy like the intuition is not intuitive for a lot of people I feel like this white obvious a little bit like assumes a lot already but yeah this white up worry assumes a lot of stuff I think yeah and maybe that's why the rating is pretty low in this one solution yeah but otherwise hope you enjoy my so my explanation oh yeah cool
Largest Component Size by Common Factor
word-subsets
You are given an integer array of unique positive integers `nums`. Consider the following graph: * There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`, * There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`. Return _the size of the largest connected component in the graph_. **Example 1:** **Input:** nums = \[4,6,15,35\] **Output:** 4 **Example 2:** **Input:** nums = \[20,50,9,63\] **Output:** 2 **Example 3:** **Input:** nums = \[2,3,6,7,4,12,21,39\] **Output:** 8 **Constraints:** * `1 <= nums.length <= 2 * 104` * `1 <= nums[i] <= 105` * All the values of `nums` are **unique**.
null
Array,Hash Table,String
Medium
null
199
welcome to february's lego challenge today's problem is binary tree right side view given a binary tree imagine yourself standing on the right side of it return the values of the nodes you can see ordered from the top to the bottom so here with this example we can see the answer should be 1 3 4 because these nodes are the ones that are on the right side now there's a couple approaches you could take we already know that we need to traverse the entire tree to determine what the height of the tree is because we're not going to know that until we traverse the entire tree um so we could either do that in a breath first search or a depth first search i'm going to do a depth first search and just do a pre-order traversal what i'll do is pre-order traversal what i'll do is pre-order traversal what i'll do is create some sort of lookup table that's going to store the height of our tree as the key and append every single node value into that as a list so if we traversed it just that first search what would happen is we would add that to level zero then we come here add that to level one then we go here add that to level two then we'll come back here to add this into level one and then this to level two at the very last node value is going to be the rightmost side right for each key so we just need to return that so that seems simple enough first let's start off by creating some sort of lookup and i'm going to make this a list what i'll do is write a depth first search function and what we'll need to do is pass in the node as well as the height so if not node we know that we should return immediately otherwise let's add our node value to this lookup table what we'll say is to lh do an append the no dot value after that we can just do a search to the left and add one to the height as well as never search to the right and add one to the height as well so after that make sure to run it on the root the height will start off with zero and we will need to just return let's say four key value in l dot items we're going to need to sort this right by height and we need to return the v the last one here the last item from our list for each one of these heights and that should return us the right answers let's see here this should be one three four it is see if that works and it does so time complexity wise it's o n times the sorting of the heights which would be probably h log h but one thing to keep in mind here is we actually don't even need to sort it dictionaries are sorted by how they get keys generated so the height is always going to be in order for this dictionary already so we actually don't even need to sort it would take care of the sorting itself by the traversal now one other thing that we might realize is we actually don't even need to keep all the previous information inside of a list right what we can do instead is traverse from the reverse order like we can go the right way first and whatever gets added first that should be the very last node so instead of having a list here what i'm going to do is make this integer and we'll say if h not in rl then we can just say lh is going to be equal to the node value the only thing we can make sure here is to traverse right first instead of left and this would end up being the same in fact we don't even need to do this we can just say return l dot values which will return a list already sorted to us so let's see if this works and this works as well time complexity is still the same but we do save some memory if this was like a big binary tree we wouldn't have a list full of all the node values all right so i'm gonna leave at that thanks for watching my channel and remember do not trust me i know nothing
Binary Tree Right Side View
binary-tree-right-side-view
Given the `root` of a binary tree, imagine yourself standing on the **right side** of it, return _the values of the nodes you can see ordered from top to bottom_. **Example 1:** **Input:** root = \[1,2,3,null,5,null,4\] **Output:** \[1,3,4\] **Example 2:** **Input:** root = \[1,null,3\] **Output:** \[1,3\] **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
Medium
116,545
1,854
all right so this question is maximum population so you're giving a 2d array logs and then you want to okay logs I is going be representing birth and death and then uh you want to make uh make sure what is the maximum population for the current year it has to be a year right so um here we go so um for example one you know this guy was born in 1993 all the way to 1999 2000 and 20 2010 so the earlier year would be 1993 because there's only one person you know survive between this period of time right and then you want to make sure um your current year is the earliest year for the maximum population uh let's look at this 1950 this guy was born 1950 and um you know some pass away at 1961 this gu is was born 1960 1971 1970 1981 so if we can tell like I just draw a interval okay so this is 1950 come on where's okay and this is 90 81 something this so it's from here to here let's look at this from here to here right and the interval between the 19050 and 1961 is be you know somewhere around here right and then now interval is going to be 1960 to 1971 so it's something about you know here anyway and 1970 and 1981 something about here so they overlap right so the earliest here is going to be this period of time right so it's going to be 1960 right so one of the strategy is actually using the counting array so let's look at this so the constraint is small that's okay so I'm going to um you know add add1 + one going to um you know add add1 + one going to um you know add add1 + one based on the birth and death right so I'm say 90501 and then 90 601 - one and this is 90501 and then 90 601 - one and this is 90501 and then 90 601 - one and this is 9060 + 1 9071 - one and then so on right 9060 + 1 9071 - one and then so on right 9060 + 1 9071 - one and then so on right and at the end I'm going to just keep adding the previous value so 90 50 19051 1952 so this is what one right and 1951 nobody actually was born on 1951 so initial value was Zero but you need to add the previous value is going to be what 0 + 1 one 1952 is going to be one what 0 + 1 one 1952 is going to be one what 0 + 1 one 1952 is going to be one until 19 1959 is still one how about 1960 the initial value for counter is already one already and 1 plus one equal to two and if this value is more than you know whatever you have and you want to record the value all right let's back to the coding I mean straightfor enough so I'm going to say years year new year so the year is going to be between what this year and this year but I'm not going to too worry about this I'm going to just initial 2 one space I need to have a return value so later on will find out one ear earli year so for in log with logs make sure I have a counting ARR uh already so this is first Plus+ this is the person who say goodbye Plus+ this is the person who say goodbye Plus+ this is the person who say goodbye minus from in I = to minus from in I = to minus from in I = to 1950 I less than equal to 2 50 and i++ 1950 I less than equal to 2 50 and i++ 1950 I less than equal to 2 50 and i++ right and I basically what years plus equal years minus one right so get the previous value so you'll keep adding and then if the result sorry so if the years I is greater than years at result so result should be zero right initially it will be zero you will have to update the result equal to I right so um yeah so this is p so you have 9050 and then this is one and then this is uh result zero years of zero this is zero right you update the year the earlier year and you get this solution should be okay pause so for the time in space this is space I'm going to say constant right this is time this one is I'm going to say constant for the time for here but this one I'm going to say all of l represent end of the log so this will be a solution and I'll see you next time bye
Maximum Population Year
maximum-population-year
You are given a 2D integer array `logs` where each `logs[i] = [birthi, deathi]` indicates the birth and death years of the `ith` person. The **population** of some year `x` is the number of people alive during that year. The `ith` person is counted in year `x`'s population if `x` is in the **inclusive** range `[birthi, deathi - 1]`. Note that the person is **not** counted in the year that they die. Return _the **earliest** year with the **maximum population**_. **Example 1:** **Input:** logs = \[\[1993,1999\],\[2000,2010\]\] **Output:** 1993 **Explanation:** The maximum population is 1, and 1993 is the earliest year with this population. **Example 2:** **Input:** logs = \[\[1950,1961\],\[1960,1971\],\[1970,1981\]\] **Output:** 1960 **Explanation:** The maximum population is 2, and it had happened in years 1960 and 1970. The earlier year between them is 1960. **Constraints:** * `1 <= logs.length <= 100` * `1950 <= birthi < deathi <= 2050`
null
null
Easy
null
846
hey what's up guys knee right here I do technically stuff on twitch and YouTube solving all the way code hankering problems explaining the code cuz people don't understand the algorithms that's fine this is hand of straights 846 medium problem please like and subscribe so the channel grows thank you it helps more than you know this is yeah let's do it Alice has a hand of cards Alice has a bunch of hand up not a bunch of hands but has cards and it's an int array called hand and these so yeah the cards are array of integers and they are you know cards are integers you know there's a card that says 1 there's a card that has 2 up into like 10 or whatever so you know cards have integers so that makes sense right she wants to rearrange these cards into groups okay of size W so we're gonna have a size W and we want that many groups of these cards so you know if there's ten cards and we want to groups we might split them into two groups of five right okay now the groups have to also consist of W cards so we actually can't do that so what we're gonna return is if we can do that or not okay so you know in an example like this we have you know how many cards we have nine cards right and we want three groups right so we have three groups so three groups could be like you know what do you what like five and then - and then - but no like five and then - and then - but no like five and then - and then - but no they all have to have the same amount of cards otherwise we have to return false so that's to be 333 so in this case we can do that so first thing we have to do is make sure that we can split this group length up into an even amount of cards in each group right so it has to be W groups with W size each so first thing we could do this is simple is just say okay is the length of all of the cards we have like is nine evenly divisible by three if it's not we're returning false automatically so if hand dot length mod W so if all the cards we have divided into groups isn't going to have an even number of cards in each group you know then we're gonna have to return false automatically so might as well just get that out of the way right now how else do we do this what is the only other problem like figuring this out like that would be the solution if it was just splitting into groups or I figuring it out well we also have to have the integers being consecutive so you can see 1 2 3 and we're talking about consecutive and value right not consecutive and order so 1 2 3 are consecutive and value correct so we have this is a group that's consecutive and value now 6 2 3 we would just go ahead and try maybe 6 to 3 if we were just looping through or something like that's not going to work those are not consecutive and values we need 2 3 4 so we actually need two three four that's consecutive and then we do 6 7 8 because those are consecutive now how are we gonna do this well there's actually a very handy data structure to do this called a tree map and a tree map is basically a hash map except it has ordering so if you look up here benefit of a tree map some main advantages it allows you to store key value pairs in a sorted order so this is gonna be really good for our algorithm because we can basically extract a minimum value what we're gonna do is we can extract the minimum value because the tree map allows us to do that and then we can loop up to W size so we can say ok what we start here and then we do plus 1 so we get a size of 3 we make sure that our something is size of 3 and as we loop we check widget we're just gonna take the first card the minimum value will do okay 1 plus 1 and we'll just loop it will add 1 each time because it has to be consecutive value so it has to be plus 1 for the next element so you know 1 plus 1 is 2 contained in the tree map ok if so we'll extract it plus 1 is 3 contained in the tree map ok then we will pull that out of the tree map ok we have a size 3 group now let's move on to the next group in the next it will just start over in process will extract the minimum value we extract 2 ok and then we have to go up to size W again 2 plus 1 is 3 there's another 3 in there so we pulled that down plus 1 is 4 there's a 4 in there we pull that down we have another group of size 3 we extract the minimum value so that's 6 that's left ok now we do plus 1 is 7 we do plus 1 is 8 and then we get whole group so that's kind of the strategy here that's why the tree map is useful so we're basically just gonna do a tree map integer key value pair it's just kind of like a hash map it has even the same methods basically a little bit different but you know we could call this card counts right so these are going to be the frequency of each card that we have because there could be duplicate cards right one two three four this to two is to threes right so new tree map so we are now going to loop through each card in our hands and we're gonna say okay if card counts doc contains key just like a hash map contains key card then if it doesn't contain the key then we're gonna put it in for the first time so card count stop put we're gonna put card with a value of one because we saw it once that's the frequency otherwise we're gonna do okay card counts dot replace that's a different method and we're gonna replace the value for card with card counts get card plus one that's it's similar to a hash map it's almost the same right okay what's the main condition now well we're gonna loop until we're out of cards in card counts so we're gonna say wall card counts dot size is greater than zero we're gonna loop and then we're gonna do all of these checks to make sure that we can get these groups that we need and if we can't we're gonna return false within this little loop here so outside if we make it out of this loop we can just return true right so we're gonna try and disprove this within this loop here okay so first thing like what I said we're gonna do we're just gonna extract that min Val so min val is going to be equal to card counts which is the tree map dot first key right so that the tree map gets filled up like one there's two's there's two threes it's filled up with all these and it's in sorted order the tree maps in sorted order so first key gets the minimum value so it gets that one right now we want to loop up so we're gonna loop up we're gonna say int card is equal to min Val so you know the cards gonna be equal to one and then we're gonna say while card is less than min Val plus W so while it's less than this what we're gonna up to the size we need and increment those values then we're gonna do card plus then what we're gonna do here is we're going to say if card counts doesn't contain the current card like if we go we look at one is the minimum value right in our tree map we pull it out now we're gonna go up to two we're gonna say okay two in the if two is in the cup if two isn't in because we're just adding one to the value because we need consecutive values consecutive growth and values by one so one plus one is two okay the next loop one plus one is two in our tree map if it's not we cannot make this group because it's not gonna be a consecutive value right to it we don't even have to as a card so we're checking if two is a card so we're gonna say okay do we have this two as a card so if we don't then it's false so this is where we're disproving that we're able to actually do this and split the groups up into consecutive values because if we don't have this consecutive value we're gonna return false otherwise we're gonna pull it out we're gonna use it in this group and then we're gonna decrease the whole thing so int count will be equal to card account stock yeah because this is if we have it so we'll just get the card count and if the count was equal to one then we're gonna remove it right because it'll just stay in there it's gonna just stay in the tree map so we have to remove that card if there's only one in frequency cuz count is the frequency of the card we get the frequency how many times it occurs so for example one is only in there once so when we pull one or like you know six is only in there once if we pull six or something is not only in there once so when we pull seven we want to remove it from the tree map now because we're using it in this group right so we're just gonna remove that card from our tree map if there was only one of it in there right so we'll remove you just remove it by the card and then else if it had more than one in frequency we want to replace that frequency right with the current frequency minus one so we could just do char counts out replace that card and then we have the count of it pulled down so we'll just to count minus one so that's pretty much it's a pretty elegant solution not too many card counts sorry not card count card counts so you remove it from there you go that's the name of the tree map I just messed up else shark counts card counts okay we are losing our minds card counts there we go okay my dogs are barking I gotta go take care of that but hopefully I mean I it's a pretty elegant solution pretty clear not too many tree map problems so it's pretty cool hopefully we can look at some more of these because I actually did get some tree map tree maps I actually had to use in an interview before and I wasn't familiar with them so I'd like to get more comfortable with them I don't think they come up that much but I have gotten them and interviewed before so thank you guys for watching let me know what you guys think other solutions questions whatever join the discord below and all that stuff thanks for watching like and I'll see you in the next video alright peace
Hand of Straights
hand-of-straights
Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size `groupSize`, and consists of `groupSize` consecutive cards. Given an integer array `hand` where `hand[i]` is the value written on the `ith` card and an integer `groupSize`, return `true` if she can rearrange the cards, or `false` otherwise. **Example 1:** **Input:** hand = \[1,2,3,6,2,3,4,7,8\], groupSize = 3 **Output:** true **Explanation:** Alice's hand can be rearranged as \[1,2,3\],\[2,3,4\],\[6,7,8\] **Example 2:** **Input:** hand = \[1,2,3,4,5\], groupSize = 4 **Output:** false **Explanation:** Alice's hand can not be rearranged into groups of 4. **Constraints:** * `1 <= hand.length <= 104` * `0 <= hand[i] <= 109` * `1 <= groupSize <= hand.length` **Note:** This question is the same as 1296: [https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/](https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/)
null
null
Medium
null
237
hello friends welcome back to my channel hope you are doing great if you haven't subscribed to my channel yet please go ahead and subscribe I have created bunch of playlists to cover various categories of problems such as dynamic programming breadth-first search dynamic programming breadth-first search dynamic programming breadth-first search depth or search and some of the playlists a bit are based on the data structures such as trees graphs linked lists and so on please check them out I have uploaded the code for this problem to the github repository you can get the link from the description below this video let's jump into today's problem delete node in a linked list write a function to delete a node except the tail in a singly linked list given only access to that node given linked list had four five one nine which looks like following four five one nine right so basically we are asked to delete one node in a linked list so the catch here is we are not given the access to the head node but we are given access to somewhere in the middle and we have to delete that node so for example if you go to the example one and look at this linked list eight four five one nine it's same as whatever it's shown the picture and node given is five so basically we need to remove the node five and once we remove the node 5 the contents will be four one nine right so that's what it will be after so if you go look at the example two it asked to remove node one so if you remove node one right it will be four five nine right that's what it will be so that's the problem description right so we are not given the head of the having access to the head of the linked list so we are only given access to the node which we are supposed to delete right so normally when we want to delete a node in a singly linked list so that's on also one more important point right so if it was a doubly linked list we know we have the access to the previous nodes pointer also right but in a singly linked list we don't have access to the previous node but without access to the previous node we won't be able to carry that delete operation ween we must need access to the previous node right so that we can connect whatever the previous list with the list what it is after deleting this right so in this example so four five one nine right when we delete five in this case right so the there will be two lists that will be formed right so something like this so if we delete it for five right so there will be two lists that will be formed so we want to join those two lists how can we join if we don't have a pointer to the previous node we won't be able to join those right so ultimately yeah if we remove this we want to join the previous list with the list by splitting at the joint I mean at the deletion point right so we want an access to the previous pointer so since we are not given the access to the previous pointer the regular deletion method won't work so we must create sort of previous pointer somehow right so we must create a pointer to the previous pointer previous node somehow so what we are going to do this we need we will do a technique of shifting the values okay so let's take that off and we have the same thing okay and we are asking so node five red that is an example five so an example one so node is five so we are asked to remove node five so the resultant answer will be four one nine right so what we are going to do is copy the nodes after five and shift them one by one right so what I'm saying is so this is starting so initial so given right so what we are saying is so one copy it over right and nine copy it over so nine will be there so for nine since that is the last element you cannot copy it anyway so the linked list will become like this and you can just delete the last node so once we delete the last node what it will be one nine right so this will be the answer that we want right so this is the shifting technique basically you are deleting the last no by shifting all the values subsequently after the node that you are given access to right so we are given access to five you copied over all the elements and you delete the last node so this is one approach right so this will take the order of some complexity right so the time complexity would be since we don't know the number of nodes in this particular linked list we would say okay whatever the number of nodes after five right so whatever the number of nodes are taught to fly let's say there are n nodes after pirates so that would take order of n time complexity right so order of n time complexity where n needs nor count after size right so in this case node 5 so after the node to be dedicated node to be deleted right so that is 5 in this case right so let's try to improve this the same technique and see if we have to really copy or all the elements are not right so that's one thing so what we can do is so we are given with this right we are given with this so we shift and copy okay we shift and copy so that means we have one so sorry it will be 1 and 9 right so this will be first after the first copy right so first once this element is copied that will be the first after first coffee after the first copy so obviously after the second copy it will be like this right 9 so this will be second copy right that's what we went through right so what is there in the line 24 mo right so what we are going to see is we don't have to do this copying at all right we don't have to copy this at all once we have the first copy what we can do is all we have to do is since we have already copied this one to here we can delete this one nor right whatever the copy that we did we can just delete that so delete the copy node right so what it will become four one nine right so this is what the answer that we want right simple yeah this is what the answer that is one right so four one nine what we are saying is we just copy over whatever the next element for the node into a current element right so delete the next one right till you the copied no right that's it that will be our answer so this will be how many operations that we are doing just one copy and one delete that's it so it will be order of one operation right so we have improved from order of Iran and to order of one that is linear time to constant time so all we are doing is just copy one element and then delete that copy element the next element basically right time so that will be a very simple code to look at so let go look let's go ahead and look at the core so we have a list node temp what I'm putting is in tamp no dot next not next what is that no dot next so in this particular case we have node dot next is this so that's next pointer is this so nine we are keeping in the temp right and no dot value note that next third value no dot next is no ds5 right no dust next is for one so not that value we are copying it to the note that next dot value so one is being copied in spring place of five that's what we are doing here right and then no dot next is equal to temp so what is Nord is still pointing to one next this dot next is equal to temp what is temp nine so we are pointing this pointer to one so basically if I have to represent in a visual way right so let me put in the visual way right so it's like this right so what we are saying is right so this is what we are trying to point right exactly this is what we are trying to point one is pointed to nine so this one will be lost now right so coming back so that will be right so now this visual representation is gone that's it so that's how the representation this is a very simple core which is which can be done in order of one operation so that is the time complexity right time complexity so what is the space complexity we are just using a temporary node right for this operation so this is like a again a constant space so space is also constant and time also constant so this is a constant time and constant type constant time and constant space complexity algorithm so if you have any questions please post them in the comment section below this video I will get back to you as soon as I can I have posted the code to the github repository you can find the link in the description below for the github repository if you haven't subscribed to my channel yet please go ahead and subscribe and also share among your friends please click on the bell icon so that you will be notified about my future videos thank you for watching I will be back with another problem very soon till then stay safe and good bye 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
1,047
welcome back everyone we're going to be solving leak code 1047 remove all adjacent duplicates in a string so we're given a string s consisting of lowercase English letters a duplicate removal consists of choosing two adjacent and equal letters and removing them we repeatedly make a duplicate removals on S until we no longer can and return the final string after all such duplicate removals have been made it can be proven that the answer is unique okay so s only consists of lowercase English letters and a b a c a is going to Output CA because we'll have a BB we can pop off once we do that we'll have a pop that off and with CA okay so we're gonna use a stack here but let's actually yeah we'll call it stack and let's say four character in our string if yeah if a stack of negative one is also equal to that character what are we going to do we're gonna pop it off stack that pop but let's say we have nothing in our stack right so we do have to check um if our stack is truthy right so we'll have to say if stack and uh the last item is equal to C then we pop otherwise we will do a stack dot append of that character and then we can should just be able to return a string join of our stack all right so let's run through this 4C and s a um we it's not truthy it's empty so we're gonna append a we'll go to B it's not equal to C so we append it B again so this time we're going to pop so now our stack only has a in it then we get to a for the fourth letter we're going to end up popping off this a so now our stack is empty so now we run into C that's gonna append it and then a will just yeah so we should end up with the correct answer here one argument ah it would help if I pass in all of the arguments return the string join of our stack okay so we do pass both test cases let's submit see what we get okay accepted now what is the time complexity of this well that's the time complexity is going to be o of n we are looping through every character in our given input string so hold n and the space complexity is going to be the length of the stack that we are returning as a string join so it will be the length of whatever our stack is so we can say o of what stack.length so we can say o of what stack.length so we can say o of what stack.length and that should be it for leeco 1047 remove all adjacent duplicates in a string
Remove All Adjacent Duplicates In String
maximize-sum-of-array-after-k-negations
You are given a string `s` consisting of lowercase English letters. A **duplicate removal** consists of choosing two **adjacent** and **equal** letters and removing them. We repeatedly make **duplicate removals** on `s` until we no longer can. Return _the final string after all such duplicate removals have been made_. It can be proven that the answer is **unique**. **Example 1:** **Input:** s = "abbaca " **Output:** "ca " **Explanation:** For example, in "abbaca " we could remove "bb " since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca ", of which only "aa " is possible, so the final string is "ca ". **Example 2:** **Input:** s = "azxxzy " **Output:** "ay " **Constraints:** * `1 <= s.length <= 105` * `s` consists of lowercase English letters.
null
Array,Greedy,Sorting
Easy
2204
1,650
hey guys so in this video we're gonna discuss Lee code 1650 find it find the lowest common ancestors of a binary tree so in this problem we're going to be given the two nodes in a binary tree p and Q and the return their lowest common ancestor so for example in this these three now this three and we have two nodes five and a one so they are commons the lower ancestor would be three so five and one and their common flu answers is here another example is like for node uh five and four which is five and four here their lowest common ancestor would be five itself because five is apparent is an ancestor of uh four so to the algorithm to solve this problem is for one of the nodes let's say node P we're gonna find all the ancestors of node P including P itself because P can be a be an ancestor of the other node and then we store all the audio all the P ancestors into a set and then we find the ancestors of the node Q one by one like we find the parent of node q and then the parent of the parent until we find which a parent where um it exists in the cheap ancestor set and that will be the lowest common ancestor so let's get started so let's say we need to find the first step is to need to find all the P parents what you can do is like P G elements equals to the set and uh y or p K parents would have would add a p and the P equals to p the parent P to p parent right now we find all the key parents so now we find the lowest common ancestor what you can do is like while Q if Q in foreign else Q equals all right so let's run and see how it goes yep it works so basically the time and space complexity the time would be order of n so we basically Traverse through um like one leg of the two legs of the binary tree so like the P lack and the Q lag so it will be order of N and the so we travel like maximum wise like we have all the node in the tree so it will be Autobahn and space wise we have a set so it will be Auto open maximum like which gonna store every node in the set so that will be the maximum time and space complexity so yeah this is the end of the video and I'll see you guys in the next one foreign
Lowest Common Ancestor of a Binary Tree III
find-root-of-n-ary-tree
Given two nodes of a binary tree `p` and `q`, return _their lowest common ancestor (LCA)_. Each node will have a reference to its parent node. The definition for `Node` is below: class Node { public int val; public Node left; public Node right; public Node parent; } According to the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor)**: "The lowest common ancestor of two nodes p and q in a tree T is the lowest node that has both p and q as descendants (where we allow **a node to be a descendant of itself**). " **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 1 **Output:** 3 **Explanation:** The LCA of nodes 5 and 1 is 3. **Example 2:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4 **Output:** 5 **Explanation:** The LCA of nodes 5 and 4 is 5 since a node can be a descendant of itself according to the LCA definition. **Example 3:** **Input:** root = \[1,2\], p = 1, q = 2 **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[2, 105]`. * `-109 <= Node.val <= 109` * All `Node.val` are **unique**. * `p != q` * `p` and `q` exist in the tree.
Node with indegree 0 is the root
Hash Table,Bit Manipulation,Tree,Depth-First Search
Medium
1655
131
Hello Hi Everyone Welcome To My Channel It's All The Problem Calendars Party Sanjeevani Stringers Patient Added Every Service Revolver Partitions On Part In ROM And Written All Possible Param Partitioning Of Its Parents Can Visit For Same From The Backward And Forward To Example1 Wear Dresses Problem And Eid Party 100 first partition a history like in atishay devi abc voice and visiting this pen drive vikas singhal character a palindrome between candidacy for this is the meaning of the answer let's divide mode van wick and partition like and noida monitoring and been taken during fever seeds that Both be selected first installment veer hindi answer 9 and spa quit android goddess that show her like a pearl drop but for a desert land forms will not veer warm and partition and allied audition take full history amazon roms for this is not possible to Be tried all this possible partition and check all the substring in the partition shift after partition spring is informed on this and will head into the region set otherwise funny one of the following is not fair of but not and with his being written in this example one should Is Here Deactivate Amazon 2010 What We Have To Fennel Will Solve This Problem Soft Checking The Spelling Ram And 90 Will U Will Just Tasting Lab Se Id That 2.1 Launde Tasting Lab Se Id That 2.1 Launde Tasting Lab Se Id That 2.1 Launde Start And Dars On The Right Regular And EVs Key Book Inside Lag Increase Torch Light End Increase Decrease Loop Last Day Characters and Matching Characters Add These Indexes Me Tissues And Veer Is On The Fifth Class Life Wishes Meanwhile Menu Most Loud And Subscribe This Way Problem Solve This Problem So Let's See What Will U Can Cut Hair Partition And Hairs Only Due Plessis Will Start From Chronic Length Belt Length Of Partition Will Be Divided Into Two Parts Chief Visits A Leftist Regrets For Later Left This String And Evening Point Is Which Is Called Sre Distic Up Ki Saugat Mil U Will First Check Weather Our Left Spelling Rome Is This Is Spelling Rome Fennel Bane To Check Is This Parties Also Giving White Ram And Notice On Depot Website In This Is The Possible Candidates Of Rather This A Palindrome In To-Do List Switch Off Into Its Own When To-Do List Switch Off Into Its Own When To-Do List Switch Off Into Its Own When Will They are into the difficulties of freedom and will keep trying for the I call for the Vivo mode on and again also partition and into parts and green forest and discordant is no basis in Rome and decisions of women everywhere in to-do list Sudesh in to-do list Sudesh in to-do list Sudesh Vikram Vansh Solution 9 News One Solution From One Will Be Amazed And It Will Be Added In To-Do List From In To-Do List From In To-Do List From 9th Me Abhinav Se Method To Partition BB 100MB By Vikram Tripathi Sets Of Which Will Be Coming In This Will Be In The Left End Welcome All In This Will Help And Will Stop Power Record Schools Will Right Developed Solutions In The Spring Specially Thisawar Methodical Chipak Wedding SSC Committee Ne Vide And The Results Admiral Sentinel Staff List Which Will Hold Over All The Solution List OffSpring Of This Will Keep Sharing This system will keep growing state forward flex implemented for coding for already raised in the very straightforward fennel and 10 result list of history for this college result is not what will you call helper method is new Delhi per method bill try to generate all also First Gram Party Singh And Sacrifice Successfully Generated In To The Results Otherwise Exactly 350 Result And Also Been Under Current Affairs Which Will Contain All The String In The Current Partition Suvvi Pass Indian Thursday Mid Day To All Indians Should Boys Have Problems With Very Similar To Do Nothing Special No Strings List of Winners List Play List Which Will Hold List of History of 167 Naav Effective MP Effigy of Bach Means Wearable to Partition This is Successfully with Pure Current Water Works at Least I Got the Year Will End in 2D Result Daughter At Least Not Tried To Put All The Nation From Noida To Hai High Plus Sunna Ho Will First Cutlet Defeating The First Politician Late To Left Which Will Be Added To String Ki Servicing From Zero Do I Ki And Which Will Go On Airtel Digital Equal To The Land Records In All Spring Bath This Last Index In Exclusive Sudhir Vikram Singh Simreli Letter Writing Pure Rights Reserved Seats Of String Subscribe To The Length Of The Triumph Will Check That Then Spelling Of Medicine Long Life Is Spelling Of This Is The First Features 04 First List Subscribe Switch Off That From Our Current Leswa Festival Sudhir Wing Coping Disconnect Developed Job Jain Vinod Jain Wiki Update In The Name Of Sacrifice Will Update For pmtv24chd Current subscribe The Channel and subscribe the Channel Please subscribe and subscribe the Channel The combination will get a the participants of severe cutting also correct answers left right some test cases for a daily wage select shifting for friend maximum test cases should not do and sorry no deficiency of getting a correct answers for all concentration lights of medicine code and Accepted Member Solution Like What Withdraw All Possible Partition And Check Weather Its Present Times Now Let's See What Is The Time Complexity Of Solution Sorry For The Spelling Of Link And There Will Be Minus One Partition Like Places And Partition First Is Who Is The Length Of The Systems And You Have Any Mention Places Show And Wick In Thy Pocket Morning Is Two Option Cutting And Not So Late This Toe Key Power And Minus One Combination Fennel 125 Definition Combination And Also Work Hard Spring Loop System Spring Boot Left A Give Something For This Left back to check dispel any form or not and such spelling of instead of to take off in time for all this service team all the partition bf take off fun time with check penalty splendor notes for the time complexity of dissolution inch to take off in to the power And minus one and wich nothing but in soak of and to the power to power and wich expansion and what is method space complexity shoaib vacancy districts and investigative way that bill gori attracted polytechnic slide khan3 dhera his dream the end of the question will go up to The like subscribe and what are the real subscribe like share and subscribe my channel and the mission problem my channel thank you
Palindrome Partitioning
palindrome-partitioning
Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`. **Example 1:** **Input:** s = "aab" **Output:** \[\["a","a","b"\],\["aa","b"\]\] **Example 2:** **Input:** s = "a" **Output:** \[\["a"\]\] **Constraints:** * `1 <= s.length <= 16` * `s` contains only lowercase English letters.
null
String,Dynamic Programming,Backtracking
Medium
132,1871
841
hey what's up guys it's Nick white here I do tech and coding stuff on twitch and YouTube and I do all the Lea code problems and I got a ton of them up on my YouTube so if you want these explained or if you have other problems you're struggling with just go check those out probably got it in there by now so this one's called keys in rooms there are n rooms and you start in room 0 each room has a distinct number 0 1 2 n minus 1 right so we're given this is a cool problem ok so we're given a bunch of rooms we're given a 2d list right so the inputs gonna look like this and we're given each sub list is gonna be a room in each room has keys right so room 0 the rooms are referenced by index so this would be room 0 this list containing one room 1 would be a list containing 2 and room 3 would be a list containing sorry room 2 would be a list containing 3 so 0 1 2 by index and then these keys reference where the index of the room you can open right so in room 0 we can find a key to room 1 so now we're able to open room 1 which has a key to room 2 which we can open on to now and then we have a key to room 3 and we can open room 3 so the goal is to find loop through this all these rooms and keys and find out if we can visit every single room finding keys one room at a time right so yeah if you read that you can hopefully I did an okay job at explaining that if you read through it maybe you can understand it a little better it's kind of the same thing that I just said but yeah it was it's a cool concept I liked it for sure so here's the solution basically what we're gonna do is we're going to have a boolean array a visit called scene right so we could just literally declare that right now so boolean scene will equal it's a new boolean rooms dot size and it's gonna be the same as rooms dot size so at the end this boolean array is going to start at all falses right but it's going to be the same number of rooms there are and at the end we want all of them to be true because it means that we'll visit so each time we visit a room we're gonna mark one of these spots in the current room's index and the boolean array we're going to change that false to a true and at the end we'll do this check we could just read it right here and see we've the first room we're automatically visit so all rooms start locked except for room 0 so we get to visit the so seeing of 0 we're automatically marking true so now it's just a true and a bunch of falses so right at the end we can just read this right now we're basically going to do for boolean visited in the scene I'm just calling it visited you can call whatever you want if not visited so if we see in false at the end we're just going to return false and that would be the end of it otherwise we're gonna return true so that's kind of the basics behind the problem right here now to actually be visiting these rooms and keep track of all the keys we're going to have a stack called keys is equal to new stack so we'll have a stack of integers called keys because each key is an integer representing the index of the next room you can visit and keys will add 0 immediately because we and then will do this is like a lot of problems while keys is not empty well the stack is not empty we're gonna pop the current key just like a lot of these stack problems current key is equal to keys da pop and then what we're gonna want to do is access we're gonna take the current key from the stack so in room 0 we'd find we're 1 so we'd be able to axe now we're going to access room 1 which is going to have the keys room 2 so we're going to access room 1 so for int new key in we're gonna loop through the keys in the new room that we can access so in rooms yet so we're accessing we're taking that key we're at right here rooms get the new room and we're looping through all the keys in the new room so we would find two in the next one in that case and we're gonna take that new key and if we haven't seen it if we haven't seen the room already we were looping through the new keys so we find some new keys and if this on if these new keys unlock a room we haven't seen yet we'll mark that new the room is seen now because we have the key to unlock it so we can mark it a seam and then we'll add that key to the stack because we're gonna have to keep going so it's kind of thinking one step ahead it might take a second to wrap your mind around that it's kind of this looping is kind of thinking like a little bit one step of hat it's like a one step ahead kind of trick Keys dot add new key so you just gotta kind of sit there take it in and conceptualize it this loop is probably the hardest part to understand you find so once again we just wait and let's see if this runs first try yep so we got it running first try hopefully I get a job of explaining that we have the scene boolean array that the first element of that is going to be true the rest are going to be false it's the same size as the rooms so as we loop through we're visiting the rooms and we're updating scene boolean array so that all of them will be true by the end if they're not we haven't visited all the rooms and we return false that concept I think you guys will understand real easily otherwise we have a stack of keys and as we visit these rooms we keep adding keys onto the stack and then as we loop through we pop the keys off the stack because these are keys to rooms we're hopefully not we haven't visited yet we pop keys off the stack we check if we visited the rooms that the keys unlock already and if we haven't we have we find the new keys and we add those onto the stack and we also mark the new rooms visited that we unlocked so you know I tried as best as I could to explain this one it's a little tricky because it is thinking and kind of one step ahead but I think yes we're watching it just take a second and kind of like breathe this little while loop in and yeah that's pretty much it I think that's a cool problem I like when they have like kind of little mystery puzzle mysterious problems like this so thank you guys for watching and yeah check out the other ones if you need help see ya
Keys and Rooms
shortest-distance-to-a-character
There are `n` rooms labeled from `0` to `n - 1` and all the rooms are locked except for room `0`. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of **distinct keys** in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms. Given an array `rooms` where `rooms[i]` is the set of keys that you can obtain if you visited room `i`, return `true` _if you can visit **all** the rooms, or_ `false` _otherwise_. **Example 1:** **Input:** rooms = \[\[1\],\[2\],\[3\],\[\]\] **Output:** true **Explanation:** We visit room 0 and pick up key 1. We then visit room 1 and pick up key 2. We then visit room 2 and pick up key 3. We then visit room 3. Since we were able to visit every room, we return true. **Example 2:** **Input:** rooms = \[\[1,3\],\[3,0,1\],\[2\],\[0\]\] **Output:** false **Explanation:** We can not enter room number 2 since the only key that unlocks it is in that room. **Constraints:** * `n == rooms.length` * `2 <= n <= 1000` * `0 <= rooms[i].length <= 1000` * `1 <= sum(rooms[i].length) <= 3000` * `0 <= rooms[i][j] < n` * All the values of `rooms[i]` are **unique**.
null
Array,Two Pointers,String
Easy
null
119
hi guys I Amit in this video we shall see another problem on Le pascals triangle part two so given an integer row index written the row index row of the pascals triangle so in the Pascal triangle each number is a sum of two numbers directly above it so they have given zero indexed row here and we have to write the return if given an integer n row we have to return in the Pascal triangle uh I hope you guys how do we know how do perform the Pascal so we start with the zeroth index so to compete the first index 1 one uh here you don't have any previous sment here don't have previous so you take one inherit that next for the second row I mean zero Row first row second row for second row as we know how do we compute one no other element so one you inherit and for two it's both previous element you take it and you can see the last element will remain the ending elements will remain the one in each row so next when you come to the third row for computing 3 1 + 2 again third row for computing 3 1 + 2 again third row for computing 3 1 + 2 again for this three 1 + 2 so next coming to for this three 1 + 2 so next coming to for this three 1 + 2 so next coming to the 1 second third fourth row so 0 1 2 3 4th row how do you compute this element the previous elements 3 + 1 of the above row and here elements 3 + 1 of the above row and here elements 3 + 1 of the above row and here how do we get uh six so we get 6 by 3 + how do we get uh six so we get 6 by 3 + how do we get uh six so we get 6 by 3 + 3 that is how we get the six here also 3 + 1 will be 4 so you how do we comp + 1 will be 4 so you how do we comp + 1 will be 4 so you how do we comp here is so 1 + 1 this will be 2 these here is so 1 + 1 this will be 2 these here is so 1 + 1 this will be 2 these two will combine together will give you three again 2 + 1 3 + 1 4 3 + 3 6 3 + three again 2 + 1 3 + 1 4 3 + 3 6 3 + three again 2 + 1 3 + 1 4 3 + 3 6 3 + 1 4 so this is 03 0 1 2 3 4 and why aming zero through because they said that it's a zero index row so that's the reason so now our task is they given some n okay row index and we have to return the that row values of that pascals triangle so how do we do that so if you actually observe this what is happening over here is we start with one next you compute again one next one to one how do you get it extra one element you add third element to compete the middle element the previous row take that particular index and previous index so 1 + 1 will be and previous index so 1 + 1 will be and previous index so 1 + 1 will be two then coming to the third uh row how one again one more here so compete how do we compete these two elements so for this element previous Row the element at this position at the previous position so 2 + 1 will be 3 and previous position so 2 + 1 will be 3 and previous position so 2 + 1 will be 3 and here again 2 + 1 will be 3 again for the here again 2 + 1 will be 3 again for the here again 2 + 1 will be 3 again for the last how do we compete so have one more one and then so it length will be five so how do you get this element 3 + 1 4 so how do you get this element 3 + 1 4 so how do you get this element 3 + 1 4 for this element uh that position and a previous position of the previous row this row so 3 + 3 will be 6 again 3 + 1 this row so 3 + 3 will be 6 again 3 + 1 this row so 3 + 3 will be 6 again 3 + 1 will be 4 so this is how we compute the paral triangle value so if they say n = paral triangle value so if they say n = paral triangle value so if they say n = to 4 then you have to return this particular row if they say Nal 2 3 then this Nal 2 means this Nal 1 means this n0 means this so this is what they ask in the question so how do we perform the operation actually so one thing we got to know is if they ask Nal 4 the length of that row will be n + 1 right so 0 1 2 of that row will be n + 1 right so 0 1 2 of that row will be n + 1 right so 0 1 2 3 4 index so five elements are present in N row nth row means fourth row so if they given Nal to 4 we will create an array of size 1 2 3 4 5 okay let's say and initially let's initialize all the elements with one 1 so if they given Nal 4 let's say so we create an array of size five and all the elements initialized to one so once we done with this do we need to calculate this what if this say equal to Z do we need to calculate anything no just return an array with element one uh of length one with element one if they say Nal to 1 also we will an AR of size 2 with elements equal to 1 directly we can return it what if they say Nal 2 then we need to compute this middle element right because first and last element Remains the Same if Nal to 2 means the length of the AR will be three in this case so for if they say l n equal to0 means first one length if n equal to 1 means of length two then this length Okay so if Nal to 3 means this entire length till here so this is aray length of three not Nal 3 if n equal to 2 means we will return the array of length three where first and last element in the array will be one itself how do we compute the middle element is how do we compute is the previous we take one for that position element and the previous element we add this to 1+ one previous element we add this to 1+ one previous element we add this to 1+ one but the 1+ one actually in this if you but the 1+ one actually in this if you but the 1+ one actually in this if you see this is nothing but this element and this element right so if you want to compute element this position we compute we add the element at this position and the previous position how much it is 1 + the previous position how much it is 1 + the previous position how much it is 1 + one will become got it so basically we are doing 1 + 1 but 1 + 1 is nothing but if we 1 + 1 but 1 + 1 is nothing but if we 1 + 1 but 1 + 1 is nothing but if we consider an AR length of two that will be this only here so in this only 1 + 1 that is two here so in this only 1 + 1 that is two here so in this only 1 + 1 that is two what we need to compete okay so that's it now what we'll do is so now we could see if we have AR length of three yes we have completed 1 to one as per the condition if you want to complete AR length of four that means Nal to 3 how do we compute this so Computing this we need to have a length of four AR length of four if Nal 3 so AR length of four the first and last element in the array will remain one itself how do we compete the middle two elements so if you how do you get three is from one and two here so 1 + 2 so actually if you want to so 1 + 2 so actually if you want to so 1 + 2 so actually if you want to compete the element in this position 0 1 2 two index so I'll write 0 1 2 3 4 so two index if you want to calculate twoth index plus one index first index you add the elements so 2 + first index you add the elements so 2 + first index you add the elements so 2 + 1 will be how much it will be three next again for this element first index how do you calculate this two plus this one this two and this one how much it is three So within the array you calculating the elements imagine that the size of the array is temporarily four now so now we have got 1 3 1 yes we have got this thing so let's say what n = 4 we have to let's say what n = 4 we have to let's say what n = 4 we have to calculate now how do we calculate Nal 4 in that case n + 1 will be the length 4 in that case n + 1 will be the length 4 in that case n + 1 will be the length of the AR so just increment the length of the so this entire AR will be the length so how the first and last element will remain the same how do you compete this element now 4 1 + 3 so 1 plus this element now 4 1 + 3 so 1 plus this element now 4 1 + 3 so 1 plus this element and the previous element how much it is four next how do you compute this six 3 + 3 so if you want to this six 3 + 3 so if you want to this six 3 + 3 so if you want to update the element at this position this particular element and the previous element 3 + 3 will be 6 but one more element 3 + 3 will be 6 but one more element 3 + 3 will be 6 but one more thing which we need to notice here is okay now this is done how do you compete the this element position again 3 + 1 the this element position again 3 + 1 the this element position again 3 + 1 they elemented this position previous position that will be 3 + 1 will be 4 position that will be 3 + 1 will be 4 position that will be 3 + 1 will be 4 okay so we have got 14 64 1 but one more thing which we notice here is I'll just do everything reverse Okay so initially we have this 1 3 31 1 so what we start from here for computing this element this position element 3 + 1 how element this position element 3 + 1 how element this position element 3 + 1 how much it is 4 for computing this element 3 + 1 4 we have got yes for computing 3 + 1 4 we have got yes for computing 3 + 1 4 we have got yes for computing this element 3 + 3 should be 4 but we this element 3 + 3 should be 4 but we this element 3 + 3 should be 4 but we have lost track of it we have four here 4 + 3 will be 7 here which is not 4 + 3 will be 7 here which is not 4 + 3 will be 7 here which is not correct so that is the reason why we start competing from the end this element this four it will not affect the next element so Computing six means this element it will not compute affect the any other element in the AR because you're taking element at that position and the previous position so again I'll erase all yeah so that's why what we do is 1 + all yeah so that's why what we do is 1 + all yeah so that's why what we do is 1 + 3 how much it is four so this is done it will not affect any further elements before to this now when you come to this position this three plus previous to this how much it is six again for this question this 3 plus previous to this 1 + 3 4 so this is what we do if you have + 3 4 so this is what we do if you have + 3 4 so this is what we do if you have update here then it will affect the next positions in the AR so this is how we calculate the Pascal triangle n row value so basically we have this so as you know we keep on updating the values by adding the elements in the previous row that position and the previous position but how do we represent this 1 then 3 4 5 if n Al to one they given then length of the resultant array will be equal to 2 so that will be the length of the resultant array so what should we do so Nal means I'm telling the resultant array okay so if Nal 4 they given first we start competing with n = we start competing with n = we start competing with n = 1 n = 1 n = 2 N = 3 Nal 4 apparently Nal 1 n = 1 n = 2 N = 3 Nal 4 apparently Nal 1 n = 1 n = 2 N = 3 Nal 4 apparently Nal to 0 and Nal 1 are not required to compute because they already one we initialized the array with one from 2 to three uh two then onwards any row if they ask we need to compute the values so how do we logically implement the answer here so as I said first what we need to do if n equal to something they given n + 1 will be the length of they given n + 1 will be the length of they given n + 1 will be the length of the array so let's say five is the length of the AR because Nal 4 we have consider next what we do we initialize all the elements with one okay once you initialize all the elements with one how many Loops we need to run so if they say Nal to 4 we have to run from 2 3 4 so I = to 1 4 we have to run from 2 3 4 so I = to 1 4 we have to run from 2 3 4 so I = to 1 till I less than 4 those are the number of Loops which we need to run right so what we do is the outer loop will be nothing but for I = 1 I less for I = 1 I less for I = 1 I less than the N value whatever index given I ++ do we need to give I less than equal ++ do we need to give I less than equal ++ do we need to give I less than equal to n if they given n = 4 1A 2A 3A 4 to n if they given n = 4 1A 2A 3A 4 to n if they given n = 4 1A 2A 3A 4 four itations is it required no as I said these two itation you can skip from here we do so whatever n they give nus one iterations we need so nus 1 means I = 1 till I less than n i ++ this are the = 1 till I less than n i ++ this are the = 1 till I less than n i ++ this are the number of iterations so this represent I = to = to = to 1 I = to 1 I = to 1 I = to 1 okay so this is I = 1 I = 2 I = 3 so okay so this is I = 1 I = 2 I = 3 so okay so this is I = 1 I = 2 I = 3 so when we are = to 1 this is I equal to 1 when we are = to 1 this is I equal to 1 when we are = to 1 this is I equal to 1 right when we at I equal 1 now we will look into each row when we at I equal to 1 we Computing only one value when we at I equal 2 we need to compute two values this three and this three when we have I equal to 3 we need to compute three values so the inner loop will be for computing the values at each row for J equal to i j greater than Z jusus why if I equal to 1 only one Loop we have to run right so J greater than Z should be given J equal to0 means 1A 0 two Loops will be run so only one Lo we have to run so Jal y j great than Z jusus how do you add the elements so as you know if you create an array let's say row of I will be plus equals to row of IUS one not i j here in so this element will be equal to this element plus this element will this element plus this element equal to this element plus previous element so that's why we create so if you let's say if you run for uh n = 2 = 2 = 2 here so if n equal 2 you initialize array of elements 3 1 then I = to 1 array of elements 3 1 then I = to 1 array of elements 3 1 then I = to 1 you run so I = to you run so I = to you run so I = to 1 I lesser than N means I lesser than 2 I ++ so initially I will be equal to 1 2 I ++ so initially I will be equal to 1 2 I ++ so initially I will be equal to 1 so J will be run from J = 1 J greater so J will be run from J = 1 J greater so J will be run from J = 1 J greater than Z j-- so J = 1 so row of J will be equal Z j-- so J = 1 so row of J will be equal Z j-- so J = 1 so row of J will be equal to plus = to row of j- 1 so that is to plus = to row of j- 1 so that is to plus = to row of j- 1 so that is means row of J plus row of Jus 1 soow of J is nothing but Jal 1 here so this is Index this element will be equal to this element plus this element that will be updated to two that's it then Jal Z will R here because meal 0 which is not greater than Z done so you come out of the loop then I = 2 so you come out of the loop then I = 2 so you come out of the loop then I = 2 is it possible no I lesser than 2 so that's it you return the answer so this is how we calculate but one again question why did I give the loop in the uh negative Direction ending from the array because this as I said if you keep first update this 1 + 3 = to 4 then keep first update this 1 + 3 = to 4 then keep first update this 1 + 3 = to 4 then when you come here 4 + 3 will be equal when you come here 4 + 3 will be equal when you come here 4 + 3 will be equal to 7 here so that's why that's that will be a problem right so if we have three here so if you do 1 + 3 4 + here three here so if you do 1 + 3 4 + here three here so if you do 1 + 3 4 + 3 will be 7 so that will be a problem that's why what we do is if you have 3 + that's why what we do is if you have 3 + that's why what we do is if you have 3 + 3 so 1 + 3 will be 4 this will not 3 so 1 + 3 will be 4 this will not 3 so 1 + 3 will be 4 this will not affect anything 3 + 3 will be 6 3 + 1 affect anything 3 + 3 will be 6 3 + 1 affect anything 3 + 3 will be 6 3 + 1 will be 4 so we run the loop from ending to the beginning of the array so this is the logic so we will implement this at first we will have a array let's name it as row of size what row index + 1 and row of size what row index + 1 and row of size what row index + 1 and initialize everything to one fine so later what we need to do once you initialize the array so we have initialized the array and every Define the array declare the array and initialized it with one so next We Run The Loop so for I = 1 I lesser than for I = 1 I lesser than for I = 1 I lesser than index I ++ in the look will index I ++ in the look will index I ++ in the look will be J will be equal to i j greater than zero and J should be decrement so simple row of J plus equals to row of Jus 1 basically row of JAL to row of J + row of J minus 1 so at the row of J + row of J minus 1 so at the row of J + row of J minus 1 so at the end we return the through that's it so we will run this s check yeah and for Java I'll explain the logic also same thing we initialize the list because the given WR list integer here so you run over the row index I trate add one to it initially that means we can't initialize as we do in the C++ right like this we as we do in the C++ right like this we as we do in the C++ right like this we can't do it so that's why you add one so later J = to 1 J great than Z jusus you later J = to 1 J great than Z jusus you later J = to 1 J great than Z jusus you set the each uh index value in the list with row of uh the element at J position J minus one position you assign it at J position you return the list integer at the end so we shall submit this also yes successfully submitted if understood the concept please do like the subscribe to the channel we'll come up with other video in the next session until then keep learning thank you
Pascal's Triangle II
pascals-triangle-ii
Given an integer `rowIndex`, return the `rowIndexth` (**0-indexed**) row of the **Pascal's triangle**. In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown: **Example 1:** **Input:** rowIndex = 3 **Output:** \[1,3,3,1\] **Example 2:** **Input:** rowIndex = 0 **Output:** \[1\] **Example 3:** **Input:** rowIndex = 1 **Output:** \[1,1\] **Constraints:** * `0 <= rowIndex <= 33` **Follow up:** Could you optimize your algorithm to use only `O(rowIndex)` extra space?
null
Array,Dynamic Programming
Easy
118,2324
1,961
Hello Everyone Welcome To Tips So N Subscribe Like and Subscribe Must Subscribe Problem Statement Festival Two in One Drop of Things That is the Giver Subscribe and Subscribe The First World Positive Life Your Knowledge Bank Words Start Length 100 Office Part Subscribe Example Sua This Example Watering Give Impetus Subscribe To hua tha left string Of Words Which Can Be Made By Contrasting The First K Siddha Words For This Tube School District Come Quantity Meeting K String In The World Can Anything Like 1234 Is So Common Coming To Here Like Chal Question And Correct Watering Should Not Withdraw It's For This Accountant In the middle of 2004 Swift Subscribe This is coming to the example list Subscribe With I love you all the best Half in all should be sworn in for a big boss Apple comes in front is so aa the first woman A prefix indicating specific Setting off but in this case is not affecting the yes or no 102 ki jai so how we can do this of web programming what we can do it is paint for monitoring 100 for this of what we can do it a that it shows what we can Do apps the fast they can do song that tempering is a aapke a the second they can keep which canteen meeting that tempering hua main anil that common times singh ka length is equal to ideals benefits England and greater than giving free water and reducing aa 5282 elements and subscribe third element in serial vikram others like this aa they can keep adding times singh till at times string size lehar the giver in putting a times singh data is written test size what is subscribe now key Cutting And Resettlement Act Like In The Length Of I Love You All Subscribe Eleventh Idli Sandwich Subscribe 37th Love You Eid 910 Victims Not Interested Merge Go For This Website And Defeat Imminent Computers A Ko Bandha Stamping In Which Bihar Contaminating 10 Leo Swift Aimed At Size Comes Great Dane What Is The Biggest Size In Return For This Happened That And Khoj Ke Main Sirf A Time Equals To A As That Tanvi Can't To That And Return Gifts Or Suggestion Absolutely 10 Part In The Spot Where were we forming one times Singh and where contaminating the elements of Don't tell the size of tempering Subscribe button and bell till the time when contacted Vidangbhed for the hidden superintendent A kar do ki kya soul will phone bandh ki tempering and what we can do Is Tunisia is the first element of the words is so what we can do now boil aa a temple at length that is wavy we start ho a temple main anyway kal to ko whatsapp aaye virat universalise ayo re so what we can do in type 121 The blind imitation increment of i10 will add one more condition for show worst mode and WhatsApp word length is of the world and all the number of elements in the words should and that eye lashes dance is what WhatsApp is Directors and Producers That New Year Can Do We Can Directly Compare Dress Ka Vrat Aa Can Directly Complete The Contacted Tampering With Inputs And Gas Key And Effective Equal Dilute Transfer Rule Is Otherwise Well Written Test For Those Who Hare Vihar Handling The Condition Of The Contacted Time Singh Vikram Lal Gurjar Inside Anil Automatically Go to the Statement and Effective Verbal to this Computer Science All the Characters Subscribe to a Slack Friend Escort or Sweet Five for the One Test K or Electronic Doctor Test Cases or Dedicated Thank You for Watching My Video Good Bye
Check If String Is a Prefix of Array
maximum-ice-cream-bars
Given a string `s` and an array of strings `words`, determine whether `s` is a **prefix string** of `words`. A string `s` is a **prefix string** of `words` if `s` can be made by concatenating the first `k` strings in `words` for some **positive** `k` no larger than `words.length`. Return `true` _if_ `s` _is a **prefix string** of_ `words`_, or_ `false` _otherwise_. **Example 1:** **Input:** s = "iloveleetcode ", words = \[ "i ", "love ", "leetcode ", "apples "\] **Output:** true **Explanation:** s can be made by concatenating "i ", "love ", and "leetcode " together. **Example 2:** **Input:** s = "iloveleetcode ", words = \[ "apples ", "i ", "love ", "leetcode "\] **Output:** false **Explanation:** It is impossible to make s using a prefix of arr. **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 20` * `1 <= s.length <= 1000` * `words[i]` and `s` consist of only lowercase English letters.
It is always optimal to buy the least expensive ice cream bar first. Sort the prices so that the cheapest ice cream bar comes first.
Array,Greedy,Sorting
Medium
null
30
guys let's take a look at number 30 substrate with concatenation this all words so we're given a strain like this and a list of words are all in the same name in the same meant okay so find all study indices of substrate in s that is a continuation of each word in a words exactly at once and then without any intervene intervening characters so bar flu the flu bar man there is a words called fubar so the first one bahu and the fubar is the same so we should return 0 &amp; 9 let's try to so we should return 0 &amp; 9 let's try to so we should return 0 &amp; 9 let's try to solve this problem in the solve this problem in a good force way first one is a deep loop through s this Oh N say o n2 loop to M words Oh m3 loop through word okay so for each word we try to match up rematch we go to next one and then continue right so this will actually loop through again times n so we if we match the one word what try to match the next one without that word well there are a lot of details to handle that will generally give us I think would be + / K times n give us I think would be + / K times n give us I think would be + / K times n times M times K would be I don't know what I'm a right or not sorry should be n times n square ok 4 check it again so there will be n minus K cases for each case we will match again for each this K factors will need to match that here okay yeah so it's January and / K times M times K and then January and / K times M times K and then January and / K times M times K and then we have n words right and cough and as the length of the string so it's kind of like this but it's actually hard to write this is a sort of we need to because they're unique right we need to keep track of the unique ones because they are up the same names I think we can use first we try to use set to keep the words and say we start foot bar with check if bar is in the word if it is when we remove it right from there and then check through naive solution oh cool tweak here I'm not sure I'm doing it right okay improve we use set so loop through s OB o n check if oh it's the same actually what we're doing is the same we're just okay you set okay so the set equals word set word I'm not sure whether it's right to you set like this set new set I it is so you set it's like this for elect I equals 0 equals where 0 then cost result if s equals MT or world and cause 0 return results ok for each time we loop through the s we create a new set upward and let J equals I while J plus YJ plus K this is the N minus 1 is smaller than a start an end if there are still if they are still a sub strain there Const a sub equals s slice j+ k there Const a sub equals s slice j+ k there Const a sub equals s slice j+ k right yeah we slice it and j plus equals k and the okay we keep the flag is matched no you don't do this so if set if words set has sat if has it then we're set remove or delete I forgot whether is remove a delete God delete okay deletes sub when this is done if not break don't do anything this break and if word set size or length size right sighs yeah if size equals zero result push I think I and then we go to mix the JIT next I finally return results kind of feel that this right but it's very slow I think well pass uh it doesn't work for these cases word good best word 12 for 12 days good best word good password huh good best word and there's still word ah we should he is set Oh God miss duplicate word then we should use set issue words actually is word slice mm wait a minute we should actually use a hash map yeah we should keep track of the existence of each cap each tag each word right so wishes use a map now set Wow this okay so const map equals new map for that 0 I plus if math path if Matt has words I my set right I let get words I plus 1 if here is we updated to updates the number to update the occurrence to 1 i increments the occurrence if not we set it to where it said it to one okay so this has the map now if the map has it then okay word Matt we need to create a new map Oh new map if word map has it then we should work that if get its new alright it's undefined so I'll define or word or some numbers so if it get it has it and the occur is bigger than 0 this right and then we should set sub word map get a septum - one house break this year at a septum - one house break this year at a septum - one house break this year at this kind of work what unexpected in 13 voice who wear spot there's no food word said it's not defined mmm word Matt okay so fine Andy if the mat every time we - one and if there isn't we time we - one and if there isn't we time we - one and if there isn't we break so it will work just if we met don't need to check the size we just need to check if J - J because J it's need to check if J - J because J it's need to check if J - J because J it's the next one so the amount like e one two three four please five thanks one is right so the numbers should be yeah if J minus I is equal to words then times okay it's the brute force solution it's time we got the original one wrong console.log smack fool 1 bar 1 okay for console.log smack fool 1 bar 1 okay for console.log smack fool 1 bar 1 okay for the water first it's fruit bar also log ah God the check should be here my bad hmm this time I think I'm getting it right oh yeah it passes well it's not that fast let's see the details wow it's really slow let's take a look at the fastest edition yeah this guy efforts equals at a worse count what's lend offset math for each word we use a map and sequence chart for the end and then seize s then - word length and then seize s then - word length and then seize s then - word length uh-huh so for J through and we and get the substring and check get word entries used it's not equals to word and we needed words found what words introduced means map get word man what is math map is a word map where it's interest needed let's get worried tip Medicaid word I don't know what he's doing but they can do like we're doing not that difficult I could be mad and huh let's see it again maybe this one looks better man too hard okay word entries needed word entry used snore right word to move remove substring start set tips Maps works out mmm I think we kindly do the same right we check if they are there yeah anyway you submission is it to take a look at the disgust tumor solution we used ordered man another map to record expected times of each word and another on order map to record at times we have seen then we check if for every possible position of I once we've made an unexpected word of the times where it's larger and expected times we stop the check ah I see my pride hmm finally I'm saying well gee I quote Jase - - string substring weird I quote Jase - - string substring weird I quote Jase - - string substring weird okay counts contains key counts countess this scene put +1 sing get countess this scene put +1 sing get countess this scene put +1 sing get worried if it's bigger then gets all default break that's break plus 1 actually it's Tizen he's doing the same except that our solution where every time we clone the map and do call in a man and update it I know me either way oh wait a minute what okay so gets or default mmm okay and then a word is this if counts has this word we put it saying if get were saying get word is bigger than here break yeah actually we are doing almost the same except that we are cloning this map and do the - and what he is doing is that he do the - and what he is doing is that he do the - and what he is doing is that he was creating a new map and the check dude new map and the check and collected that existence if that's the case it doesn't matter that much I think mmm yeah okay so that's all for this one see you next time
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string `s` and an array of strings `words`. All the strings of `words` are of **the same length**. A **concatenated substring** in `s` is a substring that contains all the strings of any permutation of `words` concatenated. * For example, if `words = [ "ab ", "cd ", "ef "]`, then `"abcdef "`, `"abefcd "`, `"cdabef "`, `"cdefab "`, `"efabcd "`, and `"efcdab "` are all concatenated strings. `"acdbef "` is not a concatenated substring because it is not the concatenation of any permutation of `words`. Return _the starting indices of all the concatenated substrings in_ `s`. You can return the answer in **any order**. **Example 1:** **Input:** s = "barfoothefoobarman ", words = \[ "foo ", "bar "\] **Output:** \[0,9\] **Explanation:** Since words.length == 2 and words\[i\].length == 3, the concatenated substring has to be of length 6. The substring starting at 0 is "barfoo ". It is the concatenation of \[ "bar ", "foo "\] which is a permutation of words. The substring starting at 9 is "foobar ". It is the concatenation of \[ "foo ", "bar "\] which is a permutation of words. The output order does not matter. Returning \[9,0\] is fine too. **Example 2:** **Input:** s = "wordgoodgoodgoodbestword ", words = \[ "word ", "good ", "best ", "word "\] **Output:** \[\] **Explanation:** Since words.length == 4 and words\[i\].length == 4, the concatenated substring has to be of length 16. There is no substring of length 16 is s that is equal to the concatenation of any permutation of words. We return an empty array. **Example 3:** **Input:** s = "barfoofoobarthefoobarman ", words = \[ "bar ", "foo ", "the "\] **Output:** \[6,9,12\] **Explanation:** Since words.length == 3 and words\[i\].length == 3, the concatenated substring has to be of length 9. The substring starting at 6 is "foobarthe ". It is the concatenation of \[ "foo ", "bar ", "the "\] which is a permutation of words. The substring starting at 9 is "barthefoo ". It is the concatenation of \[ "bar ", "the ", "foo "\] which is a permutation of words. The substring starting at 12 is "thefoobar ". It is the concatenation of \[ "the ", "foo ", "bar "\] which is a permutation of words. **Constraints:** * `1 <= s.length <= 104` * `1 <= words.length <= 5000` * `1 <= words[i].length <= 30` * `s` and `words[i]` consist of lowercase English letters.
null
Hash Table,String,Sliding Window
Hard
76
807
what's up guys Nick white here doing some more leak code might as well right now please join the discourse for me on patreon if you can really appreciate that spend a lot of time on these and yeah let's get into it max increase to keep city skyline medium level difficulty some dislikes will give it a like you're given a two-dimensional grid like you're given a two-dimensional grid like you're given a two-dimensional grid array or grid so right here 2d array each value of grit oh I of J represents the height of a building located there okay so we have a grid and we have a bunch of buildings each individual index is a building so these are all buildings the 3 the 0 the 8 the four all the ok we are allowed to increase the height of any number of buildings by any amount and the amounts can be different for each building so we can increase the height of any of these buildings like the 3 we can change to 4 or we could change it to 5 or we could change it to 15 or whatever we could change 0 to 5 we can change 6 to 9 we can do whatever we want and you know one way to make it change we if we change this by 3 if we increase this by 3 it doesn't mean we have to increase all of them by 3 we could change each of them individually with different amounts but we're only increasing ok and these are all the heights of the buildings by the way so this building is a height of 3 this one and it says height 0 is considered a building as well even though a height of 0 usually means nothing so it would be like a building that goes from underground to like floor level I guess but you know no it's a height 0 I guess basically just a building with height 0 okay so what's the objective we have these buildings we're allowed to increase the heights of any of them so what is the objective okay at the end it looks like the skyline viewed from all four directions bottom left top right must be the same as the original grid okay so we can increase the buildings as much as we want but the skyline has to be the same as the original grid and I'll get into what that means in a second a city skyline is the outer contour of the rectangles formed by the building when viewed from a distance what is the maximum total sum of the height of the buildings that can be increased okay so this might seem confusing what is a skyline we're looking at a 2d array this is you know there's buildings well what they mean is they mean that the highest the maximum value in each column has to stay the same and the maximum value in each row has to say the same so let's look at these examples the first row what is the maximum row value is 8 well in the output array the maximum row value is also 8 the second row is 7 the second row of the output 7 still maximum then 9 3 right see what I'm saying all of the maximum row values have to be the same for the columns first one's 9 output array 9 4 you know what I'm saying 8 7 ok but for any value that isn't to the maximum row or column value we want to increase those as much as we can we just cannot go past the highest value in each row and the highest value in each column right so we can increase this 3 to an 8 because the maximum column is 9 in the maximum row is 8 so as long as we don't go above 9 or 8 we can increase it to 8 we cannot go above the minimum of the column or the row value and what we want to do is we want to increase each of the buildings as much as we can without going past the skyline is the maximum row maximum column values and as long as we do that we're going to be adding so if we increase this 3 to an 8 that's a 5 height difference so we add that on to an ongoing sum and then we output it when we increase the 0 to a 4 because the 4 is the max column we can only go up to the either the minimum of the max column in the maximum row so the max columns for max rows 8 and then we have 2 we can only go up to 4 ok so that's pretty much easy what we do here to solve this problem it was a little wordy bad but the problem is pretty cool all we want to do is we want to find the maximum row value for each row and put it into an array and we want to find the maximum column value of each column and put that into an array and then the formula is basically we have this result variable or like some or whatever you want to call it and we're gonna be adding the minimum of the max column Val and the max row Val and then subtracting the current element and we this is the whole formula right here we do result plus equal min of the max column Val in the max row Val minus the current value so if the minimum of the so for example 0 the max the minimum of 4 &amp; 8 because 4 is the minimum of 4 &amp; 8 because 4 is the minimum of 4 &amp; 8 because 4 is the max column and 8 is the max row is 4 so we do 4 minus the current element which is 0 and then we get the answer which is 4 and we subtract the current element just to get how much we would increase it by if that makes sense right like for example 7 is the max column value and 8 is the max row value so we can only go to 7 so we wouldn't be increasing by 3 so we just take the minimum of these value 7 we subtract 4 and that gives us what we would have increased it by 3 I think it's really straightforward all right so yeah that's it so first let's just get n is going to be equal to grid length we're gonna set up some max row Val's array is equal to new in Turay of n and int max column Val's is equal to nu into then as well so we can say n is and is going to be the side of the number of rows or the number of columns because if you look here it says number of rows and columns are same is what this statement says so it's like a square grid basically so that's why we can do this because there's gonna be the same number of columns and rows so you just get the number of rows is n and then you just say okay the we're gonna this Verret this array max row valves is going to store the maximum value in each row so if the it's a four by four it's gonna store four values and then this is going to store the max value in each column that's gonna store four values as well how do we get these values well we just loop through the Ray rows by column loop here which kind of stinks but it's no big deal you could really just do less than n since you do that for everything honestly so we could do less than and J plus make sure you're doing J not being dumb like me so standard loop through a 2d array right and we're gonna need to do these twice so let me just put that there what so first we construct that we get the maximum row value of each row and that is the math dot max between the current maximum row value we have in the index which they all start a zero and the current grid cell that's it and it's the same for the columns obviously with J's so if you look at this I don't know if I want to explain this because it might take I feel like this video is already getting along but if while you're looping through you're checking the max these are just empty arrays that start as a bunch of zeros so you check the current element so on the first let's do the column ones so on the columns it goes you know J goes one two three four right so it goes well it goes zero one two three that's the indexes so we do max row values of zero is equal to the max of 0 in the current element right so the column valves would check against 3 and 0 and be like ok this is the max column value is 3 okay now the max column value is 0 it stays 0 ok now the max column value is 8 for this one you just get it by index now the max column values for and then as you go through the whole thing you keep updating them because it goes back to 0 1 2 3 J does that a bunch of times checks all the values and puts them in the right indexes should be pretty straightforward maybe think about it comment below if you don't get it and maybe I'll message you an explanation and now once you have all these you have the all the max row valves in the max column value so we just use the formula from earlier we do result plus equals the minimum of those values the minimum of the current max row val max row valves of i and max column vows of J minus grid of I of J and yeah that should be it and then you return the result I feel like I messed up and just have a bad feeling but I also nope there we go perfect okay so that's it yeah we used the formula from earlier you just get the minimum of those I mean I explained it already but you get the to find out how much you're increasing each element by you would just check ok what's the minimum of the max column values for here max row val is 8 here so the minimum is 4 and then you just do 4 minus 0 is 4 and then that's what you updated to you add that to have some and you're returning at the end result thank you guys for watching I really appreciate it or appreciate everyone that sports and let me know if you have any questions I think this is a cool problem and you know thanks for watching see you guys in the next
Max Increase to Keep City Skyline
custom-sort-string
There is a city composed of `n x n` blocks, where each block contains a single building shaped like a vertical square prism. You are given a **0-indexed** `n x n` integer matrix `grid` where `grid[r][c]` represents the **height** of the building located in the block at row `r` and column `c`. A city's **skyline** is the outer contour formed by all the building when viewing the side of the city from a distance. The **skyline** from each cardinal direction north, east, south, and west may be different. We are allowed to increase the height of **any number of buildings by any amount** (the amount can be different per building). The height of a `0`\-height building can also be increased. However, increasing the height of a building should **not** affect the city's **skyline** from any cardinal direction. Return _the **maximum total sum** that the height of the buildings can be increased by **without** changing the city's **skyline** from any cardinal direction_. **Example 1:** **Input:** grid = \[\[3,0,8,4\],\[2,4,5,7\],\[9,2,6,3\],\[0,3,1,0\]\] **Output:** 35 **Explanation:** The building heights are shown in the center of the above image. The skylines when viewed from each cardinal direction are drawn in red. The grid after increasing the height of buildings without affecting skylines is: gridNew = \[ \[8, 4, 8, 7\], \[7, 4, 7, 7\], \[9, 4, 8, 7\], \[3, 3, 3, 3\] \] **Example 2:** **Input:** grid = \[\[0,0,0\],\[0,0,0\],\[0,0,0\]\] **Output:** 0 **Explanation:** Increasing the height of any building will result in the skyline changing. **Constraints:** * `n == grid.length` * `n == grid[r].length` * `2 <= n <= 50` * `0 <= grid[r][c] <= 100`
null
Hash Table,String,Sorting
Medium
null
1,996
hello friends uh welcome to my channel let's have a look at problem 1996 the number of weak characters in the game so in this video we're going to share a solution based on monotonic stack so first i'll read through the statement of the problem to digest the requirements of the problem then we will look at the simple analysis and share the short code first let's look at the statement of the problem so we are playing a game that contains multiple characters and each of the characters has two main properties attack and defense so we are also given a 2d integer array called properties where properties i equals attack i and defense i represents the properties of the ice character in the game a character is that to be weak if any other character has both attacked at the defense levels strictly greater that this character's attack and defense levels so here is a formal definition in mathematical formulas so we are required to return the number of weak characters so that's the main body of the statement here are three examples so in example one so actually so this has no mixed characters so if you examine these three elements you've found that there's no such relation defined by weak so in example 2 so the output is what so we have this character 2 which is weaker than 3 so the return is 1 and in the example three so we know that one seven um let's see 4 3 is bigger than 10 4 because 10 is greater than 4 and 4 is greater than 3. notice that so 1 5 and 4 3 does not form a weak relation so here 1 is less than 4 however 5 is greater than 3 so that's the three examples so here are the constraints or additional assumptions for this problem first the length of the properties is bounded below by 2 and bonded above by 10 to the power 5. so this item of the constraints defines the problem size we are looking at so property i has length 2. so each of the elements is a pair in the properties array so the attack and defense range or value is in between one and ten to the power five so this is the main problem statement at the constraints or we can see the additional assumptions so with that said actually we are ready to look at methods so the method here is based on monotonic stack so here i'm going to use a stack of the defense so actually you can also use the stack of the attack so because this tool we can choose one and then use the other as the scene we're looking we're going to check so the idea is simple so we're going to sort according to the attack power increasingly and then the distance power decreasingly so this is going to be our sorting key then we're going to use the monotonic stack to fit how many weak characters that the current character we are looking at we may do linear traversal so each time if we do vamp pop of operations so actually the atom popped corresponding to a weak character so we just need to do the counting each time we have a pop operation so we're going to give a weak walkthrough first and then after we do the code so you can come back to look at this example again or work through again so the whole picture will be crystally clear um here before we do anything let's make some comments so here the weak um the weak weakness defined by the problem here actually forms a partial set so the partial set actually is a concept in mathematics so if you have learned something um instead theory or major theory so there's a famous theorem called zones lemma so basically we want to find uh how many maximal elements or how many uh what's the tin chain length of a partial set so this comment actually is more towards the audience with a mathematical background so for other people we can just ignore that so with that said let's do a quick walk through so first i'll quick up a special example so here we have felt valve and they have valve six so in this case the attacked the attack power or often the power fell the are the same so in this case these two elements does not form a order so based on weakness so the output should be zero so our sorting we have this one five six and five seven then the stack state will be six when we finish looking at the first element and then because five is less than six so no pop operations so the result is zero so this is the one of the example so let's look at example two so this corresponds to example three i guess in the main statement so after starting we have one five four three and ten four so if we do not put it in the code format we can interpret that so 4 3 is weaker than 10 4 so we have very large is one but if we look at the monotonic stack after we do the sorting and examining the of um ascend power so when i equals zero so we look at the stack we push the five into the stack so we get five and then we look at three because three is less than five so it's still okay so when there's no um pop operations so when we look at four so four is um greater than three so we pop three then so we are going to have one character which is weaker so this character is corresponding to four and three so each time we do a pop operation so we increment the count by one so as also you can see from the this log through so we are good we are trying to maintain a locally decreasing stack that's why this is the monotonic stack so actually we have practiced quite a number of such problems so monotonic stack so the valve condition actually is very straightforward for us if you have already checked out the relevant videos in my playlist so afterwards we put this 4 into the stack so the stack is 5 and 4. so the return is meant in this problem so an important point to notice or the suddenness of this logic here is that uh if there's a tie in attack power so due to the way we thought the difference power so the logic is sound so the stack in the traversal will be locally decreasing so this is actually very important locally so sometimes it's not globally decreasing so um here we let's have another example we cooked up so let's go to look at the following example one five ten four three and ten six and eleven six so this six um and this tool so we have one and different power of the scene so this um this one and zero and four are ten and four and ten and six they have the same uh often the power of attack power so after sorting we have this one so for this problem the final state of the stack will be six the return is three so you can come back to digest this after we share the code so now let's look at the code so i have changed the properties to be p just for the convenience of writing so with that said first make some preparations so we're going to start right so we're going to sort the p corresponding to one of the two uh element uh increasingly and the other decreasingly so here i'm choosing to sort the first element or the offend power increasingly and the other decreasingly so here let's specify the sorting key so i'm going to use a lambda function so i'm going to sort this as the first one or the attack power increasingly and then if there's time i'm going to sort the second element decreasingly so this is actually important so you can also choose to sort the first one decreasingly and the second one increasingly and use the first one to be the elements to push into the monotonic stack if you sort the second one to be decreasing so we're going to use the second one as the monotonic stack object so with that side so let's initialize a stack so this is going to be the monotonic stack so the result we're going to initialize it to be zero so this is going to use for counting the weak characters so next is a monotonic stack so here the stack will be a monotonic decreasing locally and then the main work this if you have digest above logic this should be very straightforward so for attack a defense in this p so what we are going to do is the monotonic stack step monotonic stack so this uh monotonic stack will be very straightforward now so first we need to check if the stack is empty or not if not so we can check this condition if the top of the stack is um smaller so maybe let's read this if this d the current power is strictly larger and then the top element in the stack if so what we're going to do is that we're going to do the pop operation so each pop corresponding to a weak character which is weaker than the current ad in other words this weaker learner does form a partial relation with the ad currency we are looking at so because of this we are going to increment this result by one so after we access this loop so you know so we are going to either have an empty stance or d will be less than or equal to stack then we need to push this d to the stack that way so um the stack will be always locally decreasing so or if originally the stack is empty or we look at the first character so we should first append the d to the stack so that's logic so this code is very short but it contains dedicated logic here so with that said actually we can return the result so that's the main code and it forms a solution format here so let's first do a special case check yeah it passes the one of the examples so now let's look at the generic case yeah it passes all the cases so i guess for this problem it's about it so here uh we're using the monotonic stack so if you have them you are welcome to check out the corresponding playlist on practices of monotonic stack problems so with that said i guess that's about it for this video thank you very much
The Number of Weak Characters in the Game
number-of-ways-to-rearrange-sticks-with-k-sticks-visible
You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game. A character is said to be **weak** if any other character has **both** attack and defense levels **strictly greater** than this character's attack and defense levels. More formally, a character `i` is said to be **weak** if there exists another character `j` where `attackj > attacki` and `defensej > defensei`. Return _the number of **weak** characters_. **Example 1:** **Input:** properties = \[\[5,5\],\[6,3\],\[3,6\]\] **Output:** 0 **Explanation:** No character has strictly greater attack and defense than the other. **Example 2:** **Input:** properties = \[\[2,2\],\[3,3\]\] **Output:** 1 **Explanation:** The first character is weak because the second character has a strictly greater attack and defense. **Example 3:** **Input:** properties = \[\[1,5\],\[10,4\],\[4,3\]\] **Output:** 1 **Explanation:** The third character is weak because the second character has a strictly greater attack and defense. **Constraints:** * `2 <= properties.length <= 105` * `properties[i].length == 2` * `1 <= attacki, defensei <= 105`
Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick?
Math,Dynamic Programming,Combinatorics
Hard
null
92
Hey guys welcome to take to live nivedita and in this video we are going to solve reverse least to swiss problem statement me wheat ke hai par aapko ek single ne kiska hai na de rakha hai and 2ND year de rakha hai left and right where What is your left in this daily west to right and what do you have to do in between left and right also, we have to reverse them, finally we have to turn reverse in English, so first write the example that you understand, what has been given to you 10 Have given it and have given it left and right. See here on the famous name. I have hanged two. It is an Android phone. All the notes of Admin, Circulation and Fourth Position, what to do with them and what to use them, then it is in this video channel one two. What will be the information 1234 Vipin among them whatever navy what to do is to reverse it will be done after reversing 142 50 Your final English student is fine then how can you solve this problem that for you, here I will take an example. That is, we take the fruits inside so that if you understand the approach that we are going to tell here, then it is okay. File Six 97 98290 Understand all this, it is given in English, now what to do between this position and this position, this is yours. Left is that your tight that there is a list and a note in it, then what to do is to do the table. Okay, then on reverse, what will happen finally, your lineage will go to the tree of both of them that you will become one. Add deposited collection of class 6. Maths Papa, what will be five-five connect for five-five connect for five-five connect for phone connection? Stone actor's award to that not to ninth and tenth light because we have to do it between them. From here to here, the sum is fine. So see, how will the people who submit here solve this problem. No reverse, first what will we do, we will vote for these two, then we will fry these three, then we will do these four, then these five will cause harm, friends will note this, okay, then how much time will you do, 12345 times, we have to process the same, I am okay, sorry, that too. I will tell you that if you want to do it for the first time, then why do you have to do it for the first time, because there is a six of navy total powder between the left and right side, okay, how much is the six on the Google account, 123 456, will you do the operation Kumar, how much time will you have? Part time, which is going to be your total notes - one time, so your total notes - one time, so your total notes - one time, so click here, will you use these two first? Let's see what will happen to you, but Vishal, you can write the initials of five properly - 97, 98 or 90. write the initials of five properly - 97, 98 or 90. write the initials of five properly - 97, 98 or 90. Yes, yes. Which is and from here, what do we have to do from here, that this is what we assume to be the value of this, we assume control, okay, from here I have to do, so we assume this to be current and what is this, standard entry note, okay, its owner Previous node and this word, what is the part of cant? Next9 is okay. CN Let's assume this is what is cant? Next9 is okay. Now what we have to do is we have to reverse both of them. Okay see if we use these two then two will be my and former will be ours. It will be done here and the second one will be done here, it will be done here, okay now look here two is pointing to this, look here to point the flowers after using i.e. what after using i.e. what after using i.e. what is behind is appointing the expellee makers. Appointing the next of Cantt 156 97 98100 OK, now where has the current reached, where has it reached here, add more and mix, it has come here, our previous will remain the same because we are from the environment of Cantt, you are there only. We will also keep the two here, okay, now look at the time, now we will use it, what will we do here, then only what will we do, will we appoint whom will we do next to the cant, okay, so we take pimples, Vansh how to, so what will we do here, file because This belt of fine will be taken 453 please 67 1789 Shyam Cantt where is your current note here non note tax next month is this and previous will be everyone's PM accommodation and reverse na what will we do now will appoint picos which will be next na what will be that This love will be appointed to the next one, okay, what will you do, stir it again, do the device, go to six 504 and three, it is sure, again stop this point in A, open the setting, use one true. The film producer is doing 272 points, there are five and I am 423, after this, 80 ok printer needs to be connected here it keeps the time because we can see how much time we have done, here one time, two time two. time this is the last time this is our okay so p point it here ka you can appoint the next okay so here is this press takes him want to two a this who point dad to one seven to seven six to We are at 65.50 90 This is our final Sajna, this is our are at 65.50 90 This is our final Sajna, this is our are at 65.50 90 This is our final Sajna, this is our final, not ours, put it here, now what did we have to do, we had to bring three here, Kent, we had to bring friend here, this is what I had to do, right here or Calcutta or embroidery was there, we had to finalize it, we had to send the comment here, we should have prevented this, it should have remained ok, reverse should have been collected, next 7x 6543 210 of 8708, we have got it here only, we have got it here, now look, now we have to stop this operation. Keep doing SIM operation, for how long are we doing the operation, which is our total, the note in the middle of the total loaded electrolyte, till the time, till the total minus one, we follow this process, now what is this process we are following, this is what we will beat. Whatever we are constrained here, we will take advantage of it. See what you are doing here Pintu, where should you point? Prevent's neck is always pointing to whom. Look at whom it is pointing to the next cantt. Please pick the constraint in. Next point is drinking, turn on the next nine planets, here is Fida, next point is appointing collect, here, before doing reverse, check that yours is free, okay, this is you, previous note, Arghya, this is your friend note, okay, this is it. Previous this is your current note a can connect what is the phone and reverse after this you see pick connect is jointing it pickup next which was before reverse the pen card next is the same neither tight here now can connect they are fiber After this, JP Connect's phase has been formed, so look here again, look below only, you can collect here, there is six, after this pimple is formed, whose next one has become, two connect has been formed, which is our previous one, so what will happen here. What will we do with the previous one? We will make it the next one with the previous one. Call it the next Ghanshyam of the current one or call it current connect. This is how it does it. This is fine. This is the friend list. Now we will see who can't connect and how it is changing. Is it okay? So now here CAN is connecting but here two printer connect has become one which is what is the criteria of cancer here. Thanks for listening friend connect has become 36 which is what is the next of five which is the next of cancer. So here, after mixing from here, we will write here that what is next has changed. Next 9 News, now one more here, what is next here, but here what is the next of the previous. Now the previous one, this is your next, ok, press collect here, next apna kya phone hai, but here, press next, do next apna kya, it is free here, ok, then invest here, next connect apna kya hai. Which is what is yours, it has become ripe by doing next to the previous one. Now look here, by doing next to the environment here, next, here you get connected to the next one of the previous one, which is what has become of the previous one after the day, which has become next tight. Andhi Previous Yesterday A Bit Reverse Connect i.e. A Bit Reverse Connect i.e. A Bit Reverse Connect i.e. after reverse here this page 169 Today Mumbai's Red Chilli One Time Mist Time A Copious Connect Kar Next which is yours Previous's I-Next Or Either Next Previous's I-Next Or Either Next Previous's I-Next Or Either Next Here It is given which on investing is to be selected here which was before sleeping. On doing previous it is to be played here. Next is next five which is what is the mixture of previous. Before sleeping the arrangement list is here so here we are. Previous Next but here you have selected what we will do now what we will do for one more minute in this is before changing this we will subscribe to the generation and to select this we will sign Preeti here, okay this It is simple, at what time to call, as much as there is hatred, left right side - loot hatred, left right side - loot hatred, left right side - loot plus one time, see here what yours is 123, do the waterfront, take this Pathde 123 not and here that yours again is 12345 681 i.e. Left or Right - And science is 12345 681 i.e. Left or Right - And science is 12345 681 i.e. Left or Right - And science is not updating, wrap left minor light - while not updating, wrap left minor light - while not updating, wrap left minor light - while adding note plus one, digest two SIM professor. Okay, so now let's come to the pet previous, how will you do it before the flight, please, what will you do, you see, what is this? If this is your third note, then we will need a second. Okay, so we can do both these points. What will we do? We will come here by facing the light minus one time. We will sign this. What will happen with the Prevention of Money Waste note? How will we fold the note? Consultant, what is the tax prevention act, so what all the transportation we will do, then Pravesh Kumar will take the arrangement list, okay, I want to go to the man- okay, I want to go to the man- okay, I want to go to the man- eater part, so here you will do it, what will you do in the initials, contemporary dummy and let's take - from the wall, okay, we are here. and let's take - from the wall, okay, we are here. and let's take - from the wall, okay, we are here. What will we do - we will start one - we will What will we do - we will start one - we will What will we do - we will start one - we will start one, this is vitamin and it's your time, okay who will it appoint, whoever is next, it will do one point, okay who will it appoint, it will appoint that one, okay now after that, if you like, then that We will do this so that when we return, we will neither submit this domino temple nor its neck because our answer is Agravanshi, so what will we do here, this temple is on WhatsApp, so what will we do now? Here we have taken minus one for the temple, here we have given it one, we have made a note, after this we consider the environment as shampoo, okay, in the standing world championship, then make the next thing in time, get any word pointed, okay point. Got it done, then what should I do, you mood the previous. Left - Monitor OK, so this is different from size zero Left - Monitor OK, so this is different from size zero Left - Monitor OK, so this is different from size zero - what should we do with it from 110, - what should we do with it from 110, - what should we do with it from 110, this Laxman science of business will remain till time only, this will free it from the previous, that is, what will happen to your previous mouth. Your will come here, will come on two, ok unknown, then we will find the current, what happened previous connect, we have done this, now what will we do the same process which we will tell you how much time we have to do now, termite - on the left side. Till now we have to termite - on the left side. Till now we have to termite - on the left side. Till now we have to start the guide user, we will keep it in Lebanon, otherwise this same process, what will we do, we will follow PTI, what have we done in the prevent list, previous is next, left in cant's next, Praveshika next and cant connect. What will happen to education? Friend will connect. Set up will have to be reversed. Selected will have PTR which is your previous next that final what will we do? Will we tweet the neck of the tank? Do time connect quantum because time which I have taken - mind taken. But time which I have taken - mind taken. But time which I have taken - mind taken. But we need the answer from one, so what did we do here? Temple Run Next, this pattern is done, okay, the warden does that by submitting Ramesh to the court, if you liked the video, then use your phone, like, share and subscribe. Dena thank you
Reverse Linked List II
reverse-linked-list-ii
Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_. **Example 1:** **Input:** head = \[1,2,3,4,5\], left = 2, right = 4 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[5\], left = 1, right = 1 **Output:** \[5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= n <= 500` * `-500 <= Node.val <= 500` * `1 <= left <= right <= n` **Follow up:** Could you do it in one pass?
null
Linked List
Medium
206
216
foreign we have to find all value combination of K numbers that sum up to n such the following conditions are true we can only choose numbers one two nine and each number is used at most one so we don't have repeating numbers and we can only choose from one uh to nine we have to that's basically our set of candidates we have to return a list of all possible valid combination and the list must not contain the same combination twice and the combination may be a return than any other so we have to skip the uh the duplicates and the uh the list can be returned in any order so for example we have K3 and we have N7 and we can choose the numbers one and two and four so we are choosing three numbers they are all from one two nine and they are summing up to uh number seven uh now for the second example we have k equal three and then I is equal to nine so we have one two six which is one plus two is three plus six is nine the same goes from one three and five and two three four so there are three valid combinations that we are returning and in the last example we have K it's equal to uh four and N is equal to one because we cannot repeat numbers and uh the numbers are from uh from one to nine we cannot have one plus zero because this is first of all repeating numbers and also zero is not allowed as the is not part of the candidates that we can choose so there are no valid uh there are no belt combinations now the K ranges from two to nine and the N is basically uh from 1 to 60. now so there are a few restrictions that are actually making our problem easier uh we can just use the uh the logic that we have used for the combinations of one uh but for the set of candidates we are using uh one and uh of one two numbers one two uh nine so that those are the only numbers that can choose we can use uh the start variable so in our for Loop in the helper function we'll be starting from the start not the zero to prevent using the number multiple times and because we are going uh in sorted order I want to nine always uh the array is already sorted so there will be no duplicates uh the uh we don't have to worry about uh about that as always we started defining our list of all the combinations that we have managed to generate uh we call our helper function and return uh the result this is a common uh flow when we are dealing with the backtracking problems now we for the helper function we just propagate the K number of elements that we have to choose that's the language of the r combination n is the number that uh the uh that our combination uh the element that we have chosen for inside our combination have to sum up the current sum is the current sum that has matched the N start is the index Forum via our helper each helper function starting from uh current list is the list that is the combination that you are currently generating and the result is the closest result that we propagated from the manufacturing that you are returning as the SD final output uh very first check if the current list size is larger than K in that case we can just return it because we are not uh we are not considering the uh combinations that are larger and less than K because we can only choose K elements uh if the current sum is equal to n and the current list size is equal to k then we have a valid uh combination and we can just add it to the result and return uh from our code from our function and go up to the up in the recursion tree uh we start from the uh we implement the for Loop and we start from the um by declaring that I is equal to the start so that we can control that each element is used once because if we use the current element in the first school of the helper it will not be possible to use it in the second one because the start will be uh incremented by one uh in the previous call uh when we are calling the helper function recursively also because the numbers are sorted uh and the candidates are sorted and there are no duplicates in the candidates there are numbers just one two nine we don't have to worry about the uh the duplicates in the output list we just check if the current sum plus the candidate that we are adding is still uh is still smaller or equal to the n and if that's the case we add the current candidate to our current combination and we called helper function occursively by adding the current candidate to the current sum and also increment start for the next Call of the helper function finally we uh after we are done we are back into this call of the function we have to backtrack and we remove the element that has been added before we are we called the helper function now for the time complexity we have at most nine choices and the depth of the recursion tree is at most K so and we will have 9 to the K times the multiplier K we are the which corresponds to the maximum size of the current list that we are operating on uh which is also our space complexity
Combination Sum III
combination-sum-iii
Find all valid combinations of `k` numbers that sum up to `n` such that the following conditions are true: * Only numbers `1` through `9` are used. * Each number is used **at most once**. Return _a list of all possible valid combinations_. The list must not contain the same combination twice, and the combinations may be returned in any order. **Example 1:** **Input:** k = 3, n = 7 **Output:** \[\[1,2,4\]\] **Explanation:** 1 + 2 + 4 = 7 There are no other valid combinations. **Example 2:** **Input:** k = 3, n = 9 **Output:** \[\[1,2,6\],\[1,3,5\],\[2,3,4\]\] **Explanation:** 1 + 2 + 6 = 9 1 + 3 + 5 = 9 2 + 3 + 4 = 9 There are no other valid combinations. **Example 3:** **Input:** k = 4, n = 1 **Output:** \[\] **Explanation:** There are no valid combinations. Using 4 different numbers in the range \[1,9\], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination. **Constraints:** * `2 <= k <= 9` * `1 <= n <= 60`
null
Array,Backtracking
Medium
39
191
hey everyone today we'll be doing another lead code 191 number of one bits this is an easy problem and we have already done a problem much harder than this so which was reverse the bits and this is um number of one bits we have to tell how many one bits are there in a 32 bits I think this is a 32 bits they didn't specify it but I think it is a 32 bits integer so unsigned integer it doesn't matter it is signed or unsigned but we have to return once how many one bits are there so this is simple we can just mod by two and add it to our result obviously if it is divisible by 2 0 will add nothing and whenever there is one which is not usable two we will add it to our result and after doing this we will just shift our um Point not pointer uh not pointer we will just uh left shift not left shift we will just right shift by one to our input so in that way we can uh prevent uh that one digit we are going to repeat if we didn't do that so that's it now let's code so there will be our result and while n is not zero you can say it like that in Python and now what you will be doing is just adding result with like this foreign to the n and we can return result this will give us the one bits in it and this was an easy solution and let's submit it now that's it foreign
Number of 1 Bits
number-of-1-bits
Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the [Hamming weight](http://en.wikipedia.org/wiki/Hamming_weight)). **Note:** * Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. * In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 3**, the input represents the signed integer. `-3`. **Example 1:** **Input:** n = 00000000000000000000000000001011 **Output:** 3 **Explanation:** The input binary string **00000000000000000000000000001011** has a total of three '1' bits. **Example 2:** **Input:** n = 00000000000000000000000010000000 **Output:** 1 **Explanation:** The input binary string **00000000000000000000000010000000** has a total of one '1' bit. **Example 3:** **Input:** n = 11111111111111111111111111111101 **Output:** 31 **Explanation:** The input binary string **11111111111111111111111111111101** has a total of thirty one '1' bits. **Constraints:** * The input must be a **binary string** of length `32`. **Follow up:** If this function is called many times, how would you optimize it?
null
Bit Manipulation
Easy
190,231,338,401,461,693,767
91
hello and welcome to another video in this video we're going to be working on decode ways and in the problem you are given a message containing letters from A to Z that can be coded into numbers using the following mapping where you just convert a letter to its um number and so if you have something like a JF you can convert it to 11 106 and then so on and you can't have a mapping like 06 because you can't convert zero into something so if you have just a character six we just have it as six and given a string s containing only digits return the number of ways to decode it the test cases generated so the answer fits into their three bit integer so for 12 for example they can show you that you can either decode it into AB or L and for 226 you can either decode it into VZ VF or BBF and 06 can't because you can't decode the zero so this problem is going to be a standard DP problem and I'll kind of show why to get why you would arrive that solution and I'll talk about some optimizations you can make so let's say we have some kind of encoding like let's just say we have some random numbers like this these are numbers and how would we start this problem so it's pretty straightforward right basically you have two cases and this is what goes to show that this is DP right you have two cases when you're on a digit and you're trying to decode so let's say we're over here and we're trying to decode let's actually draw an arrow we can either decode this into one digit or we can try to get two digits right so in this case we can't because 42 isn't anything but that's essentially what we can do so we can write that down when on a digit and trying to decode we can either use one or two digits and so basically it's going to be like a uh you know like all of these like climbing stairs problems or all these problems where essentially you can either do one thing or the other and the total number of ways for total outputs is going to be the sum of both right so we try it one way recurse get some kind of solution then we try it another way recurse um get some kind of solution right all these like climbing stairs or valid paths or any of these things rely on this spe we have like some choices we can make we try to make all of them we get the count by making all of them and then we basically just return the total so essentially what it would look like is it would be some kind of DP and there are a few cases we need to consider so let's write down those like edge cases so first The Edge case is if the digit we are on is zero then they showed that we can't decode this right so if we're on a zero we can't DEC code it we can't use one digit or two digit cuz like zero anything wouldn't work like 09 or so on so this case we just want to return zero right then another case is we need to consider the actual like any other one-digit number will work so any number one-digit number will work so any number one-digit number will work so any number one through n will be fine because we can just change that always decodes into a letter and the other case is the two-digit number right so two-digit numbers have to be between 10 and 26 so for example if we're considering like decoding this into a one-digit number or a two-digit into a one-digit number or a two-digit into a one-digit number or a two-digit number we can't really decode this into a two-digit number because 42 is not a two-digit number because 42 is not a two-digit number because 42 is not a letter right so here we'd have to say Okay first we have to decode it into the four which whatever the letter is for the four and then we'd have to recurse to the next part right so we'd say like okay we can turn it into a four and then we would just recurse into the next part right so we would just go over here but here you can convert this into either two which is a b or 23 which is like w or something right and either one of those would be fine and these are essentially going to be our recursive cases so let's write down some cases and things like that we need to actually care about so let's move this over here let's talk about like base cases recursive cases and yeah the main reason why it's DP is because at every situation you have two choices either take one digit or two and then recurse appropriately and that's how you know that it's going to be DP problem um because your States rely on each other right you make some decision and then like if I want to know how much I can map this into it's going to be all of the recursions combined so the only way I can recurse is this so whatever I can map this into is going to be whatever I can map this into and so on right so that's why you know it's DP so for DP you need a couple things you need state and we want to minimize this as much as possible to make our time and space as little as possible so for State all we really need to know is just the index we are at right it's just one dimensional DP pretty straightforward base case so basically the base case we're going to have a few right so one of the base cases we are on a zero so if we are on a zero we can't decode so we just return zero and the second base case is if we actually went and if we uh actually decoded the word and I equals length of the word right so essentially we recurse and then we are out of bounds so once we're out of bounds that means we decoded the whole word so how many were asked the total ways so whenever you asked like the total ways to do something your base case should be once it's done to return one right so like return one when it succeeded and return zero when it failed so when we're on a zero we want to turn zero right like let's say this number started with a zero we would want to return zero because there's no way to decode thing or anytime we're on is Z when we recursed okay and now the recursive case so the recursive case is we either take one digit or take two digits if possible and then we recurse appropriately right so like in this beginning section we can't really like we can't take two digits because 42 is invalid but when we do our first recursion now if we take one digit we would recurse over here and 23 is a possibility so we would just recurse over here so our two recursions are just going to be at so recurse 2 I + 1 if one digit or I + 2 recurse 2 I + 1 if one digit or I + 2 recurse 2 I + 1 if one digit or I + 2 that's basically the same thing like I said all these climbing stairs if you can jump one stair or two stairs or any of that kind of stuff and that's basically all we need to do for this problem we just need to add every single point check can we take one digit and can we take two digits we can always take one digit unless we're at a zero and we can always take two digits if the two digits from the index we are at are between 10 and 26 we can just take the string convert into an in and check for that so pretty straight 4 DP and now we can code it up and I'll talk about some optimizations that you should look for so uh standard DP will just have a cache and we're going to have a DP function that will just take an index so if index is let's just say we can say greater than or equal to Links but I don't think we're ever going to be greater but either way like if we're able to go through the whole thing we want to return one if index in Cache let's return the cash value and then the other case so we do have the base case of if the character we're on is a zero so if s index equals z we can't decode this so we'll just return zero so those are our base cases and now let's actually do the recursive case right so we know we can recurse to I + one we know we can recurse to I + one we know we can recurse to I + one because any character one through 9 is going to be fine so we can get that value so we can just say like result equals DP of index + one we can get that equals DP of index + one we can get that equals DP of index + one we can get that value and now we want to actually check can we take the two-digit number so can we take the two-digit number so can we take the two-digit number so we're going to say if um if it and like we don't really need to know what to decode it to right we don't really care as long as it's possible to decode so we're never getting like the character we just need to know like is the value in range so we want to get the two-digit value and we want to get the two-digit value and we want to get the two-digit value and we can easily do that so we can just uh do a slice so we can say like index plus two if this two letter slice is and we want to turn it into an integer so integer if this is between 10 and 26 then this is valid right that's what we need to do so we'll just say if it's between 10 and 26 then we have a valid two digit character so if this is valid then let's recurse as well and let's add this value so res plus equals DP of index 2 and finally let's cach the value so cache index equals result and let's return it and finally we can just return DP of zero and that should give us our answer let take a look like it's accepted there we go and you can run this a few times all these Solutions are pretty close so you know they're all about the same runtime now I will say I'm not going to code it up here but notice how uh this is if you do want to go further into DP if you want to do bottom of DP or space optimize bottom of DP notice how we are only recursing to the index one or two past the one we're at so similarly to like House robber or climbing stairs or something you can code up a bottom up DP where it would be array and then you don't actually need to store the whole array so this is possible just holding two numbers so for example if we have some value at like index plus one right we have that DP value and then we have the value at index plus two then we're at when we're at I we can say like okay well if we're at I and we need to recurse to these two we already have these two so you can just solve this bottom up just by storing like a first and a last value and you can look at like a House robber implementation for space optimized bottom optp and I'll also link in this video um but yeah the reason I don't want to code up a space optimized bottom up DP solution as a default I think it's kind of confusing I think memorization is easiest one and it's kind of like a above and beyond type of thing if you want to do it so I will C the video on how to do it um but yeah and that is like the main thing you want to look for is it is possible to do so if you want to do it you definitely can just because their Curren relation only goes one or two indices if this recurred like you know a thousand indices uh down then you wouldn't be able to do it but because every recursion is only one or two then you can just store that state okay so for the time here it's going to be o of let's just take a look at what we're doing in our DP first of all uh the number of states is going to be o n and then we have to take a look at what we're doing in our DP like are we doing a for Loop or what are we doing so in our DP we're only we basically just have a couple if statements so this is going to be uh one time like this DP is going to be over one time once we have this same cache and the space is going to be oen because we use a cache like I said if you do the space optimized one you can get it down to 01 space if you want to um but yeah that's going to be all for this one it's a pretty standard DP problem definitely one that you should know how to do um and if you are struggling with this then I would definitely recommend doing a bunch more DP problems because like pretty cookie cutter you know nothing too crazy so if you did like this video please like it and please subscribe to your channel and I'll see you in the next one thanks for watching
Decode Ways
decode-ways
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: 'A' -> "1 " 'B' -> "2 " ... 'Z' -> "26 " To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into: * `"AAJF "` with the grouping `(1 1 10 6)` * `"KJF "` with the grouping `(11 10 6)` Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`. Given a string `s` containing only digits, return _the **number** of ways to **decode** it_. The test cases are generated so that the answer fits in a **32-bit** integer. **Example 1:** **Input:** s = "12 " **Output:** 2 **Explanation:** "12 " could be decoded as "AB " (1 2) or "L " (12). **Example 2:** **Input:** s = "226 " **Output:** 3 **Explanation:** "226 " could be decoded as "BZ " (2 26), "VF " (22 6), or "BBF " (2 2 6). **Example 3:** **Input:** s = "06 " **Output:** 0 **Explanation:** "06 " cannot be mapped to "F " because of the leading zero ( "6 " is different from "06 "). **Constraints:** * `1 <= s.length <= 100` * `s` contains only digits and may contain leading zero(s).
null
String,Dynamic Programming
Medium
639,2091
451
my name is himanshu today bihar going tu solve frequency of characters d problem description of character in d string return sorted string if there are multiple answers return anevan dem need tu count frequency of character in d string and give c need tu return education d first example Small Veer Tu So Small Only Maximum 128 Different Characters So I Will Use Counts Frequency of Character Accounts C Will Indicate Frequency of Character Will Be Character Position End C Will Just Increase D Account of Character C Initially Value of County Zero for H Character C End Whenever C encounter C will have frequency of H character in D given string S C want you sort dem in decreasing order frequency but I just short this account C will lose track of actual character They don't know which character has these frequency fields when Character and frequency of par pet and d accounts their respective frequency in the purse list only if d count make it greater zero county zero accounts are s key value of d record par s list but ho do you want tu sort this purse and ho do You want to compare to parse for tha compable interface method called compared to which will tell you to compare to object of D from class to objects first is this second order frequency tha mains the frequency of this is greater than frequency of air is frequency of paris Less give frequency of this date min this will be negative number list and so date and compare tu method and pairs using this comparison nine way can list and builder s list character where you apprentice tree and c want you appointed in Times Sample Input S Submit the Solution Great Solution About Time and Space Complexity Solution They are doing two operations which are constant time operation so d time complex of n in d second time operation but it is constant is high par list the length of pers can be At Most 128 So They Can Say This Is Also Constant Time Operation And Loop And Wildlife Both Children And Times Because So D Complexity Total Time Complexity Of Let's Talk About Space Complexity This Account List 128 So This Is Also Constant Time Complexity Video Thank Everyone
Sort Characters By Frequency
sort-characters-by-frequency
Given a string `s`, sort it in **decreasing order** based on the **frequency** of the characters. The **frequency** of a character is the number of times it appears in the string. Return _the sorted string_. If there are multiple answers, return _any of them_. **Example 1:** **Input:** s = "tree " **Output:** "eert " **Explanation:** 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr " is also a valid answer. **Example 2:** **Input:** s = "cccaaa " **Output:** "aaaccc " **Explanation:** Both 'c' and 'a' appear three times, so both "cccaaa " and "aaaccc " are valid answers. Note that "cacaca " is incorrect, as the same characters must be together. **Example 3:** **Input:** s = "Aabb " **Output:** "bbAa " **Explanation:** "bbaA " is also a valid answer, but "Aabb " is incorrect. Note that 'A' and 'a' are treated as two different characters. **Constraints:** * `1 <= s.length <= 5 * 105` * `s` consists of uppercase and lowercase English letters and digits.
null
Hash Table,String,Sorting,Heap (Priority Queue),Bucket Sort,Counting
Medium
347,387,1741
284
hey folks welcome back to another video today we'll be looking at question 284 making iterators the way we'll be approaching this problem is by using a cube so let's jump right in um let's initialize not initialize just like declare a cue right outside and the reason why we are doing that is because we want to be able to access that um in these methods right here and then you'll initialize the queue right here so q equals new linked list and you would want to add all of the elements to the queue so what you would do is you would say hey while let's just ctrl c iterator dot has next you would just keep adding that to the queue q dot offer um iterator dot next right uh so what's peak you need to return um the element that's uh at the top of the cube so you would return um q dot peak and the next would be just pulling the queue and has next would you just return if the queue is empty or not so this is pretty simple problem if you read through the solution itself like the question um all of these properties that you see come with like an input queue so you could just use that so let's quickly compile this and see if it's okay all right so the first test case is okay everything else is okay as well so let's quickly talk about the space and time complexity the time complexity of um of these solutions um like for these methods right peak a pole and has next is off one since uh it's all done in constant time this however um obviously will take off end time but we're looking at these methods which would take off one this way complexity is off and again since you're using a queue to store all of the elements well that's the solution if you have any questions please let me know in the comments below and please don't forget to subscribe i would really appreciate that see you all in the next video peace
Peeking Iterator
peeking-iterator
Design an iterator that supports the `peek` operation on an existing iterator in addition to the `hasNext` and the `next` operations. Implement the `PeekingIterator` class: * `PeekingIterator(Iterator nums)` Initializes the object with the given integer iterator `iterator`. * `int next()` Returns the next element in the array and moves the pointer to the next element. * `boolean hasNext()` Returns `true` if there are still elements in the array. * `int peek()` Returns the next element in the array **without** moving the pointer. **Note:** Each language may have a different implementation of the constructor and `Iterator`, but they all support the `int next()` and `boolean hasNext()` functions. **Example 1:** **Input** \[ "PeekingIterator ", "next ", "peek ", "next ", "next ", "hasNext "\] \[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\] **Output** \[null, 1, 2, 2, 3, false\] **Explanation** PeekingIterator peekingIterator = new PeekingIterator(\[1, 2, 3\]); // \[**1**,2,3\] peekingIterator.next(); // return 1, the pointer moves to the next element \[1,**2**,3\]. peekingIterator.peek(); // return 2, the pointer does not move \[1,**2**,3\]. peekingIterator.next(); // return 2, the pointer moves to the next element \[1,2,**3**\] peekingIterator.next(); // return 3, the pointer moves to the next element \[1,2,3\] peekingIterator.hasNext(); // return False **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 1000` * All the calls to `next` and `peek` are valid. * At most `1000` calls will be made to `next`, `hasNext`, and `peek`. **Follow up:** How would you extend your design to be generic and work with all types, not just integer?
Think of "looking ahead". You want to cache the next element. Is one variable sufficient? Why or why not? Test your design with call order of peek() before next() vs next() before peek(). For a clean implementation, check out Google's guava library source code.
Array,Design,Iterator
Medium
173,251,281
1,679
Hello Everyone Welcome To Date 16th January 14 Injured S Questions Maximum Number Of Care Of Examples Unit Youtube Channel To Tarzan Into Account The Maximum Number Of Peru Time And Not Utilize 12345 Subscribe Do n't Believe Way Don't Forget To Subscribe To During The Technique Now It's Election 2014 A Solemn Just Take Talk Modification Mind They Are This Question Exam Point to Point Approach for Doing Something Similar to What Do We Call The Subscribe to the Page if you liked The Video then subscribe to the Page if you liked The Video then soon for watching for not giving and ₹5 soon for watching for not giving and ₹5 soon for watching for not giving and ₹5 in internet points point weak election 2014 difficult do subscribe and subscribe the Channel Please subscribe and subscribe the Channel time idioms and long and not aware of intense love you Subscribe to love you to do subscribe channel after elements for watching for k - after elements for watching for k - after elements for watching for k - most element seen it's not element ko subscribe to subscribe our against african sequence updated phase and vote for the new york actress bhagyashree lar zee5 subscribe indian Mother subscribe and subscribe the Channel and subscirbe Tapish aur Loo Lipstick Bansilal Cricket Stadium 291 Andheri West Ki Unidentified Also Will Update Do Answer Account com2018 Adham Aap Simply 500 in Term of Address Has Completed Without Contest to subscribe And subscribe The Amazing Hotspot on Main Anil Tattoo points statement pretty simple regular technique and pink aged account around 16000 ifik inter plus point that sum is ribbon opposite means from your to machandar left and minus otherwise and ff7 we is loot ke chutney 2001 decree star plus that phelps habit means 9 Mirch Abhiul To K Not Writing Contest Auditor Missal Pav One Instance And Minus Plus I 10 Lakh Was Also Trying To Count Taste Rice Of Oo AContest And Sorry Name Sulabh Nahi Silai Sundar Last Hello Hi Dad I Shyamalharsi-2 Dad I Shyamalharsi-2 Dad I Shyamalharsi-2 Ko WhatsApp Jhal Accept Let's Talk About This And Approach Road With Amost Time Complexity And Law And Order For Court Tak Has A How To Unlock Talk About And Dadar Pathak Vaishnav Lakshmi Ashtakam And Sharp And Solitude In A Technique Mind Technique Se Definition Of Web And Posted A Limited The Question This Is The Beginning Within Start Let's Create Another Year Deposit Account Is According To Treat Surajmal Interview Real Power Bank Apna Karya Namaskar A Mistake Of Water Content That In-Between Singapore Of Water Content That In-Between Singapore Of Water Content That In-Between Singapore Month Serial Doob Scheme K Name Tweet A K Get K - Serial K Get K - Serial K Get K - Serial and Sudesh Video Frequency hai hua ki one frequency Unwanted Difficult See Request One Shall Be Country Mingus Remove This Element Measure Remove K - Serial Measure Remove K - Serial Measure Remove K - Serial Ek Anda Om Otherwise Scripters Grade 141 Lakshmi Pendant Haar K - Will Come On 141 Lakshmi Pendant Haar K - Will Come On 141 Lakshmi Pendant Haar K - Will Come On Sequence - 5 The Sequence - 5 The Sequence - 5 The Students Got All So Let's Update Account On This Bell Fruits Vegetables Not Storing It Will Take This Practice That You Have Elements This WhatsApp Condom City - Ear Under Garment Pimples Condom City - Ear Under Garment Pimples Condom City - Ear Under Garment Pimples Otherwise Civil Code Center In Term Of Welcome Not Forget And Difficult Voice Mail Commercial Phone Lakshman Ko Ki Hanuman Ji Ka Dance Class 10th Account Not Very Difficult For A Discussion Between Ruffians Medium Questions On All This Scott Ki Accepted Hotspot Its To Your Eyes Were Not Alone In All This Information Subscribe to Channel Like Comment - Element of Elements of - Element of Elements of - Element of Elements of obscurism during
Max Number of K-Sum Pairs
shortest-subarray-to-be-removed-to-make-array-sorted
You are given an integer array `nums` and an integer `k`. In one operation, you can pick two numbers from the array whose sum equals `k` and remove them from the array. Return _the maximum number of operations you can perform on the array_. **Example 1:** **Input:** nums = \[1,2,3,4\], k = 5 **Output:** 2 **Explanation:** Starting with nums = \[1,2,3,4\]: - Remove numbers 1 and 4, then nums = \[2,3\] - Remove numbers 2 and 3, then nums = \[\] There are no more pairs that sum up to 5, hence a total of 2 operations. **Example 2:** **Input:** nums = \[3,1,3,4,3\], k = 6 **Output:** 1 **Explanation:** Starting with nums = \[3,1,3,4,3\]: - Remove the first two 3's, then nums = \[1,4,3\] There are no more pairs that sum up to 6, hence a total of 1 operation. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 109` * `1 <= k <= 109`
The key is to find the longest non-decreasing subarray starting with the first element or ending with the last element, respectively. After removing some subarray, the result is the concatenation of a sorted prefix and a sorted suffix, where the last element of the prefix is smaller than the first element of the suffix.
Array,Two Pointers,Binary Search,Stack,Monotonic Stack
Medium
null
96
let's solve leak code 96 unique binary search trees so we're given an integer n in this example we're given the integer 3 and we want to know how many unique binary search trees can we make from these integers so this sounds like a pretty simple problem right so let's think about the most simple case what if we were given just one number and let's say it was 1 then we can only make one search a binary search tree with this right just 1 as a root node ok what if we were given two numbers 1 &amp; 2 we were given two numbers 1 &amp; 2 we were given two numbers 1 &amp; 2 there's two trees we could make with this right what if the root node was 1 in that case we have a root 1 and then we can only put the 2 in the right subtree right because that's how a binary search tree works so that this is one solution another one is what if 2 was the root of this tree then we can only put the 1 in the left subtree because that's how a binary search tree works so summarizing what we know if we had the number of nodes so in this table if we had one node then we would only have one tree if we had two nodes we would have two trees now in this example they even tell us if we have three nodes then we can only have five trees but the question is how can you figure this out let's take a look at if we had three nodes so let's say we have three values 1 2 &amp; 3 now if we had 1 as the root node 1 2 &amp; 3 now if we had 1 as the root node 1 2 &amp; 3 now if we had 1 as the root node that means we have to put these two values in the right subtree of 1 now they could be ordered in two different ways obviously we could have two as the root or two as the parent and then 3 as the child or we could have 3 as the parent and then 2 as the left child do you kind of notice how the numbers themselves don't matter whether it's a 2 and a 3 or it's a 1 and a 2 the number of trees we can make from it is the same regardless of what the values are now if we had two as the root then we only have one possible way right we have to put the one in the left subtree and we have to put the three in the right subtree if our three is the root though then we got to put both of these in the left subtree so it's kind of symmetrical to what happened when one was our root remember we had to put these two values in the right subtree but now we're doing the opposite three is the root so we got to put one and two in the left subtree it could either be like this or it could be like this basically this is a recursive problem right assuming we had an arbitrary number of values right 1 2 3 4 5 and some other value we have to consider that each value could be the root at some point right so for example let's say 2 is the root then that means one value is going to go in its left subtree and three values are gonna go in the right subtree so then the result of this becomes so how many trees could we have where 2 is our root and then let's say we have two sub trees well it's gonna be the number of trees we can make from just one value right so number of trees with just 1 as the input so with one value and we already know that right that's the base case with only one node you can only have one tree that's pretty easy what about 3 what if we have 3 nodes in our right subtree well if we compute that before number of trees in the right subtree let's say we already know that because we kind of do right we just computed that here we know it's 5 so then we can take these 2 values and multiply them together because we're getting the total number of combinations right and since we want the number of combinations we have to multiply that's just the rule right and we have to do this for every single root so in the case where 1 is the root if 1 was our root then that means in the left subtree there's nothing here right so the number of trees of 0 now with zero that's also kind of a base case if you have no nodes well you can only have one possible tree right and in the right subtree we have four different values so we want the number of trees we can get with four values and we're going to multiply these together again and we're basically going to take these multiplications that we're doing and we're going to do that for every single value considered as the root node and we're going to sum them up so the thing another thing to notice is that if we want to compute the number of trees of let's say four then to compute that we have to have the number of trees of one number of trees of two number of trees of three nodes as well because we know that the sub trees could be this large as well as 0 of course but that's a base case that we don't really have to compute now since we're doing this is kind of like a dynamic programming problem right you solve the subproblem so for example how many trees could you make with one node and then you solved how many you could make with two nodes three nodes up until we get to n now the time complexity of this is I think Big O of N squared because if we want to compute the number of nodes a number of trees we can make with four nodes for example we got to iterate through the entire list of four numbers considering each number as the root node and if we wanted to do that for three nodes we'd have to do the same thing and so since we are doing it in order right from one to two to three all the way up into n it's going to be oh of N squared now for space complexity it's also we are using some space because we're gonna store the result where we don't want have to recompute how many trees we can make with four nodes for example so we're gonna store that result we're gonna store it for each value from 1 to n so it's going to be big of n space complexity so now let me show you the code and it might be even more easy to understand ok so now let's look at the code let me write a comment to really show you exactly what we're gonna do so for example if we wanted the number of trees for example with four nodes we would get considering each value is the root node so for example the firt if we considered the first value as a root we get a left subtree with zero nodes in it and we get a right subtree of three nodes in it and we want to multiply those together and then with this we want to add another one because we could consider the second value as the root node in that case our left subtree would have one value in it and our right subtree would have two values in it remember we have a total of four nodes so the root is one node the left subtree has one node and the right subtree has two nodes and we can keep doing this considering each of the four values as the root node if the third value is the root node we'd have two values in our left subtree and one value in the right subtree if the last the fourth value was the root node we'd have three values in our left subtree and one value in our right subtree so with this in mind i'm going to go straight into the dynamic programming solution so remember we're going to compute the number of trees from each number from zero all the way to n so i'm going to have an initial array which i'm going to initialize with ones and it's going to be the length of n plus one because we're going from 0 to n and we remember the base case one or zero nodes equals one tree right the empty tree one node is also one tree with just one root node right so we don't have to compute those we can start right at two so for starting at two the number of nodes is in range of two all the way to end okay and now we want to consider each of these nodes as the root node so for example in the first iteration nodes is going to be two we want each we want to consider each of those two values as the root so we're gonna go through in range from one all the way to number of nodes and from this remember we're computing this big sum up over here so I'm going to declare a variable called total to compute that sum which I'm going to initially say is zero the reason we initialize our array to all ones is for this these two base cases pretty much so each iteration of this loop I'm gonna add two total so I'm going to take number of tree so how do we get how many are in the left subtree and how do we get how many are in the right subtree let's compute that so the left subtree is basically going to be root minus one because for example if we were taking the third node as the root then the left subtree would have two nodes three minus one the right subtree is going to be the total number of nodes - what root node we have for example if - what root node we have for example if - what root node we have for example if we had four total nodes and the root node was the second node we'd have four minus two meaning two nodes are in the right subtree so knowing that let's compute the total let's update our total so we're gonna get the number of trees that we can make with the left number of nodes multiplied by the number of trees we can make with the right number of nodes the nodes that are on the right subtree and we're gonna add that to total now at the end we're gonna take this total and put it into our cache which i've called number of trees of these number of nodes so for the first iteration of the loop it's going to be two nodes is going to be mapped to the total so we're going to do that we're going to compute the number of trees we can get all the way from one to n and so at the end remember we just have to return the one result number of trees we can make with n nodes the input was n and we can return we can submit this code and I'm gonna pray that it works hopefully I don't have a bug and it works perfectly because I just did this 18 minutes ago so I really hope this was helpful we went straight to the dynamic programming solution we didn't do any recursion or anything but I think this is a straightforward enough problem that you can understand from the dynamic programming perspective if this was helpful please leave a like and subscribe and thank you for watching
Unique Binary Search Trees
unique-binary-search-trees
Given an integer `n`, return _the number of structurally unique **BST'**s (binary search trees) which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. **Example 1:** **Input:** n = 3 **Output:** 5 **Example 2:** **Input:** n = 1 **Output:** 1 **Constraints:** * `1 <= n <= 19`
null
Math,Dynamic Programming,Tree,Binary Search Tree,Binary Tree
Medium
95
51
Hello friends in this video we will try to solve a problem which is quite a standard problem and once we read the problem statement it is a puzzle problem of placing a cross ends bow and gets stuck given entry and return distance. Solution to the n puzzle you return the answer in any order e solution cont distinct board conf of a placement g and dot both indicate queen and m space so this is our output which will look like this is hums do solution for two a e 4 and If we have to const, then N problem would have arisen, then the computer will start from G, so we try to place the queen here, we have placed it on Y, now if we cannot place the next queen in the same row, then in the next row. While trying to place, in the next row, we place it here, but not the same, it will come in the same column, here the same will come in the diagonal, here we can do yes, then now there will be no queen place in this row, we come to the next row. In this row we will place the queen. Same column here. Same diagonal here. Same column here. We can't do diagonal here either. Now we have to back track. Now we have to place this queen here instead of here. Done here. Now according to this, you cannot place a queen here, you can place a queen here, now look in this row, you cannot place a queen here, you cannot place it here and you cannot place it here. Can because the same column has come, now let's back track it and go here. Now if we go to this here, now these coins are fighting among themselves, so we can't place this here. We can place this here. No, we can't place this here either. Now when we backtracked this, it was also at its last position, so now we have to change the first one, so if we placed the first one here, then we can place the second one here, no, we can't do it here, we ca n't do it, we can't do it. You can do it here, yes, now you have placed it in Y, then the next row came to P and what place on Y, you ca n't do it, you can do it, yes you can do it, now there can't be any other queen in this row. Come to this row, take it to the last row. No, we can't do it here, we can do it, yes, we have found a solution, so now from this solution we clearly know that we have to check all the possible positions, then this is a We cannot do recursive problem. No, we can do it here. Yes, we have found a solution. So now from this solution we clearly know that we have to check all possible positions. So this is a recursive problem and we can also back track. We were changing our answers so that we can reach the correct answer so this is also a back packing problem so now what we have is a recursive problem and back tucking problem okay so five to solve the recursive problem Point is step, first step is called fine recursion function, two things are important in this, what and how, second is number of argument and return, third is base case, fourth is recursion call and final calculation, find answer. Now define the function, what is function and what does it do? It is very important for us to define these two things, how the function works, so many times it is not clear what the function does and how it works, then we make a decision tree, but we have to clearly know what work. What work has to be done and how to work? We have approached the problem above, so from that we are getting a clear idea of what work has to be done and how to work, so let us see what work has to be done, the answer given to us is given below. Have to write a recursive function which will go to each row, go to each column and then check on each column whether the queen can be placed there or not. If the queen can be placed then it will update the board and go to the next row. For this, we will move to the next row and if we cannot place the coin then we will go to the next column. Okay, so this is our flow chart. Now we need to know what will be the number of parameters. One, we will iterate on each row. We will do a row index and row index of whose board, we also need a board. Please note that in this question, board is not given, so we will have to create the board in the main function. Okay, and then we will have to pass that board here. Now what is the return type? So if you see, this function will call itself and we just need to update the board, the return type will be void. Okay, now the problem with this is that some children may think, some beginners may think. Why doesn't it return a vector of a vector string ? That's what we want in the main function to ? That's what we want in the main function to ? That's what we want in the main function to return all possible confines. So this is a recursive function. When it calls its smaller sub function, then if its return is a vector. If it is a string, then its sub function will return vector string. And its bigger function will return vector string to its parent. But do we need vector string when we are calling the function? No, we just need The board is to keep updating it in every request. We do not need to create a new vector string every time and it is not returning, rather we just have to update the old vector string. So I hope that this thing will help you. You must have understood. One pro tip I would like to give is that the return type of non- primitive mostly recursive function is not. Okay, if we move ahead, we have written the code because we have made it very clear that if we go ahead enough, then our T type should be. Gone void or solved, we got a row index and board which we have to update and then update it and store the answer, so we have to pass the answer as well. Now we see that it is telling us for each row, we said no. One then e row m uch column a e 0 to j lesson a j plus here Now after that what we have to do is to check so let's put check function on y check function i will take j will take and board will take and this What will it do? It will check and tell whether we can place the queen there or not. If this function returns true then the simple thing to do is to update the board of IJ and not call for the next row. Now its After this, we have to write a backtracking step. In case of backtracking, this is a backtracking step, so we should not be so afraid of backtracking. Some people write a backtracking step below it and if backtracking becomes a problem, then I know. I find this name very strange, back packing, because it sounds very self-evident it sounds very self-evident it sounds very self-evident that I don't know what will happen, but it is not that much, so now we have done it and if the check falls, then what will happen, then it is okay. It will move to the next column, so we have done back tracking, now we have to update the next column and board, we have moved to the next row cell, so it is done. Now if we see, here our step is done, what we have defined, how we have done it. After making flow chart, number of armament return time is done, now our recurse call and backing step is done, calculation to find answer is done but no calculation is needed, we just have to update the board, this is also done, just have to write a base case. The base case has to be written that when we are moving the rows one after the other, it is okay that there is a time when the row will be equal to A, assuming that we have finished the last row also, it is okay when we have finished the last one, then we have the answer. If we get answer dot push back then what we will do simple inside this is we will push the board and then we return it is ok and here also we return it is ok and the important thing is that here at the end we will return the same board. If we want to update and if we want to update the last board in answers, then we will put an end point in both of them and now we will have to pay a little attention to the check function that how will we check or what is the matter, we will put the queen here. Keeping it in the middle, it will take up this entire row, it will cover this column too, it will fill this diagonal too and it will fill this too, so what are the steps, same row should not have two queens, same column should not have two queens. There should not be two sides of the same diagonal. Primary diagonal and this is called primary diagonal and this is called non-primary. There should not be two sides of the same non-primary called non-primary. There should not be two sides of the same non-primary called non-primary. There should not be two sides of the same non-primary diagonal. Now by improving it a little, let me show you one thing and I want to tell you that in this One more thing, if we want to place the queen here, then we simply need to look at the one above it. If we place the queen here, then we will see that there is no queen here. There is no queen and here we do not need to check in the lower part that there is no queen because we are doing row wise, otherwise the cones of the upper row will always be filled before the lower row. The cones will be filled daily, below we do not need to check, so now we write the check function, then the return type of the check function is NULL CHECK, what are we getting IJ&amp; NULL CHECK, what are we getting IJ&amp; NULL CHECK, what are we getting IJ&amp; B is ok and what we have to do is that first of all Check if board of Off Iwa Return Falls Now once we look at the primary diagonal equal zero primary diagonal less than min of i h Look basically what I want is that if I have a queen present here then what do we have to do to go to this index. What to do to go to this index -2 What to do to go to this index -2 What to do to go to this index -2 -2 So we have to go to the primary diagonal so -2 So we have to go to the primary diagonal so -2 So we have to go to the primary diagonal so what we did is that board of i minus primary diagonal and j minus primary diagonal if this is equal to why then return false right And similarly, now we have to see non pra, if we are here then we have to go here. Okay, so let's write diagonal in the same way, it will be one diagonal. Now the condition is a little important. Look carefully, what condition will I write here, diagonal plus. What we have to do is basically we have to move like this then what will happen here if the point here is a then the point here will be i -1 and i -1 and i -1 and j + 1 j + 1 j + 1 what will happen here is i might j p then here we write Let's take the board of I minus D JPS D E K E and write it down. Now you see that what should be I minus D? Multiple conditions can also be written And J Ps B Must B Lesson A Simple Key I Minus Should Be Positive J Plane Now I Know It You Can Also Write Optimize Fm But Not My Only Goal Is To Help You Logic Building Problem Solving P Optimization You Do It By Yourself Stay tuned, you will get many codes on lead code and there are more videos which teach optimization. My only purpose is to help you in problem solving, so I want to teach you the problem solving method which directly comes to your brain. So if you want to check everything then If we still don't get anything then we will return to brother and with this our code ends. Happy coding friends, the problem was long, I know but the problem was not tough, so see you in the next coding challenge. Till then, Tech. care bye
N-Queens
n-queens
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 _all distinct solutions to the **n-queens puzzle**_. You may return the answer in **any order**. Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively. **Example 1:** **Input:** n = 4 **Output:** \[\[ ".Q.. ", "...Q ", "Q... ", "..Q. "\],\[ "..Q. ", "Q... ", "...Q ", ".Q.. "\]\] **Explanation:** There exist two distinct solutions to the 4-queens puzzle as shown above **Example 2:** **Input:** n = 1 **Output:** \[\[ "Q "\]\] **Constraints:** * `1 <= n <= 9`
null
Array,Backtracking
Hard
52,1043
208
lead code problem 208 Implement try a prefix tree so this problem wants us to implement a prefix tree which is a data structure used to store strings right and the reason why we have to use a try instead of a traditional data structure is because we have to account for autocomplete and spell checker right so there is this function called starts with where we have to uh return true if there is a string that starts with the prefix right the string that we previously inserted okay so the way I did this was to use uh obviously use the tri but let's go show how I actually do it so in this case when we insert Apple uh let me just go through so here I have the TR note so each note have 26 child so 26 is the number of alphabets and then I have a Boolean here that will tell me whether or not this specific note is De okay I'll explain why we need it later but just know that this try note we just initialize all the child as now the end as false when it is constructed okay so when I have my notes starting out like this and we iterate through all the characters like if you see here I am iterating through all the characters okay so initially I will construct a new TR Noe in the on the root right and then the current will be the root which is currently just a placeholder it doesn't have any notes yet and then I iterate through every character in the word and I will find the index right so what I'm planning to do is create a node called a right and this a node will be another TR Noe where it can has like multiple characters underneath it as well right for this instance for this child a if it is null I'll create a new node which in this case it is now so note and then I my current will be at a now okay and then for the next note P I'll create another P right the P go into P until we reach the nend okay when we reach the end the for Loop will finish for finishes iterating and you mark this specific Noe as the end as true this means that this note signals the end of a uh the end of a word right because the end of word is e in this case so we have e here okay when we search over here when we search what I'm doing is I iterating through all the characters in the word and then I'm finding whether or not that node exists right for this instance since we're searching for Apple so you search for a in this case exists search for p right because you I'll iterate true and then I'll recurse into it so P not necessary recurse but I will iterate through the uh try so p l and then when we reach e the F Lo ends and then I will return whether or not this is a end of a word which in this case it is so this will be true but let's say if it searches for something like app right A P okay so the same thing you go to a go to P go to p and on P since this p is not marked as the end of the word you return false because there's no such word as app since we have only inserted apple right okay let's move on let's try start with right so start with uses the same uh iterating algorithm as search but the difference is I return true instead of checking whether or not this is a valid note so start with ap so I go a p okay since nothing went wrong during the for Loop did not return false because there's no n noes so you just hey sorry that uh nothing went wrong in the for Loop no n uh no n note was found did not return false so I just return true this means that there is a word in our dictionary that starts with ap which in this case is Apple okay then when we insert another app AP so what I do is insert so I check if it's null then I create Noe but in this case since it's not now so I just reuse the same Noe over here and when we reach here I'll mark this as n of a note so when we search again this will be return true okay so let's say if we insert another word let's say we call uh Aspire for example right it's bit a long word but what you do is you create a since there's no s so you create another s and then in this s you go again right p i r e okay so the try look like this will be marked as a end node and if we add like uh ask right so you go to a s then here you create a k Mark this n so you can see how our try is like a map that finds the word for example so there just some examples hopefully that's sufficient that's all I have to say thanks
Implement Trie (Prefix Tree)
implement-trie-prefix-tree
A [**trie**](https://en.wikipedia.org/wiki/Trie) (pronounced as "try ") or **prefix tree** is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker. Implement the Trie class: * `Trie()` Initializes the trie object. * `void insert(String word)` Inserts the string `word` into the trie. * `boolean search(String word)` Returns `true` if the string `word` is in the trie (i.e., was inserted before), and `false` otherwise. * `boolean startsWith(String prefix)` Returns `true` if there is a previously inserted string `word` that has the prefix `prefix`, and `false` otherwise. **Example 1:** **Input** \[ "Trie ", "insert ", "search ", "search ", "startsWith ", "insert ", "search "\] \[\[\], \[ "apple "\], \[ "apple "\], \[ "app "\], \[ "app "\], \[ "app "\], \[ "app "\]\] **Output** \[null, null, true, false, true, null, true\] **Explanation** Trie trie = new Trie(); trie.insert( "apple "); trie.search( "apple "); // return True trie.search( "app "); // return False trie.startsWith( "app "); // return True trie.insert( "app "); trie.search( "app "); // return True **Constraints:** * `1 <= word.length, prefix.length <= 2000` * `word` and `prefix` consist only of lowercase English letters. * At most `3 * 104` calls **in total** will be made to `insert`, `search`, and `startsWith`.
null
Hash Table,String,Design,Trie
Medium
211,642,648,676,1433,1949
269
hey guys how's everything going this is Jay sir who is not good at algorithms I'm making these videos to prepare my job interviewing June which is actually one month later from Facebook so yeah let's start today is about 2 6 9 alien dictionary there's a new alien language which uses the Latin alphabet however the order among the letters are known to you to me yeah we receive a list of non empty words from the dictionary where words are sorted lexicographically by the rules of this new language mm-hmm the rules of this new language mm-hmm the rules of this new language mm-hmm derived the order of the letters in his language so yeah so like wrt wrf because it's older this way so T must be before F similarly W is before e re before t e before are so we get wer TF this is order Z X so the Z X is n XX this it's invalid right so return empty we may assume all letters are lowercase if the order is invalid return empty string like this there may be multiple valid letters return any of the form them is fine okay so let's first analyze what we can get from this input right the order between these two adjacent nodes means literally we could gather how to say a relationship relation between two letters from each comparison we can get T before F and W up before E so let's write that down so the first compare double e TF something like this right and W E Artie and II are so actually we're gonna - we're gonna generate a we're gonna - we're gonna generate a we're gonna - we're gonna generate a strain from this relationship of course there might be some other alphabets what would they don't matter it doesn't matter because there's no restraint on them we can put in anywhere so how we could collect the result let's suppose that let's suppose let's analyze what the what are the alphabets which could be put before them well let's say there's T before F so f could not be put in front W e ikan ah be pretty front double RT t could not be pretty front er R cannot be front so actually there's only W could be put front right so if you want to pick the letters in the front head in the front which means there be there must be no this kind of pairs which W which points W right is this right yeah so we could actually we loop through the loop through all the characters and check if there is a there is some path like this pair leave with this character a BN which means the path points to this letter if no we could put it we couldn't collect it as a into our final array right but after we collect a result collected a collect to this letter we need to remove the path from this letter right yeah and after that who could do it over and over again and collect the result what if there is a circle like this well if there is a circle there means we could not which means happy when we match these Toula to who meets the case like this there will be no I'll say we Robin no how can I shoot put it there will be no elements which has no path pointing at him right for Zed there was a path from X for X and there's a path pointing to X so that would be that will be invalid case so we are trying to collect the result if you find this case there would be nothing there but there you still there when there still when there is still the pair's Oh No when there is still the let the characters but we couldn't find any available alphabets then it fails all right so we can return the empty well the things become clear so how could we determine if there is a if okay the idea is kind of not sure to us let's write it down we first moved through all the letters check if any leading to them to it how could do this first of how we could collect all the letters well we loop first we loop through all the words collect alphabets now loop through all the letters check if it into it how can we do this we could loop to all the paths right I know we're sorry we fur collect the alphabets and also we need to collect all the paths leading to it so how can we do this we could loop through the pass and to see if there is it so that would cause us a lot of time because for each letters we need to traverse all the paths it's a waste of time these finite paths so we could actually store the passes Maps right and a reamer smap's also who could a store a map of t2f and also issues store if a map of F 2 T so we could check by check reverse map all right if yeah check them any math leading to it if no path leading no paths collected as a result if no character collected and that there is still letters in that it right so we collect the results we need to remove the pass right we move the past so we have to reflect it we need to remove the result renew the pass from map and the reverse map right so now we can start working on it first we create a map ask caught it called forward map and reverse map backward map ok backward map now we need to loop through all words we need to compare the previous one so let's say let's are we start with use for index loops we first we will traverse through the words by collecting the okay for collecting the alphabets of course we need to say off bits we need a set to do that well alphabets we just add words I J right okay now if there is previous one previous word get a map look at the path how we should do it what means I'm gonna traverse through this if there is previous one okay we'll good dear I'm there if there is a for this previous one and different than it I should stop so hmm I'll create a new I'll use a new form app for this to make things clearer if I speaker than zero then there means there's a previous word right compared with previous word to get the path which equals zero just more than word I minus one button and just more than words i dot then J plus right we can pair it so if words I minus 1 is not equal to where's I J if they are different we're sure we can break right and there is a path called with the letters from previous one to the second one which means I added to for a map set our words I minus 1 J 2 oh there might be one letter to several different letters so it will be the map would be from set to just like this right yeah if I'll cause a caster variables caster from equals words I minus one J I'll do it like this i J&amp;A for from it's not to if from is J&amp;A for from it's not to if from is J&amp;A for from it's not to if from is different from to then we were added to the path right so if it is not in it should I still yet we said from as new set and now we could get from add to and we break right at the same time we need to add it to the backward the map right we do the same if backward map pass to back Rama set to new set get to front okay so after these four if we ever check okay so with the previous one we get to the path break and if we if the J if one of the two words is traversed Traverse there might be some letters still left writing in one of the letters might be there's a case that if the previous one has longer digits letters and then a lateral then it is invalid right it should not happen if they are all matched so we say if for break and if you break it's okay but if we get it to if how can I do this mmm the only case that it is invalid is that J whoa be the latter one is Travis and the previous to their right so invalid case if J equals words I touch them which means that the latter one is already all looped and J is not equal to words previous was next we should break brig and return force there's four so we could return MC okay so now when this is done we won't get now alphabets for where map backward map all generated now let's to the second one loop through all letters check if any path lead into it by checking a reverse map and now we click the result right so we create a result array we traverse through all the alphabet I'll just use T for short from alphabets well I use a character okay it off not from if there is no path pointed to it collect cool so if backward map past character if recent nothing there I can say result push character right and we need to remove it from alphabet for set is deletes we'll do this round by round so actually Whitney needs to be for this we need to use a while loop right so when there is still alphabets in this set then we loop through the alphabets as we mentioned if no letters collected and a su alphabets there we should return it is invalid the case right so out Li set a flag fat is headphone we set it to false you found this we updated it and when all the letters are Travis and still there is nothing found if nothing found because you need wearing this while loop alphabet is not empty while this for this wire loop we delete it so if not found and there is steals letters we return empty right this is invalid case it means there's a loop in it now after we collect it we need to update the map update both maps it is here reflected and we need to remove the pass yeah it's we need to update both pass we do it here Wow the removal part process is simple we move it from we check the forward map and first we delete the elements in a format for a map and it is a backward map from them and then did a forward map right it's like we want to delete T we first to find the to the from the F and then deletes the flee to the F from the reverse map first right yeah cool so because there is not okay f my if not we okay we first go to the forward map but it might be empty right so if forward map has this character if it has it so said a to z-- equals forward map it so said a to z-- equals forward map it so said a to z-- equals forward map and get and character T need the delete character from a reverse map of each to write from okay we will for let to Arthus if there is a for if there is a to in a forward there must be of a path in the reverse in a backward right so we will get from x' equals backward map and get to and we x' equals backward map and get to and we x' equals backward map and get to and we will remove it did it character right and if it is empty remove it backward map did it - right and now if backward map did it - right and now if backward map did it - right and now if the from app is empty for this chapter we still we could remove it so if mm is empty we forward map did it to the character okay so now we updated the two maps yeah I know student is invalid okay so actually we have done we're finished we return the result and result joined by empty let's try to review our code one last time for case like this we first travels through all the world and first we collect all the alphabets is your set so it's okay this for loop is right this is right and if it's a second word there will be previous words so we can do the comparison so we start with the index for both letters and at each when eat when any of them is Travis and then we get to the front and get the two if they are different we update to the backward map and for a map forward and to cool and we break yeah and there's in that case if J is Travis down and do not previous one is not previous word has long is longer than this one then it's invalid a cool now we collect a result when still there is alphabets there we check if there is nothing pointing to this character so backward map if is empty we were collected after we collected we did it from the efforts and we set his head phone here's true when there is nothing found during one pack in one of the check and there's two alphabets it means it's an invalid okay when we are collecting this character we push to the result we did it from the alphabets and then we need to update the two maps so a forward has this character we get the tooth of this former map because we if we have right if their pasts from this point we get the twos and for each two we need to delete from sket we deletes from a character if there is no nothing from France we delete the two yeah and if there is nothing in the tools we deleted from the format I think so should work right so theoretically the algorithm works let's try round the code of course J is not defined where is it's 51 J oh this is your mistakes I made a common mistake I need to define here cool let's try to submit yeah we are accepted a faster than 70 77% let's try analyze the faster than 70 77% let's try analyze the faster than 70 77% let's try analyze the time and space complexity time first we for all the words I mean I say this actually takes n endings it means the total length of all the characters right okay this takes us in for each this extra forward we compare all the words actually each alphabet actually will be checked once for the previous one once for the other one only right so actually it's another linear time cool a map it's constant and then we will check alphabets is still linear time for each we will get one character from alphabets if the previous one has it and direct access we move to rack directly rekt direct Wow isn't it this stuff no wait a minute so for each word for each chapter so isn't it neat in your time and is the total characters let's check again this is an inner time oh no this is an inner time but this is not refer each word this is for each word we compare them with previous word right so if there is like let's suppose if eminence by N word this will be M this is n our M and N word M then so this is n this is M and this would be M again so this is direct access so it's M and N and for this would be alphabets M N and this is direct access update for net 2 for the worst case 2 OB m MN o there is a there is something like this worst case is that he will be a man and right there will be a path for each of the pair for this case there will be worst Oh M n minus 1 and this will be M and so actually this cost much more time if we say there is a total en letters it would be actually N squared right because n minus 1 plus n minus 2 plus 2 1 so it's n squared space we keep a forward map and backward map it's all linear to the count of the counts of the total meant right alphabets to the lengths but in this format there will be maximum n minus 1 nodes in a set so actually it's still I think it's n to the square so ok that's all for our or this solution actually could we improve mmm actually yes dears this is now came by me I saw some materials a first actual first solution actually I did make it but first second improvement I didn't cut came up didn't come up with it so we are using a backward map to keep drop the previous one right actually we're doing the here if backward map has this character actually we could only you see we are sinking the 4 map with the backward map right actually we only we could only keep track of the length of the count of the paths which leads to each node so the operations like this said and get it could be compressed into minus 1 and plus 1 and minus 1 right so the former map is inevitable but backward map who created user use is a use count method cool I try to rewrite it another without only you avoid keep being track off path hits so for backward map we will use what we will use count inbound map count I'll use this one so it's a character to count of paths leading to it this is a number it's count okay so when we are generating the background map will use this inbound count map it's not said anymore it should be zero so we should and get set it to a scanner to this no set it to we plus one right so get to here's a problem like what if the two is from and two is the same so this is not right we're getting a from it's not front we set a new set and we add to it's not okay I think you should say if we get from has two if there's no - yet we get from has two if there's no - yet we get from has two if there's no - yet we add to it and we update the add to it we add to it and we update the inbound count right to avoid the duplicates so now we add it only if the two is not added after we add it we opted inbound count plus one cool now this is the same so here it becomes for each character we checked inbound count if it is zero or if it is hot see if it is zero or not so we will be if there is no inbound count of course it's okay or it has it but it's zero for the zero case we actually would remove it from when we are processing it so we could avoid this I think so inbound count is there's no path leading to this character we push it we did it and head is true now if it has for a map we will okay we choose for each of the tools when where did we remove it from the deduced afford map uh-huh mmm there's a deduced afford map uh-huh mmm there's a deduced afford map uh-huh mmm there's a problem here wait a minute for each character if there is for the previous solution if and then for each did this to the ninth oh there is a problem of previous solution where did we remove the from map are we didn't but we move we remove it from the alphabet so actually it was not Traverse anymore ok I think we should do that ok anyway if forward has this character we get all the tools and for each two instead of deletes they're from we-we-we subtract one from each of we-we-we subtract one from each of we-we-we subtract one from each of the inbounder right so it's inbound map in Bama you get to set to inbound get to minus one okay now if inbound can get to is zero we delete this - mm-hmm get to is zero we delete this - mm-hmm get to is zero we delete this - mm-hmm cool ah I didn't miss I did a mistake it's actually we should I made a mistake there is nothing I'd like this does not work it should be just delete it sorry okay so we did it from for map did it the character doesn't matter but didn't it would be better okay said from oh I think this should work hope there will be no mistakes cool that's a myth yay we yeah we improve it with another is so there's a slight improvement but the general idea you're saying so the time and space complexity for here tying the core would be here right so character will be the length of our total alphabets and still there will be twos right so it's its worst case it's the same for worst case to space well for a map it's near time but yes still developing night like four paths for all of this all of the rest characters so it still like this but it's generally better than the previous one we've reduced a worst square quadratic cut a space into this linear space so this is obviously is better and also the time here you see for the oh I still made I made a mistake here so this is the total length of the alphabets and for each we use tools for each tool we updated the character ah no problem I thought oh I just thought maybe it's a cubic but we there's no loop from this from so it's the right access it's a it's okay and it doesn't change time complexity anyway that's all for this problem hope it helps it's a little complicated but the idea is very pretty straightforward the only error prom ever from a place every prom point is that we need to handle to in battle case like here and here right okay that's all hope you enjoy hope you enjoyed it and see you next time please don't forget to follow subscribe my channel there will be more and more videos about algorithms and a front-end development yeah see you and a front-end development yeah see you and a front-end development yeah see you next time bye
Alien Dictionary
alien-dictionary
There is a new alien language that uses the English alphabet. However, the order among the letters is unknown to you. You are given a list of strings `words` from the alien language's dictionary, where the strings in `words` are **sorted lexicographically** by the rules of this new language. Return _a string of the unique letters in the new alien language sorted in **lexicographically increasing order** by the new language's rules._ If there is no solution, return `" "`_._ If there are multiple solutions, return _**any of them**_. **Example 1:** **Input:** words = \[ "wrt ", "wrf ", "er ", "ett ", "rftt "\] **Output:** "wertf " **Example 2:** **Input:** words = \[ "z ", "x "\] **Output:** "zx " **Example 3:** **Input:** words = \[ "z ", "x ", "z "\] **Output:** " " **Explanation:** The order is invalid, so return ` " "`. **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 100` * `words[i]` consists of only lowercase English letters.
null
Array,String,Depth-First Search,Breadth-First Search,Graph,Topological Sort
Hard
210
16
hello everyone and welcome back to another video so today we're going to be solving the leakout question threesome closest all right so this question is very similar to the threesome question itself so i did make a video about it some time ago so do check it out if you don't know how to solve the threesome question but also go over it really quickly over here okay so over here we're going to be given an array of nums with n integers and an integer called target our goal is to find three integers and nums such that the sum is closest to target return the sum of the three integers and you may assume that each input would have exactly one solution okay so the way we actually solve this is we first sort our numbers and the reason for that is because let's say we are just looking for two numbers right and let's say the sum of these two numbers what we're gonna do is we're gonna have one be the smallest number in other words the leftmost number since it is going to be sorted in ascending order and one the rightmost number or the largest number uh again because it's ascending order okay so what we're going to do is we find the sum and if the sum is greater than our target that means that we want smaller numbers so what we do is we move the right pointer to the left by one because when we move to the left we get smaller numbers and the same way of this sum is too small we move the left pointer to the right by one since we want larger numbers but that's for two values but over here we're looking for three numbers so how do we do that so to do that it's pretty simple what we do is we fix one number and assume that one number is going to be the first number right so let's say over here we have this we would sort it and then we would just say whatever is at the zeroth index is going to be one of the numbers for sure then what we have a new target and this new target so originally the target is one and let's say the first number is negative one so then our target is now going to be one minus one and that's going to be two right so what that basically is doing is that it ensures that the current the first number which is negative 1 in this case has been accounted for now again just remember that this is going to be sorted beforehand okay next once we get the first number we look for the two numbers that are equal to the new target so in this case that third space is going to be this over here and we're going to do the same way by using a left and a right pointer and again if you want more information about this do check out the threesome video but in this case there's a small twist to the question which is we might we're not going to have something which is equal to the target so the way we do this is we want some sort of value which is closest to the target okay and the way we actually get this is we're going to keep track of a variable called closest distance to target and this is going to uh keep track of whatever is the distance from the actual target and so let's say we have a distance of zero then in that case that means we've reached the target itself okay and a quick example so let's say the target is one in this case and let's say we get a sum of two and a sum of four so two would have a distance of one away and uh the value four would have a distance of two away so using that knowledge we're going to find the actual value okay so let's see how this looks like in code and i think it's a lot easier to understand that way all right so again the first thing is to sort our nums okay so our numbers okay and now we're going to have another variable called distance and this is going to be the distance from our target and to start off we're going to just have a really large value so we're just going to have positive infinity in the beginning so now we're going to iterate in a go in a for loop so for index in range length of nums minus two so first of all this for loop over here is going to be the first number right so in the beginning the first number is negative one then two and so on right and in this case we're only going to go up to last but two value and the reason for that so in this case is the value two right over here and then we would have the left pointer here and the right pointer here right now let's say we go and this is our first number we won't have any space for the left and the right pointer so we're only going to go up to the last but two value okay so we have this and now we're looking for the next two values okay now so the way we do that is we have a left and a right pointer and the left pointer is going to start off at index plus one right and the right pointer is just always going to start off at the last or the last index length of nums minus one so now we need to define our new target now this new target takes into account the first number which we fixed and this target is just going to be target minus the first number that we have which is nothing else but nums index okay now we need to go in a while loop and we keep going as long as l is less than r and what we're going to do is we first need to find the sum of these two values okay so we'll just call it sum val and it's going to be the sum of whatever is at the left pointer plus the sum of whatever is at the right pointer so now that we have the sum what we need to do is we need to check if the sum is equal to our target okay so if this over here if some underscore value is equal to our new target right then in that case we're done and in that case we can just directly return our target since the sum is equal to the target itself okay so that's the first condition but now what if it's smaller than it okay so let's do that so if some underscore value is smaller than our new target then in that case that means the value is too small so we're looking for larger numbers and in that case we're going to increase the left pointer to the right or move it to the right by 1. but if this is not the case then that means some vowel is greater than the new target and in that case we want smaller values and we do that by decreasing the right pointer to the left by one okay so this over here moves the left and the right pointer but now what we need to do is we need to update our distance over here and the way we do that is we check for the distance so we have if and the condition here is we're checking if the absolute value of whatever distance we have is greater than the absolute value of the new distance and the new distance is nothing else but the new target minus the current sum value that we have okay so this is over here the new distance so each time we just want the smallest distance now why are we taking the absolute value and the reason for that is because we don't care about direction so if you think of a number line right and let's say the target is the number one so zero is to the left of one while the number two is to the right of one right we don't care about the direction but zero is actually closer so again that means that we do not worry about the direction in this case so that's where we're taking the absolute value itself okay so now if this condition over here is true then that means that we need to update our distance and we're going to update it with the new distance over here which is nothing else but this so the new target minus the sum value okay so this is that and finally outside of this for loop so if we do get the same target we return the target itself and real quickly why we're returning target and not new target is because if the second and third number are equal to new target that automatically means that the three numbers together is equal to the target itself okay so that's where we return the target now if we do not end up returning the target that means we've got close to it but we didn't reach the target itself so how do we get this value now so one thing we could do is we could keep track of that as well and keep updating it or in where since we only know how far away it is by distance we can just use that distance to get the value and in that case it's just going to be the target minus whatever distance we have so this over here is our final answer so let's submit this and as you can see our submission was accepted so hopefully this video did help you out and again do check out the first video of just threesome if this was a little bit more confusing for you okay so thanks a lot for watching guys
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
787
hello everyone this is sham Saar and I welcome you again in the new video of our YouTube channel so this is the lead code medium problem which was asked on 23rd of February so this is cheapest flights within K stops here there are n cities connected by some number of flights and we have given an array flights where flights of I equals to from to price indicates that there is a flight from City from I to City to I with cost of price ey and they have given Al uh three integers Source destination and K we need to return the cheapest price from source to destination with at most K stops and if there is no such route then return minus one so in this example one there are n = to this example one there are n = to this example one there are n = to 4 what is n is the four cities so there are n four cities and flights are sheduled according to this so zero and one means from this to this and price of that so 0 to 1 uh it will cost 100 uh from 1 to two it will cost 100 2 to0 it will cost 100 this is the image we are seeing visual representation of the array then 1 to 3 = to 600 cost then the array then 1 to 3 = to 600 cost then the array then 1 to 3 = to 600 cost then 2 to3 it cost 200 and uh we need to calculate the cheapest price from 0 to 3 Source 0 to Destination 3 with maximum of K = to one Destination 3 with maximum of K = to one Destination 3 with maximum of K = to one stops so our output will be 700 how let's see so the graph is shown the optimal path with at most One Stop from City 0 to three is marked in red and has cost of this so this red marked way is a optimal path so 100 + 600 = 700 way is a optimal path so 100 + 600 = 700 way is a optimal path so 100 + 600 = 700 and note that the path through cities is cheaper but is invalid because it uses two stops so 0 1 2 3 it is cheapest but um we need to calculate we need to think at most One Stop so it will here they have used two stops that's why it is invalid solution in the example second there are nend cities and flights are scheduled accordingly to the array then source is zero and destination is two and K = to zero and destination is two and K = to zero and destination is two and K = to one stops so the optimal answer chipest price will be 200 from 0 1 to 2 in the example three source is z destination is 2 and K = to 0 so 0 set 2 destination is 2 and K = to 0 so 0 set 2 destination is 2 and K = to 0 so 0 set 2 there it will be only 500 the optimal path with no stops from City 0 to two is marked in that's why so how to approach this type of problem let's see so we need to construct an adjacency list to represent the graph using an unordered map where each vertex is mapped to a list of its neighboring vertexes along with the corresponding flight prices so we will calculate an adjacent list to represent the graph uh using an order map then after that we will initialize a vector uh disc of size n to store minimum distances from The Source vertex to all other vertexes and initialize all the distances to Infinity except for the source vertex which is set to zero now we will create a queue to perform dep first search traversal of the graph after that we will NQ The Source vertex along with its distance initialized to0 into the CU after that we will initialize a variable stops to track the number of stops made during the traversal then perform breath first search traversal until the Q becomes empty or the number of stops exceed K inside the traversal Loop process each vertex and its distance from the source for each vertex iate through its neighbors and update their distances if a shorter path is found and enq the updated neighbor vertices into the queue for further explor exploration then increment the stops counter after processing each level in the bre first traversing and after the Ral return the minimum distance of the destination vertex from the distance vector and if the distance is still Infinity we return minus one and indicating that there is no valid path from The Source dep destination within case stops so this is the overall approach uh let's see what will be the code for better understanding of the approach read the approach once again and after that follow the code and check uh one check what how the code is uh is getting from this approach so before that if you are new to the channel hit the like button and subscribe for more content so let's declare an unordered M first in Comm Vector of P of int comma in adjacent this is a vector this is unordered map so key is in and value is a vector after that uh we will populate this using for Lo for Auto IGN FL in flights we will do what we will do adjacent of flly of zero and we will push back flight of one Comm flight of two means we are pushing back uh in the adjacent uned map uh as because of this it is a vector we will insert in the form of vector here after populating this map we will create a vector in this of size and value in Max and the distance of SRC equals to zero so after that we will Implement a q of pair then we will push uh SRC Comm 0 and the Q in the form of pair here then we will initialize stops variable to Z after that we will Implement a while Lo so while q. mty and stops less than equal to K uh we will do what we will create a new variable as said let's call it and it will take the value of Q do size and Y I said uh TS to zero they will perform Auto no distance equals to Q do so we are creating two variables node and distance and then again we will pop out this thing after that we will check if Adent do. no is false if so then we will continue and we will use for Loop next for Lo or auto numberb price in adjacency of in it ads of node and if prce plus distance is greater than equal to distance of neighbor then we will continue and if distance and here we will update distance of n equal to Price Plus distance and at last we will push Q do push NE and this of NE neighor and NE and after this inside of this value we will increment Stops Plus and at last will return list of DST equals to int max if it is int Max and if it is true then we will return Min - one else we will return Min - one else we will return Min - one else we will return list of DST this so this is the code uh based on this approach if you want to have more clarity then if you want more clarity then again go through this approach as well as this code parall you will get the solution let's run this code so expected qualification qualif ID so there was a syntax error here we need to decrement as said and then check greater than if it is greater than zero or not why is it taking so much time let's go to this refresh the page so okay let's run this again yeah the test cases run successfully check for the hidden test cases yeah the solution is right here the time complexity will be big of V + e because complexity will be big of V + e because complexity will be big of V + e because uh V is the vertices and E is the number of edges so overall time complexity will be bigger of v+ be bigger of v+ be bigger of v+ e and the space complexity will also be big of v+ e so that's it if you enjoyed big of v+ e so that's it if you enjoyed big of v+ e so that's it if you enjoyed the video or found it helpful don't forget to hit the like button and subscribe for more content your feedback is crucial so give feedback if any and stay tuned for up stay tuned for upcoming dat code problem of the day videos and exciting month St web development projects happy coding and let's make this year a fantastic work together 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
1,842
hey everybody this is Larry this is March 5th here in uh leod land and also New York why do I say so awkwardly uh but yeah I'm today I'm this video I'm going to do a PR I haven't done before so let's RNG it let's go oh we have a hard one today so let's take a look hopefully it's not too bad because I have to meet up with friend afterwards uh but yeah uh 1842 next pum using same digits uh okay so you give one two one okay so you have um a number with 10 to the fifth number of digits and we're trying to get the next pan drum so getting pan drum is not that hard given that you're already have a pound drum we have to get the next one that is kind of tricky I think it's not that bad in theory but it is just annoying it but I don't I think initially that's what I think anyway but I think the first thing to do is to look at um I mean the first thing to do is break it in half because you know that's what a pandrum is right so what does the next biggest number mean the next bigger number means let's say we have half to F because the other half is imp Pride um reaction I mean initially I was going to say given the second half we want to just increment the into uh we want to increase this one but I guess that's not true is it because that means that this goes up and that you know to kind of in a greedy way you want to get the next smallest number or next number that is bigger you want to increase it by as small as possible so then now you actually want to um update the middle digit as much as possible that means that basically we just try to get the next pandrum or next permutation of half the digit and that's pretty much it I think to be honest um because it cannot really cross right because if it cross then it stops being pound so we have half the number so let's just say we first half is equal to num uh and over two I think that's right let's um well like I have to make sure for our digits cuz sometimes I just mess up on this so let's see so this is 12 which is what we expect okay OD number okay so this is where we're WR so we just went to round up that's pretty much it that's the only difference but I just want to make sure cuz I don't I guess I could have done the math a little bit lazy yeah so then now it's 3 2 1 so then now we just try to find the next p uh next I keep on saying it the next um next peration algorithm um and there's a linear one well and for this one you have to doing linear time anyway but yeah uh how there's a linear solution and to be honest I have to remember it a little bit cuz there is an invariant where basically you're just trying to find the first number where um I don't remember exactly cuz it just doesn't come up enough I suppose but it does come up off not often but just like it comes up once in a while but maybe not super a lot um but yeah but basically you just get the experimentation first and there doesn't exist then you return empty string right um H what is the next experation uh yeah basically for example if you have I don't know 1 2 three all I mean I guess we could play around with some examples uh a little bit also because the digits are not unique for obvious reason so then basically you get the last position where two is minus three and you swap them is that good and then now what right and one is greater than two so then now you have two what is the there is an invariant but I don't remember to be honest I mean I know that I can write it out I'm just trying to like you know and then here well um 2 three you went swwa the two and three what is the Province right H honest I don't remember this part I mean I'm going to try to it's such a Google both thing that like you know so if you want to skip ahead you should because it's not I don't know if I'm going to come up with anything that interesting to say but I am trying to figure out from first principles because I'm here to learn I'm not here to Google if I'm just Googling it's not that interesting uh and I did I do notice at some point but clearly that some point is not now so um h i know that there's something about getting like a number and then the next okay the idea is here then maybe it's okay is there um okay last number I guess we can in a way remove the last digit from consideration only because it's forced so then now the second last number can we increment this we can increment this if there's a number that is bigger to the right of it right and then basically we're trying to find the last number in which we can increment I guess that's it and then we just sort the rest which in theory is just the reverse because yeah it's the reverse of all the digits because of how um if this is the last digit to increase by definition it means that you have a decreasing order so you just okay yeah all right um how do I do that I mean I know I'm trying to I know that there is like some crazy alos that allow you to do that like you know but I'm trying to think there should be like a very basic operation because I remembered or I remember having recollection of it but I don't remember the exact like uh invariant about it um well I guess if any number is next to if any number is smaller than the next number then it can be a candidate because by definition it um that is the last number because basically here in a way you're trying to find the maximum number because by definition some number to the left of it can swap and okay I think I'm okay with that one so then basically you now what that comes down to is that now the first digit that is smaller than the next number this number can be incremented okay fine so then now maybe I current is zero um while current is less than n and num of current I guess we could start actually at the nend right uh at the N oh it's not even n it's n minus one okay so wait maybe I could spite N2 for n and a half is equal to this thing and then now you have N2 and then now we start at I think N2 maybe N2 minus one to be more precise actually um first of current is if this is so I want to write some operation this operation is not quite right um and what happens if they're the same well if they're the same you keep on going because you can increment this one this number yeah okay so that means that if then we break so that means that if this is then we do what and maybe we do n two okay so then now that means that this number can be incremented at the current index so then we take the next number that is bigger than this number how do people I'm writing this in a way like I think you Google like this is a way known algo so if you Google it you'll get the queen version my code is not going to be cleen because I'm coming from it from scratch but uh all right so then now we won um hm so basically we're trying to in increment current and we find the next ditchit after that I guess I don't know something like this if first of next digit is I guess we count from the B end because as we said the invariant is that it's going to be decreasing so we count from the end we can break at the first one right so okay I guess we can try this again um next bigger index is right is greater than then we uh oh this is what we break so if it's smaller than or equal to we just keep getting um smaller right so then now okay so first to the current this is the uh I don't know I just put it here right and then we want aen uh first next bigger so the character and then we want to I wouldn't say swap it's a really awkward way of writing it uh after that then it's just like um after that then we go from first to current or like from the end to current right so for i e for n and range from n to uh minus one we want to go to current minus one wait no we could skip current is that true when do we put in current well we put in current okay so if first of e is less than or equal to um first of current then we can just append first of you else no the other way um well if this is or like we always append this but if this is bigger we want to append um the current part like basically like a insertion thing um and then maybe this is very yucky I maybe I need to look up how to do it right if e is not you go the next bigger so we don't do this either and then if not done then maybe I don't know this is very awkward code I may have to like study this a little bit but yeah oh we have to return the case which means basically which means this never happen so uh if curent is less than zero return to otherwise we can just return to right I may be off on this algo it's very awkward the way I wrote it oh yeah and of course um we only return half the stuff so I'm definitely very wrong but um but I'm also just like wrong in like another way seems like uh okay we have empty string cuz it's the first string okay and then um so this is empty the next figure is going to be should be a two U maybe this part end it all maybe I need to do this yeah okay so then now this is a two um this does stuff but I don't know what okay so after one iteration it already does this that doesn't Mi so then now it starts at the two right and the current is one so this is bigger than it and we append this oh I have to do a contain oh no I don't but it is bigger than current is it this part that one no it includes no this so then the next bigger number is two is it this part that is adding or the other part was the first of current should be two okay so that means that this is so this is adding first of year um what is next bigger oh I guess this includes current is that right H did I have an off by one on that okay fine no that's next bigger is negative one which doesn't oh so this is actually WR n two is zero it checks it this is wait what is current should be zero right uh maybe I'm buy one in some place all right current is zero that's good next bigger oh maybe I do need to include the next the last digit in that one that's why all right yeah very silly cuz I didn't in the last one to negative that's what I don't like about Nega indexes in Python um because some it obscured what my expectations are as a result but uh but yeah so basically now we want to say enter. appen the reverse of it and that should be it in theory uh oh because uh this is should be an extend because I guess it's just a no that's not true I mean it is kind of true but some of these are strings so we actually need this to be something like the something like that actually uh yeah it's a way awkward way of writing it for sure uh ooh oh I forgot the odd number thing um yeah I did forget the odd number thing cuz I was just looking at how did it this accidentally work I guess uh but yeah I didn't consider the odd number so that's why it doesn't uh work because I'm just outputting missing a digit oh not actually that uh I guess it's not even that it's just that actually this does not include the OD number right um cuz I included it for the next thing but that's wrong what I should have done is like okay if uh I think I just need cases uh yeah if and uh extra is so maybe I have like extra isal to and then extra isal to num of just n two exactly and then now here we want to um we want to pen extra and then okay there we go I just totally forgot about it cuz I rushed it a little bit did I mess this up still oh um because then now this includes that's a little bit awkward actually but okay fine maybe I can just write it this way instead so that it doesn't use the intermediate thing but this is definitely a very awkward quote um I just kind of forgot about the odd case I don't know I got distracted by all the other but like yeah if you know your experimentation thing or if you're using C++ for example because there's a C++ uh C++ for example because there's a C++ uh C++ for example because there's a C++ uh yeah like library for an experimentation then this is pretty straightforward um in fact I'm going to upsolve this a little bit using C++ uh and then see what I can do let's C++ uh and then see what I can do let's C++ uh and then see what I can do let's just copy this for a second all right let's see if I can do in C++ in C++ in C++ right so I have this so then yeah uh in isal to num. size um I don't know how to write C++ enough um I don't know how to write C++ enough um I don't know how to write C++ enough it's been a while like it's just not um second nature but it's fine and this is a okay maybe that's fine N2 um I don't know if this is quite this right syntax to be honest but yeah and then yeah first all right then now you have this and then now you can do next permutation um I want to say this is true if next peration then we can return first plus extra plus um so maybe like R isal first uh maybe I don't remember how exactly so I don't think I'm writing this very efficiently but or even maybe correctly uh oh but conceptu is easier if you know if you have done C++ stuff um h how did I convert a string to a thing again I don't remember um H I forget how to do it other than like using a to or one of the other one doesn't really come up that much maybe I don't know I'm just guring real quick I don't know how to canver a single calor I guess I can just write something like this as well maybe is it not substring oh sub uh like St I think could be well um H uh string substring C++ I forget what H uh string substring C++ I forget what H uh string substring C++ I forget what to okay we oh maybe I'm thinking up some else h i mean this uh a template that's like a VOR thing but so it doesn't take Str I thought strength could be a VOR of characters but I don't know how it can convert it I'm going to convert it like Dum but I really don't know how to do it maybe it's true let see if there's a queen web doing it yeah I guess there it is that's fine maybe am I Ming that up experimentation right oh one oh I am dumb I'm dumb I knew that one actually but I forgot all right and then I don't need this anymore yeah some uh syntax stuff but you know looks okay give a submit yeah much easier because we don't have to do the experimentation thing so it's about knowing your library though clearly I don't know my library other than dysfunction exists so but yeah um what is the complexity here uh the complexity here this is linear time you can kind of see it out right this is linear time linear space um I'm a little bit inefficient in the space but it's still linear it's just a little bit yucky linear so yeah uh that's what I have for this one let me know what you think stay good stay healthy to your mental health I'll see y'all later and take care byebye
Next Palindrome Using Same Digits
number-of-calls-between-two-persons
You are given a numeric string `num`, representing a very large **palindrome**. Return _the **smallest palindrome larger than**_ `num` _that can be created by rearranging its digits. If no such palindrome exists, return an empty string_ `" "`. A **palindrome** is a number that reads the same backward as forward. **Example 1:** **Input:** num = "1221 " **Output:** "2112 " **Explanation:** The next palindrome larger than "1221 " is "2112 ". **Example 2:** **Input:** num = "32123 " **Output:** " " **Explanation:** No palindromes larger than "32123 " can be made by rearranging the digits. **Example 3:** **Input:** num = "45544554 " **Output:** "54455445 " **Explanation:** The next palindrome larger than "45544554 " is "54455445 ". **Constraints:** * `1 <= num.length <= 105` * `num` is a **palindrome**.
null
Database
Medium
null
493
cool 493 we were spares given away numbers requires of junior and important skill peer advised SNJ a number sub I is greater than two times time subject okay you need to return the number of important we were as Paris in a given away okay that's maybe that's easy to say at least the other one had like five pages of instructions okay so we want so I listened SNJ meaning if in this case three and one is one and also the other three and one is one because it's bigger stripped later okay hmm so right off the bat to think I'm thinking of is the to a couple of strategies maybe one is divide and conquer something I'll recurs and stuff and it's fifty thousand so you can't do aunt square but if I could do some kind of n log n type merge sort type thing with counting inversions because this is almost like counting inversions and then you just merge so it the number of yeah maybe that's right it's just like inversions but with two times and then when you're on the merge step you just have to do certain things and make sure you pop two things in an easy way and then store it afterwards good yeah okay let me try that approach then interesting inversion okay yeah we turn 0 I suppose otherwise okay well now we also underway so I guess we need a helper what's hoping to do it kind of cool recursively or something I still can actually but now you need a way to merge okay mmm so we've returned the top over the second is to account since we twist it up and this is real inspired so then count is just you go to one place rights of one and then we turn merge comes with count but to do the merging now and then justice should be more powerful I can so that's just - be more powerful I can so that's just - be more powerful I can so that's just - I don't have an M okay so that means Wow it's just I'm gonna get you out of case just later okay so now does it just standard mergesort I think okay I mean we have to be sorted afterwards but I think we could you said he stumped a letter the numbers in a bit yeah actually they say we don't even need to sort it actually now we yeah we should sort it so ad will be like we attract I forget the number of it yeah okay if that is so the love if this is greater than two times might sepcial then we count now we count more than that means hmm that's fing about this maybe we don't want to know why don't know maybe we want to reverse and the structure should be recursive anyway oops so now we want okay what happens when this is the case that means this is just a smaller size oh I think that's right actually that means we because love is smallest this is going to be the size of love because if this number is smaller than the smallest number of love then it's more than everything else that's enough I've left enough okay that's just a mouthful left enough okay and then also we pop what do we pop means we pop - we pop what do we pop means we pop - we pop what do we pop means we pop - right yes he should be Dex okay I just go index that's not to it this fancy way let's try to be I'm just usually I don't care about that much about space but I think I'm 50 K isn't it and I were a little bit about I do worry a little bit about space usage um just use the pointer well that's well this is the case and what's so that's kind of - the index may be minus one kind of - the index may be minus one kind of - the index may be minus one of them may be just off I wonder but and pretend now we write int X pause elves start a pen cap I don't knock out once again right number character before obviously otherwise we just yeah do it to the love and that's it yes we I don't really need to do this yeah I mean you know I'm just because we're gonna sort it anyway is already not gonna be sorta cuz it's only two times whatever so then in that case noon I'm just equal to love persuade and then sort it okay well I need a place case that would be nice right if n is you to zero return 0 well it's just less time where you go to 1 return 0 maybe that's okay in top check tie not return it everything well you're obviously hmm okay well okay let's just print stuff out maybe there's enough I wonder something mm-hmm mm-hmm mm-hmm and that's really that's fair you don't do the entire way why do we never return the entire array maybe something pythonic no I mean we do well I don't know what let's do a one way just for illustration that the distinct numbers for debugging yeah so we only take stuff that's what I was expecting that's why it won't change up the numbers then this is the right answer Tadashi's by accident well I went to the right now we cursed I know I do because today right I'm just being dumb cuz I don't I said I would do it I did but when dis is stuff that stops being true so this doesn't make sense for ya I mean I definitely don't handle everything there that's for sanity check let's print this for a second maybe even the price is not right I thought that's right yeah why is the right wall step input and we'll still have from the right hmm not getting that form that's for you yeah okay no I still nothing it out my 71 element queerly wait why am i off by one well maybe this is off by one I'm always pretty bad at inclusive and exclusive touch my right should also debug that faster if that's the case but okay still unintentionally right so let's give it the example case actually we come in another case you may need to print this okay well actually got both of them right I taught this and educate there is definite in that case where I don't handle so I so this is also another case of being wipe accident so I think I could do a big case of like which is also unfortunate when that happens to you if we go but that's why you have to stay vigilant because sometimes just because your past cases doesn't mean is right because I don't handle what happens after this while loop and you should and I think you have to times it by what okay well because I think what you need to do is care with you too if ya left I'm gonna happen you have left elements left or by elements left well did your pen it and that's fine no I guess it just happens to be right in a sense that well you should when you need to sort you would put it in the back of their way but that also means that in this case it means that this condition will no longer be true no matter what so wait is that right he was there's no numbers laugh because that means number on the right it's times to it's bigger than all the numbers on the left which is there's not in love and in the other direction we already did all the math so okay so maybe that's right huh it's always fun to think about let's hope there's just something timeout or that I have to do the smaller maybe wait okay if this could be faster because I just use a naive sort you could imagine this adds another maybe like in fact you or some of lager and say that's actually not I forget how the math goes but you have just actually put this in the same loop and then that would make sure guys n log n so - Deborah a little bit slower n log n so - Deborah a little bit slower n log n so - Deborah a little bit slower though no still faster than 70% I though no still faster than 70% I though no still faster than 70% I suppose one seven seconds ago slow no 20 mega I use what more memory like I use more memory now I guess I construct a new away every time on this story so maybe if you do it in place maybe that's okay that would have made memory much lower that's fine so yeah so in theory if you do it correctly and less lazy this is n log N and space you could too you know with merge sort you could well now we'll be trick to do in place actually don't there ways to do it but it's not really standard but prettier so of an extra space I guess in this case n log an extra space because the end of the end tap is the way I did it maybe yeah I guess you can make it over vent space to be a bit smarter about it but yeah but that's kind of hi to Paul my first it's I mean I think one of the Proms tied to like ace is an interior when I give interviews is just promise that you have what the tourists for you should have all the tools for you know all the basic functions meaning signings stretching most you know ones that first search breadth first search well when I say searching I guess I'm in binary but like you know those kind problems and this one it's kind of like hey do you know merge sort without actually be like just implement much soy and it's kind of it gets well I mean I some people might still hate it anyway but that way people were like you'll get people who are like why would I ever need to know how to implement merge sort and then do it that way right and I've been in this case it's not I mean for me as a just in general not necessary for interviews it's not that you need to know merge so it is that for merge sort you learn a lesson about divide and conquer in a consistent way and an analysis of God and kind of like you know like recursion in a way as well to some degree you don't need to pay anyway so I think that's and that's in theory there are the lesson to be learned from the merge sort so then and when you learn that lesson then you can reapply it in different cases like in this one do I do we say that I am yeah that I have a sort of a finger on this one because I do recognize his problem it's like a variation of some ink or an inversion is just measures how unsorted upon a statement uh in a way yes and that's just basically this thing it's the same definition except of about the two times number sub J and that would kind of give you the inversion this and that's a merge soleus and you guys should do this with quicksort as well but merge-join is wander straight or but merge-join is wander straight or but merge-join is wander straight or more that you guarantees and again versus like in a really bad case you could do like it you could use quick so it to cal minimum in motions and in a similar way but you could fall into n square an N squared worst case way and that's also something that you know you they teacher in school though in real world click so it goes by quick sort is very hard to be N squared because you go you could always mix up your inputs by like just randomly sorted ones before running the album very high probability will be n log n but you can't do that it for counting inversions right so please not maybe I should say I don't know but I don't think any Soph my head so yeah so that's kind this prom I recommend it's no I mean you know it's implement merge sort so I'm that's something that I do my command so yeah and I do feel happy that I got it done
Reverse Pairs
reverse-pairs
Given an integer array `nums`, return _the number of **reverse pairs** in the array_. A **reverse pair** is a pair `(i, j)` where: * `0 <= i < j < nums.length` and * `nums[i] > 2 * nums[j]`. **Example 1:** **Input:** nums = \[1,3,2,3,1\] **Output:** 2 **Explanation:** The reverse pairs are: (1, 4) --> nums\[1\] = 3, nums\[4\] = 1, 3 > 2 \* 1 (3, 4) --> nums\[3\] = 3, nums\[4\] = 1, 3 > 2 \* 1 **Example 2:** **Input:** nums = \[2,4,3,5,1\] **Output:** 3 **Explanation:** The reverse pairs are: (1, 4) --> nums\[1\] = 4, nums\[4\] = 1, 4 > 2 \* 1 (2, 4) --> nums\[2\] = 3, nums\[4\] = 1, 3 > 2 \* 1 (3, 4) --> nums\[3\] = 5, nums\[4\] = 1, 5 > 2 \* 1 **Constraints:** * `1 <= nums.length <= 5 * 104` * `-231 <= nums[i] <= 231 - 1`
null
Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set
Hard
315,327
425
hey what's up guys this is chung here so uh so today uh let's take a look at today's daily challenge uh number 425 word squares i think it's a cool problem here so you're given like a set of words without duplicates find all word squares you can build from them okay and the sequence of words form a valid word square if the case row and column read exactly the same thing so this is one of the examples here basically if it's the words bar area lead and ladies it forms like a square basically every uh on each of the row and columns the uh the letters the strings are the same for example the bar horizontal with the bar and also vertically it's also a bar and the second one is area so the array is like same thing this is also an area right and the lead this is also a lead and then the last one is a lady okay so which means this is a valid answer here as you guys can see the sequence matters here right okay and it asks you to return all the possible uh word squares given like a list of the word here as you guys can see the size of this the size of the word square is the same of the length of the word here so the main intuition for this problem is that you know basically given like a list of words here we are basically we're trying to basically we're trying all the possible the auto combinations so first we're adding a ball here let's say we're adding like a bar b a l basically we're trying to try the ball first and then we try the area and then we lead and we tried ladies let's say if we try a bar here okay if we put the box on the first one so what's going to be the second one so the second one you know with any so this is going to be the second word here right so what's going to be the second valid the second uh valid answer for this right the second valid so for to be able to satisfy this word so the word has to be starting from what has to be starting from a because as you guys can see here if the word starting from a here basically if the prefix is the same as the uh if the prefix of the of this word is the same as the uh the prefix vertically then we know okay so this one is a candidate we can use that in this case it's an area here so that's why since the area here has a prefix of a which is the same of this one that's why uh this the second one is the area here a r e and a okay now so now it's time to fill in the third word so same thing with the uh when we uh as when we are feeling the second one so with to feel the third one as you guys can see it has to be what the prefix has to be equal to the l e here okay because we need the uh the word to be the same as horizontally and vertically right that's why i mean the prefix of the second word of the third word has to be le which in this case has happened to be a the weather l e ad right and then the last one of course the last one the prefix has to be a what l80 lad and we're looking for the l a d and y cool and we're doing this for all the other words so now i think for this part i think it's pretty obvious that we're gonna use like uh what a backtracking problem right and at each of the step of the backtracking functions here we need to so as you guys are besides the backtracking here so and by the time we reach the last one that the last row here and then we know okay we find a valid square otherwise we just abandoned abandon it now the problem comes down to how can we find the uh the prefix of a word by given this like a word list here i mean we can of course use the uh use the hash table basically we i think the hashtable the key will be all the uh the prefix and the value gonna be the list of the uh of gonna be the list of that word the words uh who is who starts with the same prefix right that's the hash table solutions and another solution is by you using the try right you know i tried trie right tri the tri structure is it's famous of basically it's also called a prefix tree and this is also like a good candidate of solving this kind of problem basically that's exactly what we need a prefix uh we need to find the pre all the words with the same prefix you know this thing i think if you guys have seen like system design problem you know there's like google like a search recommendations right basically if there's a search bar here even in google there's a search bar basically you type in the abc here and down here it will give you like the deferred some recommendations right start recommendation tendencies or words starting with abc okay right basically it will give you i think the top 10 most popular one that's okay so the way the google implemented this or that for that interview problem you know i think it's uh we usually just you we use the try structure to store that basically you know as you guys can see this is exactly what this problem is where it's asking us to find basically you we're given like a prefix and we need to utilize the this try to try structure to find all the words right that's uh starting with this the same this prefix and then for each of the word we can basically we can try uh we can try each one of them right um cool so with that being said let's try to create this try uh the try structure here uh okay you know to create a try structure uh usually we need a like a node here a tree node i'm just going to cut a node here you know and in this for this uh in this note here we go we will have like two we already have two uh properties okay so the first one is that the children okay the children it's a dictionary basically you know the key is the character on this note you know and the value is the it's all the other child all the child nodes for this for the current node and the second one you know the second one is the it's like further the normal template you know the second template the second property of the of node is the word basically this property tells you if this node is the ending of a word and that can help us you know find the uh the other words from the front of prefix basically the way we're finding it is like this you know let's say we if we have like a here we have a here right and then we have a i think the root node is empty here we have a b right so here we have a c uh d let's see the prefix is a and a ac so now our the last node is this one now what whatever undersea here right let's see we have a word here this is also a word and this is also a word so basically and then we're gonna have like three uh then basically we'll have three words here we'll have three words for this thing here this is the word one word two and word three and our hyper functions uh just basically we'll just take uh any uh prefix and then it will return a list of the words that having the same prefix and you know we can do this right i mean we can do the self dot word itself and then we can uh you can store the word on each of the leaf node here okay but then so for that i know it's going to be a little bit time uh time consuming because you know the way and then if you're only storing that's the word i mean on the uh on the leaf node okay then to be able to find all the uh the words having the same prefix uh after we reach the uh this note here we're gonna do a dfi search basically we're gonna uh we're gonna traverse all the other subtrees from this node until we have find all the uh the leaf node that has that's marked as the is word equals to true okay and then we're gonna read that value and read and return it instead you know instead what we can do here is we can like uh we can add each of the node here even uh if it's not the leaf node we can also like store like a list of words that's i mean currently uh currently like uh starting from this character basically you know for a here right you if we have like uh let's say the word is a b c a c d uh a c d and a b so here at the node a here we're gonna store the list of this all three words abc acd and abb and here at ace asc here we're going we're only going to store the acd here because that's the uh the word that has the prefix uh of a and c basically you know what we're doing we're trying to do we're doing here is instead of uh marking uh using the leaf node you restoring we're adding like one more or like adding one more like properties on each of the node here and where this properties here is gonna store all the words that uh having the same prefix up until this node here and we're going to populate this uh these properties while we're building the this prefix tree or like a try right and so that later on right so that later on when we're trying to get the prefix all we need to do is we just use the prefix here and we are trying we're going all we need to we just re traverse to this last node here and then we will be using that words properties of this node then we can very we can quickly get our the words having the same prefix cool so um all right so that's that and uh let me continue building the uh the tree node here so we have a train over here and you know for the uh for to build the tri structure we need to basically we need to two helper functions now to build it we only need the one add here basically add is to add this word into this try right the prefix tree and to do that we need like a root uh we need a root first so here uh current equals the root okay and then for character in the word uh for those who still don't know how to implement the tries prefix three structures i highly recommend you to try and look for one of the templates and then try to remember how to populate how to build this prefix tree basically the way we're building it we are for each of the word here right i mean we have to maintain like a root because for the prefix tree the root is always it's empty that's why i'm creating an empty node as a root node and everything and anything after that is part of the of our prefix so basically for c in the words if c is not in the current dot children okay it means that okay if the c is not if it's not here we are going to create a new node to hold this c here basically we're gonna have like a node current right current dot uh children c equals the equals to note okay i mean what every time we create a node you know since the uh a children right a children is a key value pair and the key is the uh is the current character and the value is a another note see basically if this there's like a c here right and uh another note is it's children here it can have many other children here that's why each of the child is a note it's another note that's why i'm creating a note type assigning to these children here okay and then we just need to update we just uh children dot c okay now we just need to uh assign this current one with the child node so that we can assign the uh the next character right uh after this the new child notes here or if there's a or there if there is already one here uh we can simply skip this one here but we still need to keep go moving forward down the wall down the road basically if there's like uh a here and there we have a b c here now we're at a here so we're trying to find b if there's a b here then fine we'll look for c here and cool so that's that and remember uh we're trying to also populate these words for each of the note here so what that it means that for each of the node here right we're gonna current dot words dot append the current word this is a little bit of variations of the traditional uh traditional tri structure here basically for each of the note here we are appending the word to it okay cool and yeah so to populate to build the build a try right so we just need to do this uh add words now we have a try structure here and the next one is going to be the you know let me try to this build try so the next one is the back tracking okay and backtracking so we have an answer here right the answer is this one and we try all the possible words okay and for word in words okay we'll do a backtracking and the backtracking basically will have like two parameters the first one is the index the current index and the second one is the current list of words you know because at the beginning right so we always assign the this word to the current one to the to this list here so then in the end we simply return the answer yeah that's basically the backtracking structure and to implement this backtracking method here let me do this uh basically the backtrack okay we have a we have index right so the index and then we have a current words so if the index equal to the n or what is n uh the n is this so that the n is the length of the size of the uh this the square right which is the uh the what the length of the word right we can pick any words here because all the words have the same length here if this thing is n here and then we know okay we have find a valid word square we can simply append uh this current words right and we do this since we're going to do a copy because this current word is getting up it gets updated constantly and we don't want our answer also gets updated that's why we do a clone here and then we return otherwise if we haven't reached the end uh we need to get a prefix right so the prefix so what's the prefix you know we have the index here right so the index is what the index is the uh is the hot it's how many is this the places right so let's say if index is two or let's say if the index is it's two here the index two means we're at here it means that we have we'll have like two so we're going to get the prefix from this column here right and how many strings we have basically everything inside our current words here we're getting the set the third characters from each of them to form the uh the prefix okay so that's going to be a join okay join what join the uh this is a little bit the shortcut of the uh so we have a word of index okay right for four words in current words right so basically what i'm doing here is for each of word in the inner current word list i'm getting the this index word from each of the word and then i concatenate them together to be our prefix okay and then we're going to have a words here right so the word is going to be we're going to have like another uh hopper functions right so we're like i said this power function is going to give us all the words that starts with this prefix and then for words in words we're gonna because only those words are the valid candidates right that can keep moving forward right so that uh we're gonna add the current words append to words right and then we have a backtracking uh index plus one because we have already uh include one more word here and then current words since you know since the current word is a list we have to uh remove it afterwards so that we uh so that the next for loop will have the same state right yeah so that's that and now yeah now the uh the get words hyper functions here right so to get words the prefix okay so to get a prefix for get the word for is always the same prefix uh we have we need to do the same thing we have to do uh we have to get the root first and then for c in the prefix okay and basically if c is not it's not in uh not in current dot children as long as the any of the prefix is not in the current three structures and then we know okay so we have nothing we haven't we have zero word that uh starts with this prefix okay so that's why we can simply return an empty string here empty list here otherwise we just keep uh moving downwards right just like what we did in the add half functions there right so and that now so if everything works fine now we're at the end of the prefix and we so here we can simply return the current uh dot words yeah because the current dot word store stores the other words that's uh having this prefix you know as you guys can see if we are not using like these words uh adding these properties basically from here onwards we have to do a dfi search right to find all the uh trying to find out all the sub nodes starting from this current node here so this is gonna save us some time here cool so and yeah i think once we have all this stuff here and we have a backtracking here and we have this yeah i think that's pretty much it is let me try to run the code here yeah quotes it's accepted submit yeah so it works i mean uh so how about the space and time complexity right so and let's see the space and time the space complexity the time complexity is we have uh we have a word here so the length of the word is okay so let's say we this is n here let's say we have n words here okay so that's why we have an n here and each words have like uh the word lens is at least one at most five okay then we have a n times five yeah because to add of this word add this word here we need to loop through each of the word okay which is the uh for prefix okay we need to loop through the uh sorry add here for each of the word yeah we're gonna have like the end times five to add this word into the uh into the into this prefix tree here and then for the backtracking right so that's the n times five for the backtracking here we have like uh we also have of n here n times let's see so i think the backtracking time complexity it's a little bit tricky because here you know we have a n here and you know for a for our like uh prefix tree here from one of the nodes they're like total like what how many that can this one note have can this one not have it can have up to 26 because everything's in lower ladder that's why the eight at each note at least you know there are like 26 in total so the other dotted loop is n and the inner loop right to back to backtrack all the possible words here is n to the 26 uh it's n times 26 to the power of five here i mean the word length is at least one and at the most five so it's going to be at 26 to the power of five okay and that's the number of the backtracking right and in inside of the back trackings we are uh we are doing this we're doing like this in the number of the so this part is the current words i think this is five this is the l right this is a five here because at most we will have like uh five here and how about this gets worse here so the guys words here where basically we're looking through from the uh from the first one from the first node all the way down to the uh to the to this space to this node here this time this will take l time yeah so it's gonna be a another five yeah because the way we're doing like this get worse here we'll spend like the this the amount of the prefix and to get to the current node and then from here we just get it from there we just get the words from there yeah so yeah i think that's the time complexity and for the space complexity right space complexity we have like uh we have in total n words right so in total we have a n times what of each of the nodes here we have we can store up to 1000 up to this end length of the afterwards here okay and how many nodes we have here we have like uh let's see we have so basically it will store like uh like this let's see this l we're gonna store like l times of the words for each of the uh the notes here for each of out of the words so the space complexity is going to be a n times l in this case space cool yeah i think that's it for this problem i know the time and space complexity analysis is not that clear for this problem but i think that's not the most important thing for this problem to me that the most important thing for this problem is that you have to be able to find a way right of start solving this problem which is the uh basically the backtracking right we just try to put the words into the square one by one okay and we're basically trying all the possible ways we try the first word and we try the second we try the third one and for each of the word here we try to start here from here we're trying to put place the candidates to the next one until we have place we have filled the entire word square and to do that we will need to i mean to guess the words that is based on our prefix and then we just continue our back backtrack logic here okay i think that's pretty much i want to talk about for this problem i don't know why i feel so tired maybe i don't know why because this is maybe the explaining the tries the prefix structure is kind of annoying or i'm just having a hard time trying explaining this problem to you guys today sorry about that but anyway thank you so much uh for watching the videos stay tuned see you guys soon bye
Word Squares
word-squares
Given an array of **unique** strings `words`, return _all the_ **[word squares](https://en.wikipedia.org/wiki/Word_square)** _you can build from_ `words`. The same word from `words` can be used **multiple times**. You can return the answer in **any order**. A sequence of strings forms a valid **word square** if the `kth` row and column read the same string, where `0 <= k < max(numRows, numColumns)`. * For example, the word sequence `[ "ball ", "area ", "lead ", "lady "]` forms a word square because each word reads the same both horizontally and vertically. **Example 1:** **Input:** words = \[ "area ", "lead ", "wall ", "lady ", "ball "\] **Output:** \[\[ "ball ", "area ", "lead ", "lady "\],\[ "wall ", "area ", "lead ", "lady "\]\] **Explanation:** The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters). **Example 2:** **Input:** words = \[ "abat ", "baba ", "atan ", "atal "\] **Output:** \[\[ "baba ", "abat ", "baba ", "atal "\],\[ "baba ", "abat ", "baba ", "atan "\]\] **Explanation:** The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters). **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 4` * All `words[i]` have the same length. * `words[i]` consists of only lowercase English letters. * All `words[i]` are **unique**.
null
Array,String,Backtracking,Trie
Hard
422
1,859
Salam alikum so in this leth C question I'll be discussing uh 1859 sorting sentence simply stated all we have is this drink as a parameter that's provided and what we need to do is order it or sort it based on the ending of the integers the end of each if we break this down into an array and take the last character within that uh word we'll get the was it theorder which the string supposed to be laid out and how we're going to tackle this we'll tackle this by uh creating an array a string of array uh now with this string array we're going to input the S and split it into an array of words and we're going to remove the empty space between the words now string array word array will name it and we'll pass the S to split the empty spaces or space between the words so that will capture each word as an array list or as an array with its own value at its index now then we're going to have another array which sorts through the length of the word array now we need to create another string array name it sort and string array and we're going to pass um the word array with its length so what does this do is that it creates the same length as the word array and this array we'll be using to store this sorted arrays um then we're going to have for Loop where we it R through the uh the array of sort now the array of word array uh word array within the logic of this for Loop will create an integer name it as I and we're going to assign words. length of that each string and then we're going to get the index of those words by getting the last character index we'll have a word that J at while I is less than one we'll have minus the character Zero and then we're going to use our sorting the index where we're going to assign it to word. substring to get our last value i - one zero i - one and we're going to return um a strength and we're going to join them together join with sort now just to iterate through we're creating a word of array string array called word array that splits Dr array uh every empty uh character then we're going to create another uh string array name it sort which will create the same length as the word array and this will be used to store the sorted words and then we're going to have uh a loop for Loop which will have a process that will go through each word within the word array and be used to store sorted uh where we create an integer I where we going to assign the word with the length and then get the index where the word of that character we going to extract the last character of the integer this integer will represent the index of each current words that should be in the sorted array and on the last P portion of the logic block we're going to have the sort the string array where we're going to pass the index minus one that'll be assigned to wording the substring so it assigns the current word excluding the last character where subtracting one and it will sort array at a calculated index minus one the minus one is used to because the indication are zero based and finally after processing all the words the code joins the sorted words in a sorted array using spaces as separate that will turn hopefully that makes sense uh and the translation the sentence meod short sentence parameter s string foreign speech for fore speee foreign spee fore forch fore for foreign for speech fore character knowledge spee for index sub word foreign foree return stat FR that joint y for um word K hi fore character IUS one substring C returning string join sort e fore speee a y um string that join separate okay and the daam rat k
Sorting the Sentence
change-minimum-characters-to-satisfy-one-of-three-conditions
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters. A sentence can be **shuffled** by appending the **1-indexed word position** to each word then rearranging the words in the sentence. * For example, the sentence `"This is a sentence "` can be shuffled as `"sentence4 a3 is2 This1 "` or `"is2 sentence4 This1 a3 "`. Given a **shuffled sentence** `s` containing no more than `9` words, reconstruct and return _the original sentence_. **Example 1:** **Input:** s = "is2 sentence4 This1 a3 " **Output:** "This is a sentence " **Explanation:** Sort the words in s to their original positions "This1 is2 a3 sentence4 ", then remove the numbers. **Example 2:** **Input:** s = "Myself2 Me1 I4 and3 " **Output:** "Me Myself and I " **Explanation:** Sort the words in s to their original positions "Me1 Myself2 and3 I4 ", then remove the numbers. **Constraints:** * `2 <= s.length <= 200` * `s` consists of lowercase and uppercase English letters, spaces, and digits from `1` to `9`. * The number of words in `s` is between `1` and `9`. * The words in `s` are separated by a single space. * `s` contains no leading or trailing spaces. 1\. All characters in a are strictly less than those in b (i.e., a\[i\] < b\[i\] for all i). 2. All characters in b are strictly less than those in a (i.e., a\[i\] > b\[i\] for all i). 3. All characters in a and b are the same (i.e., a\[i\] = b\[i\] for all i).
Iterate on each letter in the alphabet, and check the smallest number of operations needed to make it one of the following: the largest letter in a and smaller than the smallest one in b, vice versa, or let a and b consist only of this letter. For the first 2 conditions, take care that you can only change characters to lowercase letters, so you can't make 'z' the smallest letter in one of the strings or 'a' the largest letter in one of them.
Hash Table,String,Counting,Prefix Sum
Medium
null
374
so we are playing the guess game the game is as follows I pick a number from 1 to n you have to guess which number I pick every time you guess wrong I will tell you whether the number you picked is higher or lower than your case so we have a pretty different function integrals of num which returns three possible results minus 1 if your guess is higher than what you uh function has been uh one if you guess is lower than the what I have been and zero it is equal to the pick number so you have to return the number which I have picked until you get that number we have to call the function guess so what is the method so let's say we have a number ranging from one to five okay so one two three four five so one thing what we can do is we'll start iterating love you so guess of one what it will give you one and let the guess number be four okay if number be equal to four okay get some fun that way we will store it in result okay if it is giving you in this case one is less than four so if the guess number if it is lower than the number you pick it will return you as the answer 1. so no that is not the case until you get the result of 0 you keep migrating so next we'll compare it to five and two is less than 4 which will give you answer response there it's not zero again for three is less than four at least again it will give you the answer s but not zero and you do four guess of four that will give you answer as zero why because your guess is equal to the number which the program has picked so in such case what would be the answer will be zero so the result answer will be 0 so if the result is zero you just return this particular number where the pointer is pointing so this is a linear approach vertical method but if you see the given number one to N means that the numbers are in sorted order they are in ascending order and you have to search for some number here so that means what algorithm comes to our mind is present so as you know we'll have two pointers one pointing to less another Point into right and we have to find the mid will be left right by two so in such case we will be pointing here so if you see the index input 0 1 2 3 4 5 0 1 2 3 4 but here since the numbers are given range from 1 to n we will keep it as one to naught so once you have the mid here now perform gets the fluid what it will give you three since three is less than 4 it will give you the answer as 1. so if it is giving answer as one it is submit as one that means the number which you are finding is lesser than a number your Peak no so since 3 is lesser than the number which has to be picked that means the number appearing should is next to Mid so what we will do is low equal to Mid plus one similarly if case of mid if it is equal to minus one when will it become minus one let's say the number to be pick is two so in such case get guess of 3 will be equal to minus 1 because 3 is greater than 2. so if the given condition you could see the guess number is higher than the number which they have picked so 3 is greater than 2 in such case what we have to make high equal to Mid minus 1 why because the number to be picked is before two three that's a high will be with minus 1. what if guests have made for our pick number itself is 3 then guess of made if it is equal to 0 when you add p 0 if it is equal to the number you pick when your case is equal to the number you are picked so 3 is equal to equal that will give you 0. so in such case you have to return three there is one there mentioning here so we will apply the binary search methodology so first we'll have variable end left equal to zero and one more variable right pointing to the right point of the array so while left is less or equal to right what we need to do first we have to calculate submit will be equal to left place array minus left by 2. so why am I doing this to avoid the overview let's say we have some integer 2 power 31 minus one value so 1 to this number if we have then left is pointing here right is pointing here so this plus this will be given overflow case so that is why let's say okay instead of one let's say left is pointing here and right is pointing here so 2 power 31 minus 1 plus 3 will give you 2 power 31 plus 2 so that will cause an integer overflow to avoid this case what we will do is if the number engine from one two three four five six and left this pointing here let's say Matrix point should be here so from here it's two pointers now so the right is pointing at the end of the array so what is the difference here F22 right what is the size that is nothing but right when it's left 6 minus 2 will be 4. so once you get the size as four by two if you do that will point to the mid indexing from left ear to point o two parties that will give you the width so that is what we are doing so first you do right that will give you size of that particular portion left to right and if you divide by 2 that will point the mid indexing of that portion left to right so from left ear to point the size by 2 point us ahead to get the width so that is what we are doing here so next once you get the mid let's have a variable called result and we call the API function guess of net so if result is equal to 0 then you have to return the weight else if what if the result is higher than the if let's say result is not higher if the result is equal to minus 1 that is the number guess number is higher than the number you have paid then you have to make High equal to minus 1 else will be equal to Mid plus 1 where your guess number is lower than the number you have picked it so at last let us minus one if the number is number that will not be the case since you cannot leave it empty we have to return something integer so I'm just writing minus 1. okay so I have mentioned here left and right which will be right and instead of low they should be left so in the naming convention was different what is the mistake I have okay so this is what left should be pointing to one and right should be pointing to the end of the ring that is n and why did I leave zero I don't know yeah yes and for jaw also the same logic nothing change yes successfully submitted if you understood the concept please do like the video and subscribe to the channel will come with another video in the next session until then keep planning thank you
Guess Number Higher or Lower
guess-number-higher-or-lower
We are playing the Guess Game. The game is as follows: I pick a number from `1` to `n`. You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API `int guess(int num)`, which returns three possible results: * `-1`: Your guess is higher than the number I picked (i.e. `num > pick`). * `1`: Your guess is lower than the number I picked (i.e. `num < pick`). * `0`: your guess is equal to the number I picked (i.e. `num == pick`). Return _the number that I picked_. **Example 1:** **Input:** n = 10, pick = 6 **Output:** 6 **Example 2:** **Input:** n = 1, pick = 1 **Output:** 1 **Example 3:** **Input:** n = 2, pick = 1 **Output:** 1 **Constraints:** * `1 <= n <= 231 - 1` * `1 <= pick <= n`
null
Binary Search,Interactive
Easy
278,375,658
1,338
hi everyone once again welcome to the channel today in this video we are going to solve a let code problem reduce array size to the half so given an array you can choose a set of integers and remove all the occurrence of this integers in the array and we have to return the minimum size of that set so that at least half of the integers of the array are removed so let us understand this problem with the example given in the problem itself so here we need to remove the occurrence of the number and we have to select the number such that the selection of the number is minimum and we can delete remove all the occurrence of that number which we select so for example if i select 3 first then i can remove all the occurrence of three so i will able to remove four theories but the total length of this array input array is n which is ten so still we need to remove more so we can then select five so once we remove the all the occurrence of three and five so we selected three and five and we remove all the occurrence so in our side we select it first greedy three and five so after that only two to seven is left over and this is three which is less than equals to the half size so half of 10 is 5 so is yes this is the one answer so the answer we need to return the size of our selection sort selected set so which is 2. so we can return 2 is the answer is there any other solution yeah there are many other solutions like instead of second five we can select two as well so we can remove all the occurrence of three and two then after that we will left over like three five and seven which is total count is four and it is again we remove uh at least half element so again this answer is two because we are only able to we are selecting only two integers and there is any other solution yeah there is other solution like we can select instead of two as well we can select 7 so we can have another answer like 3 7 but we don't have to return this answer we just need to return the size the minimum size of our selected set so how we will solve this problem once you got this idea like the idea is behind this we first need to find out the frequency of each element and then somehow we can sort the frequency in the decreasing order and then greedily we can pick the highest like the most frequent number first and we will keep picked in our selected set such that we once we reach the half of the size we will stop there and that is the count of number of distinct element in our set which is the answer so how to solve like once you got this idea this is very straightforward problem you can solve this problem in many different ways so first we need to do find out the frequency of each element in our set so here we can use map or dictionary in python so first we will count the frequency the three occurrence of three is four times occurrence of five is here three times occurrence of two is two times and occurrence of seven is one time now once we got the frequency map what we need to do we need to greedily pick the highest frequency occurrence element first and then keep doing until we find the total sum of the frequency of element is half so what we can do so one of the best data structure we can use here heap so which is max heap so we will build the maxi of the frequency of the elements once we build we will pull this element from the maxi first we will get four so we will keep adding this in some variable like total count and we also create a answer variable that we every time increment one whenever we pick the element from our uh max heaps so still this and every time we will keep check if the total count selected is great like cross or not the half so we will run this while the count so let us say if this variable is count so then i can keep running until count is less than n by 2 then we will keep picking and update this value into the count like count initially is 0 initializes 0 then it become 4 still it is less than 5 then we will add 3 so it becomes 7 and it will stop and here answer will be updated from 0 to 1 to 2 so 2 is the answer so you can now pause the video and implement this code by yourself so let's see i already implemented this code here so this code is like first we are building the frequency map then we declared a maxheap using the priority key implementation in java so if you are using ce plus and python you can use priority queue for or the maxi so this is the comparator for maxi like reversing this once it done we are adding all the frequency frequencies from the map values into the prior maxi once it done now we initialize to variable like answer from 0 and count is 0 and declared a half is like half of the length and this loop file will be run until as i explained count less than half and update the count by the value from the polling from the maxi the maximum value then update the count y answer y one and keep doing it in the end we will return so what is the time complexity of the solution so in worst case if all we have all the distinct element occurrence is one by one which is the size of our array is n then in that case building this heap will take n log n and that is will be the dominant factor like this will be o n this is n log n and this is also n so overall time complexity of this code will be o of l log n so that is the time complexity and the space complexity as we are storing over here so if an element then we will have an key value pair similarly n over so this overall dominant space complexity of n so this is balance good you can solve in your interview but interviewer must have a follow up question can you do it better than l log n so you must have guessed like whenever we are dealing with these counting problems in that case we must try something using extra space or space like we are already using some space can we use so here we will use the bucket sort so how to use the bucket sort let me show you the constraint over here it is given that the array element are in the range of 10 to the power 5 and total element in array is also 10 to the power 5. so once let's understand that bucket solution so first of all we have to build again the counting map that is we need it anyway once we done what we will do instead of like creating priority key or you can create a array and sort that we will try to store this frequency in a bucket of based on the frequency bucket so first we will create a bucket array so that is let us say capital b over here and we create the size of this array like either you can find out the maximum frequency by one pass or you can take the max which is given the maximum frequency can be of in the arrays 10 raised to power 5. so we will create array of 10 raised power 5 plus 1 so that we can incorporate all the frequency once it done we need to mark the presence of each different frequency in our array so we trade through this element data so we mark like frequency of at four so this will be four let us say and after that there are more so at four we have one occurrence so the frequency of four is occurred in our counting is one then three is one time then two is one time then one is one time so okay that is okay extra so here is a zero this is 1 2 3 4 like that this is our bucket once we mark the frequency after that now we can do multiple like picking from the end so the maximum whatever the maximum index of our bucket we will start check picking and again we create like two variable same like one is answer another is count so in count we will add the frequency the that frequency is representing the we will initialize another variable let's say frequency that is from the max value of 10 power 5 or you can find out the maximum frequency occurrence in your data that doesn't matter it's like same so we can initialize from this highest value and like 10 power 5 now we need to check if there are occurrence of this frequency like what is the number is there if it is like not 0 if it is 0 we just decrease the frequency y1 frequency by one and continue it if it is not zero then we will sub add that frequency into our counter value and increase answer y one so because we are selecting this occurrence like this many elements to remove in uh from the original array and that we will keep run until again the same condition while like count is less than equal to half by 2. so that is the idea now let's pause the video and you can try the code by yourself let me implement this code so for this we need this as it is here just we will twist the code over here instead of this we will declare first a bucket array so let us say b is a bucket array and now this is or lets better to name it better so that it will be more readable and this code the size of our bucket is 10 power 5 plus one so this is one over here once it done now again this we need to mark the presence of each frequency so that presents marking like we will iterate over our map so v the values in the map so map dot values so once we are going through we will update bucket or better to call this as a f so frequency this representing frequency so bucket of f is plus so once it done this after that now we need to select the numbers and fill in so we will declare here another variable let's say frequency so that freak or from the 10 power 5 so this will become 10 power 5 now this loop keep running as it is until our count is there then we will check first if bucket of current frequency is 0 if bucket of current frequency is zero then we just decrease frequency by one so frick minus and continue from here there is no need to update our count and answer otherwise we will update our count by adding the frequency in it and this is okay and after that we also increment our answer by one and also here we need to update the object we selected one time this current frequency item and we just decrease this y1 we don't have to decrease here frequency because so there might be chance like for same frequency we have multiple occurrence so that will be taken care over here once the bucket of that frequency becomes zero so let us try to compile this code and see if this works so this is my earlier submission so yeah it is working as it is now we can submit this code and it got accepted now what is the time complexity of this solution so let's see so this is building the map often building like filling the bucket often as the maximum frequency can be 10 power 5 plus so that's y of n again now we are going through frequency like every time we are reducing the either the frequency by one or the bucket of frequency one so there as you can see the constraint which is like in any how total we will run the 10 power five so that is the o of n as well so the overall time complexity of this solution is o of n and the space complexity is again o of n as so that is the solution if you want to do further little bit more optimization in this code you can like here you can find out the maximum frequency so maximum frequency you can declare some maximum frequency variable over here and like max frequency and initialize from zero or like there must be a one element so you can inside any number and you can keep update this maximum frequency over here while filling your bucket once is done so instead here instead of initializing this frequency from the battery most 10 power 5 you can initialize it from the max frequency itself and then keep doing it so that is if you like this solution please subscribe this channel and share this video thanks for watching
Reduce Array Size to The Half
queries-quality-and-percentage
You are given an integer array `arr`. You can choose a set of integers and remove all the occurrences of these integers in the array. Return _the minimum size of the set so that **at least** half of the integers of the array are removed_. **Example 1:** **Input:** arr = \[3,3,3,3,5,5,5,2,2,7\] **Output:** 2 **Explanation:** Choosing {3,7} will make the new array \[5,5,5,2,2\] which has size 5 (i.e equal to half of the size of the old array). Possible sets of size 2 are {3,5},{3,2},{5,2}. Choosing set {2,7} is not possible as it will make the new array \[3,3,3,3,5,5,5\] which has a size greater than half of the size of the old array. **Example 2:** **Input:** arr = \[7,7,7,7,7,7\] **Output:** 1 **Explanation:** The only possible set you can choose is {7}. This will make the new array empty. **Constraints:** * `2 <= arr.length <= 105` * `arr.length` is even. * `1 <= arr[i] <= 105`
null
Database
Easy
1773
835
So gas welcome back to my channel thank you and today I have given you this lead code challenge image overlapping and what you can do in this image is you can shift the lineage of this image up or down left or right, what can you do with this If you can shift it to the right, what will happen? What can you do, if you can shift it to the right, then what can you do? So now, like I shifted it down, what will happen if I shift it to Township, so whatever, like what was here and If we shift it down, then this one van will go out, okay, and this top van, here, will go 00, and if this one will go down, then what will A go, zero van, okay, and this one will go down, so what? A will go, zero van is a van and this one van will go, okay, even after doing anything, if we had done it, we would have returned it, so it is okay to move us like this, so how will we do it, see, what will we do, we will write all the steps okay. If we are going to perform, what can we do? What can we do? We have a van from zero to zero, so we would like it to go here, or here, shift everything down here. So what did we do first? This van of ours went here, so if we wanted to move it, what would we do? Move it down once in the entire matrix and then move it right once. So this van reaches here, it's okay, if we have to take this van here, we do down once and right twice, okay, zero earn 1, we can reach here, okay, our down is okay and it will be done, okay. So it will reach from here to here and then where can we reach the zero van, so down and right is fine for that, we can reach it, so for that, down twice, right once is fine and then we can also send it to this van here. We can send it here for that, we can send it to the right servant van, ours is zero, sorry, this has become mines van, so what is the meaning of mines van, so we will have to do this because this and this difference has become zero, now this thing samjhaunga ok. How am I leaving? So where will we go now on 2 1? We can go here also and it will happen once right. Okay, if we do 12 on this, then what will happen to our highest number of vans. We will reach the van and overlap on the van. Like now, which one is the most common among these, we count them all by two, the vans are two and the labs will be cut, one will go, and one given will follow us, move right, okay, so now we see all like this, we are these Gaya will do two for R if we follow R and like if we follow the rate then how many times has the rate come so if the rate has come once then what does it mean if we follow the rate means down right Puri If we do , then down right Puri If we do , then down right Puri If we do , then only one of our vans will overlap. Okay, take any other van. Okay, if we do any other van, then this will become our 110 and this will become this and then we will follow R. In this we will put R. If we give R then we will put R in it, then ours will become this and this will become this, so what will happen from this, our three van overlap posts will go, okay, from this one to this one will go from here to here and here to here, so this will be our answer. If we follow this then how will we do it right then how will we know what we would have done if we move down then plus van will move right then also plus van will do To van kama tu hota to van mines becomes zero di and tu mines Zero will come here, okay, so now what we have to do is that we can do this thing like this and this minus this, then we can remove this thing, here we go, we will take the difference and whatever difference came, like what is this? Is 1 - and whatever difference came, like what is this? Is 1 - and whatever difference came, like what is this? Is 1 - 0 1 and 1 - 0 1 so what is 1 doing 0 1 and 1 - 0 1 so what is 1 doing 0 1 and 1 - 0 1 so what is 1 doing di and r so we will make it plus van okay so 1 will be plus van like what happened here also what happened this is this minus Van and this - this what happened this is this minus Van and this - this what happened this is this minus Van and this - this what happened to van to go back a so van com what will we do back to plus van okay I have here also our this minus this what will happen van and this minus what will happen van so van mines van common a So what will happen if he goes? 3 So we will create everyone's account like this, what will be his account, this van will be van and this will be you van's van, your account will be done, now the van is fine, like this, we will create his account. We will make everyone like this and then at the end we will return the maximum. Okay, so now we will go to the court. Okay, now we will take the maximum, the space and premises will become square.
Image Overlap
linked-list-components
You are given two images, `img1` and `img2`, represented as binary, square matrices of size `n x n`. A binary matrix has only `0`s and `1`s as values. We **translate** one image however we choose by sliding all the `1` bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the **overlap** by counting the number of positions that have a `1` in **both** images. Note also that a translation does **not** include any kind of rotation. Any `1` bits that are translated outside of the matrix borders are erased. Return _the largest possible overlap_. **Example 1:** **Input:** img1 = \[\[1,1,0\],\[0,1,0\],\[0,1,0\]\], img2 = \[\[0,0,0\],\[0,1,1\],\[0,0,1\]\] **Output:** 3 **Explanation:** We translate img1 to right by 1 unit and down by 1 unit. The number of positions that have a 1 in both images is 3 (shown in red). **Example 2:** **Input:** img1 = \[\[1\]\], img2 = \[\[1\]\] **Output:** 1 **Example 3:** **Input:** img1 = \[\[0\]\], img2 = \[\[0\]\] **Output:** 0 **Constraints:** * `n == img1.length == img1[i].length` * `n == img2.length == img2[i].length` * `1 <= n <= 30` * `img1[i][j]` is either `0` or `1`. * `img2[i][j]` is either `0` or `1`.
null
Hash Table,Linked List
Medium
2299
1,913
hi my name is david today we're going to do number 1913 maximum product difference between two pairs only code and we'll be solving this in javascript so we have a function here that takes in an array of numbers and it wants to return a number and that number is the maximum output you can get by getting the difference of multiplying two numbers and subtracting them to get together and multiplying two numbers i'm subtracting it to the difference of two numbers so if you look at this example five six two seven four we return 34 because the maximum difference we have is 6 times 7 minus 2 times 4 equals 34 and we can see here that the pattern is that we need to get the two largest numbers and then minus it by the two smallest numbers and that is going to give us our output so one way we can do this is that we can sort this array and then get the index of zero index of one and the in the last index and then the last index minus one and use that to calculate our output but that will require sorting and it'll be log of time complexity of n log n so let's see if we can figure out a way to solve this in a single loop and then there's a clever way of solving this in and at first i was thinking we'll just find the largest will loop through this and if it's the largest we make it larger if it's a second larger make it the second largest if it's the smallest we make it the smallest and then uh if it's a second mars making a second smallest and it costs a lot if else but we can just focus instead of sorting it just for the those four categories we focus on the two largest ones and then the two smallest ones and then used only if else for this largest or the second mark but we're using if else for the largest and second largest and i use a separate nfls for the smallest and the second smallest and then we can find the output so here what i mean so we first we want to create a largest variable to and we want it the constraints is that it's going to be 1 to 10 to the 4th so we don't have to do it so we want to replace this variable f in the first loop when we see the largest so we do zero so we're going to compare that so it's going to get updated now we can create a second largest two because that's what we need and that can also be a zero that we're going to update in our loop and now we have to do the smallest so create smallest variable and this is going to we can set it up to infinity and then update see if any numbers can be smaller than infinity so it's going to be updated in the first iteration and now we also have to create second smallest to infinity now we're going to loop through nums and inside of this loop we first check and if else for the largest so if current num so nums i is created and or just so if it's the largest it goes to down the chain so whatever is the largest becomes the second largest so second largest is equal to largest now and then the largest gets updated and now we have else osis and now we check for the second largest as well so because there's two ways the second largest can be updated from we just update the largest it goes down the second largest or we find the number that's the second largest so if else if the current number is best and largest and bigger than the second largest and here we can only just update the second largest so we do this fl just for the largest now we do a separate if else in the same loop for the smallest so if nums i is less than smallest we just do the opposite of what we had before it so i mean we just do what we had with 4 but with the smallest so second smallest let me update my variables equals smallest and then smallness equals the current number and now we add that other else if and we have to see if it's bigger than the smallest but less than the second smallest now we update the smaller second great so after we do this loop we have what we want as the variables and now we can just perform this calculation of multiplying them and then using finding the difference so we can just return largest times largest second minus smallness times smallest second great so to put this in code we do let largest equal to zero that largest second equal to zero that smallest equal to infinity that smallest second equal to infinity now we loop through for that i equals zero as less than realms.length as less than realms.length as less than realms.length i plus and now we check for the largest so if and i can just we can just create a variable for the current num so if current num is greater and largest we have to update the second largest first great now we do the elsif for the second largest so in the case that the current num is less than largest and also current num is greater than a larger second we update larger second great so now after this if else we check for smallest and second smallest so if current num is less than smallest we update the second smallest first and now we do our s if for when the current number is greater than smallest and also less than a second so we update it that will be pretty much the opposite of what we have for the second largest okay and now we can just return the math equation so or just times or just second minus smallest times smallest second great oh sorry there's also another edge case where if they're all equal to each other so we can simply do at the less than or greater than for each one because a number can also be the smallest very largest the largest or the second largest and also the smallest and sixth floors and there we go that's how we do this one i mean it's adding the there we go and then the time and space complexity because we are doing a single loop it's going to be oven where n is the length of nums or another arms are right here and then our space complexity we're just creating constant variables no matter how long everything is so it's going to be o over 1. so that's how you solve this problem thank you so much
Maximum Product Difference Between Two Pairs
make-the-xor-of-all-segments-equal-to-zero
The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`. * For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`. Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product difference** between pairs `(nums[w], nums[x])` and `(nums[y], nums[z])` is **maximized**. Return _the **maximum** such product difference_. **Example 1:** **Input:** nums = \[5,6,2,7,4\] **Output:** 34 **Explanation:** We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4). The product difference is (6 \* 7) - (2 \* 4) = 34. **Example 2:** **Input:** nums = \[4,2,5,9,7,4,8\] **Output:** 64 **Explanation:** We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4). The product difference is (9 \* 8) - (2 \* 4) = 64. **Constraints:** * `4 <= nums.length <= 104` * `1 <= nums[i] <= 104`
Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them.
Array,Dynamic Programming,Bit Manipulation
Hard
null
1,275
Hello Everyone Welcome To Date 28th September Light On Android Question This Point Thursday Subscribe This Point Winner On Text To Give One To Say Zinc Valid Code Dial Subscribe To That With Its Total Here Mix Group And Mixer Mood For Exhibition More Returns Gift Veer Withdrawal And Subscribe To That However In This Video Zindagi Aur Bandagi And Daughters Rule For Winning A Idhar Yeh 0.5 Inch And Video subscribe Video Channel subscribe and subscribe the Channel subscribe In The Post Move Will Be Done By To Ek Group Subscribe Must Subscribe E Will Have Day VS Aisi 151 Report Subscribe Now To Please Subscribe Now Shroff All Subscribe To Bind To Right All The Rules For Winning And Meeting Dry And David Beckham Dab Screening Test Hai To Left Right Lutb Recording Logic And Will Do Something Today Water Falls Identification आफ subscribe and subscribe the मिदिंग मिदिंग मिदिंग मिदिंग मिदिंग मिदिंग मिदिंग 8 में आक्टीव बॉर्ड एफ सिड़ इस एफ इस में आक्टीव बॉर्ड एफ सिड़ इस एफ इस में आक्टीव बॉर्ड एफ सिड़ इस एफ इस यॉर्क स्ट्रीट यॉर्क स्ट्रीट यॉर्क स्ट्रीट लिट्स ऑफ बिर्थ मीन था लिट्स ऑफ बिर्थ मीन था लिट्स ऑफ बिर्थ मीन था मैथ डॉटर subscribe to the Page if you liked The Video then subscribe to की एंड इफीजी मॉडल्स टो इस 90 घंडु की एंड इफीजी मॉडल्स टो इस 90 घंडु की एंड इफीजी मॉडल्स टो इस 90 घंडु विद्रो टो-डॉ विद्रो टो-डॉ विद्रो टो-डॉ List Meanwhile Signified By 20 Dance With All Major David Subscribe To APolyglot Remain Civil Volume Mute The Volume Is Hair Oil And Oil subscribe and subscribe the Channel Please subscribe and subscirbe ke din Next Winning Indian Advocates Act In The Producers Patient Annette Schwarz Common Man Sacrifice in Improving Research Company Subscribe Must Visit subscribe The Channel Please subscribe and subscribe the Channel And subscribe The Amazing The Pigment Ek Aaj Hum In Places Has Been Fielded By 10 Wickets Account It Content With To 9 Video Then That Akshay During Sameer Version if you liked The Video then subscribe to the Page
Find Winner on a Tic Tac Toe Game
validate-binary-tree-nodes
**Tic-tac-toe** is played by two players `A` and `B` on a `3 x 3` grid. The rules of Tic-Tac-Toe are: * Players take turns placing characters into empty squares `' '`. * The first player `A` always places `'X'` characters, while the second player `B` always places `'O'` characters. * `'X'` and `'O'` characters are always placed into empty squares, never on filled ones. * The game ends when there are **three** of the same (non-empty) character filling any row, column, or diagonal. * The game also ends if all squares are non-empty. * No more moves can be played if the game is over. Given a 2D integer array `moves` where `moves[i] = [rowi, coli]` indicates that the `ith` move will be played on `grid[rowi][coli]`. return _the winner of the game if it exists_ (`A` or `B`). In case the game ends in a draw return `"Draw "`. If there are still movements to play return `"Pending "`. You can assume that `moves` is valid (i.e., it follows the rules of **Tic-Tac-Toe**), the grid is initially empty, and `A` will play first. **Example 1:** **Input:** moves = \[\[0,0\],\[2,0\],\[1,1\],\[2,1\],\[2,2\]\] **Output:** "A " **Explanation:** A wins, they always play first. **Example 2:** **Input:** moves = \[\[0,0\],\[1,1\],\[0,1\],\[0,2\],\[1,0\],\[2,0\]\] **Output:** "B " **Explanation:** B wins. **Example 3:** **Input:** moves = \[\[0,0\],\[1,1\],\[2,0\],\[1,0\],\[1,2\],\[2,1\],\[0,1\],\[0,2\],\[2,2\]\] **Output:** "Draw " **Explanation:** The game ends in a draw since there are no moves to make. **Constraints:** * `1 <= moves.length <= 9` * `moves[i].length == 2` * `0 <= rowi, coli <= 2` * There are no repeated elements on `moves`. * `moves` follow the rules of tic tac toe.
Find the parent of each node. A valid tree must have nodes with only one parent and exactly one node with no parent.
Tree,Depth-First Search,Breadth-First Search,Union Find,Graph,Binary Tree
Medium
null
378
hello all welcome to code hub uh today let us solve the lead codes daily challenge and the problem is kth smallest element in a sorted matrix given a n cross n matrix where each of the rows and columns is sorted in ascending order return the kth smallest element in the matrix so note that it is the kth smallest element in this ordered array not the kth distinct element so we have to do this problem so obviously the brute force approach that comes to our mind is we have a matrix so we will be storing it the whole matrix into a vector or an array and after which we will be sorting that whole entire vector and return the k minus one uh k minus one element uh since it is zero based indexing and what will be the time complexity here we will be sorting this uh whole vector so it is order of m log m where i will say that m is nothing m is equal to n square since there will be n square elements and the space complexity will be uh we will be using a vector so m is nothing but the n square elements m equals to n square elements so we can uh this is the obvious approach that comes to our mind let us think of some other approach so that um so somewhat little bit uh we can improve on the time complexity uh here uh obviously whenever we face a problem to find the kth smallest or kth largest uh we can use a priority queue where uh where we will put all the elements in the priority queue in an increasing order fashion that sorry and decreasing order fashion so that we will be using a max heap uh why it is maxip let us uh dry run this problem so that it will be clear why it is a max heap so we can traverse this whole matrix first we will have a ma we will have a maxi so we will be having an increasing order in the in from left from right to left let us uh put that uh let us do a dry run here first uh we'll be inserting uh my one into a maxi since the it is not having k elements then we will put a five in our maxi since it is not having k elements we will put even 9 then our 10 then 11 then 13 then 12 then uh 13 but now you if you see here there are eight elements already uh there are eight elements already so whenever we have eight elements in uh whenever we have k elements in our priority queue after which we are we want to insert an element then we have to do some then we have to take a sum of the logic what is that is uh if there is a key element then if the incoming element is greater than the uh top element then we don't want to insert the top element since 15 is greater than top element then we don't want to insert this 15 so after which we have exam we have exhausted our elements from our matrix so the top element will be the kth smallest element in from the sorted matrix uh so let us consider we are having a 6 here ah we have instead inserted k elements and next we want to insert 6 uh before inserting 6 we have to check for the condition whether the top element is greater or smaller since 6 is smaller than 13 we this 13 is useless this 13 is not needed so what we have to do is we have to remove this 13 so once we remove this 13 we have to insert this six uh where it will get inserted uh here the it will get inserted here six so now that we have 13 elements and this 13 is the eighth smallest element in our entire matrix so this is how we will be doing so what will be the time complexity here the time complexity will be order of k log k uh since uh we will be having our k elements inserted and i say k elements insert since there are k elements inserted that will be type obviously is r of k log k and the space complexity will be order of k we will be uh reducing the space complexity but if there is uh if the k is equal to n then obviously the space complexity will be order of n which is equal to the n square elements so let us do this approach here first we will be initially we will be initializing the priority queue in pq and next we'll be traversing the entire elements from the matrix in the n equal to matrix dot size it is an n square matrix so in we can have an itself i equal to 0 i less than n a plus 0 till n j plus if my pq dot size is less than k then we can just push the elements into our priority queue matrix of i j if this is equal to or greater than uh it will not be greater than but if it is equal if the priority q size is equal to the psi is k then what we have to check is if the pq dot top if the top element is greater than the matrix of i j if the top element is greater than matrix of i j what we have to do is we have to remove the top element then we have to push pq dot push off matrix of ij we have to push that current matrix element else we don't want to perform any operation so finally we will be just returning the pq dot top so let us run our code it got accepted let us use the example test cases and run okay let us submit our code yeah it got accepted and this is the priority solution than this we can optimize this uh but uh that approach is uh based on binary search uh so i'm not going to take this uh approach uh hope you hope i made clear with this priority queue solution let us see in tomorrow's sleep daily challenge until then bye
Kth Smallest Element in a Sorted Matrix
kth-smallest-element-in-a-sorted-matrix
Given an `n x n` `matrix` where each of the rows and columns is sorted in ascending order, return _the_ `kth` _smallest element in the matrix_. Note that it is the `kth` smallest element **in the sorted order**, not the `kth` **distinct** element. You must find a solution with a memory complexity better than `O(n2)`. **Example 1:** **Input:** matrix = \[\[1,5,9\],\[10,11,13\],\[12,13,15\]\], k = 8 **Output:** 13 **Explanation:** The elements in the matrix are \[1,5,9,10,11,12,13,**13**,15\], and the 8th smallest number is 13 **Example 2:** **Input:** matrix = \[\[-5\]\], k = 1 **Output:** -5 **Constraints:** * `n == matrix.length == matrix[i].length` * `1 <= n <= 300` * `-109 <= matrix[i][j] <= 109` * All the rows and columns of `matrix` are **guaranteed** to be sorted in **non-decreasing order**. * `1 <= k <= n2` **Follow up:** * Could you solve the problem with a constant memory (i.e., `O(1)` memory complexity)? * Could you solve the problem in `O(n)` time complexity? The solution may be too advanced for an interview but you may find reading [this paper](http://www.cse.yorku.ca/~andy/pubs/X+Y.pdf) fun.
null
Array,Binary Search,Sorting,Heap (Priority Queue),Matrix
Medium
373,668,719,802
1,646
Hello everyone welcome to day vihar into victory of pimple east questions where is the question is that maximum in generated there are a great veer vidya valley of flowers falling into a variety of subscribe Video then subscribe to the Page if you liked The Video then speak Entry frame with updated for love special names came in clear only that is i isi van one drop desi equal to names of my bittu name fennel i s so come pound and hear a beneficial hold two numbers of my bittu plus form of a bittu A Plus One Main Abhi To Jab Date Form Me Setting Verification Very Easy For Research And United Accord And To See How They Want To Do The Given To Modi's 90 Se Start The Self Journey To The Self Written In The Mid-Day Mid-Day Mid-Day Record New End Plus One Dashrath With A Requesting For Endowment And Tourism Services 1205 125 Way Do Uttar Pradesh Sikkim Start With The Stars Back After Back-to-Back Us Stars Back After Back-to-Back Us Stars Back After Back-to-Back Us Unwanted Karo Besan Use Na Let's account subscribe this video dr a percentage to table equal to zero by seeing it is not involved in the written in this country is equal to name of 100 counter tattoo on a quiet years back in its an order number plain this is equal to names Of countries buy two a plus tum sab counter buy two a plus one phone number se right side this year old BTC 's effigy of December 21 2019 2012 's effigy of December 21 2019 2012 's effigy of December 21 2019 2012 calculated the value of p kyun kata hai ki rights and ultimate account places in Lucknow ki mujhe meeting distance Between simply return is Maxwell so let's check the clean and this mark to tax translate samete me once updated guys javodio fast competitor like and comment it is the number of sentences into her and subscribe that chop half thanks alot please like and Subscribe How did you like the solution? * Keep posting. Add your upcoming * Keep posting. Add your upcoming * Keep posting. Add your upcoming question into being a noted scholar. Thank you thanks a lot.
Get Maximum in Generated Array
kth-missing-positive-number
You are given an integer `n`. A **0-indexed** integer array `nums` of length `n + 1` is generated in the following way: * `nums[0] = 0` * `nums[1] = 1` * `nums[2 * i] = nums[i]` when `2 <= 2 * i <= n` * `nums[2 * i + 1] = nums[i] + nums[i + 1]` when `2 <= 2 * i + 1 <= n` Return _the **maximum** integer in the array_ `nums`​​​. **Example 1:** **Input:** n = 7 **Output:** 3 **Explanation:** According to the given rules: nums\[0\] = 0 nums\[1\] = 1 nums\[(1 \* 2) = 2\] = nums\[1\] = 1 nums\[(1 \* 2) + 1 = 3\] = nums\[1\] + nums\[2\] = 1 + 1 = 2 nums\[(2 \* 2) = 4\] = nums\[2\] = 1 nums\[(2 \* 2) + 1 = 5\] = nums\[2\] + nums\[3\] = 1 + 2 = 3 nums\[(3 \* 2) = 6\] = nums\[3\] = 2 nums\[(3 \* 2) + 1 = 7\] = nums\[3\] + nums\[4\] = 2 + 1 = 3 Hence, nums = \[0,1,1,2,1,3,2,3\], and the maximum is max(0,1,1,2,1,3,2,3) = 3. **Example 2:** **Input:** n = 2 **Output:** 1 **Explanation:** According to the given rules, nums = \[0,1,1\]. The maximum is max(0,1,1) = 1. **Example 3:** **Input:** n = 3 **Output:** 2 **Explanation:** According to the given rules, nums = \[0,1,1,2\]. The maximum is max(0,1,1,2) = 2. **Constraints:** * `0 <= n <= 100`
Keep track of how many positive numbers are missing as you scan the array.
Array,Binary Search
Easy
2305
636
hello and welcome back to the cracking Thing YouTube channel today we're going to be solving lead code problem 636 exclusive time of functions before we do you guys know the drill like and leave a comment on the video it helps so much with the YouTube algorithm all right let's read the question prompt on a single threaded CPU we execute a program containing n functions each function has a unique ID between 0 and N minus 1. function calls are stored in a call stack when a function call starts its ID is pushed onto the stack and when a function call ends its ID is popped off of the stack the function whose ID is at the top of the stack is the current function being executed each time a function starts or ends we write a log with the ID whether it started or ended and the timestamp you are given a list of logs where logs of I represents the ith log message formatted as a string function ID colon start or end colon timestamp for example zero start 3 means a function call with ID 0 started at the beginning of timestamp 3 and 1 and 2 means a function call with the function id1 ended at time two note that a function can be called multiple times possibly recursively a function's exclusive time is the sum of all the execution times for function calls in the program for example if a function is called twice one call executing two time units and another call executing for one time unit the exclusive time is two plus one equals three return the exclusive time of each function in an array where the value at the ith index represents the exclusive time for the function with id1 me that was a lot of reading Jesus Christ is this an English exam or a lead code question anyway as you can see there's an absolute wall of text here let's get rid of this and actually look at an example because there is all room to actually do anything here so I'm gonna erase this and I'll be back in a second we wiped away all of that text now let's actually solve the question and we're gonna have a few functions here so I'm going to change my colors as we go but essentially we start function zero at time zero so let's kind of write that and we'll have our number line here and it looks like function zero starts here and then the next function starts at time two so let's kind of write a few things on our number line and it looks like we go up to six just for clarity I'll write it out because it might be a little bit confusing so 6 is kind of the end point there so let's use red to depict function zero so function zero will start at time 0 and it will run up until time two at which point function 1 will start at time 2 and it will actually run until the end of time five so Function One kicks off here at time two and runs all the way to the end of the minute five right and then what's gonna happen then is that function one will resume again because remember it's a single threaded so only one thing can run at a time so it's going to run from the start of the sixth minute until the end of the sixth minute so function zero as you can see it runs for one two three units of time so runs for three units then if we go back to our blue here uh function one will run for how long well it runs here that's one unit here another unit and then here another unit so four so our solution should be uh three four because remember the index here represents the function ID and function zero runs through three and function one runs for four units of time so that's essentially what we want to do uh to solve this question but the way that we do that is going to be a little bit tricky and we know that we have a single threaded function and that we were told to use a call stack so that's actually the data structure that we want to use here is we're going to use a stack to basically represent what is currently running and what was running before because remember we first start function zero and then it's function one right and Function One this is the only function that can ever end right we can't end function zero before Function One ends because it's a single threaded CPU so by definition whenever we get an end uh log that comes up it will always pop the top of the stack because that's how single threaded applications work right we can't have an application in the background finish before the one that's currently running whatever we get an end it's always going to be popping from the top and then we can calculate the difference in the time from when we started and the current time when we're ending and then once we pop the top uh when we get an end then the next one that is currently running will run and it's either going to run until we get another start in which case something will populate the stack or it will end and then we can simply calculate the time difference and put it into our um our array to actually store the results here so that's essentially what we want to do so if we get a start what are we gonna do we're gonna um you know push to the stack push to stack and then if we get an end we're gonna pop from the stack and we're gonna find the Delta of the time right because we obviously have to figure out the time that it ends and you have to be a little bit careful because when you get an end it's actually inclusive right so here it says five and if you accidentally calculated it to the five itself uh that would be wrong you'd get three units but it's actually it ends at the end of five but it starts at the beginning of one so when it says start it's starting at literally two but ending it's actually ending at you know what it is technically times six uh right before then so you have to be careful about that when calculating the Deltas but other than that's the idea when you get a start push it to the stack and keep track of the time when you get an end pop it from the stack and then we just need to calculate the Delta so how we're going to do this is actually quite simple let's go to the code editor and type this out this question is really simple and not that bad if you can kind of grasp your head around you know this timeline how it works and also around the call stack how essentially you're only going to be popping um you know whatever's at the top because it's a single threaded application so when something ends it's always going to be whatever the top of the stack is you don't have to worry about any of these lower ones actually finishing before because again it's single threaded so that's enough talking let's actually go to the code editor and type this up it's really simple it's probably like 20 lines of code so I'll see you there we are in the code editor let's type this up so remember that we need to return a list where the index is going to be the time that the I function runs for so we're gonna have to create a list for our solution which is actually going to be of length whatever n is right so we'll call it execution times and we will basically just set this equal to zero times n right because obviously we haven't computed anything uh yet so obviously the times are zero and N is the um you know number of functions so that's how long it should be anyway we need a variable to keep track of our call Stacks so let's call it call stack and we'll have an empty list here and we need to keep track of the time when the previous function started because we can use that to actually calculate the difference between when it ends and when it actually started so we're going to say previous start time and this is going to be zero and now we need to actually parse the logs so we're going to say 4 log in logs uh we're going to say the function ID why is it doing that's so weird um I had my code here before anyway that's weird so we're going to say the call type uh so remember that the way it is it's uh the ID so it was like ID the type and the time stamp right so we're going to say function ID call type and time stamp is going to equal to log dot split uh log dot split on colon right so that's how we're going to be doing it and remember that splitting it is going to give a string so we actually need to say it's an integer because we need to use the actual integer to access the index and obviously we can't do that with strings so we're going to say function ID is going to be an INT of whatever function ID is and we also need to do the same thing for the timestamp because obviously we can't do math with strings so we're going to call integer on the timestamp and there we go we have processed that part of the result now obviously we have two types of you know call we can have it can either be an end of a function or the start of a function so we're going to say if call type equals to what if it's a start what do we want to do remember uh what we want to do is we want to basically put something onto the stack right so if we have a call stack so basically if something was running before then we need to update the amount of time that thing was running and remember the amount of time that it was running for was whatever the time was when it started minus the current time so if we have something on the call stack then we need to account for the time that it just spent running so we're going to say execution times of whatever is on the top of the call stack so call stack of minus one we want to add to that value in execution times because remember in the call stack we're just going to put the function ID and we want to put we want to add to the value because we want to sum the amount of time that it's just been running and that is going to be the current timestamp minus the previous start time so previous start time was when the last function started running obviously timestamp is our current function and we want to update the time for whatever the previous function that is running in execution time so we want to take account of the time that it's been running since basically started because now we're calling the function I guess recursively so we want to basically or some functions being called inside of R1 so processing for the current function is going to stop and the next one is going to begin so now that we've done that we actually want to add you know our current function to the call stack because it's starting so now the current function that's running is whatever function ID is and then what we want to do is we want to update the previous start time so obviously the new start time when this function started running is our current timestamp so we're just going to assign that to timestamp and that's all you have to do if it is a start Command right otherwise it's an end command so let's take care of that so we're going to say execute oops exit execution times so remember the top of the stack is the function that's currently running and obviously we just got an end command so we want to process that so we're actually going to say callstack dot pop so we're going to pop from the top of the call stack which is going to give us the function ID that's currently running and to that value in the actual execution times array we want to add the difference between the current timestamp and the previous timestamp where the function started which we store in prevstart time but remember since the endpoint is actually inclusive we need to actually add one to account for the fact that we are including that endpoint because remember the end is actually up until the end of whatever the timestamp is like we saw in the example if you actually don't count it and just use the difference between the timestamp and the prep start time you're actually going to have an off by one error so make sure that you have this plus one here now the last thing we need to do obviously our function has now ended and whatever is next in the call stack can now begin and it's actually going to begin at you know whatever um you know the timestamp plus one is right so basically our function runs up until the timestamp and then on the next one uh so timestamp plus one is actually when it starts up again because remember this time stamp is it's going up until the end of it so be careful with the boundaries here you do need these plus ones here otherwise you'll throw yourself off so that is how you handle starts and we just handled ends so all we need to do now is simply return turn the execution time so um where's my submit okay let's just find it let me make sure I didn't make any syntax mistakes and it looks good here so let's submit this and ah okay so we are accepted brilliant okay so let us think about the time and space complexity here so time complexity wise as you can see we go over all of the logs and we do it once we process each one individually so this is going to be Big O of n because we just have to process every single log there are n logs in our thing here so it's just going to take Big O event time to process them all for the space whoops so spit time is Big O of n space is also going to be Big O of n because we need this execution times uh which is essentially going to store our result here and this is obviously length n where n is the number of um you know functions we have and then also we have the call stack which is going to be dependent on the number of logs we have in the worst case we're just going to have uh the recursive functions happening at the beginning so that means that half of the array would be taken up uh in the call stack and then we would actually start popping them so this is where we get the Big O event so that is how you solve this question Big O of n on the time Big O of n on the space I implore you if you didn't quite understand this part to go back in with the diagram and kind of walk through it uh piece by piece and see how it works but essentially the thing you have to remember here is that it's a single threaded machine right which means that whenever you end a function uh that will always be whatever is at the top of the stack right you cannot finish something below it because it's single threaded so whatever is currently running needs to finish before anything else can start up again so that is really the crucial part to understanding this question everything else is kind of just like mechanically actually coding it up anyway that's enough blobbing hopefully you enjoyed this video if you did please leave a like and a comment it helps me tremendously with the YouTube algorithm otherwise if you want to see more content like this subscribe to the channel if you want to join our Discord Community which uh we basically talk about all things Fang Lee code questions interview preparation system design you can have your resume reviewed by me you can ask me random questions if that sounds interesting to you join the Discord Channel otherwise thank you so much for watching and have a great rest of your day
Exclusive Time of Functions
exclusive-time-of-functions
On a **single-threaded** CPU, we execute a program containing `n` functions. Each function has a unique ID between `0` and `n-1`. Function calls are **stored in a [call stack](https://en.wikipedia.org/wiki/Call_stack)**: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is **the current function being executed**. Each time a function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp. You are given a list `logs`, where `logs[i]` represents the `ith` log message formatted as a string `"{function_id}:{ "start " | "end "}:{timestamp} "`. For example, `"0:start:3 "` means a function call with function ID `0` **started at the beginning** of timestamp `3`, and `"1:end:2 "` means a function call with function ID `1` **ended at the end** of timestamp `2`. Note that a function can be called **multiple times, possibly recursively**. A function's **exclusive time** is the sum of execution times for all function calls in the program. For example, if a function is called twice, one call executing for `2` time units and another call executing for `1` time unit, the **exclusive time** is `2 + 1 = 3`. Return _the **exclusive time** of each function in an array, where the value at the_ `ith` _index represents the exclusive time for the function with ID_ `i`. **Example 1:** **Input:** n = 2, logs = \[ "0:start:0 ", "1:start:2 ", "1:end:5 ", "0:end:6 "\] **Output:** \[3,4\] **Explanation:** Function 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1. Function 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5. Function 0 resumes execution at the beginning of time 6 and executes for 1 unit of time. So function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing. **Example 2:** **Input:** n = 1, logs = \[ "0:start:0 ", "0:start:2 ", "0:end:5 ", "0:start:6 ", "0:end:6 ", "0:end:7 "\] **Output:** \[8\] **Explanation:** Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls itself again. Function 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time. Function 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time. So function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing. **Example 3:** **Input:** n = 2, logs = \[ "0:start:0 ", "0:start:2 ", "0:end:5 ", "1:start:6 ", "1:end:6 ", "0:end:7 "\] **Output:** \[7,1\] **Explanation:** Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls function 1. Function 1 starts at the beginning of time 6, executes 1 unit of time, and ends at the end of time 6. Function 0 resumes execution at the beginning of time 6 and executes for 2 units of time. So function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing. **Constraints:** * `1 <= n <= 100` * `1 <= logs.length <= 500` * `0 <= function_id < n` * `0 <= timestamp <= 109` * No two start events will happen at the same timestamp. * No two end events will happen at the same timestamp. * Each function has an `"end "` log for each `"start "` log.
null
Array,Stack
Medium
null
243
hello everyone in this video i'll be talking about lead code question number 243 shortest word distance so given an array of strings words dict and two different strings that already exist in the array word one and word two return the shortest distance between these two words in the list so we are given a list of words or an area of words strings and we are given two words word one and over two which are part of this array now we want to find what is the distance between these two words and the words can repeat multiple times so if you see here makes is twice and again makes this twice so we want to give that distance between coding and practice uh which is like one two three now the practice has index zero one two three so three minus zero is three now makes and coding so makes encoding is this one comparison is this other one is this so this uh gap is less so we should return this so let's start coding it the way we will do is we'll keep two variables to track to find um the index of each of these words in the given array we will basically traverse the array and we'll keep noting the index of both the words and then at the same time keep recording the least distance between these two indexes that we found okay so that's the basic logic so let's get started we will say okay i want index 1 is equal to minus 1 as initialization index 2 as minus 1 and then we will basically have a min parameter which is basically equal to integer dot max value and then we iterate over this array okay and we say um like we can iterate or like we need to know what is the index of this currently being traversed uh words list words dictionary dot length okay i plus okay now we say if this word uh of i okay dot equals word one then we record its index okay similarly we do the same for second word this is index and then we say if index one is not equal to minus one because we initialized it at minus one and they have updated their values and index two is not equal to minus one in that case you record the minimum of this distance so math.absolute this distance so math.absolute this distance so math.absolute of index one minus index two this way you are keeping track of the minimum and then you return the minimum let's see if that works i hope this was useful and please like comment and share this video and do subscribe to this channel i'm going to give more videos on similar questions thank you
Shortest Word Distance
shortest-word-distance
Given an array of strings `wordsDict` and two different strings that already exist in the array `word1` and `word2`, return _the shortest distance between these two words in the list_. **Example 1:** **Input:** wordsDict = \[ "practice ", "makes ", "perfect ", "coding ", "makes "\], word1 = "coding ", word2 = "practice " **Output:** 3 **Example 2:** **Input:** wordsDict = \[ "practice ", "makes ", "perfect ", "coding ", "makes "\], word1 = "makes ", word2 = "coding " **Output:** 1 **Constraints:** * `2 <= wordsDict.length <= 3 * 104` * `1 <= wordsDict[i].length <= 10` * `wordsDict[i]` consists of lowercase English letters. * `word1` and `word2` are in `wordsDict`. * `word1 != word2`
null
Array,String
Easy
244,245,2320
81
hello everyone welcome back here's van damson and today we are diving deep into a fascinating problem from a liquid daily challenge search in a rotated sorted array too so if you are interested in how we can apply binary search in a rotate it all right possible with duplicates uh you are in the right place and don't forget to check the description below for a code in other programming languages like rust go C plus and much more okay so here is the premise uh we have sorted array that has been rotated as some unknown pivot and our task so yeah this is uh sources RI and it was uh pivoted and our task is to determine whether a Target value exists in this alternate array and sounds simple uh yes but there is a catch our RI can contain duplicates so let's visualize uh example so given array of two five six zero uh one and two let's consider a test case when we need to find Target of two so we start with a simple binary search so left pointer right pointer mid value then we consider going right and our left Prem pointer become middle plus one and if it was for example somewhere to the right so right pointer right Prim we call middle -1 so pointer right Prim we call middle -1 so pointer right Prim we call middle -1 so s in classic binary search and then we have our M Prim so new MID and we do uh yep change uh left pointer so it will be left to and our new M2 will be here so we immediately return uh true because we have found our value of two and basically if we have found this value or this it doesn't matter we return uh true but the trick here is imagine that we have uh almost uh yeah array with duplicates so basically flat array will be a sorted array with duplicates and then if just one element will be somewhere at the end or other considerations so in worst case scenario it could become all and time complexity rather than uh or a log and a Time complexity as in binary research due to duplicates and uh yeah so it's basically uh harder than uh without duplicates because we cannot see the gradient in some particular test cases so let's Implement our binary search so low high will be 0 Len num minus one and now while low less than High meet will be low plus High divided by 2 without remainder uh num meet will be Target we return immediately through okay so this was the uh easy part so we are using a binary search as you can see and here low and high represent our current search boundaries so uh we calculate the midpoint mid to check the middle element uh of our current range so now if our midpoint value is the target Bingo we have found number and will return true but what if it's not that simple so duplicates can be tricky if our leftmost value and midpoint value are the same we can determine which half is sorted so we move low one step to the right and continue our search so if we cannot determine the sorted half due to duplicate if num low equals num meet low plus 1 continue and then if left half is sorted okay so what we are doing here so duplicates can be tricky and as mentioned previously because we cannot determine what half was sorted it might be possible that in worst case scenario the time complexity will be linear so now we have if num low and this ensure we are not stuck in infinity loop due to duplicates so now let's check which half of our array is sorted if the left half is sorted uh what we do is if num low less than num mid so it's sorted and if num low less than Target Nam meet hi I meet minus one so we change the pointer and else low will be mid plus one so this part is uh as in classic binary search but we make sure uh in what uh have our Target lies within this sorted aha so uh we will adjust our height pointer to Mid -1 if not we look in the pointer to Mid -1 if not we look in the pointer to Mid -1 if not we look in the right half by adjusting our low pointer and if the right half is sorted then if right half is sorted else so if num less than Target less than num hi low meets plus one else High mid minus one and return false so we return Force at the end because we have now found nothing so what we did we adjust our pointer similarly based on whether our Target might be but for the right half so and that's it if we exit the loop so main while loop here without finding anything so just without returning true we return a force in the end so that's it so let's run it for uh this simple test cases so as you can see Zero is in Array so we return true a free is not in the array so we'll return a false so really simple and Visually for small data is obvious so let's run it for on synthesis cases so hopefully it will run yes so we have completed it successfully and our implementation bit 94 with respect to runtime and 47 with respect to memory so it's quite memory and runtime efficient uh yeah and binary search is a powerful Tool uh and with a few tweaks uh like in this case we have adapted it for a more complex scenario so it's elegant efficient and uh fun so I hope you found this deep dive helpful if you did please give this video a thumbs up and if you have any question or inside drop them in the comments below and remember the code in other languages is in the description and most importantly keep practicing keep coding happy coding and see you next time
Search in Rotated Sorted Array II
search-in-rotated-sorted-array-ii
There is an integer array `nums` sorted in non-decreasing order (not necessarily with **distinct** values). Before being passed to your function, `nums` is **rotated** at an unknown pivot index `k` (`0 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,4,4,5,6,6,7]` might be rotated at pivot index `5` and become `[4,5,6,6,7,0,1,2,4,4]`. Given the array `nums` **after** the rotation and an integer `target`, return `true` _if_ `target` _is in_ `nums`_, or_ `false` _if it is not in_ `nums`_._ You must decrease the overall operation steps as much as possible. **Example 1:** **Input:** nums = \[2,5,6,0,0,1,2\], target = 0 **Output:** true **Example 2:** **Input:** nums = \[2,5,6,0,0,1,2\], target = 3 **Output:** false **Constraints:** * `1 <= nums.length <= 5000` * `-104 <= nums[i] <= 104` * `nums` is guaranteed to be rotated at some pivot. * `-104 <= target <= 104` **Follow up:** This problem is similar to Search in Rotated Sorted Array, but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why?
null
Array,Binary Search
Medium
33
91
hey so welcome back in this another daily code problem so today it's called decode ways and let's take a peek at it so essentially it's a dynamic programming problem that's like a medium level one and all that you want to do is you're given a string here and you want to translate it into like letters from A to Z and what those numbers kind of map to is like a one-to-one relationship between like a one-to-one relationship between like a one-to-one relationship between like one and it's corresponding like uh uppercase alphabetical number and so really like it goes 1 to 26 where really it's the first letter of the alphabet all the way to the last letter of the alphabet which is z or Z and so really what this would be is like two three what kind of map to B and then the letter c and so forth okay just from left to light right there all right and so what you can imagine here is that say if you have the number 12 here which I believe is yeah the first example this can actually map to two different uh possible ways one is you could kind of consider the split happening in the middle here where it's kind of a and then the letter B here or you could just visualize it as just one number so really just the number 12 and that would then map to I believe L which is the 12th letter of the alphabet okay and so that's great so you'd return to that case because you found two possible like combinations or permutations or whatever the right word is for it and so if you have 26 well that gives you three possible combinations and so while I explain this one I'll kind of map out what the recursive um uh what do I call it recursive nature recursive there's a word for it but I'll show you the pattern the recursive relationship that's happening here that's the right word so if we have 2 6 we can first consider either just two or we can consider 22. right and then from 2 if we expand this we could either consider as two space two or we could consider as 2 space 26. and then finally from here you can just consider it 22 which you already have and then just Space six and then the last thing that we can expand is from here which is 2 and then we would add an additional space for six and that's how we get these three possible paths which results in our answer here of three okay and so what you see here is at every point you can kind of go down up Mo at most two possible paths and that's where okay you can either consider just adding one extra digit or if you have two digits and that digit is within the range of 10 um to 26 because it really has to be out at least 10 if you have two digits and the last letter of the output is z or Z and that maps to 26 here okay so if this doesn't make quite enough sense we're gonna do the uh that top-down memorization solution so that top-down memorization solution so that top-down memorization solution so that you can kind of better visualize it so let's go ahead and Implement that so what we're going to return is our dynamic programming function here which will Define just right here and typically you start at zero because you're going to go from the leftmost digit from left to right onwards to the final digit here and so you just start at index zero and the first thing that we're going to want to do is Define our base case and that scenario we're just going to say okay if we reach the end of our string then naturally we found um I'm not sure oh I actually changed my keyboard there we go and so naturally we found a possible combination or path here so that's just okay if the length of our string is less than or equal to where we are currently then we found a possible path and so we kind of get a point if we reach this uh case and we just return from there and that way we kind of propagate that answer upwards the other base case that we have to consider is okay otherwise if s at I is zero then we're gonna just stop right there and return early the answer is zero and that's just this scenario here where okay if we have zero in here we can't map it to anything because you have to have at least one and so in that case we just want to quickly abruptly return zero all right so that finishes our base case and now we kind of have those two possible paths that we can go down and so what that is okay one scenario is we just return the current step plus one all right and that's just the path where okay let's just consider the next digit but we also have that other case where we want to consider both um One Step or we also want to be able to consider um Two Steps from this point all right and so basically this is just going to be an if else case and so we know that we can consider both of these paths if we find that it's within the range of uh like at most 26 otherwise we don't want to consider like anything else from there and so that all that is okay if I is less than or equal to the length of s minus one because we don't want to go to Out of Bounds here and so and we just want to make sure that we're within that range of uh 26 at this point and so because we're dealing with strings here we're just going to have to convert it into an integer and so in Python you can just slice it and so it's just from I oh I to I plus two we're not doing I plus 1 because uh it's not inclusive in Python so you just add an extra one here some people do like I plus one but we just do that and we just want to make sure that this is less than or equal to 26. all right and so this will work but the only thing or it won't work because the last thing that we have to do is just cache this and so this just converts the function here into a what do you call it a kind of a lookup table where the key is the uh parameters and then the value that it's returning is whatever is being returning at that point in this function so let's run this oh looks like we have a problem here and so what could that be ah we want to make sure that this is that and success so sorry about that we were just kind of considering too many cases here and we didn't want to go out of bounds there so we just want to limit it to this particular scope all right and so let's go ahead and try submitting it and success so for time and space complexity um basically it is O of n time but then also o of n space because well we're caching here and it's a recursive function but because of the caching and the added space we're using it's allowing us to not get like a time limit exceeded in Lee code or tle so that we're bounded to just o of n time complexity as well you can actually do a bottom-up approach that enables you do a bottom-up approach that enables you do a bottom-up approach that enables you to do of one space complexity but for today I thought this was enough for me but feel free to look at the solution to see um how you can do a bottom-up see um how you can do a bottom-up see um how you can do a bottom-up approach that allows you to save on some space here but this is pretty good and you can also convert this if we look at another one of my submissions um I believe this one here you can convert it also to a bottom up with the same space complexity of oven um very easily where basically you just create a DP array instead of doing it recursively and you just preset the first two Apostle paths to one because naturally there's only one possible way to start and then you just move forward always considering the step previous of it um and if you can and you're within these bounds of 10 to 26 then let's also consider the possible permutations that you can get at the step two steps behind it okay better different way of thinking about it I won't go too depth or too far in depth explaining this I'll just stop here but if you want to stop and pause the video and take a look at this feel free to do it but yeah I hope this helped a little bit um and good luck with the rest of your algorithms thanks for watching
Decode Ways
decode-ways
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: 'A' -> "1 " 'B' -> "2 " ... 'Z' -> "26 " To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into: * `"AAJF "` with the grouping `(1 1 10 6)` * `"KJF "` with the grouping `(11 10 6)` Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`. Given a string `s` containing only digits, return _the **number** of ways to **decode** it_. The test cases are generated so that the answer fits in a **32-bit** integer. **Example 1:** **Input:** s = "12 " **Output:** 2 **Explanation:** "12 " could be decoded as "AB " (1 2) or "L " (12). **Example 2:** **Input:** s = "226 " **Output:** 3 **Explanation:** "226 " could be decoded as "BZ " (2 26), "VF " (22 6), or "BBF " (2 2 6). **Example 3:** **Input:** s = "06 " **Output:** 0 **Explanation:** "06 " cannot be mapped to "F " because of the leading zero ( "6 " is different from "06 "). **Constraints:** * `1 <= s.length <= 100` * `s` contains only digits and may contain leading zero(s).
null
String,Dynamic Programming
Medium
639,2091
7
yo Chuck what the Chuck is up YouTube in this video I'm gonna go over Lee code 7 reverse integer so as you may imagine we're just going to take a number and reverse it this is going to be a little bit trickier if the number is negative but we can just do a simple test for that and it's not too bad the constraint we have is our number needs to fall in between this range and that also is easy to implement we cannot store the range however in a variable that is just one of the constraints in this problem so typically the way people solve this problem is they take a number and convert it into a string then they take that string convert it into an array then they reverse that array and then they combine those values back into a number now it's reversed so I'm going to show you a bunch of different ways to do that but then I'm also going to show you the best solution to my knowledge which we can actually reverse a number just using math operations and of course that's going to be much faster okay let's hop into the code sweet so here is my function I just copied it off of leak code and I'm passing in negative one two three and I need to reverse this so the first thing I want to do is just return the number to make sure it's firing so let's run this code and we return the number as we would expect that's good so I need to test is this number less than zero and if it is then I'll make a variable called negative and I will set it initially to false but I'm going to say if the number we pass is less than zero the negative will be true and this is just to make sure that I have the correct value at the very end I can make it negative right okay so from here what I want to do is convert this value to a string so then I can use some reverse methods to actually reverse the number so I'm going to say x equals x dot to string now if I do that and return well I gotta return X for turn X if I do that you can see I have now a string number you can tell it's a string because it's no longer yellow in the console okay so I actually want to get rid of that negative sign so I'm going to make this an absolute so I'll say math absolute and then I'll pass in that X right here just like that and now my string number is no longer it doesn't have that negative anymore okay so like I said we can't actually reverse this string until we make it an array so I need to make this an array I'm going to do that with the split method recall that I must make this an array because strings are immutable which means that you can't change their value at an index but arrays are mutable and you can change the value at a specific index so now that I've converted this string to an array what does it look like looks like that it's just a array of digits and each of those digits is a string of value Okay so there's a bunch of different ways we can reverse easiest way is using the built-in reverse method in JavaScript built-in reverse method in JavaScript built-in reverse method in JavaScript just like that and now we have reversed our array so now we need to basically bring this back to a number form so I'm going to use the join method here and say join just like that and now I've joined this number but it's still a string okay so to make it a number again I'm going to use the number object and just wrap everything that I just created right there save that guy and then run it you can tell it's a number now because it's yellow so now I have my number right okay so if my number is negative I want to make sure to times it by negative 1 to make it negative again at the end because remember we use math absolute value here to get the absolute value so we need to change it back if it was negative so I'll say if negative equals true then I want x times equals negative 1 because that is going to be my number times itself times negative 1. so let's see what happens so now we're returning a reverse negative three two one but recall from the problem statement we have to fall in this range right here of numbers but we cannot store that 32-bit numbers but we cannot store that 32-bit numbers but we cannot store that 32-bit integer number as a variable so what I'm going to do is back in my code I can say return X is less than math dot pow pass in two to the 31st power and X is greater than math dot pow negative 2 and then passing the 31st power so I'm going to put this all in parentheses like this and then I'm basically going to use a ternary operator here so if this condition is true this is basically saying if x Falls in the appropriate range that they've dictated in the problem statement back here right so if x Falls in this range that's good we can just return X and the way you do that with a ternary operator is you use the question mark and you would just say return X so imagine this question mark is like an if statement right and then your else statement is going to be a colon and then you're going to pass in whatever happens if this isn't true if this statement isn't true right here so you would just pass in zero because the problem statement says Hey return zero if your number does not fall in that range so now if I run the code I still get three to one right what would happen if I passed in an absurdly large number like this I should get zero right or I guess this would be a crazy uh large negative number let's try with a very large big number I also get zero so that's what we want for our test case so that looks good let's run this code and see what happens in lead code so I'm going to put it back in here paste it submit looks good so it definitely works okay so that was one way to reverse a number or an integer I want to show you different ways of reversing that doesn't rely on this built-in reverse method rely on this built-in reverse method rely on this built-in reverse method so what I'm actually going to do here is just get rid of this let's return X at this point so I can show you what it looks like um let's get rid of this return X oh we have a syntax error because I removed a parenthesis we actually want to convert this back into an array right now the number is just a number because I'm using that number wrapper um let's delete this code and make math absolute value of x to string and then we're going to convert this string of numbers are yeah the string number into an array I'm going to use the split method for that and now we're back to where we were unreversed so we want to reverse these numbers and I want to show you different ways we can do that so a fun way to do that might be to make two pointers I'll say left equals zero and right is going to be x dot length minus one because recall X right now is an array so x dot length minus 1 would be index two and then obviously zero would be index 0 right here so basically making two index values and I'm going to use them to swap each other so I'll say while left is less than right we're going to perform a swap you can do this by making a temp variable storing the value of x at index left setting X at index left equal to X at Index right so I'm just setting these different index values equal to each other or the digits at that respective index equal to each other and then I'm going to set X at Index right equal to temp so set this equal to Temp and now because you imagine I've got those two pointers at either ends of my digit so I've got a pointer here and then I've got a pointer here I need to have them basically meet together so I'm going to say left plus and then right minus okay now we're going to return X again let's see what happens you can see we've reversed it right so instead of using that built-in so instead of using that built-in so instead of using that built-in reverse method that JavaScript gives us we've just basically just done the same thing but we've used a while loop with two pointers and from here I can do the same thing that I did before so I'll say x equals x dot join so I'm going to turn this array back into a string right there and then I'm just going to wrap this in the number object you can see we have our number let's get rid of this return statement so we have this if conditional down here okay if I return that looks good let's run this in Lee code back to our submissions put this guy in there run it and that also is valid so that looks good okay I want to show you another way to do the same exact thing we just did we're no longer going to use reverse method we just use the while um Loop to basically perform that swap you can actually perform that swap with a for Loop too let me show you that so we'll make a variable called I is less than x dot length because remember X is still in an array at this point and while that is true I'm going to increment I am going to get rid of these index values of left and right since we don't need them anymore okay so just to recall on return X and go back to my console and run it and you can see this is what my x value is right now so I just need to reverse this number so the way to do that with a for Loop we can make a temp variable and set it to the very beginning digit at index 0 initially so I'm going to say temp equals I at index or X at index I and then I'm going to set the x at index I equal to X at x dot length minus 1 minus I so what this is saying is initially I'm going to basically set this index I to the very first value or the first digit right and then I'm also going to have a pointer pointing to the very last digit okay so this is the same thing we just did with the while loop but now you can see my variables they look a little bit different I'm not using index left and Index right I'm using index I and basically x dot length minus 1 minus I is my two index values so I need to just perform that swap just like we were doing actually let's do it like this x dot length minus 1 minus I and then to perform the swap minus 1 minus I equals temp now if we run this code you can see we are reversing our number but wait we actually didn't reverse it we just kept it the same because didn't we input negative one two three so notice here on my for Loop Let's uh console log what my value of x is each iteration I want to show you something so I run this code you can see I'm at one two three then I'm at three two one hey that's actually reversed then I'm at three two one hey that's actually reverse but then I return uh negative one two three what happened there so if you imagine we're doing this for Loop while I is less than x dot length that's actually twice as many iterations as we actually need to perform this swap so what I need to do here is use math.floor and when I take my x dot length I want to divide that by two because I only need half the operations to perform those swaps that are the length of X right because if I perform so many iterations that there are digits in X I'm actually going to reverse too many times and the number as you can see is not even reversed because I did too many uh swaps so I need to do half as many swaps now when we return the number it's reversed okay so that's pretty cool there's actually um even niftier ways to perform swaps let's run this code real fast though make sure it works Elite code we'll come in here to submissions all right it's gonna paste this bad boy yada it works okay cool so this works let me show you the best way to swap so JavaScript introduced an easier swapping syntax so instead of this what we're going to do is just make an array bracket like so I'm going to pass in my X at index I and then also my X at index x dot length minus 1 minus I just like we did and then I'm going to say equals and use the brackets again and then I'm going to just reverse the position of this accident Dex X our exit index I should say and then this one right here so watch How I do this x dot length minus I minus 1 comma exit index I so these are actually saying the same exact thing but you can tell this syntax is like a one-liner and it looks a lot more like a one-liner and it looks a lot more like a one-liner and it looks a lot more clean so let's delete this now if I run the code whoops if I run the code on my terminal I get the same answer let me run this in decode submissions okay here we go plug it in and it still works excellent so that is a little trick you'll see people use this logic so if you've never encountered it before it might look kind of intimidating but it's basically performing that same swap logic we wrote right here so those are the same thing okay now that I've showed you how to reverse and how everyone pretty much reverses an integer by converting it to a string and then converting it to an array and then converting that array into reverse and then combining that back into a number I'm going to show you how to do the same thing but with math operations and this is much faster all right to reverse an integer just using math equations or operations first I'm going to delete all this code we just wrote then I'm going to comment out this return statement and I'm going to make a variable and this is going to be the variable that we return I'm going to call it output initially I'm going to set that to zero so what I'm basically going to do is grab the last digit of whatever we passed in on X and then put it into output so output is going to be initially 0 then the next iteration is going to be equal to 3 then the next iteration is going to be 3 2 then 3 2 1. so I'm just grabbing the value from X and I'm putting it into output okay so I'm going to make a while loop to perform this operation I'll say while X does not equal 0 perform some logic so what I want to do here is obviously I'm going to decrease X by its digit or the last digit it has every time and then I'm going to put that digit into output so the first thing I'm going to do is say output equals itself times 10 okay so the reason I'm doing that is because if you imagine you've got a number say 13 and then you multiply 13 by 10 that gives you 130. if you multiply 130 by 10 you get 1300. if you multiply 1300 by 10 you get 13 000. notice how by multiplying by 10 we add that 0 on the end which is what we want because we want to put numbers into the output all right from X so from here I'm just I initially start at zero so If I multiply 0 by 0 I multiply 0 by 10 rather you just get zero so what I'm going to do is say plus X modulo 10. okay what is x modulo 10 mean modulo is just a reducer so for instance if my x value it's initially one two three if I perform x modulo 10 I'm going to be left with three if I had a number say five six four and I did 564 modulo 10 I'm left with 4. if I did a number say 760 modulo 10 I'd be left with zero notice how by using modulo 10 we can get the last digit on each of these numbers so by doing x modulo 10 I'm just grabbing that numbered value right so 3 for instance and then I'm adding it to Output so output times 10 is still 0 because output is initially zero but then I add the x modulo 10 which is 3. now my output is 3 times 10 equals 30 and then I'm going to add x modulo 10 which is now going to be 2. and I'm going to have 32. so you can kind of see how I'm just adding those values from X one at a time back into output but now I have to obviously decrement X somehow otherwise this will be an infinite Loop that will never stop running so I'm going to say x equals x minus and we have to subtract that modulo 10 value right so I'm going to say x modulo 10 just like this okay so I'm subtracting that 3 and then I'm subtracting that 2 and that one and then we also need to get rid of the zero place because if I just subtract if my X is one two three and I just subtract 3 it'll be 120. so how do I get rid of that zero to get rid of the zero we divide by ten so if I divide by 10 now x equals 12. and then I subtract that 2 again so I say 12 minus mod x modulo 10 which is 2 that gives me 10 and then how do I get rid of the zero well I divide by 10. and now I have one okay so I need to divide by 10 here so let's delete these commented out code and then we'll return output see what happens if I run this we get our number reversed which is really awesome so basically you just got to wrap your head around what you're doing but it's pretty easy Once you kind of grasp like oh modulo 10 just grabs that last digit and then I need to decrement X and then multiply them by 10 gives me another zeros place and then dividing by 10 just does the opposite okay so let's take this and uncomment out our range that we that's acceptable and then instead of X now we're going to put in output so I'll say output is less than that and then output is greater than that we want to return output okay let's run this in lead code and see what happens submissions plug it in here this is going to be much faster I imagine if I submit we'll see what it says yes okay well that's on it all right 80 percentile not too bad I was messing around with it last night and I got to like 99th percentile so usually Math A good rule of thumb is like if you can perform one of these algorithms just using math it's probably going to be faster but yes that is how to reverse a number or integer just using math operations pretty powerful once you kind of figure out how this works okay I hope you guys found this video enjoyable and valuable if you did please like it subscribe and I will see you in the next one
Reverse Integer
reverse-integer
Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`. **Assume the environment does not allow you to store 64-bit integers (signed or unsigned).** **Example 1:** **Input:** x = 123 **Output:** 321 **Example 2:** **Input:** x = -123 **Output:** -321 **Example 3:** **Input:** x = 120 **Output:** 21 **Constraints:** * `-231 <= x <= 231 - 1`
null
Math
Medium
8,190,2238
1,095
so hello everyone myself Aditi and uh today I'll be solving the very first lead code daily challenge problem on YouTube and the question is find in Mountain array the question belongs to 12th of October 2023 and uh the question says that an array is a mountain array if and only if the length of the array is greater than equal to three and if there exists some index I such that elements up to that index I are in strictly increasing order and after which the elements are in strictly decreasing order so in the question you are given a mountain array they are asking you to return the minimum index such that the value at that index is equal to Target so if in case that index exists which at which the value is equal to Target you will simply return the value of that index otherwise you will return minus one and there is one more condition that you cannot access the mountain array directly you can only access using a mountain array interface so what is the mountain array interface uh it is it's it is such that if you have to return the elements of the array at index K you will use this function if you have to return the length of the array you will use this function right so in order to understand the question in a better manner you can take this example let's suppose uh we are given an array which is 1 2 3 4 5 3 1 and the target value is given to us as three now we can clearly see that the values or the elements in this array they are strictly increasing up to five and they are strictly decreasing after five what does that mean it means that five is the peak element right from 1 to 5 five is the greatest and from 5 to 1 again five is the greatest so five is the peak element in this whole array right so this is this gives us some intuition that you cannot you that you can divide the whole array into two parts one up to 1 to 5 another one from 3 to 1 and here or this way we can apply binary search okay so uh in this input you input example we are given Target value equal to three now we have to search for an index at which we get the value three and then we will return the index so let's search do we have value three in the array yes we have spotted three twice right so the first three occurs at index 2 since it is a zero indexed array uh this is zero this is at Z Index this is first and this is second so right uh the this first three uh just exists at an index 2 then this is index 3 this is index 4 and this is index 5 so basically there exists two three right or you can say three exists twice in the array one at index two another at index 5 since you were clearly asked to return the minimum Index right so you will return two and not five I hope this is clear and uh let's take another example we are given 0 1 2 4 2 1 again it is clearly visible that the elements in the array are strictly increasing up to this point that is up to four and then they are strictly decreasing now they have given a Target value as three so let's search for three in the array we can clearly see there is no value that matches the T Target so we'll return minus1 in this case right so let's get back to the code as an intuition we can uh think of binary search and let's see how to implement it so like I said we can only implement it when we have the peak element right so first let's initialize the peak element what can be what should be the peak element should be uh int Peak is equal to find Peak in what find Peak peak in Mountain array uh sorry okay so M uh find Peak is nothing but a function which is used to find Peak in a mountain array itself it is specifically designed for Mountain array and not any usual kind of array so now we'll initialize result okay uh let's initialize result as so before initializing it let me tell you we are going to divide the whole array into two parts and by that I simply mean that firstly I'll divide the array starting from index zero up to the peak element and then I'll uh um just you know use the other part of my AR starting from uh the index Peak + one up to the last the index Peak + one up to the last the index Peak + one up to the last element so obviously like we said we have to return the minimum index we are going to search the target value first in the left side of the array or up to Peak okay so let's search binary search ascending that is in the increasing part that is up to uh the peak element okay so what are we going to pass as our inputs we can just pass our Mountain array okay we'll pass integer Target we will pass uh since we are searching from index zero up to Peak so we are going to pass arguments as Mountain array inder Target zero uh zero index and the index Peak okay so we have initialized the result now as given in the question if we find such index we will return the index otherwise we'll return minus one okay so first we are done when we are done with searching in the left part of the array if we find that result is not equal to minus1 what does this mean this simply means that we have actually found a value or an index at which the value is equal to Target so if we have already found what are we going to do we are going to return the result fine but otherwise what are we going to do otherwise we will just return we'll uh move to the right part and we will start searching for our Target value in the right part okay I hope this much is clear I hope the code part is clear and uh return binary sour descending we'll again pass the arguments as Mountain array okay we'll pass the array we'll pass integer Target we will pass the element starting from the or you can say from where it is descending obviously it is descending from index Peak + one from index Peak + one from index Peak + one till um Mountain array dot length Min -1 right so we'll return this length Min -1 right so we'll return this length Min -1 right so we'll return this now so basically this is the um end result right now in order to find the peak element let's find Peak okay let's find Peak so we are going to find Peak here we are going to pass array as our argument Mountain array okay this is we are taking this method and now let's initialize our left as zero let's initialize our right as Mountain array dot length and uh we have to use the interface right we have to inter you have to use the interface correctly and in order to use its length you have to use this okay so we have initialized left and right now what are we going to do we are going to check while left is less than right we are going to initialize our middle element which has to be equal to left plus right minus left divided 2 okay so we have initialized our middle element and now we'll check if the value at index mid okay if we see the value at index mid is if we see if it is less than the value at index mid + 1 what does this value at index mid + 1 what does this value at index mid + 1 what does this imply this simply implies that the middle element is not the peak element we are still continuing in the ascending part so this simply means that mid + 1 part so this simply means that mid + 1 part so this simply means that mid + 1 is also greater than mid right so basically mid is not the peak okay and uh up till this condition is met what are we going to do we are simply going to assign left as the mid + simply going to assign left as the mid + simply going to assign left as the mid + one value okay otherwise what are we going to do else we will just assign right to Mid okay I hope this is clear and uh I hope this is clear now uh after this we will return left okay now we are going to search our Target value in the left part of the array or you can say we are going to search it up to the peak element so binary search ascending what are the parameters we are going to pass Mountain array we are going to pass our integer Target we are going to pass integer left integer right okay also what are we going to check here now again we'll check while left is less than equal to right what are we going to check we are going to check yeah so we are going to check if integer sorry in mid uh yeah we clearly know mid is equal to right minus left divide divided by 2 and what are we going to check here we are also initializing that mid value as mountain array. get the value at index mid okay so we have initialized it now what are we going to check in the left part of the array what we are going to check we'll just check if the mid value is equal to Target we'll simply return mid okay we will simply return mid but if this is not the case there can be two cases right when the middle value is greater than Target or the other case will be when the middle value is less than Target since we are searching in the left part else if right now uh yeah so what are we going to search again yeah just give me a second guys yeah I hope there is no error and uh sending yeah there is no such error and yeah so we are first for the we'll just search mid value if mid value is less than Target what are we going to do if it is less than Target we'll assign left as mid + one okay otherwise assign left as mid + one okay otherwise assign left as mid + one okay otherwise we will just assign right as mid minus one okay and the same procedure we are going to follow for uh the descending part also otherwise we are going to return minus one and uh yeah let's copy paste the same for the descending part and uh yeah that's because the code remains same the only difference here is you have to check if the middle value is greater than if it is greater than this then left will be mid + one else right will left will be mid + one else right will left will be mid + one else right will be mid minus one and then we are going to return this okay and yeah let's hope it works let's just hope it works okay there is some error in line 13 I hope to find the error yeah so I hope this need not to be mentioned same okay I hope this works okay guys so this is the basic mistake we I did and uh hope there is no other errors in the code see my God so guys yeah I have just found the error so basically what I did is I just copy pasted this and I didn't change this to descending basically there is duplicate occurring for the same function I hope this works let's see yeah so it works now and you can clearly see it is accepted okay let's try to submit the code yeah okay I hope uh the solution works for you and if there are some doubts please post in the comment section also I want to mention one more thing like I'll be um uh eager to post daily challenge videos on YouTube if you feel like also let me know about the language barrier if you want to if you want completely English videos that's fine if you want English or Hindi English mix videos that's also fine I just want you guys to let me know thank you so much for watching
Find in Mountain Array
two-city-scheduling
_(This problem is an **interactive problem**.)_ You may recall that an array `arr` is a **mountain array** if and only if: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `mountainArr`, return the **minimum** `index` such that `mountainArr.get(index) == target`. If such an `index` does not exist, return `-1`. **You cannot access the mountain array directly.** You may only access the array using a `MountainArray` interface: * `MountainArray.get(k)` returns the element of the array at index `k` (0-indexed). * `MountainArray.length()` returns the length of the array. Submissions making more than `100` calls to `MountainArray.get` will be judged _Wrong Answer_. Also, any solutions that attempt to circumvent the judge will result in disqualification. **Example 1:** **Input:** array = \[1,2,3,4,5,3,1\], target = 3 **Output:** 2 **Explanation:** 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2. **Example 2:** **Input:** array = \[0,1,2,4,2,1\], target = 3 **Output:** -1 **Explanation:** 3 does not exist in `the array,` so we return -1. **Constraints:** * `3 <= mountain_arr.length() <= 104` * `0 <= target <= 109` * `0 <= mountain_arr.get(index) <= 109`
null
Array,Greedy,Sorting
Medium
null
480
hey what's up guys this is john here so today uh let's take a look at this number 480 sliding window medium heart problem okay so you know median is the middle value in an other integer list if the size of the list is even then there's no middle value basically um if the number of the wind of the size is odd it's the odd number then the medium is the middle one but if it's the even the number is even then the middle is the middle two numbers divided by two okay and then okay given this definition of the median and then you're given like an array of numbers and there's a sliding window of size k which is moving from the left to the right basically the sliding windows of size k and it asks you to calculate uh each median value of each the sliding window basically while your the sliding window is moved every time when it reaches a new location it asks you to calculate the medium and in the end you need to return the other medium numbers from left to right okay so um i think that the description is it's pretty clear and so i think the brutal force way right i think i believe everyone should have already realized that basically we just need to maintain like this like array of the sliding window and every time when we have a new sliding windows erase we just store it we just sort it right we store the side sliding window and then we use the binary search to find not okay actually sorry not binary search uh we just find the middle one or the middle two numbers okay then we simply uh return the value basically that's the brutal force way right and cool let me try to implement that real quick to give us a starting point okay basically um all we need to do is we just need to maintain like a sliding window here okay and also so when we maintain the sliding windows right we can just uh remove the last card the last number right and then we added the front end the front number so that we can maintain like the size of k okay uh so the way i'm doing it like i'm just going to define like a current array here okay and then uh so at the beginning i'm just giving it like the k minus one okay and then we have our answer here so basically from i in range like k minus one to n right because the reason i'm doing this k minus one is i'm only i initialize two numbers here so that every uh so basically we start from here we start from k minus one and then we uh we loop through until the last one and here so and if the k sorry if the i is greater than k minus 1 right basically if the k is greater than the length of the uh if the length is greater than k then we simply do a pop right we pop the first element by doing the pop zero okay and then after that we add that right we add the current array with the latest number here so basically here we're trying to like uh renew basically to update the sliding window array okay so now we have a updated sliding window we can simply like trying to get the medium right so what's the media basically we have two options right if the k is even okay sorry uh so here is odd if the odd one then we know actually so now we need to do a sorted okay sorry the array equals to a sorted kernel array okay and then the uh the answer is simply the append uh sorted array uh k divided by two okay else if it's even right if it's even one we need to get two numbers okay so what's the two numbers it's the uh k divided by two and what so this two here and the sorted array k divided by two minus one okay and then we need to divide it by two so yeah it's pretty straightforward let's say we have one two three four okay so the k is equal to four okay and when we do the divided by two we uh we have two here two the index two which is pointing to three here so that we need to uh find the ones on the left for the other part of the median right and then in the end we just divided by two okay and then we simply return right i think this should just work yeah submit cool at least it accepted but as you guys can see here it's not that fast it only beats like 11 so why is that it's because of the time complexity here basically as you guys can see for the outer loop we have oh and we have n here right how about the inner loop so for the inner loop we always sort the current array so which is the k times log k that's basically the uh the time complexity for the first you can call it brutal force uh solutions basically we just uh maintain like a sliding window and every time we just sort stored with the sliding window and then we just get the medium directly that's why we have n times k times log k because sorting is a k log k and then on top of that we have an n here that's why it's kind of slow and i mean if it's like just like this solutions here probably this is not shouldn't be marked as a hard problem it would be like more like a medium or even an easy one maybe okay so let's make this one the hard problem is the second solution where uh if we want to improve this okay basically the problem for not right now is the how can we effectively find those two medium numbers or one medium number okay obviously sorting is not that efficient so what's the other way basically uh we can use like a two priority queue to store those two numbers okay why is that because if we split i'm just using like this even sliding window size as an example because this is easier to help us understand the two priority solutions basically if we split uh those uh this array let's say if we have minus one two three four and 5. so if we split this array into two parts so the medium number for this one is basically is the last character is the last number of the first part subarray and the first number of the second part okay and notice that note notice that they are like also all sorted and this part is also sorted and since we don't care about all the other parts all we always care is basically we care about the biggest number right of the first part and the smallest number of the second part so that's why we can use two priority queues basically to maintain the biggest number of the first part and the second part the under and the smallest number of the second part okay since in python you know the uh the priority queue is like the mean the a mini heap so that would just work by work uh by its nature for the second part but for the first part how can we maintain like the maximum number in the mini heap we just need to when we store the number we just need to uh convert it to an active value so that we can maintain the max number i mean respectfully okay and that's that and then how and the next thing is that when we maintain those two priority queues we have to make them balance right so why is that because and um is because you know when we uh insert right when we insert the sorry okay so why is that because when we try to uh do the insert okay we will be insert based on the uh based on the current medium value okay so if the number we are inserting is greater than the current medium values then we'll be inserting that value into the second part if the value is smaller than then the first is smaller than the median value and then we will insert into the first part but if we're only doing that and we're not a balance if we are not balanced those two arrays there it's possible that because the way we're getting the medium is we're always getting the biggest number from the first part and the smallest number from the third part if you're not going to balance these two parts here it will be let's say we have a six and sevens here in later on it will always basically uh append or always be inserting into the into one into the one part in for in this case the second part so in that case the second part will just keep increasing and basically it's not balanced which means the median value will be wrong so basically while inserting the numbers into those two uh two array to separate based on the current medium after that we also need to check the current length of the two parts if they are not balanced then we need to move one values either from this one to the other one or from the left one to the right one and the condition the threshold for that is that you know we cannot if any one of them i mean basically if the right one is of the left one the difference is greater than one then will be uh basically uh balance the uh those two arrays and yeah basically that's the basic idea of how we can maintain those two uh two parts right two sub array of the uh of the medium so that every time i mean we just need to uh either insert or also we need to remove basically once one number is has been moved outside of the sliding window we also need to remove that number from our from either to one of the two arrays right based on the value okay i think that's basic idea here and of course we also need to take care of the uh the even uh size sliding window and the outs sorry the outside sliding with nowhere even sides sliding window and so the way we are doing that is we are always storing the uh so basically if the medium if sorry if the size is odd uh we're always storing one more uh one more ladder and one more numbers on the right side which is the mini q here the mini priority q here so that i mean it's easier for us to uh to get to calculate the medium because uh whenever the left side and right side are different the length is different it we can always like get the value from the mini priority queue which will be the medium at that moment okay cool so with that uh being said let's try to code these things up i'm going to comment out here and let's see uh cool so for this one i mean we're gonna be implementing a few hyper functions but to be to make this one clear more clear i'll be implementing the main logic first basically we have a minimum priority queue okay this one and the maximum priority queue okay so for the minimum priority queue okay uh let me draw this so for the minimum priority q the values we're saving here is the is here okay one two three four five six okay and this is the max q priority q and this is the minimum priority okay basically because the uh you know the priority q is can only guarantee that the first element is the minimum one okay that's why the minimum queue basically restoring the right part of the sliding window of the sorted sliding window and the max q stores the left part okay and then basically in the minimum queue right so the something it will be storing something like this like four five and six or it could be four six five right i mean in the priority queue only the first one is guaranteed the rest is not guaranteed we only guarantee the first one is the smallest one okay so here actually it's like what uh the first one is minus three right minor three minus one or minus two okay because in order to keep the first one the biggest right in us in the mini q here we have to convert all of the members into the mean the negative value okay so um so we have n here equals to length of the numbers right nums okay and then we have answer here okay cool so now let's try to uh look through the numbers here okay so the first one is we always insert okay so we always insert the num i here okay that's how we do the insert we always insert the current one and then when the is equal or greater than k okay which means that i mean let's say the k is equals to three here right so when k when i is three it means here okay so when we are at this moment we know that okay we need to remove we so from this one onward we need to every time when you start removing the last the left most one out of the sliding window okay that's why i'm going to remove the nums uh which number i minus k okay so i'll be implementing the insert and remove later on i'm just implementing the main logic here okay so that's that and so at this moment right so we're having like uh updated same as this one we are having like updated uh sliding window or we have updated mini q and the priority queue sorry the mini q and max q here now we can simply uh get the medium but we only want to get the medium when i is equal greater than k minus one okay which means we only start getting the medium from this uh position here that's the k minus one okay and then we have answers append uh what uh gat media okay cool so and then we just return okay right so basically that's the main idea here okay and now let's implement those uh three uh hopper functions here so the first one is insert uh actually you know what actually the first one should be get medium because we'll be using the get medium in many places okay so what get medium does is assuming we have a updated mini q and a maximum q we just need to uh we just need to get the medium out of from both of the mini q and updated q uh basically if the length if the like i said if the length of the mini q is not the same as the length of the max q priority q okay so we simply return the mini priority q zero so this is for the uh for the out case for all case basically for this case in this case the uh the mini queue okay the mini q will have three and four and the max q will only have like a minus two in this case so in this case the uh we don't need to work care about the maximum one because we know the mini q the first element in the minicube will be our uh medium value here okay and yeah so i mean to do a sanity check here because since we're doing this like in index here we need to make sure there's a value inside that otherwise it will simply return zero because i because we're getting this uh okay because when we do the insert right like i said when we do the both insert and remove both of those helper functions will be using this guide medium so which means even at the first time right when the mini q when both the mini q and max q they are both zero we'll still be trying to get we're still trying to get the medium at that moment so that in that case uh the max priority q and then we simply return zero otherwise when we reach here or when we reach here okay we'll get a index does not exist exception okay so back to our main logic here so this is for odd okay odd size okay and this is like the even size okay so when it's even size what do we get the value from both uh but remember since the number the value we're storing in the max uh priority queue is the it's the com is the negative or it's a converted right converted value when we uh we are trying to get the value we also need to convert it back so which means we're going to have like mini priority queue dot zero uh here it's not a plus it should be minus max priority q zero and then same thing we also need to divide them by two okay cool so that's the definition of the get medium okay and now let's implement the insert okay insert so we insert a number here so first thing first let's get the medium right so both only to the insert either do the insert or delete we always need to get a medium first medium get medium okay and okay cool so here uh if the number is smaller it's smaller than the medium uh i'll let's do that if the number is equal or greater than the medium okay so like i said we are trying to maintain a so in the case of the odd uh sliding window size we're trying to maintain one the medium one with basically one more number in the mini queue here that's why we when we do the we're going to implement when the number is equal we're going to insert it into the uh into the mini queue okay um uh let's see here does this one really matter but let me see here okay but okay let me finish implementing this basically if the number is equal or greater than the medium right we're storing that number onto the mini q here basically the way we're doing it we're gonna do a heap cue dot heap push okay and we're gonna mini priority q and num okay because on the mini q we're storing the original value okay elsewhat else we push it to the other half which is not the max q here but when we do the push the max priority key we need to convert it to the its negative value okay and then after inserting or remove we need to balance the priority queue okay so i'm going to create another helper functions called balance priority queue okay and okay so and so how are we going to balance that right i mean like i said if uh we since we're always trying to make sure the minimum queue is always uh equal or greater than the max q okay so that when we get the median uh wins outside we can always uh only reque uh get the medium from the mini size so that when we do the balance we have two out two steps here the first one is if the length of the max priority q is greater than the minimum priority queue okay so in this case we always try to move one item from the max priority queue to the minimum one so how do we move it basically we're moving the first one basically we keep pop we hip pop the basically the biggest the first number from the max queue and then we push it back into the mini queue uh hip q dot keep push okay and mini priority queue right and the value we're getting here is that remember we always move every time we do a push to the mini q yeah to the mini q right because we are getting the value from the max q okay max priority queue and the value is not is negative here so that's why we also need to convert it back okay so that's when we need to move the product the move element from the max q to the mini q how about from mini q to max q right since uh since one difference since uh if mini q has one more element then the max q it we are fine we don't need to we don't want to move it because we want to make sure the minimum mean mini q will always has like equal or one more element than the max q so that when the only time when we need to move from minimum to max q is the difference is b greater than two which means if the mini vertical minus length of the max vertical is greater than one okay then we need to move basically we just need to opposite move from here uh we need to move into the max q okay same thing here from the mini queue that's how we do the balance okay so which means every time we have an insert we do a balance now the now what not the remove okay remove also remove number same thing here we also need to get the medium number first medium okay and if basically we need to follow the same logic here because that's we need when we follow the same logic then we need we can find out which uh which priority queue we need to move it from basically if this one and then we need to move from the mini queue here right so that's the number otherwise we move from the max queue okay and again after removal we also need to balance the queue the priority queue cool okay i think that's it let's try to run the code here in range x not in uh remove oh sorry uh when we move from the max q we need to do a uh minus one oh and also one more thing is that you know since we're going to do the remove here right and uh the thing is the thing for this remove part is the uh after removing it's not guaranteed that the remaining one is still like a heap okay because we're because the heap q does not uh give us like a remove method and so that we only like use the standard like list remove functions so basically after this removal we also need to co make sure that the heap is still the particle is still like maintained so that's when we need to do a heap hempify here minimum priority queue and same thing here the max queue okay this one accepted let's try to submit the code yeah cool so see this one is faster at least i think there are like more uh the faster ways here maybe by using the tree set in the java but since i'm using python here the only uh option i have here or at least i know is by using like the priority queue so what's the uh the time complexity now uh still first one is still end right how about insert what's the time complexity for insert uh to get medium this is one right so because when we get the medium we always we only get one letters so the first you the at most two numbers from the starting of the priority queue which is one so this again immediate is one so the remaining left is like this is a log n sorry log k um yeah it's a log k here because the hip push is a lock k so that's the insert the issue is i think the problem is not a problem i think the difference is when we do the remove here let's see so i think the you know this part remove and heapify you know this part is like it's not ideal right because i think heapify takes like k log k time something like this right basically you know when you try to remove an item uh from the sliding window right where if you try to remove that item from the priority queue in python since python itself it does not have like this uh this is a beauty like remove method for the heap for the hip cue so here ideally it should take it will take a k time so basically you know instead of unlock k it should be an n k in this case but the issue here is that i use the remove and heapify here so i believe this one is more than nk but i haven't figured out a better way of doing the remove here so i'm just remove it and then uh heapify everything all together i think this part is a little bit slow but i think maybe i can find a better way of doing the remove here later on but for now i think this should i would just stop here since this is already a kind of long videos but anyway i think you guys got get idea here basically the first one is the brutal force basically we always do a sort on each of the uh on each of the sliding window and the second one is the uh we basically we maintain like two priority q a one for the third the left half one half's uh array and the other one for the right half one half array and then we just try to maintain that those two uh the length of the prior queue and then we do that the medium we can simply uh get the first two numbers from those priority queue and then that's it uh cool guys i think that's pretty much i want to talk about for this problem yeah i hope you guys uh like this video okay thank you so much for watching the videos guys and stay tuned bye
Sliding Window Median
sliding-window-median
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. * For examples, if `arr = [2,3,4]`, the median is `3`. * For examples, if `arr = [1,2,3,4]`, the median is `(2 + 3) / 2 = 2.5`. You are given an integer array `nums` and an integer `k`. There is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position. Return _the median array for each window in the original array_. Answers within `10-5` of the actual value will be accepted. **Example 1:** **Input:** nums = \[1,3,-1,-3,5,3,6,7\], k = 3 **Output:** \[1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000\] **Explanation:** Window position Median --------------- ----- \[**1 3 -1**\] -3 5 3 6 7 1 1 \[**3 -1 -3**\] 5 3 6 7 -1 1 3 \[**\-1 -3 5**\] 3 6 7 -1 1 3 -1 \[**\-3 5 3**\] 6 7 3 1 3 -1 -3 \[**5 3 6**\] 7 5 1 3 -1 -3 5 \[**3 6 7**\] 6 **Example 2:** **Input:** nums = \[1,2,3,4,2,3,1,4,2\], k = 3 **Output:** \[2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000\] **Constraints:** * `1 <= k <= nums.length <= 105` * `-231 <= nums[i] <= 231 - 1`
The simplest of solutions comes from the basic idea of finding the median given a set of numbers. We know that by definition, a median is the center element (or an average of the two center elements). Given an unsorted list of numbers, how do we find the median element? If you know the answer to this question, can we extend this idea to every sliding window that we come across in the array? Is there a better way to do what we are doing in the above hint? Don't you think there is duplication of calculation being done there? Is there some sort of optimization that we can do to achieve the same result? This approach is merely a modification of the basic approach except that it simply reduces duplication of calculations once done. The third line of thought is also based on this same idea but achieving the result in a different way. We obviously need the window to be sorted for us to be able to find the median. Is there a data-structure out there that we can use (in one or more quantities) to obtain the median element extremely fast, say O(1) time while having the ability to perform the other operations fairly efficiently as well?
Array,Hash Table,Sliding Window,Heap (Priority Queue)
Hard
295
92
hello and welcome to today's daily lead code challenge today we'll be solving question 92. uh first I'll go through the through my thought process as I come up with the solution later I will compare my solution to the solution of others to see where I can improve my algorithm uh etc uh with that let's begin the question uh question 92 reverse linked list two given ahead of a singly linked list and two integers left and right where left is small or equal to right reverse the nodes of the POS of list from position left to position right and return the Reversed list okay in my own words I'm given a singly linked list very simple and I have to reverse some portion of that inclusively the portion is from left to right where a left is smaller than right so the visual gives it away I have to reverse a portion of that linked list right um and there's a small example I have the head pointing to a linked list that goes one two three four five and if left which points at the second node and right which points at the fourth node uh are the parameters then I reverse what is in between inclusively those two bounds okay and then there's another example where linked list is only one element which yeah I guess in that case we don't actually have to reverse anything so um here's my thinking process I see that actually this is the second um version of this problem I'm assuming the first version of the problem simply asked to reverse the whole thing which sounds probably a bit easier because there we don't have to worry about not having to reverse portions of the list here we do the reversing a list link usually happens in one of two ways either you actually move the nodes in positions meaning that you move the a node's self dot next pointer to another node and the example where we reverse the whole list that would mean that five is now pointing to four rather than the other way around 4 is pointing to 3 is pointing to two is pointing to one that is I would say the harder way and you're doing a hard reorder of the list or reverse there's another approach where we don't have to rewrite next at all what we simply do is rewrite the values so nodes stay in place and next pointer never gets is overwritten but the values in those linked lists get moved and in my opinion that is a easier implementation because we don't have to worry about where next is going to point to and there's probably going to be a ton of edge cases in the case where this is where we're reversing only a portion of that list where maybe next has to now be pointing to another value like for example here I know that I have to remember one the first note and the fifth node and then I have to know that fifth node's next is going to be pointing to the what used to be the end of the sub-linked used to be the end of the sub-linked used to be the end of the sub-linked list but now is the front of the sub-linked list sub-linked list sub-linked list etc so what I'm going to do is stick with a second approach where I simply have to rewrite the values in each of the linked list nodes rewriting the values will be easier because all I have to do is get two pointers to a position where to the correct position there would be the left pointer which points to a node and the right pointer which points to a node when I get them into the right places at the same time meaning that the left would be pointing at two the right would be pointing at four I could call a switch I could replace your values the values would be replaced and we would outcome with the outcome would be exactly what is here and we don't have to move any nodes actually and so I'm going to take that approach instead I believe that it's easier with that let's begin the implementation okay so my Approach was two uh two pointers right a left and a right pointer so let's call this left node which points to head and I'm going to start by putting left node in the correct position I'm going to put left node in the correct position because that's going to get me ready to um that's going to get one of my nodes into the correct place I'll worry about the right node later on I is equal to 1 while left no while I is less than left less than or equal to let's say less than or equal to left I'm going to say no sorry less than because if it's less than then I'm saying left node equals left node or uh next and that's it and I plus equals one all of a sudden will uh print left node value is in the correct place it's going to be pointing at 2. and now the uh print what did I spell print run as usual now we have one of them in correct position we have to worry about getting the other one into the right place standard out at 2. getting the right one into the correct position would be a little bit harder because not only do we have to get it into the right position we also have to be able to very easily move from right to left in that direction moving from left to right is very easy you'd simply call next but how do you move from right to left uh well from right to left you can define a recursive function let's call it Rec with a node and in that Rec function I'm going to say that um okay I'm I want to have a Rec function now so when I point I to it I want to say that if node let's see what is my Approach here I'm diving deep into Rec in the case where node.next is so if node is there then I'm going to say Rec node next and I plus one Rec node next I Plus 1. so this way I'm going down deep into the um into the link list and as a result of this after I executed I am essentially greeted by the rightmost node so let's say node Val if I was to Simply execute this I should let's say a wreck with a head and zero I should see a print of five four three two one let's see if we get that five four three two one great so now all that is happening here uh let me put this into the scope non-local left non-local left non-local left um what's Happening Here is I all of a sudden have access to my right node as well right node is equal to Simply node and now I have my right and my left node I really don't need this what I want now to do is I want to re I want to figure out when I can when I have to make the switch right when I can make this switch so if and the switch that I'm making is dependent on this I is my way of knowing which index I'm in so if I is less than right then I make this switch temp is equal to node Bell node vowel is equal to left node vowel left node Val is equal to temp and when I make that switch I also have to say node left node equals uh node next so what did I do here I checked if my index if my right node is in the correct place I don't actually I'm not iterating through my right nodes the same way as I'm iterating through my left nodes the way I'm iterating through my wrote write nodes is by this recursive function that I keep on exiting out of and happening to be in a previous node so if I is less than right and let's see if that's correct is or should it be I is less than or equal to well if I call this with one then it would be one two three four so it has to be right or equal to then I make that switch temp equals node a node vowel node Val left node.val temp node left node.val temp node left node.val temp and make the switch oh one more thing I want to stop switching my nodes once I get to the middle so this has to be I also greater or equal to right plus left divided by two Okay so now that I call this recursive function but the correct I value I should be able to return my head so in this case again nothing is being switched the nodes themselves stay where they are the values get switched let's hope that this runs smooth and there we go awesome um except not awesome output 5 3 left and right output three five expected five three so I'm guessing that somewhere the condition didn't go through correctly um okay so in this scenario I probably let's just see what the edge case is my guess is that one of these is wrong right is I is smaller or equal to right and if right is pointing at 2 then the first iteration I'm going to have I is equal to one and then I is equal to two next is going to be pointing at null but node is going to be pointing at a right value right node next but if I is smaller equal to 2 which is correct then I should be able to make the switch let me see what I is here oh three five I should have used up that I just I should have used up that test case use test case let's remove these for now let's run this and see where the print statement a second standard out for the two and the one ah so we are going into it but we're doing the replacement twice we only have to do the replacement once let me see if this works okay so my guess is that was the issue what was happening is if you um if you replace the same value twice so for example if we are replacing four and two and then three and then the four and the two again then we're just back at the same place where we started and this condition here was including that scenario okay and there we go so without that we are good we're beating 72 percent uh which is good but not great let's see what faster approaches are there um okay so the approach here is that dummy is equal to list node one dummy next equals head and then pre -cur I'm getting a sense that this in -cur I'm getting a sense that this in -cur I'm getting a sense that this in this case they're actually going with the first approach where you actually move the next pointers rather than the values and let's see if this how they were able to do this they placed a pre-dummy node and a placed a pre-dummy node and a placed a pre-dummy node and a node that precedes the first node first head uh and so pre incur just that find the position I and one to left I have to find the position where current is equal to current.next pre is current is equal to current.next pre is current is equal to current.next pre is equal to pre-dot next so I find the equal to pre-dot next so I find the equal to pre-dot next so I find the position where current is pointing to the beginning of the link list that we have to reverse and then reverse high in range right to left sorry right minus left uh temp is current.next uh temp is current.next uh temp is current.next ah this is way better this is way faster okay so scratch what I was saying in the beginning um I guess what I never really was comfortable with is using this dummy variable to pretend like there's something in front of me in front of the head but what they're doing here is they're saying that dummy is going to be this new node that is the first node the first list node and then they find the correct position for Uh current and previous they find the correct position for current and previous um by iterating through one to left and then for the and then for range right to left I'm going to say temp is equal to card.next going to say temp is equal to card.next going to say temp is equal to card.next temp is equal to current.next that's the temp is equal to current.next that's the temp is equal to current.next that's the node current.next is equal to temp.next current.next is equal to temp.next current.next is equal to temp.next current dot next is equal to temp.next okay I have to think about this visually I have two nodes current and previous I'm making another uh node that is actually next temp current dot next is equal to temp dot next super confused temp is looking one ahead of current so that is essentially the next over we have the current pointing at the center node previous pointing to the left temp pointing to the right I'm saying that current.next is now equal to that current.next is now equal to that current.next is now equal to temp.next which should temp.next which should temp.next which should say that is next so current.next is equal to next temp next is now equal to pre next which should be pointing at current and pre next is equal to temp oh boy I don't know if I can wrap my head around this I might have to draw this out however in the meantime let's try going through with this one here the approach there was that we have a da a dummy node that has a value of doesn't matter and the next of head now I want to have a previous which is for now just equal to none and uh four thing in range one to left I want to get uh current is also equal to um done me and this is head I want to say car is equal to current next dummy is equal to dummy dot next and now for in range right minus left this is what they are doing uh we're I'm going to um I'm going to draw this out I'm not just going to submit this right away so dumb me next so this should work oh pretty they call it pre okay um this works however I want to have this right here so I can see what is going on I can maybe write down what is going on let me give myself some space um what is temp if current is pointing at 2 which in this case it actually is temp is equal to two uh what is sorry temp is current dot next temp is equal to three uh what is current dot next 0.22 current uh what is current dot next 0.22 current uh what is current dot next 0.22 current dot next current.nextap has to be pointing to one in order for this to be reversed current dot next has to be pointing to temp.next what has to be pointing to temp.next what has to be pointing to temp.next what temp is already pointing to three so why would two be all of a sudden pointing to four okay uh Cur dot next is equal to Temp next temp is equal to three so four uh temp next which is temp next what was temp is three and three Dot and three is pointing to four temp.next is now pointing to pre next temp.next is now pointing to pre next temp.next is now pointing to pre next What is pre 3 has to be equal to 1. three dot next is actually two oh my God why is this um how do I visualize this is there a way to reset the test cases recite the test cases if I just print these guys out uh print uh current uh let's say pre current and temp since temp is actually just next so pre Val per vowel and temp vowel and so I should out of this car is spelled with one R um I should out of this the initial thing that I should see is one two three and then I should see one two four I'm really confused because I don't understand how are they not reversing are they just maybe um okay temp is equal okay I don't know if I'm comfortable with just stumbling around for this long um how would I let me do last attempt I'm going to just print everything uh occur what did I have had this five more minutes and then if you don't if you can't watch this anymore then I don't blame you um so there's only two switches that are happening and in the first case why are they not different occur dot next is because I'm only rewriting the next so I'm rewriting the current next the temp next and the pre next the current next I'm rewriting to what used to be n x t I want to call this NXT because it is pointing at 3. so if I am rewriting the current next to be the next that means that 2 is all of a sudden now pointing at through what if I um What If instead of this I do this node equals to dummy next while node print node value node um node next there we go so now I at each iteration I get to see what the linked list turns out to be and why didn't this work because I didn't not have this in the right place um so after the first iteration my linked list looks like one three two four and then one four three two so what actually happened did I just so I'm not switching them I like almost rotating it um my current I'm not gonna try to understand this um and I don't really guess I'm running out of time um that is the I guess the difficulty with these approaches they're not I would not be able to come up with this faster uh but however it is significantly faster so um yeah I guess go with what whichever one is where is better and this one doesn't even run faster so yeah I'm going to show you this but uh please if you find something if you understand the previous one and it's more intuitive then go ahead and use that one all right thanks for watching and I'll see you later bye
Reverse Linked List II
reverse-linked-list-ii
Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_. **Example 1:** **Input:** head = \[1,2,3,4,5\], left = 2, right = 4 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[5\], left = 1, right = 1 **Output:** \[5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= n <= 500` * `-500 <= Node.val <= 500` * `1 <= left <= right <= n` **Follow up:** Could you do it in one pass?
null
Linked List
Medium
206
1,832
Jhaal Jai Hind This Video Will Be Solved In Question Number 10 Researcher Ki Phir Sentences Pan Garam Aur Not Relate Serious Question Research Question Subscribe Sentence Paper of English Alphabet Appears at Least One Example Sentence Quick Brown Fox Jumps Over the Lazy Dog Subscribe To-Do Subscribe to List English Sentence for Example Sentences with Quotes Question Clear Form Ko Alami Ko for Loop and Tractor C Request to Key C Is Worth to-Read C Plus Hai Ki Rasool Ko Middle Make a Bit for This Question Users Function Boolean Necklace Function First Take That Bullion And This Will Take Then Trick This Sentence And Correct 80's Show Fear But Will Do This First Of All Will Make Up The Bullion Flag Outside The Ne Bullion Flight And Will Declare It's True A Note For Everyone Character from the to we will check fat character appears in this sentence and not soth viewers functions with its something like this leg is equal to check gift packing sentence is this sentence and correct 80's through oh they will get flag will check if it to leg I Worth requesting to polls on rape note this article that Britain 's poll 's poll 's poll okay hair supports being about inside this function support series page 2 inch one sentence is not good to check crush lubricating subscribe and share subscribe The Video then subscribe to the Page [ Sangeet] [ Sangeet] [ Sangeet] 108 Last Will Return To You Ajay Ko Once Love Letter Make Up Function On Hai And Traffic Tractor CH In Sentence Dot To Non Arrest That Effect That CHC Is Equal To Which Detail Was True Iles That Retail Spoil The Main Which Basically Difficult Dysfunction And Skimming Is Scene That To Input Fields Of Sentence And Dark Spots 800 Verse Checking For Every Character Sketch In A Sentence Ko Subscribe Now To Receive Jhal Which Will Be Capital Share And Rings Commissioner Of This Seat Translation To Committee And That Sex In Pacific More In The Voice Of Do Something Like This Key Problem Please Or Not Able To Understand Visting Concern During Assembly Open Poll Do Hai So Let's Make This Function Key Static Boolean Check Hai So Let's Used Simply For Roof For Rent I Request To 0 Is Left in a Sentence Start Length I Plus Law Will Mary's Character See Which Will Be Equal to Sentences About 8 Yes Brother Was the Inner Wheeler Maker Green Check This Chakra Knowledge Tips Dedicated Fright and True Hero CHC Equal to See That Britain So Left Right Two Vowels of ranjish and loot and start length ki this is doctor a method 100 words use for example here let's check the sentence share key 120 will give five will give loot 2345 will give oo similarly invisible dot uk remedy unauthorized strs this is the president turn it off
Check if the Sentence Is Pangram
minimum-operations-to-make-a-subsequence
A **pangram** is a sentence where every letter of the English alphabet appears at least once. Given a string `sentence` containing only lowercase English letters, return `true` _if_ `sentence` _is a **pangram**, or_ `false` _otherwise._ **Example 1:** **Input:** sentence = "thequickbrownfoxjumpsoverthelazydog " **Output:** true **Explanation:** sentence contains at least one of every letter of the English alphabet. **Example 2:** **Input:** sentence = "leetcode " **Output:** false **Constraints:** * `1 <= sentence.length <= 1000` * `sentence` consists of lowercase English letters.
The problem can be reduced to computing Longest Common Subsequence between both arrays. Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array. Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n).
Array,Hash Table,Binary Search,Greedy
Hard
null
65
hey everybody this is larry this is day 15 of the may league code daily challenge hit the like button to subscribe and join me on discord let me know what you think uh middle of the month we'll see how that goes and today's problem is rather number so i usually start this live uh and today a little bit slower because i'm a little bit tired so you know if it's a little bit slow just fast forward skip ahead whatever you need to do um but what today's problem is rated number which looks like it's going to be a very annoying problem given a string s return of is a radical number i suspect this one is going to have a lot of i'm going to have a lot of uh wrong answers to be honest but that's you know that's let's just take a look but a number can be you know what are these optional things they don't even give you a test case oh i guess they give you a couple here but uh okay a decimal number an integer okay all right i guess if i'm guessing also obviously i'm not going to just use the library if you can just use the library then it would make this a really silly problem so definitely try to solve it without using pipe or use python but without using pythons like one liner or something like that but um okay this is annoying yeah uh i know that i could use um it's numeric but obviously i'm just trying to uh do it a little bit it's digit i don't consider it cheat just because uh that's just a shorthand for you know checking whether a character is a digit so uh yeah uh okay a decimal number okay so if um so if we if not signed if signed and s 0 in plus or minus then we return force otherwise okay let's write this a little bit differently if this is here if it is signed then we just return first if this is good though we'll just will return uh is number just recursively uh this is true uh if length of s is equal to zero return force i guess i should have done that first to be honest i don't think an empty string is a thing don't let me see well it has to have at least one character anyway so in our case that would mean that's not good um okay a sign character uh the decimal number okay so as that count greater than one return force uh assuming that this is already true that means that this should at least have one otherwise this is really bad um yeah if or x if any now we have to take care of the yi stuff as well oh my that is annoying okay so now you following the ninja jogger let's do the footprint first let's also lower it too lower is it lower too long i guess we'll see also return force um otherwise let's do the g first if e is in star lower um then again let's do return this number of the first part let's do s dot how do i split on that maybe someone like that uh oh maybe just spread like this number exponent let's go to this if number and i think this is a self type whatever so yeah let me fix that i'm just going a lot of cases so i don't think there's anything interesting algorithmically that's why i'm not talking that much to be honest we already take care of the sign by at this point so yeah and uh exponential okay maybe that's right and then if this is still in s dot uh if this is just an s then number that's more or what's it called fraction maybe i forget what it's called i'm really bad today uh and then we do the same thing uh i thought otherwise at least one digit okay so actually that handles five by one digit a dot file by these one digit okay one of the five of them at least one digit four by dot so it could be zero okay uh or zero digits uh at least one digit followed by that followed by at least one digit okay a dot five by one digit so either of these can be zero so either length of number is equal to zero or this and same thing length of fraction is equal to zero or this um i get all of them i don't know to be honest there's a lot a laundry list right so i don't know that this is going to be uh right but yeah why do i just return true i don't know if this ever gets hit to be honest i don't think it should because otherwise i don't know maybe not here but uh let's see 0.1 and there's a bunch of these in the interest of time i'm probably going to just run it and then yolo a little bit but definitely at home i recommend obviously testing all the cases or not or well as many as you can and think about the edge cases that may come from your code um i'm never tired really tired actually not even just over time maybe not here that's not great i thought this is only expected to got one oh hmm wait oh let's see whoops hmm that's not great but let's see that means i maybe missed the case yeah i missed a lot of stuff really okay so the third one is false period okay oh um because this has to have at least one of these are true so yeah uh i guess it's just length of s is greater than one and this stuff okay so that got a little bit better progressively uh what's five one two three four five abc did i not check for that i thought i did oh i was gonna do it after this but then i forgot um okay um yeah i was gonna i had something okay and but i think i just forgot for some reason is this is not true and x is not equal to e for x and s then return force for the alphabets and now my fourth one is incorrect oops what happened want to do 0.1 oops what happened want to do 0.1 oops what happened want to do 0.1 i write fours but it should be true right i think point one is four so i don't factor that so length s is greater than one that's true um and that means that one of these should be good but it's just one why would adding this change one if this is if there's not a digi oh i periods as well whoops um this is so obviously bad and awkward but okay so i'm more goodies but then also a few patties let's see five six seven eight negative 0.1 how does that look good that's the first thing that i do uh but i don't do the yi stuff correctly now that i notice it but that's okay oh because then now this is whatever again so i have to remove the signs but then i still have to remove it from the x portion so yeah so i guess this is false um let's do this first i guess before i do the signs and here it could be without the other one okay so this looks good but you know how confident can you be when you know uh minutes ago you have so many wrong things so let's try all the forced ones as well um i think maybe i do the g once incorrectly actually do i what is the okay let's see okay so i have one that's four from the bottom i also have a lot of default things why is that thing uh that is i will true because this is should i do the period first how do i handle so we do the yi first and then we handle no decimals on the on there has to be an integer i think what i should have done and i didn't is um yeah uh write a decimal or an integer and then define these i think i should have just defined it more uh naturally and stuff all these kind of things that i did what i mean by that is i if i were to do it again i would have two functions one for decimal and one for integer and then just follow it through um actually let's do that again i know that i'm already about wow 14 minutes into this part oh i guess it's just really annoying so uh so let's try again let me print this out again uh i think i just i'm a little bit rusty slash tired and try to rush it but there's no watching it so that's let's get it so okay so you have a but you know the way that if you are able to kind of do it then you know if you use because this is basically like a parser and if you build a positive the way that you kind of think about it then it could be a lot queerer um yeah so let's get let's start over a little bit sorry it's a little bit slow but i hope you were watching it on skip fast forward or whatever but yeah so now we just have is indigent is that's more and okay a rounded number is so now we just have to kind of go through it uh one by one so rather number is a decimal or an integer so you know if this does more s or is that small or sorry it's in the this integer s return true uh or uh okay or there's one you and that's just uh so there's one year so we do the count of these count e is greater than one then we turn force uh we do a split on it so decimal i think for decimal i'm just going to uh change that a little bit so yeah if it's integer s return true because an integer is a decimal that's how i'm going to think about it and then now we will just split um first second is equal to s dot square of e and then we do um the first part can be a decimal and the second part has to be an integer so yeah if it's decimal first n is integer second return true and so actually that's pretty much it um because this is now a definition for an integer oh sorry for a decimal so we actually just returned this okay and now that's more can be these things uh well let's go with integer first it seems easier um so an integer can be contained as sine character so if uh okay i mean that's fine we'll just ignore it so then we'll just skip the first character otherwise it's one of the three as we did earlier which is uh oh wait what okay so now after the first character we just have to make sure that they're all digits i don't know i'm reading this at least one digit a little bit awkward but yeah so now we turn all uh x is digit for or oops for x in s okay and then now for decimal there are three versions as we saw so first if s.count saw so first if s.count saw so first if s.count of period is greater than one we return force otherwise we're first and second is equal to as that spread of period um so yeah and we can actually just do this um yeah the only three cases so yeah if length of first um now let's add this here as well if length of s is equal to zero we turn force and then we also do it again after this i guess just and then here now we go hmm how would i do this in a clean way maybe i don't have to care about it let's just do it if length of first is greater than if is equal to zero well whatever let's just be exhaustive about it because i'm exhausted right now so if this is the case then we return is integer first and is integer of second right otherwise if length of first is greater than zero then price the length of second is zero but that's fine so let me just do integer of first otherwise return is integer of second um well now they can both be zero right so yeah um if length of first is equal to zero and length of second is equal to zero then we return force but otherwise we do all these things yep let's give it a spin to my the new hotness uh has some one-time error 59 hotness uh has some one-time error 59 hotness uh has some one-time error 59 whoops hopefully that's the typo and that's it oh no did i mess up someone oh well there's no period then this is good but yeah um if this is not equal to one then this is false because there's no period and they're not in it we already checked this there that's true huh you should already so this is not true then yeah if there's no yi then we just return this i think all right this is almost all good except for this case which is let's see 11. and let's just print it out yeah okay fine this is very weird so negative let's see is that the one that i'm looking at yeah that's the one that i have wrong negative 0.9 okay why is that wrong negative 0.9 okay why is that wrong negative 0.9 okay why is that wrong so huh it's because that's really hard because it's not an integer because i have this force here but how do i want to address this then this is a weird education because basically what it's saying is that um negative 0.9 um negative 0.9 um negative 0.9 it tries it does this and then this code it finds the period so then this is the first part is negative but we don't do anything about the signs yet so okay maybe we'll just add that here um you know it's a little bit awkward because i think by did no that's not true i forgot about this part here so i was wrong on that so yeah i should have handled it though it's a little bit awkward yeah i'm just going to copy and paste okay so now it all looks okay i think yeah so let's give it a submit it's the code is not great but uh hopefully it's oh man okay until i test that but then now so what happened was that okay and it checks that this is an integer but the second part should not have a sign which i guess is technically true they don't tell you do an integer of it's just all these digit thing is a little bit weird because they should just be more specific because you can have alphabet and that's clearly not good but uh yeah so we'll do what we said earlier yeah and then there's just this one might have had my definition weird my eyes are cannot stay open so my apologies and it's still wrong did i get the science one yeah it's this part as well okay that looks better but and i'm too tired to kind of come up with more test cases so that just give it a submit and hopefully you know second time's a charm and it's good uh yeah i'm not gonna lie like i said my code is not really the most pretty but it does basically just do what they tell you in a very structured way i just spent a lot of time not doing it that way but as soon as i did i think you know it's just about transcribing it to code which at least conceptually is easier to understand uh maybe i don't know uh let me know what you think i'm a little tired right now so i think that's all i have um in terms of complexity we look at each character a fixed number of times um i know there's a lot of recursion but there's only a set number of if statements so um so each character is going to look at like you know a couple of passes and that's it so that means that it's going to be a linear time and we don't really i mean it's stuff like this aside but you know you can definitely do without it you could do it in a queen away in place or something so yeah so michael is probably gonna be linear space for reasons like that but you can do better you can do it in all of uh one extra space uh for that reason uh but yeah uh that's all i have let me know what you think i'm tired as heck so i will see you tomorrow uh bye stay good stay healthy and to good mental health take care
Valid Number
valid-number
A **valid number** can be split up into these components (in order): 1. A **decimal number** or an **integer**. 2. (Optional) An `'e'` or `'E'`, followed by an **integer**. A **decimal number** can be split up into these components (in order): 1. (Optional) A sign character (either `'+'` or `'-'`). 2. One of the following formats: 1. One or more digits, followed by a dot `'.'`. 2. One or more digits, followed by a dot `'.'`, followed by one or more digits. 3. A dot `'.'`, followed by one or more digits. An **integer** can be split up into these components (in order): 1. (Optional) A sign character (either `'+'` or `'-'`). 2. One or more digits. For example, all the following are valid numbers: `[ "2 ", "0089 ", "-0.1 ", "+3.14 ", "4. ", "-.9 ", "2e10 ", "-90E3 ", "3e+7 ", "+6e-1 ", "53.5e93 ", "-123.456e789 "]`, while the following are not valid numbers: `[ "abc ", "1a ", "1e ", "e3 ", "99e2.5 ", "--6 ", "-+3 ", "95a54e53 "]`. Given a string `s`, return `true` _if_ `s` _is a **valid number**_. **Example 1:** **Input:** s = "0 " **Output:** true **Example 2:** **Input:** s = "e " **Output:** false **Example 3:** **Input:** s = ". " **Output:** false **Constraints:** * `1 <= s.length <= 20` * `s` consists of only English letters (both uppercase and lowercase), digits (`0-9`), plus `'+'`, minus `'-'`, or dot `'.'`.
null
String
Hard
8
1,704
Hello Everyone Welcome Dresses Date - Prince House Of Life And Values Date - Prince House Of Life And Values Date - Prince House Of Life And Values Se How Can To Strings Also Like Zur Se Withdrawal Sim Number Of That Bigg Boss Independent Office To This Question Subscribe Notification More Subscribe Itni Problem Guide Subscribe Be That Aaj Bhi Guide User Character of Train Egg Account Number Valve 2819 Awal Sadar Inch Lange Its Only One Olive Oil Service Ring Beach Only One She Hugs Account You Will Quote and Transfers Pay Bills Account Wheels of This Train is Equal to Counts Votes of Very Good Udayveer What is the Difference between files without modulate mode to turn part pure posting dooms to bleed set top with tractors which indicates problems of upper casts and subscribe and it's a key typing character 12th bill set and its quite new fast dam element tweet a the voice of day Bhangarh R mode lord in fu more ger ki same commissioner pipeline entertain true jewels a quora son kishanlal k soegi oh my oh love you and capital hai capital ki kya patel aaye chapter low and finally you were added with hearts and tried to help me to Develop this account Vice President in Doctor Caller Portion now screen that solidarity winter account balance that aunty twithearts up to five meter run started stock index in the chair and its different and bear operating and the global set shubhendu sound and left side for enter i Will Screw Sa Fix Absolute And Text As In The School Intermediate As Global Saif Donnison [ Global Saif Donnison [ Global Saif Donnison That Test 48 Abs Points Available For Committing To Build Strong 15202 Anil Updates Is Dargah Bhram Unfriendly Return At Indian Behind Knowledge Latest All It's Over Gift Super tonic scientific account bill tight index 2001 sidbi length bittu so let's calculate distance best friend and scotland that this film pandey's film baaghi to bill passed in the strength and will power e believe that oo a similar to weight for the part a part time Started Villain Bittu Vitamin And Explained In The Spring Has Always Been Set In This Should Work And Destroyer Of A Tax Code Vidmate That Akshay Dead He You Like To Day Solution And Widows Don't Forget You Like Share And Comment Section Hello All Please subscribe thanks for watching this
Determine if String Halves Are Alike
special-positions-in-a-binary-matrix
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half. Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters. Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`. **Example 1:** **Input:** s = "book " **Output:** true **Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike. **Example 2:** **Input:** s = "textbook " **Output:** false **Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice. **Constraints:** * `2 <= s.length <= 1000` * `s.length` is even. * `s` consists of **uppercase and lowercase** letters.
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
Array,Matrix
Easy
null
107
Marilyn welcome back to another video from the winter forest today nice continue our little challenge today's nickel question is codon finally tree they were all the travels second let's look at a question so you will be given a banana tree and the day you put output expect Apple day it is in route important Apple labor order travels so in here they do two loads in the last one and the first earlier in the last a second one 9:20 and the de Botton in the second one 9:20 and the de Botton in the second one 9:20 and the de Botton in the first one fifteen seven for this Nico question in the early days is normal it was a simple knowledge understand a data structure I think here actually we going to use a queue and you could a go and TQ Java 10 you could have such vanities of knowledge if you haven't no idea what is DQ to him and here also have an event is quite a good one they have a video topic and Fernanda all over the queue we return to method and how we use it is the technology and that he killed data structure to solve it is one we are going to draw that one we're going to use this example to enjoy how it a working in that human so for example we have a receiver a tree not a 3 9 2015 and the 7th we're going to have cute disco dirty kill and ii simply habit and hooray and it actually is they also needed hugh disco Dan interest an interest and it is cute because every Sammy this we only can start a visitor loot a lot I searched all night somebody just a reverse but we don't need it so they some complicity we all salute him from all over da so the first vehicle into the habit s 3 so we came into this reading here was a dream we also and immediately the properties up immediately which was Papa's 3 up and we push them into array mass this popped up we're going to push this one this route a lot left if another employee push to him then if he is right another empty also pushed the you know this stable having finished I must finish a push you also put this one into your result at the moment is embodied when Joseph pushed him we are and then to a second loop are we going to decode this if this nada input it is a human body we going TQ it out must Vedic hue it out so this vines in putting every time we go into TQ something out we check that the left on the right is in wadiyan order whichever these lost left or other empathy yet we don't put them into Q but the Trinity is not embody we push the left an universe then push the right on you he must be popped up this I haven't finished yet these we needed to extra stable so in this one instead of pushing into that is why I didn't increased our we're pushing into the first item then in Kalista so you have at the order so we could so now it'll change you to 3 we have it a and the death in opposition interchange Hunnam and eternity so instead of pushing in the back put on them her artistry instead putting in the Dino position in this without the least because this is no either change to negatives and not finish this one 9 not on the 20 finish it we're going to do non-thesis finish it a mover to here do non-thesis finish it a mover to here do non-thesis finish it a mover to here now we're going to take you this one must vdq check that they have a child or no the left and right they don't have so this Q is input so these trees looking finish about here these they were haven't finished we need to one stable to do that without these are always pushing into the head so in the zero position now you have the output is fifteen seven nine twenty and the three so this is very intrusive the popper and so they have a to knowledge why is got an increased need at least the it is the employment at their cute second see it is the quality cue so every time we pull we started with the root a lot then we check the decent size this is one so one must pop it up either already finished once this is proper upper we push it at a child she even snow another it is now on push it on him if it is not enough we push elected then push the right now we could write our code so what do we need our list then we thought there is at least an integer so this they expect output which was come here so this is the result first we check the edge condition so if it is the root is an implacable tornado to anything so empathy without otherwise we're going to study the loop on what are George so we have a data structure we're going to use the DQ first up we push it a do it again I mean is it happy English you know so I just use the last card if this Q is not in body we're going to do pay the pushing in travel routes out it is not important check cannot reveal over the one so this as is one we notice as we go in to understand how many array how many needs the needed to how many loop we need a loop for finish and this label this is the shortcut this vhss I see is greater than zero or not finish one will be that coming to here the minus one you have the three notes determinant one we pull out then we either into our other into this list you haven't finished yet that we check the left and not even left another you got to know even we need a put it a child and so they child family tree only how either is left or right if the left has not a yachtie no means a has chart Timmy give a current total left he pushed onion afterwards we also check a current and total right it was also not a equal to now because also pushing into the queue once this one who put this one now a loop would finish it then we have it I can't have this list of a pushing into Alvin result we always add and into the Dino position so yet a VLP and have a so we are going to Don knitting in the end the travel the worst date once this finishes the whole Trini Travis finish it which also return your result let's test to see if I have a syntax Asia it'll look upon it adjusted a example in the past so we just asaba me to see if opposite Hardison are where you don't accept it thank you for watching bye
Binary Tree Level Order Traversal II
binary-tree-level-order-traversal-ii
Given the `root` of a binary tree, return _the bottom-up level order traversal of its nodes' values_. (i.e., from left to right, level by level from leaf to root). **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[15,7\],\[9,20\],\[3\]\] **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
102,637
1,312
hello friends so today in this video we're gonna discuss another problem from lead code which is a hard problem so the problem name is minimum insertion steps to make a string palindrome so the problem is very simple is just states that you're given a string s and you have to tell how many different characters you have to insert the minimum number of characters you have to insert in the string so that the string will become penetral now you have to first find out understand the characteristics of an intro the characteristics of palindrome is like if you read the like the string from the start to back and from back to start they are like same okay or if you divide the string into two halves then that the string will become same okay if you did so you can understand by this example this string is apparently because as you can see if you divide the string so it's a mirror image over the middle so z now what you can think in this problem is it's a clear dynamic program problem now because also you can see the constraints are small but what you can see in this problem is how you can draw the problem i will show you with the example part this is the only answer is zero but just see this example m b a m so m b a d m okay now what you can see in this problem is like what the first thing it comes to my mind is okay if i have to form this a palindrome then how you can define different states the different states to find out or like if you want to make this into a pendulum what you can think is how you can like broke down this problem into smaller problem okay so as you can see the first and the last characters are same okay if the first and the last character are same i if i can make this can i find out the minimum number of steps to make this apparent room b and d b d the minimum number of steps to make b a df and rom is same as the minimum number of steps to make m b a d m as apparently why because putting m and m in the end doesn't make any difference because if you put m and m in the end it is actually forming a palindrome only pendulum means that if you start from the start and back both the characters are same because they are same it is actually giving me that it is some part of a pendulum and if you just make the middle part palindrome then obviously that will be the palindrome because if i somehow let's do that if i put b okay if i put like a d b if i insert a d here okay and i insert a b here then it will become this string and if you again recombine this part with the whole part which was left this will eventually form a pendulum if i form the if i somehow make the middle string palindrome then i will make this string palindrome also so that what i can do is i can make two pointers i and j to actually define the states so the i and j actually will help me to find out whether if i and j are same which means that these two points are same the characters and i and j are same it means that the number of steps to make this string palindrome is equal to number of steps or number of characters you have to insert to make this string calendar so if dp of ij for this string is equal to dp of i minus 1 j minus m sorry so i plus 1 and j minus 1 so i is incremented by 1 which is like i plus 1 this point and j minus 1 which is this point so if you find out for this length the number of steps or insertion to make this a pendulum is same as a number of insertion to make this a separate draw but if they are different if this is equal to b then the state can be for dp of ij to make this length i j appellate eldrum is equal to you have to find out the minimum number of steps so either what i can do it is i can insert a character at this point to make this a pendulum so it can be like this m b a db what i can have two steps i can either put a m at this end i can put a m at this end and now i can find out the number of steps to make this apparent or because see this is the string is this m b a d b let's do that this is the string this two k's can be because the characters i and j are this and they are not same so the two case can be i can either put an m here and then the minimum number of steps to make this is this as a parent problem which is like b so i will make this a d b and m so i have inserted m here and then the string which is left is this because then the minimum number of steps to make this a plan drum is my problem or i can insert a b at the start so it can be like this b and then m b a d and b so because either if i insert a b at the start then this will become a part which i want to make a pendulum and because i've inserted one character the total number of positions will increase by one so the other tp state can be find out the minimum of both of these states the minimum of dp of as you can see i single i plus 1 j or dp of i j minus 1 and implement this by one because one step has been taken and this is the dp states and you have to just find out all over all the possibilities just do a recursion and use memoration to find out programs so that's what i've done in this problem so first because this length is 500 make the memoration table and the steps can be zero also that's why i don't initialize the tp table with zero initialize it minus one because if you haven't seen that then this is n and the two i and j to make this okay function i will send the string s and because absolute right over the string s and also the two pointers the first point is at zero index and the last one is n minus one so the base conditions can be the first condition can be if both s and e are same if b if there is only one character which is a the nancy is zero because there is no steps are required or if as you can see if the string can be left under the string is a and my i and j is at this point what i've told you the dp state of this is equal to when you both of them are same you will find out a dp state for this problem is you will subtract your add i plus 1 and j minus 1 and now i will come to this point and j will come to this point so that interchange and now this is also not a valid state because i is greater than j so in that case also if i becomes greater than j i or j r you can start at start or end if start becomes greater than end or they become same the answer is zero because in that case no steps are required else if you have find out the state answer for that state and the answer is just return that dp state okay so or else there are two states the first is the so this is i and j you can start and end if the character at the start and character at the end are same then the dp of that state the value is equal to call the ok function again with s plus 1 and e minus 1 and if they're different what you'll do you have two options the first option can be increment the s by one and remain e as it is and answer will increase by one or else e decrease by one and s will remain the same and answer will increase the one and find out the minimum them and that's the t this okay like this is not of use i'm just written on here so you can also like write down this at the end okay so this is also working perfectly fine so that's the logic and code for this problem if you still have any notes you can mention on i'll see you next time then keep quoting and bye
Minimum Insertion Steps to Make a String Palindrome
count-artifacts-that-can-be-extracted
Given a string `s`. In one step you can insert any character at any index of the string. Return _the minimum number of steps_ to make `s` palindrome. A **Palindrome String** is one that reads the same backward as well as forward. **Example 1:** **Input:** s = "zzazz " **Output:** 0 **Explanation:** The string "zzazz " is already palindrome we do not need any insertions. **Example 2:** **Input:** s = "mbadm " **Output:** 2 **Explanation:** String can be "mbdadbm " or "mdbabdm ". **Example 3:** **Input:** s = "leetcode " **Output:** 5 **Explanation:** Inserting 5 characters the string becomes "leetcodocteel ". **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Check if each coordinate of each artifact has been excavated. How can we do this quickly without iterating over the dig array every time? Consider marking all excavated cells in a 2D boolean array.
Array,Hash Table,Simulation
Medium
221
48
hello everyone welcome to learn about flow in this video we will discuss about another liquid problem that is a rotate image this is a medium level problem and we'll understand how exactly the question should be approach and how we should find a solution to this kind of question so before moving on if you haven't subscribed to this channel make sure to subscribe to learn how for regularly code videos like this so the first thing it says that you are given an n cross n to the matrix so it's a n crossing you're going to say it's the square matrix okay uh representing an image and then further it's just like rotate the image by 90 degrees okay like a clockwise okay so that's the whole idea so you need to rotate the image 90 degree uh clockwise direction so what's clockwise direction is something like this direction fine uh like it should go from like this round should go not uh like the other way around shouldn't be the clockwise this is not the anti-power so clockwise this is not the anti-power so clockwise this is not the anti-power so we should do this one right now let's understand the uh example one example is like one two three four five six seven eight nine is there and how we are finding the solution assertions like seven is being moved to uh this position four is being moved to this position and one move to uh this position so say that's like seven is here four here and one and similarly eight is moved to the position of four nine is four for the position of seven and similarly you can see six is moved to the version of eight let's see this is uh i'm talking about this thing okay and then three is pushing move to the position of nine and then two is moved to the position of six so that's the rotation happened and if there's any singular element in the middle that doesn't rotate but if there's any element like this uh like four eight three six in example two okay so this thing rotated as well in a clockwise direction you could see three went above a four went right it went down and six went to its left that's the resultant matrix we find in the middle as well so that's how rotation happened okay that's how it happened now it is how we should do this because uh the question further gives us a challenge that we have to rotate the image in place that means we have to uh like modify the given matrix like we cannot take another 2d matrix and do it okay so we cannot do that okay like it says we do not allow allocate another 2d matrix and google rotation because if we allocate other 2d matrix it will be pretty simple like there will be a loop running from uh like uh running from am crossing low like of a nested folder bank reach of the element and similarly there's other uh like function like another matrix we took and what we will do we'll simply uh take the values in like uh like in horizontal values like all the vertical values we'll take and place them in horizontal manner so that's what if you do is this is your solution but that's not what they are asking us to do because they say we should do it in place like a single matrix should only be used so how we can do this okay so let's quickly write down our example one say we have one uh two three and then four uh five and then six followed by seven eight and nine fine uh just ignore that uh your probable writing of six anyways so what's the idea is like the first thing we should do is like uh see uh can we swap this elements like four and two is it possible two should go to six but if we swap four and two what will be the answer like what will happen if we start four and two if we swap seven and three fine like what i'm trying to do is like swap the uh like elements diagonally okay so what will happen we will get a transpose of this element that means the in the first step what we're trying to do we're trying to find a transpose of the element so the output will be something like one remains in its place then four comes up okay and then seven comes up fine and then a two comes up over here because we swept 4 and 2 and then 5 remains in this place because that's a diagonal element and then 6 is in here now if this of 6 8 comes fine now post that we find that 7 was replaced by three so three comes over here and uh further six comes over here five and then nine remains in this place right so if we do this what we find actually see we actually more or less came closer to us so what we did actually you know we transpose our uh matrix fine so that's what we do we transposed our matrix fine now once you transpose like if you are not compatible transpose i mean you should start practicing those uh transposed on simple mathematics that's not i'm talking about uh any programming or something like that but transposon uh mathematics or matrix uh classes of mathematics okay so that's a simple thing we're doing now uh then what can we do once we have completed our transpose now see if we just uh like change this elements like seven and one like uh and then two and eight right if we just change this element and further three and nine just uh each of the uh on each of the rows we're just interchanging the first and the last element like just indicating the first last level and keep swapping this element so first thing what do we simply transpose like uh we're just swapping okay uh swiping of uh i j position uh okay with uh two ji position that's what transpose we're just swapping i j to g i fine that's just what swapping is and then what we did we then swap uh like the next step what we're doing we are swapping each of the elements in a row like we are swapping if i j okay uh with what we are talking with matrix length minus one minus j but that's basically like keeping our eye same keeping our i same so that means we are in the same row and we're changing it with like the last element with respect to which element we are we arrive like it's like length of the row of this n we have right length minus j now like sorry left minus yeah j length minus j because that's the j count and then minus one because uh that's the stores which element we are at so we simply do these two steps and that's how we end up having our answer right if i do this step what is your answer or answer will be something like 7 comes at the beginning then 4 then 1 then if it's up to an 8 it's like 8 5 and then 2 fine and if it's of 3 and 9 it will be like 9 6 and 3. see that's what our answer is over here find our that's what our expected answer over here fine here is what we find okay so uh there's also a case like if we are asked to do some kind of like clockwise is here if we are asked to do anti-clockwise what we are asked to do anti-clockwise what we are asked to do anti-clockwise what we could have done we should have just simply changed this uh in each column rather than changing it each row we should have changed it in each column and that would have given us an anti-clockwise 90 degree rotation fine anti-clockwise 90 degree rotation fine anti-clockwise 90 degree rotation fine uh but if since it is asking us for a clockwise 98 notation we will change like we'll swap in uh simply for each row so that's the simple idea and you can do anything with it okay so let's quickly write the code down and let's quickly uh like write it and try to solve it the first thing is transposing the matrix okay the next thing is swapping each of the elements in our row in a particular row each of the elements from both the ends okay so let's uh try to do it fine let's try to solve it so here we can see it's a pretty fast solution it's a zero millisecond solution and if we just uh look back what exactly we try to do we uh simply did of transpose in the first place okay uh and then we swapped out like each of the elements show up one by one each of the elements based on the each row so you can see like the row for our i went from zero to n like all the rows okay and we went from zero to n by two for half of the uh row like in each of the row for we went half of it because we are just swapping from the first and the last faster the last so we just went half of it okay so that's the idea over here and uh something i made a small mistake was that uh was that like when you do it when we are being transposed transpose like it's not we are going from zero to n for the rows all the rows and for the columns we go from i like the i to it till n okay that's how we just change the element if it's something at a position like this let's say it's like 0 is like over here fine if we just change uh like uh swap this is nothing happen then it will be like uh zero one is over here right so if we just go for zero one uh okay we don't swap it with anything we'll swap it with zero one with one zero fine one zero we slapped it with this because uh see you say in a case say it's going from uh like i is going from zero till n fine and then j is also going from zero to and then if we do something like that and we try to swap those elements of uh i j and with gi then we'll find like the element will end up having the same question why is it so the idea is first time i is zero so it swaps with nothing and then i like i is zero and j becomes one fine once j becomes one is like zero one and we swap it with one zero so a swap happens uh when i is at this position is zero and j is one right another when i is zero when and j is one we find like we need to swap it again likewise so we are swapping it again uh in the sense like uh we zero one and it swipe to the uh like sorry zero two and it swapped it with uh two zero fine a swap happens between them now i is already in zero and j reached 2 now in the second case when i is at 1 and if we try to if we start j from zero itself we will be swapping it again right but that's not what we are like what we are trying to do for the rest of the element when i is like one we should start j from one itself that is one okay and uh try to swap itself if there's no swap then is i is one and j becomes uh like two so one two we come across so we are just keeping this 0 1 again just making sure the i starts from like j starts from i itself okay so that's why we're just skipping uh some alias and that's how we are doing our whole transpose thing so that's how you saw like the question works for us and it gives us a pretty good result offers a 0 ml solution right so that's it about this videos guys if you have any doubts or anything related to this question make sure to comment it down in the comments below i'll be happy to help you out with the comments and also do subscribe to this channel for regular lit code videos like this thank you all you
Rotate Image
rotate-image
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise). You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\] **Example 2:** **Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\] **Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\] **Constraints:** * `n == matrix.length == matrix[i].length` * `1 <= n <= 20` * `-1000 <= matrix[i][j] <= 1000`
null
Array,Math,Matrix
Medium
2015
1,025
hello everyone so in this video let us talk about a easy problem from lead code the problem name is divisor game so let's start the problem goes like this that Alice and Bob takes turn to play a game and Alice start the game first now what the actual game is that initially there's a number n on a chalkboard on each player's turn that player makes a move Okay now what's the move choosing any X such that X is between 0 and non-inclusive of both of these bounds non-inclusive of both of these bounds non-inclusive of both of these bounds such that n mod x is equal to 0 which means that X should be a multiple of n okay now what you will do is that you will take X whatever number you have chosen you will subtract that X from the N itself such that n keeps on decreasing and eventually you will keep on playing this game until any player is unable to do this particular operation and whoever player is unable to do this or particular operation that choosing a x between 0 and n and subtracting it from n will lose and the other playable now your overall problem is that return true if Alice wins the game assuming that both the players are playing optimally so it is a game theory problem and generally try for any game theory problems try to find out any pattern okay because it's generally all the game three problems you have to find out a pattern of how all the players are playing inside this game okay and let's try to understand the pattern with different examples okay so what you'll do is that we have n from zip 1 to 1000 okay so let's try to find out for n from 1 equal to let's say five okay and then try to find out how much patterns you can formulate out so let's say for n equal to 1 we'll start to first so n equal to 1 means that Alice will start first now Alice will start first and what you can understand from here is if I just move to the let's say the rules of this particular game Alice in the first move will choose a number between 0 and 1 non-inclusive number between 0 and 1 non-inclusive number between 0 and 1 non-inclusive zero and one so there is no number actually and thus Alice cannot do a move and in that case Alice will lose so the answer for this is false so for n equal to 1 the answer is false because Alice will not do okay so answer will be depending on whether Alice will open or not for n equal to 2 the overall thing is that you have to find out that a like Alice will start the game first she can choose any number between 0 and let's say not zero let's say from 0 plus 1 that is from 1 till n minus 1 that is one so from 1 till 1 second choose any number so is that particular number should be a multiple of n so obviously one is a multiple of let's say two because uh like obviously it's a multiple because one can divide two so the other thing is that she can choose one as a multiple of two and then subtract one from two so now n will eventually become 1. okay and Alice has done her chance now Bob Stone will be there and because as we know that if we are on N equal to 1 the player will not move whatever player is or n equal to one that will not win because I cannot do any move and thus Alice have done a chance so Alice will win because Bob is losing so answer for this is true so the one thing you are trying to understand from here is that I have to somehow find factors of n that is one thing so we have to find out factors because uh we have to find out this condition so factors is important finer factors and the next thing also and the thing is that because your constraints are small and we are using the previous values whatever answer we I am getting it depends upon previous values so all of these three things are pointing me towards dynamic programming because consent are small previous values are used and we have to use factors so all of them are like pointed towards value programming that is why we will use direct programming to solve this particular problem now so what we'll do is that let's now take any random n so let's say I'm n equal to 6. okay now Alice chance will be there so Alice what you will try to do is that because she wants to win she somehow wants to make Bob loose okay so what you'll do is that you will have Alice will somehow subtract from n what n equal to 6 a number that is a multiple of six so what all are the multiple of six you can find out one okay and uh two and three okay so you will find out all the multiple of six excluding 0 and N itself so you will find out one two and three now if Alice wants to win she will move to either like if she subtract one she will move to a state to n equal to 5. because then Alice will if I at least use this number as a factor of 6 and subtract like let's say x equal to 1 then Alice will move or give Bob a state of n equal to 5 if he chooses to then Bob will be given a state of n equal to 4 and the other case will be n equal to 3. so these are the three states Bob can land if Alice will choose any number among all of these three things now because what we know that if somehow the other person lands on a false then that person will fail why because as you can see this falls in the table so we are now creating a DB table that will show that if I land upon any of these states so I have already calculated for these states because I am doing a DP now DB means that I will gradually move from one state to another I will calculate answer for n equal to 1 and equal to Big Y because every state is now depending upon its previous state values so for n equal to 6 I have to somehow know the value for n equal to what sorry n equal to 5 and equal to 4 and equal to 3. so I am using the previous values to calculate a reduced answer for this and if any of these three values is equivalent to let's say false then Alice will win why because then she is making Bob land on these states which is giving false so Bob will lose and which eventually means that Alice will win so if any of them turns out to be false then like Alice will choose that portal number and make Bob land on a state that is equal to false and Bob will lose from the state but if all of them are true so no matter which number Alice will choose all of these states will lead to Bob Winning State and thus will Bob will win so I hope you understand what's the overall idea here is that you will find out all the factors of what number Alice is on and depending upon that you will find out whether all the factors if you subtract it from n the other ends which comes out any of them is false then the answer is that uh Alice would win else Bob will win and you will cancel it out for all and from like let's say n equal to let's say form three because from n equal to why we know that the answer will be false n equal to the answer will be true so from n equal to 3 will start to calculate it out and for all the previous factors you can tell it out and for other new States you can use the previous state values that's our idea for this particular problem that is another good part now so we have created a array that is a DP array that was from all the answers of site 1 1005 because the maximum is 1000 then for answer equal to let's say answer equal to 1 the answer will be 0 why because in that state 0 means that Alice will lose and uh let's say for answer equal to which means the second set which means n equal to LS will so answer will be 1. no one denotes true that LF is 0 denotes LS will lose okay now we'll do a follow now for this I equal to 3 to I equal to n okay this I eventually exactly means that I'm telling for each state for each n equal to 3 n equal to 4 n equal to five and so on so this is for each state this I now for each state I will calculate out its factors so it's a very simple way to calculate out any factors of anything is just use a for loop from one till all the J and what you will do is that I will go till the under root of let's say whatever N I have so what you eventually I want to find out is let's say I want to find out the factors of n so I will do a for loop from I equal to 1 till I equal to under root of n because all the factors of N I want to find out so under root of N means that I into like let's say I'm doing a follow-up like let's say I'm doing a follow-up like let's say I'm doing a follow-up using J so J into J less than equal to I which eventually means that J is less than equal to under root of n is I here because I'm doing for every n okay that is how that is a little code you have to understand here and now you are doing a for Loop now for so now J this is I and I just want to check out it whether J is a multiple of I if this is true which means that now we have found out a factor of let's say any ith number I am on and what you will do is that if I minus J because it's a factor I will take ith number I am all let's die and at State I am on so I minus J because I'm taking this number so I'm subtracting out it from J and if it turns out to be 0 which eventually means that if I have only any n and if I subtract out the factor let's say a and if the subtracted state that I lead to let's say this is answer it's false which means that it is zero in that fit Alice will win so the answer of ith number will be 1 and if all the factors doesn't make Alice when if all of them are true then this will not be made like it will not be like initialized with one it will be zero because the vector answer is initialized to zero with all the states so all the safety calculator for all the end because it's the volume for all the states and the end the answer will stored in answer of n because the N is State you want to type it out okay that's over Logic for this particular problem as well nothing much computed here as well but you just have to understand how we can find the factors of any is number and for every state how we can use the previous state values to calculate the current state value so as you can see the time probability and the space Community let's talk about that space Community we have created a let's say o of n okay though I have created a second one of 1000 size only but it can also depend upon the size you can create it on like this answer and also it totally depends upon you now this is the for Loop nested for Loop now you might think that this is O of n Square it's not because this is doing let's say uh Underwood jumps so this is login so o of n log n okay that is the time of City for this particular for Loops okay these two notes are directly lasted follow because this is here this is making it login okay and this overall diversity and the space complexity for this particular problem as well and that's it if you still have it out you can mentioned there's one box for this particular video I will see you in an HD coding and bye
Divisor Game
minimum-cost-for-tickets
Alice and Bob take turns playing a game, with Alice starting first. Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of: * Choosing any `x` with `0 < x < n` and `n % x == 0`. * Replacing the number `n` on the chalkboard with `n - x`. Also, if a player cannot make a move, they lose the game. Return `true` _if and only if Alice wins the game, assuming both players play optimally_. **Example 1:** **Input:** n = 2 **Output:** true **Explanation:** Alice chooses 1, and Bob has no more moves. **Example 2:** **Input:** n = 3 **Output:** false **Explanation:** Alice chooses 1, Bob chooses 1, and Alice has no more moves. **Constraints:** * `1 <= n <= 1000`
null
Array,Dynamic Programming
Medium
322
207
hey guys it's all five one here and today we're going to be solving course schedule in this problem we're given a variable called num courses and all this tells us is the number of courses we have to take we're also given an array of prerequisites so the way the prerequisites array works is they give us a pair A and B and all this tells us is that to take course a we must take course B first so for example here we have the pair zero one all this tells us is that petite core zero you must take course one first and at the end they want us to return true if we can finish all the courses and otherwise will return false so let's think about this for a second in What scenario would return false while avikai complete the courses then we return false obviously but how do we get that the only way to get that is if we have let's edit this example here let's say we have another queer requisite and it's 0 1. well this prerequisite here tells us that we must take core zero before we can take course one but this one here tells us that we have to take course one before we take or zero so if we draw this as a graph it'll look like this where 0 points to one as a prerequisite and one point to zero as a prerequisite and as you can see we're stuck in the loop here and we'll never be able to complete any courses and then at this point is where we return false so when coming up with a solution for this we can think about it as a cycle detection problem because this is the only time we're going to return false and if we don't find any infinite Cycles like this then we just return true before going any further I want to say that if we don't understand death for a search then I recommend watching my previous video because in that video I go over extensive detail on how it works and I'll link that in the description below so from here on out I'm going to assume you understand that first search because you need to know that to understand the next part so the first thing we have to do is actually create this graph here the way I created this graph is by looking at the course and seeing what the priorities is worth for it from this prerequisite array so for example let's say we have 0 here well the only period is that is going to be one so we're going to have an array with just one the reason we're using an array is because we might have let's say we have another prerequisite here that 0 2 well then we would need to store both prerequisites there but for this example we're just doing the one and then for our course one the only prerequisite is two and then for our course two the only per exit is zero and there are two ways you can store this the first is by just using an array so for example index 0 would give us our prerequisites of just one index one would give us rpxit of two and so on or you can just use a hash map which is a little more clearer in my opinion so for example you'll have our key and you'll have the value and you're going to iterate through every key and the values and we're going to treat them as node and neighbors for example if we do DFS of zero they're going to visit all the Neighbors in the value array and we're going to have DFS of one so now for DFS of one we look at our key for one and see that the neighbor is two so we're going to make another call for dfs2 and then we do the same thing we look at 2 and then we make the DFS call for all the neighbors so we're going to make another call for DFS of zero and then at this point we'll just continue in the infinite Loop because now we're going to have to call DFS for zero and start it all over again and there's no exiting so now that we know how to create and Traverse the graph let's get into the solution of how to detect the cycle so what we're going to do is just a slightly modified depth first search so I'm going to write the steps down here so first we want to do a depth first search and then while we're doing the depth first search we want to Mark the nodes as visited so Mark nodes and normally we only Mark the nodes as visited or not visited but for this example here we have to keep track of whether we have a cycle or not so we're also going to add a third option and we're going to call it visiting so here are the three options we can label the nodes as so for example if we're starting out and we haven't visited any nodes they're all going to be initialized to zero so what we're going to do is have an array for each node so we're going to have an array for 0 1 and 2. and this array is initially all zeros so let's say we start at node 0 here well currently 0 is not visited so we can mark it as visiting for now and then we go to the neighbors and now we go to one so we see that one is also not visited yet so we can just mark it as visiting still because we haven't completed the DFS call and then we go to ones Neighbors which is two and same thing for two we mark it as visiting so now from two we visit its neighbors and we see that the neighbor is zero so we're going to do a DFS call for that but once we get to zero again we see that we're still in the process of visiting the node meaning that we haven't completed the DFS call stack so basically if you're still visiting a node from the same call stack then that means we have an infinite Loop meaning we can't complete all the courses and we would return false here okay well let's say it wasn't an infinite Loop and that this prerequisite was gone well from two here we could just mark it as visited because we already visited all the Neighbors which is none of them so we can just mark this as one and then we can go back to our EFS call for one and we're done visiting its neighbors so we also turn this into a one and then we go back to zero and we also turn that into a one and then at the end since we have no Cycles detected then we just return true our time complexity for this algorithm is going to be o of n plus m and what N means is the number of nodes and M is the number of edges so for example we have our node 0 1 and 2 and we also have all of these edges here that we have to visit meaning that we have to go through every node and we have to go through all of its neighbors so let's say we would have zero and then one and two so that's what o of n plus m means for space it's only oven because we only have a hash map and this array here which are both of size n meaning that we're only iterating through the number of courses so now let's get into the code to start we have to start by creating our hash map and I'm just going to call it graph map and what this is going to contain is our course mapped to our prerequisites so initially it's just going to be our course number initialized to no prerequisites and we're going to do this for I in range of num courses so now every single course is in our hashmap with no prerequisites and now we want to populate each course with its prerequisites so we're going to do four course and each prerequisite in our prerequisites array we're going to do graph map at the key course and we're going to append our prerequisite so now every single course and its prerequisites are mapped together and that'll help us Traverse the graph now we want to have our visited set so we're going to have our visit set and we're going to initialize that to zero for every single course and then from here we just want to iterate through every course in our num courses and we're going to check if it is a cycle for this current course then we're going to return false because this means we can't take every single course since there is a cycle otherwise at the end we just return true and now we have to create our is cycle function so we're just going to do it above here so we can reuse our graph map and visit set so I'm going to call it a cycle and our input is going to be just the course number we're at and we're going to do is first set our course to visiting so we're going to update our visit set at the key course and set it equal to two because like I said that means we are currently visiting it and then now we want to iterate through every single prerequisite for this course so for each prerequisite in our graph map at our key course we want to do some checks so first we want to check if we're in Loop and the way we do that is if we're in a loop then that means we're already visiting a previous node that we're already visiting in other words if visit set for our prerequisite is equal to two then that means we're visiting a node again and we just return true the other Tech we want to do is check if visit set at our prerequisite is equal to zero meaning that we haven't visited it then we want to do our is cycle from there because we're visiting his neighbors and then if this returns true then we also want to return true here because that means we created a loop if we get past these two then that means we can just Mark our visit set at our course equal to one since we found no loops and we can just return false here since it's not a cycle and then they should use work as you can see this code is pretty efficient and now I'll go through the code manually to start I set up this graph here that has an infinite loop at one and two and I'm not going to be writing out each and every individual step because that would just take way too long so it's going to be more of a conceptual overview so to start we want to initialize our graph map which I've already done here our zero is mapped to one is mapped to two and two is mapped to one like you can see in the graph here and then our visit set is initialized to zero for every single node in Num courses and then we want to go through every single course available and check if it's a cycle so first we're going to go through core zero because that's the first course So currently we are course zero so first we want to change our visited array to be equal to 2 at index 0 because we are currently visiting that so let's do that and now we go through every neighbor for the zero so as you can see the only neighbor is one so we're going to do our pre is one and now we check if we're currently visiting one then we return true and as you can see we're not currently visiting one because it's equal to zero so now we go to the next condition and we check if we haven't visited this node and it is a cycle so now we're doing recursion then return true so now we're doing is cycle four one and now we set visit set at 1 equal to two so now we're currently visiting node one and now we check every neighbor for one which is only two so let me just update this and now we check are we currently visiting this node well no because it's zero so now we go to the next condition and we do if we haven't visited this current node and it is a cycle then we return true so now we're going to check if two gives us a cycle so let's see now our course is two so now we set our course to two so now this array says we're visiting two and now we check every neighbor for two so our only neighbor for two is one as you can see in the graph here and now we check a revisiting node one in our current recursion stack well we can see that here we have a two so that means we are currently visiting it so we would return true here now that we have that we can pop back to one and see that it is a cycle so we also return true here and then we pop back up to zero and for zero we're visiting the neighbor so we would return true here again and then once that's done we return true for this is cycle function call here which tells us to return a false which is correct there is an infinite Loop here which means we can't complete all the courses if this video helped you in any way please leave a like And subscribe thanks for watching and I'll see you in the next video
Course Schedule
course-schedule
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`. * For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`. Return `true` if you can finish all courses. Otherwise, return `false`. **Example 1:** **Input:** numCourses = 2, prerequisites = \[\[1,0\]\] **Output:** true **Explanation:** There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. **Example 2:** **Input:** numCourses = 2, prerequisites = \[\[1,0\],\[0,1\]\] **Output:** false **Explanation:** There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. **Constraints:** * `1 <= numCourses <= 2000` * `0 <= prerequisites.length <= 5000` * `prerequisites[i].length == 2` * `0 <= ai, bi < numCourses` * All the pairs prerequisites\[i\] are **unique**.
This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.
Depth-First Search,Breadth-First Search,Graph,Topological Sort
Medium
210,261,310,630
328
hi today I will talk about problem 328 from leak code old even linked lists given a singly linked list group old notes together followed by even notes we are talking about the node number here and not the note value it then proceeds and gives you an input 1 2 3 4 5 and null and the output would be 1 3 5 which is grouped by the node number as in this was the first odd number this was the next odd number in this and then the even number if it happens that they are if it happens that this is an even and this is an odd it wouldn't matter because this question is focusing on the position of the odd and even rather than the value so I drew another diagram here so we can visualize the linked list or the singly linked list here we see the input so how do we go about and solve this challenge so the first thing we will do is create two empty list notes such as in create an even one I call it no and the code will be in the description section so how do we code this so we will simply create a variable and call it an old head and this old head will equal list node none which is that one right here and then we gonna create another one called even head and make this less note none so basically we have now created these to you up here with them we'll create another variable called odd and assign the odd head to it so this can be referred to as odd and this can be referred to as even okay so the way we go about this is the first thing we want to check if there's value so just in case there was no values or if you have arrived to the end of the list so we write while hand so while hat while there is some value r1q to assign the head to my odd next now what does that mean with the first one is always going to be the odd number so we don't have to do any if statements to check because the first position is number one so basically all we do here is as you can see this is odd so odd next which will be the pointer from this linked from this list node will point to the head which in this case is one next we will give all we will make odd next so originally what was this here the odd head now odd is gonna move and become here so now what has became this one let's do the same thing for even but the different thing is we will say that head next and I will use this to represent the head so the head was here and now you're saying head next which is this one is gonna point to even next so even next right here will be the head next so will be this way and then even the next which is this one right here will be even so even now it's become here so this is odd and this is even and now we're gonna do a simple check to make sure we are not at the end of the list of there are some more values so we're at a next statement saying if even dot next which is in this case if even dot next which is here if there is a value then we will shift head to next so we have if there is a value after here head was lying we'll put back we put back head in the original position so you see a pet was here so had dog next shift had to be here else help is no oops and when Heather's none it will exit this while loop but let's do a couple more again so let's go on the top here so your head is here so you're gonna slide up next to this one here tear in your head so three will be here and all the text will be out so now I was gonna be here head up next the head dot next is number four and you can assign that to Eve next which will be here again check if even the text has a value yes it has a value so then we will move this to here let's do one more iteration so your head which is number five will be here so we'll be here and your aunt dot next will be odd so what will be shifted here and then head dot next which in this case is the null value so that will be here and then you're even shifts and become here now this will be executed if even dot next which in this case there isn't you will return none sore about that you will return not and this while loop terminates so when this wire loop terminates on the same indentation is the wild this can be shifted over to the right we will say that odd dot next will be even doc next my apologies it will be the even head dot next because you have shifted your even here if you can attach the even dot next to the OP dot next then it wouldn't actually attach these values so it will be the even underscore head dot next which in this case your even have is this one and basically what you're doing is taking let's get another color the odd next by saying this one here and attaching it to the even next right and then you will return the alt underscore head dot next again your alt underscore head is this so the next will be everything starting from here which will be one three five two four the green one should go up into higher if you have any questions please feel free to ask thank you
Odd Even Linked List
odd-even-linked-list
Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_. The **first** node is considered **odd**, and the **second** node is **even**, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,3,5,2,4\] **Example 2:** **Input:** head = \[2,1,3,5,6,4,7\] **Output:** \[2,3,6,7,1,5,4\] **Constraints:** * The number of nodes in the linked list is in the range `[0, 104]`. * `-106 <= Node.val <= 106`
null
Linked List
Medium
725
217
hello everyone and welcome back to another video so i'm going to try to solve all of the questions in the data structures playlist or kind of module over here so starting off with the first question which is contains duplicates so let's take a look at that question okay so in this question we're going to be given an integer array called nums and our goal is to return true if any value appears at least twice in the area so if there's any sort of repetition we're going to return true but if there is no repetition and every element is distinct we're going to return false so a quick example is one two three one the number one is repeated twice so we return true uh another example is one two three four over here everything is uh unique and distinct so in this case we return false right so one very important thing to note which is uh important for this question that i recognized earlier is that the fact that these numbers don't have to be sorted so for example we have ones here and then there's a two at the ending after three and four so the numbers are not sorted and yeah so uh the range of the numbers is from negative 10 to the power of nine all the way to ten to the power of nine and we can also have some really big numbers so the length could be up to ten to the power five okay so let's first think of a very improved first solution so what we could do is we could basically have two for loops uh so what we could do is we would first equate to the first number so one and then what we would do is we would check if there's any one anywhere else right so we would go to the next number and see if it's equal to the first number then we go to the next so three is not equal to one but in this case we have one and one there's a match so that means that there is a repetition so we're going to return true okay but just for the sake of it let's say we keep going on so now we're going to move on to next number which is two so now we go into two and now we check two with three and then two with one so basically all we're doing is we're comparing the two numbers each and every time okay and if there is a match we're going to return true but this is not the best solution and this is going to give us a time limit exceeded error especially for really big numbers like 10 to the power of 5. cool so that is the first solution and this is going to be big o of n squared time complexity and the space complexity of this is going to be big o of one because we're not using any extra space so now let's move on to a second solution so a second solution that we could use is by using a set so what we could do is we could use our set to keep track of all the numbers that are coming in and each number we go to we're actually going to go to set and check if that number exists now if the number already exists well that means that there's a repetition and we're going to return true and the lookup types for a set is going to be big o of 1 but this is going to take extra space so in the worst case we might have to give a big o of n space and worst case assuming there's no repetition will be big o of n times so for this solution we're going to have a set called s for example and now we equate through each of the numbers and we check if s and not sorry if num in s we're checking if uh the number is in our set now if it is in it then that means there is a problem and there is a repetition so we're going to end up returning true but if there isn't we're going to add this number so s dot add we're going to add the number to set now if we iterate through all the numbers and we don't actually end up returning anything that means there is no repetition and we return false so this is one of the solutions so let's submit it and this solution was accepted so now let's take a look at another solution finally so in this case we use big o of and time and big o and space now let's try to come up with a solution which doesn't which use uh uses big o and time but does not take up extra space so to do that a simple solution would just be to sort the numbers so we could get all these numbers sorted and what we could do is let's say there's any repetition right so let's just take a look at this over here so we have one two three and one so after sorting it what would happen is we would get one comma two comma three so what we could do now is we could actually compare each number with the number to the right of it so we could go uh to the zeroth index and compare it with the number at the first index now if they were okay so if they are the same that means there is a repetition obviously and we return true and this works because when you sort them all the ones if there's several they're all going to be in the same space so this technique is going to work so let's see how this looks like in code so first we have to sort the numbers so sort and now what we can do is we iterate through the numbers so let's do it by index so for index in range so let's start off from the zeroth index and let's go up to the last but one index the length of nums minus one so what we're going to do is we're going to compare so uh the value at index with the value at the index in front of it so that's gonna be nums index plus one okay so we compare these so if and now if this condition here is true well that means there is a repetition and we're going to return true but if we go through the entire for loop without returning true that means there are no repetitions and in this case we return false so this over here is going to take big o of n time and it's not going to take any extra space so yeah that should be our solution and thanks a lot for watching guys
Contains Duplicate
contains-duplicate
Given an integer array `nums`, return `true` if any value appears **at least twice** in the array, and return `false` if every element is distinct. **Example 1:** **Input:** nums = \[1,2,3,1\] **Output:** true **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** false **Example 3:** **Input:** nums = \[1,1,1,3,3,4,3,2,4,2\] **Output:** true **Constraints:** * `1 <= nums.length <= 105` * `-109 <= nums[i] <= 109`
null
Array,Hash Table,Sorting
Easy
219,220
1,909
hey everybody this is larry this is me going over q1 of the biweekly contest 55. we move one element to make the race strictly increasing so this one is a little bit tricky um but you have to look at constraints so hit the like button hit the construct uh hit the constraints hit the like button hit the subscribe button join me on discord let me know what you think about this problem so the way that i did it during the contest is noting that n is equal to a thousand and the fact this is an easy problem um it's a little bit metal but because of that i just did an n square way of okay if i remove every element and then just proof force is increasing then this would get me the answer so this answer is not that interesting to be frank as n square squared there are other ways of writing it but that's n squared so if you're here then i will employ you to up solve this problem by using dynamic programming so dynamic programming is how you uh the key thing to know is that you can have you can remove at most one element i mean you can also remove zero element that doesn't make any sense in the sense that um if you could remove zero element then you can also remove one element but in any case uh there is a dynamic programming solution for this that will enable you to solve in all of n times um and you can think about it as removing k elements but where k is equal to one um i'm not gonna go over that for this problem because i think there are probably another deco problems there so if you have any questions let me know in the comments or let's send a link on that problem as well and we'll chat about it anyway that's all i have for this yeezy so yeah you can watch me start with live during the contest next prepare a little bit ahead of time okay let's see what am i doing why am i so slow today strictly uh hmm what is going on here oh that's one two five seven i'm not missing not skipping i'm not skipping the one so i have to do that okay true false force true truth that's true all right let's go that was a mess yeah thanks for watching hit the like button hit the subscribe button join me on discord thanks for your support and thanks for you know i mean this is a you know for the first time here uh haven't finished top 10 in a while so yeah anyway i'll see you later and to good coding bye
Remove One Element to Make the Array Strictly Increasing
buildings-with-an-ocean-view
Given a **0-indexed** integer array `nums`, return `true` _if it can be made **strictly increasing** after removing **exactly one** element, or_ `false` _otherwise. If the array is already strictly increasing, return_ `true`. The array `nums` is **strictly increasing** if `nums[i - 1] < nums[i]` for each index `(1 <= i < nums.length).` **Example 1:** **Input:** nums = \[1,2,10,5,7\] **Output:** true **Explanation:** By removing 10 at index 2 from nums, it becomes \[1,2,5,7\]. \[1,2,5,7\] is strictly increasing, so return true. **Example 2:** **Input:** nums = \[2,3,1,2\] **Output:** false **Explanation:** \[3,1,2\] is the result of removing the element at index 0. \[2,1,2\] is the result of removing the element at index 1. \[2,3,2\] is the result of removing the element at index 2. \[2,3,1\] is the result of removing the element at index 3. No resulting array is strictly increasing, so return false. **Example 3:** **Input:** nums = \[1,1,1\] **Output:** false **Explanation:** The result of removing any element is \[1,1\]. \[1,1\] is not strictly increasing, so return false. **Constraints:** * `2 <= nums.length <= 1000` * `1 <= nums[i] <= 1000`
You can traverse the buildings from the nearest to the ocean to the furthest. Keep with you the maximum to the right while traversing to determine if you can see the ocean or not.
Array,Stack,Monotonic Stack
Medium
1305
971
hey guys it's es wave and today we're gonna be doing we code 971 flip binary tree to magic preorder traversal so the problem is given a binary tree with n nodes each node has a different value from 1 to n a node in this binary tree can be flipped by swapping the left child and the right child of that node consider the sequence of n values reported by a preorder traversal starting from the root call such a sequence of n values the voyage of the tree our goal is to flip the least number of nodes in the tree so that the voyage of the tree matches the age we are given and if we could do so return the list of notes that we clipped and if we can't just return the list with negative 1 in it so basically the problem is flipped the least amount nodes to match the pre-order sequence nodes to match the pre-order sequence nodes to match the pre-order sequence which is called the voyage and a flip is defined as swapping inodes children so give me that this is preorder traversal or probably use DFS since we can visit like the current node then called DFS left visit that and then once we recurse back up called the FS right and kind of just keep track of the index and compare it to the voyage and if it doesn't match then we can swap the nodes if it still doesn't match then we'll know that this is impossible so kind of like the road map for this problem I would say is called DFS keeping track of the index comparing the voyage and if the current node does not equal the voyage then it's impossible and then if the node dot Left doesn't match voyage we can swap and get we basically swap and correct the node to result list and yeah so that's basically it some of the education thing cope is like if the starting route doesn't match the voyage we automatically know it's impossible since we can't swap the starting route and if left dismal and right isn't we also have to account for that then we won't be able to we'll just have to call DFS left and then bright and exit if it's null and also make sure like double swapping doesn't happen like don't swap once and then swap again later cuz that kind of defeats the purpose and yeah this problem looks a little difficult because it says the least number of nodes so it makes you think like oh I have to do a bunch of different variations and pick the best one but in this case Ike's whomping is binary it's either you swap or you don't so you can't just traverse the tree and preorder and match it with the sequence if it doesn't match swap if it sold as a match it's impossible so it's pretty like been here in that way time complexity of and since you're visiting each node space complexity also of n since we're going like worst case scenario you flip every single node that would this would be populated with all of the nodes yes so what we need to keep track of is the index the list of integers that will return at the end call it flipped and I'll just pass the voyage in here too so we don't have to passage pass it in the recursive function so initially I'll just initialize my list and index equals 0 and the stop wage and then we'll create our DFS function which is just gonna return nothing it's just gonna iterate through and if we need to swap something out of that to flicked and if we if it doesn't match the voyage then we'll add negative 1 to the list we'll first clear it then add negative 1 and then at the end we could see if the first index is negative 1 that means we hit an impossible route so if the no then no does not knowable do something and if it isn't all we just exit out so if the node for current node dot Val is not equal wage index I guess plus I can increment here too then this is impossible so this handles the case of the first node not equaling the voyage and also whenever we flip and then we call the FS that flip node we're also checking that so it would be impossible both ways so flip back here and then we'll return after that and then the case where it does match then we also want to check if we're at the end of the voyage we also want to exit or not then we'll check the left of the node so if the no doubt left is not no and the note left does not equal the voyage index the next C sequence number so we want to swap so we'll add we'll say that we're swapping this current node looked I'd add node up well and then we could flip it without actually modifying the tree just by calling DFS no doubt right instead of no doubt left so this is kind of like pseudo flipping the tree so you don't actually have to modify anything but our algorithm thinks that we flipped it since we're calling right when it actually expects left and if everything is good we just keep traversing the tree swap these yeah and then once we return we'll have our flip list so we want to first check it flicked is not empty so if it's not empty and flipped dot get zero cycling one are you does equal negative one then we know it's impossible so we'll clear it and then negative one that damn again just return flipped since if it worked it will hold all of our nodes that we flipped and if it didn't work we just return a list with negative one so yeah this handles the case sandals all the edge cases event I move in space let's run this Oh what did I do no not what's not viable cool so the test case works this would be impossible if it was just one and two because you can't match the voyage to one two since you can't actually flip one since it's a root so I'll try submitting and it should work and yeah it works seven milliseconds so yeah that's the problem I thought it was interesting DFS problem the district the description is kind of weird but it's still an interesting problem so yeah that's it thanks for watching
Flip Binary Tree To Match Preorder Traversal
shortest-bridge
You are given the `root` of a binary tree with `n` nodes, where each node is uniquely assigned a value from `1` to `n`. You are also given a sequence of `n` values `voyage`, which is the **desired** [**pre-order traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order) of the binary tree. Any node in the binary tree can be **flipped** by swapping its left and right subtrees. For example, flipping node 1 will have the following effect: Flip the **smallest** number of nodes so that the **pre-order traversal** of the tree **matches** `voyage`. Return _a list of the values of all **flipped** nodes. You may return the answer in **any order**. If it is **impossible** to flip the nodes in the tree to make the pre-order traversal match_ `voyage`_, return the list_ `[-1]`. **Example 1:** **Input:** root = \[1,2\], voyage = \[2,1\] **Output:** \[-1\] **Explanation:** It is impossible to flip the nodes such that the pre-order traversal matches voyage. **Example 2:** **Input:** root = \[1,2,3\], voyage = \[1,3,2\] **Output:** \[1\] **Explanation:** Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage. **Example 3:** **Input:** root = \[1,2,3\], voyage = \[1,2,3\] **Output:** \[\] **Explanation:** The tree's pre-order traversal already matches voyage, so no nodes need to be flipped. **Constraints:** * The number of nodes in the tree is `n`. * `n == voyage.length` * `1 <= n <= 100` * `1 <= Node.val, voyage[i] <= n` * All the values in the tree are **unique**. * All the values in `voyage` are **unique**.
null
Array,Depth-First Search,Breadth-First Search,Matrix
Medium
null
108
hello everyone today we'll be working on leak code 108 convert sorted or write a binary search tree so we are given an integer array called nums and the elements are sorted in ascending order and our goal is to convert this array into a height balanced binary search tree so to better understand what they mean by hype balanced let's look at a diagram all right so this is an example of a binary search tree that is unbalanced in its height so according to the prompt the balanced tree can only have a one layer difference in height and we have a height difference of two so the left node of 37 and the right node of 82 both stop at the third layer while the deepest branches go down two more layers so we have layer one layer two three four and five all right so let's look at a height balanced all right so we can see here that there's only a one layer difference between the nodes that are stopping here and the nodes down here and that's exactly what they want us to do with this sorted array that they're giving us is to turn it into this tree all right so let's talk about that so if we tried inserting the nodes from either start or end of the array we'll get a binary search tree that is either all left nodes that is going down this way or all right nodes because these are already sorted so we can take the sorted nature of the array and use that to our advantage so we will use the middle index in this case this is going to be 61. and that will be our root note and then from there we will look at the numbers to the left of 61 and get the middle from there which would be 37. and then we repeat this process all right look at the numbers to the left of 37 get the middle and we have 22. all right so I'm going to scroll over here so this is what our algorithm is going to be doing is we're going to get our initial root and then we're going to look to the left of it so start and end and then 61 is the node that is we're inserting a node into its left so 37 would become the left node is 61 then we look to the right of that or excuse me to the left of that 22 becomes the left note of 37 and then 12 becomes the left note is 22. we don't have any more nodes so we go back up to 22. and then get the right for it which is 34. now we're back up to 37 and we're looking at 45 and 52. so 52 becomes the right and then 45 becomes the left of 52. back all the way up to 61 and you can see how this process continues all the way to the end which will get us this tree that looks exactly like that so let's go ahead and type out this code and see what that looks like so the first thing that we need to do is we just need to create a helper function so I'm going to say function and I'm going to name it convert and this is going to take a start and an end so these are going to be integers that will point to the different indexes of our nums array so if the start is greater than the end then we're going to return null all right so if it's not North then let's figure out what the middle index will be so we're going to take math dot seal and we're going to add the start and the end indexes together and divide them by two next up const root all right so this is going to be the root for that particular level for those elements so that's going to be a new tree node and we're going to give it a value of whatever the middle index is all right so then root dot left is going to be convert and we're going to take the start and then we're going to take the middle index and subtract 1 from it all right so when we initially get 61 for example we're just going to keep the same start but then move the end one to the left of it and now for the right side dot right we're also going to convert and we're going to say mid plus one so the middle index I'm going to move it 1 over to the right and then we're going to go all the way to the end and lastly we just need to return the root and then outside of our helper we're going to call convert and we're going to start at the beginning of the array and then the end of the entire array and that's all there is to it with this so let's go ahead and submit that all right very good I don't know why it took so long but yeah so that's pretty good results right there I hope this was helpful for you if you have any suggestions on things that you would like to see please leave a comment below other than that I hope you all have a great day
Convert Sorted Array to Binary Search Tree
convert-sorted-array-to-binary-search-tree
Given an integer array `nums` where the elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_. **Example 1:** **Input:** nums = \[-10,-3,0,5,9\] **Output:** \[0,-3,9,-10,null,5\] **Explanation:** \[0,-10,5,null,-3,null,9\] is also accepted: **Example 2:** **Input:** nums = \[1,3\] **Output:** \[3,1\] **Explanation:** \[1,null,3\] and \[3,1\] are both height-balanced BSTs. **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in a **strictly increasing** order.
null
Array,Divide and Conquer,Tree,Binary Search Tree,Binary Tree
Easy
109
1,704
be solving problem 1704 determine if string halves are alike the problem statement is you are given a string s of even length split this string into two halves of equal length and let a be the first half and B be the second half two strings are alike if they have the same number of vowels in it doesn't matter if it is uppercase or lowercase return true if a and b are alike otherwise return false if you look at example number one the string is book b o k and if we split this into half the first half is b o and the second half is okay and between the two half strings the number of vowels is the same which is one hence we return true in the second example the input is textbook if we break it into half we have text and the other half is book and if we look at the number of vowels in the first one we only have one which is e but in the second one we have two o's hence there is a mismatch and we will return false it is an easy problem so I do not think it will take a lot of time to understand the problem and come up with the best possible solution now let's switch to whiteboard and talk about the solution let's take textbook as our example before we start talking about the solution there are a couple of information that is given to us in the problem statement which we need to note of before we start implementing the first is the vowels are case insensitive so we do not have to worry about if it is uppercase or lowercase and the second is any vowels will do if we have a vowel I in the first half and E in the second half it is still equal and we need to return true so it doesn't matter if they match or not as long as the count matches with that in mind let's start thinking about the solution the simplest solution and the most efficient one would be to have two counters a starting index and the ending index the first s i index will start with zero from the start of the string and the ending index will start from the end of the string so that will be s dot length minus 1. and along with that we will maintain a counter to just keep a track of how many vowels we have come across and which will be set to 0 because we are using two counters and we need to break this whole string into half we can use both of the counters at the same time and reduce our time complexity by half we will start with a while loop s i is less than e i because s is starting from the first character in the string and the E is going to point at the last index it's when they cross each other and at that point we will know that we are at the center of the string and we don't have to continue the iteration so starting with this so s i is 0 e i is in this case let's say it's 7 because we have 8 characters we will first check if my character pointed by the index s i is that a vowel or not the S car is e not a vowel so I will do nothing now let's check if the pointer pointed by e i is it a vowel or not because it is pointing to this character so in either case nothing can be done at the end of the iteration we will just increment the SI counter by 1 and e i pointer -1 the next Loop my S character pointer -1 the next Loop my S character pointer -1 the next Loop my S character is pointing at e which is a vowel so I will increment my counter by one now let's check for the end pointer now this is pointing at o which is again a vowel but because it is pointed by the end pointer we will decrement the counter the reason is we need to compare and make sure that the count number of vowels in the second half equals to the first half so the expectation is after the iteration is just this counter will be zero if it is 0 it means there are equal number of vowels so here I will do a decrement on my counter because I found one more vowel at the second half and then continue with the incrementing the pointers similarly I will continue to the next one so here I am at X which is not a vowel so we don't have to increment the counter my end pointer is pointing at o which is a vowel so I will decrement my counter so now my counter will become minus 1 because earlier we did plus one minus 1 which resulted in 0 and now we are doing a minus 1 so my current value is minus 1 and we will increment our pointers at the end my counter will be minus 1 because there are no more vowels in the remaining strings and because this is not equal to 0 I will return false if you were to look at the time complexity it is going to be o of n by 2 where n is the length of the string and our space complexity is going to be of 1 because we are maintaining these three variables to maintain the pointer and the count of number of vowels I hope you were able to understand this explanation let me show you how we can implement this using C sharp here is the equivalent solution in C sharp in this method I am initializing two pointers s index and E index to point to the start and the end of the string then I have initialized a hash set of type character with all of the vowels that we need to identify and I have this variable counter which will maintain the count of number of vowels that we came across then I start with this while loop which will run until the S index is less than e index the next step is where I am checking the value of the character pointed by the S index if it is a vowel then I am incrementing my counter then I am checking the character pointed by the E index if it is a vowel then I am decrementing the count and after this both calculations are done then I am incrementing my starting index and decrementing the end index this iteration will continue until this condition of s index less than e indexes is met after the while loop is done I am comparing the count if it is equals to 0 then we have equal number of vowels in both the halves and I am returning true else I will return false thank you for watching this video I hope you were able to understand my explanation and this solution if you have any questions feel free to reach out to me happy to hear your thoughts this solution is available on my GitHub repository the link will be there in the description below feel free to check that out and I will see you in the next one thank you
Determine if String Halves Are Alike
special-positions-in-a-binary-matrix
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half. Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters. Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`. **Example 1:** **Input:** s = "book " **Output:** true **Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike. **Example 2:** **Input:** s = "textbook " **Output:** false **Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice. **Constraints:** * `2 <= s.length <= 1000` * `s.length` is even. * `s` consists of **uppercase and lowercase** letters.
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
Array,Matrix
Easy
null
209
uh these questions is minimum size subaruism so you are given an integer positive integers and I'm sorry and a positive integer Target and return a minimum length of the sub array whose sum is actually greater than or equal to a Target and if there is no such sub array then you have to return zero so let's draw so um I definitely know the you know you definitely know the problem so I'm going to go straight to my solution so what you need to do is well you need a two pointer left and right so left and right start from zero and then you keep adding the value until the value from until the left until the value from left all the way to the right is actually what good or equal to Target right and then you check the lens then you move your left pointer plus and then go again and then if I mean if the value if a value is actually less than Target then it's going to be like right plus right so um so first thing it's gonna be what another color so two plus three is actually five plus one six plus two is eight so the first window is going to be like this right so on the value is what age right another length should be what full right so this is gonna be the first window so now I need to uh move me my left Plus and then I need to update my window I also need to obtain my value so a minus 2 is actually equal to six right so if so once you move your left you need to deduct the I mean the left index value right so uh I mean the order definitely it's not like this it's going to be Theta left and then you plus later right you plus later all right so uh yes this should be the you know uh the idea right so the if the value is actually what lessons less than a topic so this is six right so this is not the window I need to find so I need to what keep moving my right to here so level is actually 10 so now it's actually very real than a Target so I check my windows the link is full then I move my left pointer by one so the value is what seven right six seven and then the length should be three all right so uh if there are if they are equal just keep moving your left right and this will be it right and then so you can just go all the way to the right I mean definitely right so let's stop coding so I need have a eye pointer MJ pointer so I soldier from zero okay I need to have the sum I need to have my love the minimum value so I need to keep track of the minimum length right so I need to set like current events to the max value I need to have my red pointer so for every single value I need to add to the sum so while the sum is actually greater equal to the Target you need to update my research and index will be what J minus I plus one so plus one is actually represent the length right j i and J represent the index and we need to include the index 0 right and then so now I obtain my result I need to update my sum so since I added the value I need to this is J sorry and I need to subtract the I and then I need to implement my eye so I can Implement my eye afterward right so later on I will return result but if my result is actually what the integer.max result is actually what the integer.max result is actually what the integer.max value which is going to return 0. I also return result right so this will be it right and then submit so for the timing space are pretty straightforward this is a space constant this is for a time all of N and don't do the list this is actually we're just moving the inner pointer and the time is spaced I mean sorry the time for the inner value all right it's actually like a constant the main point is this right so it's going to be all the fun for the time and then all of one for the space so uh I probably need to have a breakpoint you know starting right over here and let's see the debug mode and all right so you just keep watching the windows all right so this is pretty much it right so if you have any question leave a comment below subscribe if you want it and this is pretty standard uh interview questions so good luck
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