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 |
---|---|---|---|---|---|---|---|---|
1,814 |
everyone and good afternoon to all of you today we have problem which name is Count nice PS in an array lead c844 problem so before going forward in this video please make sure that you have liked and subscribed to this Channel and also it's my advice to all of you that please read the problem and try to build up the intuition for this and also try to do the code if you will stuck at any point then see this video then it will be beneficial for you simply see the video and then do the code it will not be beneficial for you so do The Code by yourself then see this let's read the problem statement we have given an Arin nums which consist of non- given an Arin nums which consist of non- given an Arin nums which consist of non- negative integers let us Define reverse of X do you know how to find the reverse of at every for of any number we can use stack for reversing numbers and we also have the math mathematical tools like module and divider operator I will discuss them nerse of 1 2 3 is 321 and like this a pair of indices I is nice if it satisfy the following these two conditions should be satisfied for the nice pair I should be less than J it means if my pair is 34 it can't be 43 mean if the if I have a pair 3 4 then it will be uh count as one 43 will not increase our count and this condition should also satisfied nums of I plus reverse of num of J should be equals to nums of J plus reverse of nums of I so we have to return the nice Pairs and also we have to modu because it can be too large so let's go on to the coding part means that approach part so let's uh remove this from here and open this yeah we have this nums of I plus nums of J equals to nums of J Plus of nums of I so we can do this nums of I minus reverse of nums of I equals to nums of J minus reverse of nums of J we can do this like we can use two pointers to find the unique pairs but it will take big of any Square time so it will not be V official for you because our code will not work in B of any Square that's why we can do this using a single pointer so that's why we approach we use this approach let's we have given the nums are 42 11 1 and 97 the reverse of these numbers is 24 11 1 and 179 then we will find nums of I minus reverse of nums of I means this one then it will be 18 8 so if I Traverse this then it will be 18 so I will take a frequency M frequency array so frequency of 18 is initially one then frequency of zero is now two because zero comes here so we can see if two zeros are here so this can this zero can make a pair with this one so two zeros can make a pair only one pair okay so we can find the frequency a number of unique parts we can find n into nus 1 by 2 but I will use different you can use this also so let's go on to this reverse technique how we can reverse a number so we can take a variable value equals to Z then we can find the last index of that particular number how we can find we can use module operator to find the last index of last digit of that number so number modulo 10 then we will store that number how we can store value equal to value multip 10 plus last then we will find the other number means like let's take a example for this if I number I have number 123 then I find the module 12 modu 10 this will give me a last digit of that particular number three now value to initially value was zero so value equal to value mtip 10 plus last digit so it will be three now one number equals to 23/ by 10 so this one number equals to 23/ by 10 so this one number equals to 23/ by 10 so this is the approach use this huh now 12 modul 10 because now when new number is 12 so 12 modul 10 will give me the last digit of that particular number so we'll find Value equals to value in value the initial value of that initial value is three so three multiply 10 + 2 value is three so three multiply 10 + 2 value is three so three multiply 10 + 2 like 32 and now number is 31 and you can see also this so let's go on to the coding part for this let's close this from here and open this quick time layer so firstly what I will do I will oh yeah I will write the reverse technique of that particular number so in Reverse of that number how we can do this we can we will take initially value equals to Z then we will find number uh last index in last what I'm doing is num modu 10 done now what I will do value equals to Value multi 10 plus last digit last in digit of that particular number then L equals to l 10 this will give me a new integer finally I will return this return value now in main function what I will do I have to create the map so let's create the unorder web map of in comma in type because it is no character type MP now I will take a variable in answer that we have to return now what I will do I will Traverse the map the num Ser sorry for auto it belongs to nums and in this what I will do I'll find the re element of element minus reverse of that element so in let's take a variable from let's take a some variable what I can take like int value is equals to it minus reverse of that it V RS C okay now I have a value I will now I will check if that value equals means but I will add answer plus equal to so let's write this answer equals to answer plus frequency means let's take map name is the map of that value and I have to module also to do modul let's define the modulo has uh Define mod = to 1 Define mod = to 1 Define mod = to 1 E9 + 7 done this thing I have done after this I will increase this so see map of that value Plus+ and finally see map of that value Plus+ and finally see map of that value Plus+ and finally I will return so why I'm writing this out of the loop I have to write this here now I return our answer let's run this and see if this will have run or yeah num num white is giving ER num mod what happened I have to do here also mod and what is the problem in this is done I think let's define inside this h in mod = in mod = in mod = to 9 + 7 now let's why it is giving mod UND declar identify let's see what is a problem in this we are doing the uh mistake here this should be defined in this function also means in this function and we defined that in that function that's why it is not working because more let's this and see how this will work not yeah it is working perfect let's submit this code and see yeah it is working perfect so the time and space complexity you will tell me about in comment section and uh if you find this helpful then please like share and subscribe and also comment uh that will motivate you that's F comment and we will see meet in next video so stay
|
Count Nice Pairs in an Array
|
jump-game-vi
|
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions:
* `0 <= i < j < nums.length`
* `nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])`
Return _the number of nice pairs of indices_. Since that number can be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums = \[42,11,1,97\]
**Output:** 2
**Explanation:** The two pairs are:
- (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121.
- (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12.
**Example 2:**
**Input:** nums = \[13,10,35,24,76\]
**Output:** 4
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109`
|
Let dp[i] be "the maximum score to reach the end starting at index i". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value in the heap is out of bounds of the current index, remove it and keep checking.
|
Array,Dynamic Programming,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
|
Medium
|
239,2001
|
430 |
Hello Everyone Welcome to Delhi Flight Channel And subscribe The Amazing Subscribe To A Plot To Multiply Avoid During This Liquid 432 In This Question Thursday Subscribe Video subscribe and subscribe the Channel Please subscribe and subscribe the Channel Loot Superintendent Engineer and Eight This particular Doob School subscribe Video subscribe and subscribe the appointed Dash Loot Seervi subscribe level kids to keep track of subscribe Video subscribe don't push too hard with lettering suicide note liquid subscribe ki yuvraj three and most versatile patience seervi Seervi 251 Subscribe To That Explosive Keep Or Electronic Subscribe That Aap Create A New Difference Between Appointed President Subscribe My Channel Withdrawal Subscribe School Subscribe Channel Subscribe Normal Dhung Subscribe Channel Video Previous No To IDBI Swasth Aur Quid subscribe The Channel Please subscribe our is otherwise go ahead and move to do flu subscribe do subscribe to who is my next rotational check avoid next Video plz subscribe Video subscribe hai kya hua typing special bilko hai or engineer mil sakte subscribe and subscribe the Channel subscribe Video subscribe loota Do Subscribe subscribe Video Building New Short Note on the Same Topic Problem Consistency Subscribe
|
Flatten a Multilevel Doubly Linked List
|
flatten-a-multilevel-doubly-linked-list
|
You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional **child pointer**. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a **multilevel data structure** as shown in the example below.
Given the `head` of the first level of the list, **flatten** the list so that all the nodes appear in a single-level, doubly linked list. Let `curr` be a node with a child list. The nodes in the child list should appear **after** `curr` and **before** `curr.next` in the flattened list.
Return _the_ `head` _of the flattened list. The nodes in the list must have **all** of their child pointers set to_ `null`.
**Example 1:**
**Input:** head = \[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12\]
**Output:** \[1,2,3,7,8,11,12,9,10,4,5,6\]
**Explanation:** The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:
**Example 2:**
**Input:** head = \[1,2,null,3\]
**Output:** \[1,3,2\]
**Explanation:** The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Explanation:** There could be empty list in the input.
**Constraints:**
* The number of Nodes will not exceed `1000`.
* `1 <= Node.val <= 105`
**How the multilevel linked list is represented in test cases:**
We use the multilevel linked list from **Example 1** above:
1---2---3---4---5---6--NULL
|
7---8---9---10--NULL
|
11--12--NULL
The serialization of each level is as follows:
\[1,2,3,4,5,6,null\]
\[7,8,9,10,null\]
\[11,12,null\]
To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:
\[1, 2, 3, 4, 5, 6, null\]
|
\[null, null, 7, 8, 9, 10, null\]
|
\[ null, 11, 12, null\]
Merging the serialization of each level and removing trailing nulls we obtain:
\[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12\]
| null | null |
Medium
| null |
516 |
hello everyone welcome to netset os today in this video we will see how to find out longest palindromic subsequence if you have any problem in understanding subsequence i have made a special video on it the video link will be in the description below so let's start how to find out longest palindromic subsequence let's say if i take the example net set here i need to find out with all possible subsequence it can be either e t e which is also a palindromic it can be e s e either e t or e s e or in the other way if we take t it can be tst or t e t so in all the cases they are making of three length if i take the other example let's say b a b the random now if i take out the palindromic subsequence it can be bab which is also a palindromic or i can have bbb it is also following palindromic or we can have four b's palindromic means to draw a line in the middle of the string and have a look whether they are making the same string or not for bb it's bb only that makes it palindromic and if we see it is of three length this is of three length and it is of four length so the longest among all the subsequence which are also palindromic is bbb here in this video i'll discuss three approaches to achieve longest palindromic subsequence the first approach the naive solution which will be try with each with all possible way let's say if i'm taking net set as my string and i need to take out longest palindromic subsequence out of it so what i need to do i need to find out all possible subsequence which are also palindromic so here first i'll try out with subsequence which is first n then e then t then s then e then t then i need to find out the other subsequence of two length n e t s e then of three length then a four length then of 5 length and whichever subsequence will be palindromic all the palindromic subsequence out of which we will select the longest one this approach is all about subsequence if we talk about time complexity it will be order of 2 to the power n as we are going for each and every subsequence of each letter now so as to improve this complexity we'll be looking for second approach here first we need to have the string itself let's say if i'm taking the string b a b this is my string i'll take the string first then i'll do the reverse of it reverse as in first the last letter then second last then third last then the second a and then b now keeping these two strings i will calculate longest common subsequence of these two strings i have already explained the concept of longest common subsequence with recursion as well as dynamic programming i'll give the link in the description below so with this if i take the recursion method i need to calculate if they are equal it will add one plus and the cursor will move one step ahead and if they are not equal then we need to have i as it is j will move ahead and the other case i will move ahead j will be as it is and then we need to have max of both of them this i have also explained in that video with dynamic programming where the string are equal then it will add one to it otherwise it will calculate max of above and left so with this approach also you can calculate first you need to have the string then you need to reverse the string with these two strings we need to calculate longest common subsequence now if we see the time complexity by this it will be order of n square as we are computing the solution by i and j as well as we are also comparing it so here it will be order of n square and if we talk about space complexity by dynamic programming it will be order of n square as we are making with i and j now let's see the more better approach for longest palindromic subsequence here i have taken the example net set and if i index it i'll take i from front and j from the last now here i need to follow this if first character is equal to the last character because we need to match the last character let's say if i have e t e so i need to match first and last character so if e and e are matching then we will move ahead i to the second character and j to the second last character but as in this case n and t are not matching first starting from n to e and the other case from e to t that is i'll take first n e t s e avoiding the last character and in the second i'll avoid the first character e d s e t and then i need to calculate max out of this let's try to solve this by dynamic programming if i have the example b a triple b if i index it i'll have 0 1 2 3 4 as its length is 5 let's draw 2d matrix for this as like this here we have 0 to 4 and 0 to 4 for each i and j side here also i'll write the characters for both i and j axis now we will start filling up this by dynamic programming but the first step we need to take care i should be less than and equal to j that means if i have i greater than j i need to fill 0 then and there so i'll take for 1 as i and j is equal to 0 i'll fill 0 over here for all of them same with when i is equal to 2 and j is equal to 1 it will be 0 then i is equal to 3 j is equal to 0 and here 0 then the second thing we need to look for when both of them are i that means we have just single character as in here we have just b so if we have just the single character we will take it as palindrome so here we will take it as 1 for bb for aa 1 for bb again 1 for 1 and all diagonal will be taken as 1 as we are having just the one length character over here so i can say the length is of one character now i'll fill for two length character as we have the string b a b now for this i need to match up for two length character for b and a if b and a are matching if they are not matching i need to go for i j minus 1 i need to go for i and j minus 1 here i'm looking for 0 1 so here as per this we will have 0 and the other one will be 1 so 0 is this one 1 is this one here out of this i need to go for maximum 1 as they are same i will write over here 1 then i will be looking for a b whether a b is matching they are not so here i'll be looking for both these characters the maximum of it is one only as they are same one now for bb here we have b and here also b they are same now for same we need to look for i plus 1 and j minus 1 this is 2 3 character so for 2 3 i need to look for i plus 1 which will be 3 and j minus 1 that means 2 to this i need to add 2 plus so here 3 2 so i need to add to this 0 to plus why i have added two because here we have b there are two length b is always making up palindromic so it will be a palindromic subsequence that's why we have 2 over here now we will be looking for this one here b they are same character so same character i'll take the diagonal it's 0 and will add 2 to it so here also we will have 2 so with this we have taken 2 length character right now we will be looking for three length character that means this and i need to match this b with this so here we have b and here also b and b are matching so i'll be looking for the diagonal and will add 2 to it so 1 plus 2 will be 3 then we'll be iterating from a to b the 3 length character is a matching with b for filling this column a is not matching b so i'll be going for else condition here i have to fill 1 comma 3 so for 1 comma 3 i need to have first i as it is and j minus 1 3 minus 1 will be 2 and the other one i will be 1 so plus 1 j will be as it is so i need to look for 1 comma 2 which is this and 2 comma 3 will be this out of 1 and 2 whichever is maximum will be filled over here now for the other one we need to look for b and b as b and b are matching so we will look for diagonal which is 1 and will add 2 to it so here i'll get 1 plus 2 as 3 so with this we got all the three length characters now we will look for four length which is b a b is it making palindromic subsequence let's find out so for this we'll be looking for is b matching with b yes so we'll be looking for its diagonal 1 plus 2 so 1 plus 2 is 3 then i'll be looking for this string starting from a to b is a matching with b no so we'll be looking for left and bottom one whichever is maximum will be written over here now we'll be looking for all five characters so is b matching with b yes so here we'll be looking for 2 plus 2 is 4 which is the longest palindromic subsequence now if i need to understand how i got this palindromic subsequence let's verify here if i look for the last one from which i was confirmed i got the number that longest palindromic length is 4 let's find out here this 4 i got from this 2 as b is matching with b so i can write i got b over here as b was matching that means there were two with which when it was matched i got this b now if i look for this one here a is not matching with b that means it would have been taken from left or bottom now if i look for this 2 as it was taken from the bottom b is matching with b yes that means it is a palindrome so b is matching with b that means here we got b over here so four b's over here for making it palindromic subsequence so let's see how to build a program for it so for python program i'll go to pycharm before going to palindromic here i have longest common subsequence where i have verified for b a triple b first of all i have taken the normal string and then i have reversed it now so as to check this whether they are making palindromic subsequence or not i'll take out the longest common subsequence for it as per our second approach now when i see over here it's giving 4 now we will check for longest palindromic subsequence as we have discussed where we will calculate as per this so this is longest palindromic subsequence where i have taken the 2d matrix now i'll be filling for all one length character which are in diagonal to be one as we are taking it as single character now we will proceed for second length character so for that we have put a for loop from second length character up to size this size we have taken len of string whichever we are giving over here then we have taken i and j and here especially if their length is 2 then it will fill 2 for here for filling this length of 2 character now for filling 3 4 5 6 length here it will be looking for lf if they are equal then it will just go for the lower left diagonal and will add 2 to it otherwise it will be going for left or bottom whichever is maximum will be filled over here and at last we will get the last character as my returned value 0 and minus 1 to be returned as like this now let's verify for net set we have calculated it to be 3 only as i have already explained now let's check for the next example which is let's say b8 triple b now when i run here i'll get four the longest palindromic subsequence to be four b's so here we need not to look for all palindromic subsequence just we need to go for the longest palindromic subsequence length so longest palindromic subsequence the third approach i'll give this python code on github link which will be mentioned in the description below also this longest common subsequence i have already made a video on this and i have all the python code in my github link so if you face any problem just have a look on the video for concept and if you want to have a look on code you can refer github link so hopefully you understood this concept as i always say give a like to my video and please subscribe to my channel for further notifications thank you
|
Longest Palindromic Subsequence
|
longest-palindromic-subsequence
|
Given a string `s`, find _the longest palindromic **subsequence**'s length in_ `s`.
A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** s = "bbbab "
**Output:** 4
**Explanation:** One possible longest palindromic subsequence is "bbbb ".
**Example 2:**
**Input:** s = "cbbd "
**Output:** 2
**Explanation:** One possible longest palindromic subsequence is "bb ".
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists only of lowercase English letters.
| null |
String,Dynamic Programming
|
Medium
|
5,647,730,1250,1822,1897,2130
|
48 |
okay leak code question 48 rotate image you're given an n by n 2d matrix represented in an image rotate the image by 90 degrees clockwise you have to rotate the image in place which means you have to modify the input 2d matrix directly do not allocate another 2d matrix and do the rotation so in this example we have just rotated this by 90 degrees so 741 moves to the top one two three moves down the side and 369 moves across the bottom so this is a pretty tricky question especially if you don't know how to manipulate matrices this is a two-step process in the this is a two-step process in the this is a two-step process in the solution so firstly we need to transpose this and by that i mean we need to switch the diagonals so this one to begin with is going to be flipped with itself so we've got row zero column zero so we're gonna flip that with itself then we're gonna move to column one and we wanna flip that with row one so those two are going to flip then if we move to row two for example we're going to flip with column two so those two are going to flip five is going to flip with itself six and eight are going to flip together and then nine is going to flip so we're to end up with something like this so this has been completely transposed now so that's step one of this solution now step two in order to get from here to here we're going to have to just flip these values so we're going to reverse the first and last value and then move inwards okay to flip this value and the reason i say move inwards is because if we had an example like this we'd also have to flip these values on the inside here so we need to flip on the outside move inwards flip on the inside but because this array up here is so small we only flip four with itself okay so that's the general understanding of this solution and what that will return is that return us the answer right here so let's jump back into the code we'll start writing it out and then we'll come back into this and discuss how we'd actually work this out so firstly let's transpose the matrix so if we loop through from i at zero there's less than matrix.length there's less than matrix.length there's less than matrix.length i plus so we're looping through the rows here and then for the columns set that to j we're going to make sure that j is equal to i just less than matrix dot length j plus now the reason we set j equal to i is because at this point where we have i is equal to 0 is equal to 1 2 we want to make sure that the column or j is also the same so as we went through in the example if i is equal to 0 we want to make sure that j is equal to 0. and if i is equal to 1 down here we want to make sure j is equal to 1 because we're going to be flipping those values so now we can just flip those values so temp is equal to matrix i j is equal to matrix or j i and then matrix of j i is equal to temp so that's going to transpose the matrix so that's the first step done next we need to reverse elements and move inwards so with this example in order to reverse the first value and the last value it's going to be matrix i j which is this value and we need to get the last value so that's going to be matrix at i because we're at i equal to zero and it's going to be matrix dot length because it's going to be the length of this row so matrix dot length and it's going to be minus one because the index is one less because we start at zero so that will solve this problem so that'll flip those two so what happens when we move inwards well firstly let's change these up so one is going to be flipped with seven so seven and one have changed now we're in the middle so we've got four so matrix i j is equal to four and that's going to be flipped with this matrix i matrix dot length minus one which is currently at one so this isn't going to work here so we need to decrement something else well we need to decrement this by j right so j is equal to one we need to decrement by one in order to get that middle value it's the same with down here we first flip these two values so matrix at i j is equal to five and we want to flip it with the last value which is 11 and j at that moment in time is equal to 0 on the first iteration right so those two are flipped then we move inwards so we move to j is equal to 1. now we need to flip so matrix i j we're flipping one with matrix at i matrix dot length minus one minus j so j is equal to one matrix dot length minus one is five we minus one so we flip it with the nine okay and we repeat that process so let's write this part out so let j equals zero j is less than matrix dot length divide by two j plus the reason we have matrix.length divide the reason we have matrix.length divide the reason we have matrix.length divide by two is if you think about it if we switch these values up so we switch two and ten and then we switch four and eight so we've only gone to j where j is equal to one right so half the length and we flip those values so we flip those values and we've only gone up to this point if we move past this point we're going to flip them back so we're going to flip 4 and 8 again and we're going to flip 10 and 2 again so we're going to end up with what we started off at so we don't want to do that and we only want to go up to half the length of the matrix then we create the flip logic so that temp equal matrix i j is equal to matrix i matrix dot length minus 1 minus j so once that's been added in we can return the matrix let's give that a run okay so that's been accepted let's submit it and there you have it
|
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
|
443 |
hello guys today I watch other self dust during compression profit give array of characters a compress it in place a lens after compression must always be smaller than a leakage energy no array every element of the relation of your character not in tollens one after you are to be modifying the input array in place return the new length of the array here sorry to use only constant extra space okay let's see the example a ABB CCC we were cultures continuous character and there is a two day so we are right like a to be two and three we have three character see we have three characters so we all right back c3 so well let's take number two if and only one we just write like what adjust the rite-aid to not neither to right so the rite-aid to not neither to right so the rite-aid to not neither to right so on and finally a P B is troph and we were right separate sorry okay so how to do that basically we need index which indicator the place in the father is out and we also need a two characters no two pointers one point to the indicator where we have read and yes so basically we need are preserving depth this pointer point to where we are in the final result 0 will be where we have great character and we cannot read out of counter and we need a safe the current character should be indexed and when we will keep buried so we need a cult when we add some current Achara our code is one there when they're in their stomachs because we want to compare the coming and she was a knapsack air will not be going to the current character okay we will first write the current index a current Charlie chooser final result chart in a wheel we master net color plus because a current so in this flat faster because this current index up is the same character and the current character the other to do the next compare we should have move index forward and if the current equal to one pushing into wish we do not need that you write the digit her anymore I'll see if the colleges in wow we should because it has the possibility to larger than ten so we should first up changes are integer to a string and then and every character into that final okay that's productive let's see correct yes correct it's the English right to zero understand that yes I think it's correct so what's the term capacity obviously it's oh and because we should iterator the whole chartering okay thank you for watching happy closing
|
String Compression
|
string-compression
|
Given an array of characters `chars`, compress it using the following algorithm:
Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:
* If the group's length is `1`, append the character to `s`.
* Otherwise, append the character followed by the group's length.
The compressed string `s` **should not be returned separately**, but instead, be stored **in the input character array `chars`**. Note that group lengths that are `10` or longer will be split into multiple characters in `chars`.
After you are done **modifying the input array,** return _the new length of the array_.
You must write an algorithm that uses only constant extra space.
**Example 1:**
**Input:** chars = \[ "a ", "a ", "b ", "b ", "c ", "c ", "c "\]
**Output:** Return 6, and the first 6 characters of the input array should be: \[ "a ", "2 ", "b ", "2 ", "c ", "3 "\]
**Explanation:** The groups are "aa ", "bb ", and "ccc ". This compresses to "a2b2c3 ".
**Example 2:**
**Input:** chars = \[ "a "\]
**Output:** Return 1, and the first character of the input array should be: \[ "a "\]
**Explanation:** The only group is "a ", which remains uncompressed since it's a single character.
**Example 3:**
**Input:** chars = \[ "a ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b "\]
**Output:** Return 4, and the first 4 characters of the input array should be: \[ "a ", "b ", "1 ", "2 "\].
**Explanation:** The groups are "a " and "bbbbbbbbbbbb ". This compresses to "ab12 ".
**Constraints:**
* `1 <= chars.length <= 2000`
* `chars[i]` is a lowercase English letter, uppercase English letter, digit, or symbol.
|
How do you know if you are at the end of a consecutive group of characters?
|
Two Pointers,String
|
Medium
|
38,271,604,1241
|
125 |
hi everyone in this video we will solve the problem valid palindrome on lead code so the problem says given a string s return true if s is a palindrome and Falls otherwise so for example if we have the word race car we reverse the word and we still get race car so if it's the same as the original then we know that it is a patent draw how about the string 1p colon P1 well the first thing is you need to get rid of all non-alphabet characters so in this case non-alphabet characters so in this case non-alphabet characters so in this case the colon so once we get rid of the colon we reverse the string which is one pp1 and this is also a palindrome so keep in mind that in this problem you are allowed to keep numbers there are two solutions to this problem and we'll go through both of them in Python so for the first solution we take in the string s we lowercase all the characters in The String s and what is this line well this right here will Loop through the string and it will save the character into a list if that character is alphabet or is a number so basically this right here will get rid of all non-alphabet here will get rid of all non-alphabet here will get rid of all non-alphabet characters like the colon right so here we have a list and we need to convert this list into a string the join function will convert the list into a string we have S2 then here we compare S2 to its reversed version so this is the Syntax for reversing a string and if the reverse version is the same as the original and we know that it is a pattern draw let's take a look at the second solution Now using race car as an example we'll first put the indexes onto the string and then the next step is to determine something called a line and you'll see what it does in a second so the line is equal to the number of letters so there are seven letters in total one two three four five six seven then we floor divide by two okay so what is floor divide well seven divided by 2 gives you 3.5 and 3.5 rounded down gives you 3.5 and 3.5 rounded down gives you 3.5 and 3.5 rounded down gives you three so that's basically what lower divide is the length is three so we're going to put the line onto the first three letters now we're really close to finishing the last step is to put the two arrows one at the beginning and one at the end and then we compare the letters so R and R are the same okay that's good the next one A and A Yep they're the same how about C yes they're the same so one is this arrow is at the end of this line you know that this string is a pattern draw now let's take a look at another example A B C A again we have the indexes the line is four because there are four letters and we four divide by two we get two so the line goes for two letters we put the two arrows at the beginning and the end a is the same as a how about this B is not the same as C so this is a sign that tells us that this is not a pattern draw let's take a look at the second solution so we lowercase the letter s then same thing as last time this line of code will get rid of basically all the non-alphabet characters so we have S2 non-alphabet characters so we have S2 non-alphabet characters so we have S2 then we determine what is the last index on the string so the last index is the length of s2-1 then what is the line length of s2-1 then what is the line length of s2-1 then what is the line where the line is length of S2 flow divided by two and then the last step is to put the first Arrow onto the line and we Loop through the line so we compare the character at the first arrow with the character at the second arrow and what's happening here is that when we look through the line I is going to increment and this basically moves the second arrow to the left in the string and if we find a character that is not the same for the first and second arrows then we know that this string is not a pattern drum we return false and after we finish looping through the line we know that it is a palindrome so we return true so if you guys enjoy this video don't forget to subscribe and like and in the next video we will determine if two strings are anagrams and anagrams are very similar to palindromes
|
Valid Palindrome
|
valid-palindrome
|
A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string `s`, return `true` _if it is a **palindrome**, or_ `false` _otherwise_.
**Example 1:**
**Input:** s = "A man, a plan, a canal: Panama "
**Output:** true
**Explanation:** "amanaplanacanalpanama " is a palindrome.
**Example 2:**
**Input:** s = "race a car "
**Output:** false
**Explanation:** "raceacar " is not a palindrome.
**Example 3:**
**Input:** s = " "
**Output:** true
**Explanation:** s is an empty string " " after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.
**Constraints:**
* `1 <= s.length <= 2 * 105`
* `s` consists only of printable ASCII characters.
| null |
Two Pointers,String
|
Easy
|
234,680,2130,2231
|
1,857 |
hey everybody this is larry this is me going with q4 of the weekly contest 240 largest color by unit directed graph uh hit the like button hit the subscribe button join me on discord let me know what you think about this problem so this problem has a lot of different components i urge you to kind of practice it um the components and i'll let you know what the components are obviously but uh but i definitely struggle with this one because i was just a little bit sloppy i think um to be honest you know you look at the times and you see people doing like five six minutes and i'm like yeah i probably could have done it maybe not in five six minutes because these people are really good but maybe like 10 minutes uh but instead i took 25 minutes of the wrong answer because i was just sloppy and on a yeezy part and the easy part for example is that this is a directed graph you have to first detect whether there's a net uh there's a cycle and this is something that most people know and i should have known better but i spent way too long here and i kind of did an incorrect implementation and i didn't get the wrong answer from that but yeah but this is you know so basically uh first i set up an etched list actually i don't end up using the uh but yeah uh after this edge list uh this is just really basic psycho detection um i did it with the three colorway there's another way of doing it but i recommend reading up on the literature this is of n or over v plus e where we is the number of vertices and yi is the number of edges uh so this is linear the size of the input um and then the second part is something that um i just did it in a i had a really weird assumption about dynamic programming during the problem but i think i struggled with something that was or like i summed up things in a different way um basically i sum up all the edges instead of taking the max of all the edges so it was i was getting a funky answer but it somehow passed to the examples so i was a little bit sad going back basically do i um if i had a zero two and then another edge that's zero degree i double count stuff because i sum instead of getting the max which is not great um but then the way that i decompose it and you can of course watch me solve it live during the contest after this the way that i saw it was with dynamic programming the key thing to note is that you know for each input for each because now that we prove that as a dag because it doesn't contain any psycho um that means that for each node and for each color we can return the same answer um and because of that uh there's gonna be at most 26 times n where because they're only 26 colors so that's going to be fast enough because n is uh you know 10 to the fifth so this is going to be linear times 26 or if you want to do u as this number of colors then it's u times n um and that's pretty much it this is a very straightforward dynamic programming kind of once you get there because once it's the same color then you just count the number of um count the num the okay so this is actually dynamic program whereas return because i got a depth research but it's not quite true but return the max um number the path containing color starting at current creating the most color yeah so that's basically the idea behind this recursion um so first you start with count zero if it is zero the current you increment it because that's how you do the current otherwise well i mean in either case you basically take the max of the recursion of the new color that on the new edge that you go to so basically just do one on every edge and then the color um yeah so basically now this is going to be o of v times e or we plus gsi times 26 because for so the idea here on doing the uh analysis is that for each node and vertex you are going to make one call um for each color um and if i know that this for loop is a little bit scary but because you amortize all the edge out such that every edge to a color is going to you know every edge is only going to be activated once because it cannot happen the second time because it requires this to be called a second time which with cash um so yeah so this is going to be this is times u where u is the size of the where u is number of outfit bits or 26. um so yeah so this is the new ish and for this case it's going to be fast enough um we do a micro optimization where in this case we only start out with the colors because it doesn't make sense to start out with another color um so yeah but in the worst case it will still be this thing and yeah in terms of space we do linear space here with the coloring and we do linear space in terms of o d so the number of edge space to rewrite the edge list we do number of re space for um for the color so that's going to be of v and the stack space is going to be all v plus e for both psycho and uh this dynamic programming so everything together in space is gonna be v plus e um that's all i have for this problem uh it took me way too long even though each of the components are pretty easy for q4 anyway it's not a easy problem but for q5 it's easy and like i said people done it in like five to six minutes i probably should have done it uh in 10 to 12 minutes maybe if you watch me solve it live you see me just like struggling on the silly part and then i got a wrong answer because i just implemented this in a weird like my recurrence was just wrong and then after i was like oh wait i'm not supposed to sum i'm supposed to max and i'm like oh wait this recurrence doesn't make sense for max and then i'm like oh actually you could pull out a dimension and use color and then everything fell together um yeah that's all i have for this problem let me know what how you did how you know what are your how you did and yeah just let me know everything hit the like button hit the subscribe button join me on discord oh and you can actually watch me try to solve it live during the contest next okay turned out to be okay um a little bit slow today and uh it is what it is okay largest color value in the graph so to end minus 1. man 36 p have gotten this already so i'm really slow today the number of notes that are colored the most frequently along the path what are these color days are the colors cell 2 3 4 contains 3a the cycle is a little bit awkward okay maybe not it's just any cycle so it's going to be deaf research probably but so if there's this should be pretty straightforward basically okay how do i want to do it the cycle part is easy okay let's just do which one is and then um oh i guess it has to be which one is n m of edge's length uh the colors are less than n so okay now we give an n man i should know this part better so the only way that it is not is that if there's a tracer yeah okay you negative one i think hmm whoops okay otherwise it's just depth research you um i guess this could be n squared right no edges is 10 to the fifth does that matter if it's a tag my graph is very bad do i need to memorize calories are 26 26 times time it's a little bit sketch to memorize everywhere right don't memorize i should know this better here's the worst case crash i need to memorize sound expensive to memorize so this is also wrong i think oh why am i so bad yeah i need to memorize does this need to be my computer is being slow this i'm gonna do it with colors all right let's see right oh yeah that's what i try to do here but i know i'm being dumb my computer need a new computer that's not true this is bad actually because yeah i think wow i'm really bad today so because this could have a thing but there's a cycle elsewhere so i am actually pretty bad about this one this is actually really wrong um i should have named it color by now i think at this point i should be able to cash so maybe i should have done it that way if okay and now we have to do a different search that's just too there's no psycho so which this should be good but it's not is it good enough though oh man my mouth what is a map um of course pay to win okay that looks okay and now to do this part oops oh yeah that's not good it does do stuff why does it return zero oh what am i doing this is right but maybe too slow there you go though oh wrong answer that's actually not what i would have expected that's not great expected three why is there 10 in there from zero one hmm am i doing something bad with my references i don't think i'm reusing references right i mean this is new but i create a new one every time why are you so bad zero and one doesn't make sense so this is just really wrong let's see what goes to 10 why did i mess up oh i will use weave like an poop zero goes to two double zeros oh there is a zero goes to two i'm just buying okay two has all these beautiful things oh i know because i'm double counting because i'm summing up all the things i see oh wow because okay i know where i'm going wrong but how do i fix it you could cash it on color but is that messy maybe not maybe that's the way to go to be honest okay fine i think this is easier to do than i should maybe done it oh man that was a okay i don't know if this is too slow to be honest um if color is your code two hmm uh okay so that looks good three negative one three yeah i don't know if this is gonna time out but that looks good at least maybe okay um that was silly i misunder or i don't i didn't um this would have been so much easier to implement i don't know i misunderstood the i mean i understood the problem correctly i just had a wrong assumption about it over yeah uh hit the like button hit the subscribe button join me on discord let me know what you think about this promise explanation and all that good stuff um i did okay but i don't know uh anyway i will see you later uh stay good stay healthy take a mental health bye
|
Largest Color Value in a Directed Graph
|
largest-color-value-in-a-directed-graph
|
There is a **directed graph** of `n` colored nodes and `m` edges. The nodes are numbered from `0` to `n - 1`.
You are given a string `colors` where `colors[i]` is a lowercase English letter representing the **color** of the `ith` node in this graph (**0-indexed**). You are also given a 2D array `edges` where `edges[j] = [aj, bj]` indicates that there is a **directed edge** from node `aj` to node `bj`.
A valid **path** in the graph is a sequence of nodes `x1 -> x2 -> x3 -> ... -> xk` such that there is a directed edge from `xi` to `xi+1` for every `1 <= i < k`. The **color value** of the path is the number of nodes that are colored the **most frequently** occurring color along that path.
Return _the **largest color value** of any valid path in the given graph, or_ `-1` _if the graph contains a cycle_.
**Example 1:**
**Input:** colors = "abaca ", edges = \[\[0,1\],\[0,2\],\[2,3\],\[3,4\]\]
**Output:** 3
**Explanation:** The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored ` "a " (red in the above image)`.
**Example 2:**
**Input:** colors = "a ", edges = \[\[0,0\]\]
**Output:** -1
**Explanation:** There is a cycle from 0 to 0.
**Constraints:**
* `n == colors.length`
* `m == edges.length`
* `1 <= n <= 105`
* `0 <= m <= 105`
* `colors` consists of lowercase English letters.
* `0 <= aj, bj < n`
| null | null |
Hard
| null |
1,745 |
hey everybody this is larry this is me going with q4 of the weekly contest 226 of lead code palindrome petitioning 4. uh hit the like button hit the subscribe button join me on discord let me know what you think about this problem so this one is a little bit tricky for me just because in python um this is a very hard problem in python i think strategy wise and this is just me talking about it is that um i should have just changed like if i wanted to get a high score and i could have probably i should have just changed language to uh c plus or java and i'll be fast enough um and that's what i ultimately end up doing but um but i spent a long time trying to get the of n algorithm uh to work and there is an of n algorithm and we'll go over it as well uh but first i'm gonna go over the n square algorithm that i do um and we'll go over the timing as well but to be but um but yeah but the n squared algorithm is um well first of all how do we get an n square algorithm right so that we answered the uh palindrome uh question you know you could find all pairs of palindrome and of n square time if you pre-cut pre-calculated um and this is pre-cut pre-calculated um and this is pre-cut pre-calculated um and this is kind of the way that i did it uh recursively with an llu cache but uh but basically it's a memorization um which is that given the left and the right you know if this is passed left to right then return true and otherwise we return whether the end points are the same if the end points are the same you look at you know one more inside so that this just checks that um you know whether uh let me write it out this checks whether left to right is a palindrome um and do you know i usually do this in a different order but kind of go over complexity a little bit well left could be from 0 to n uh right could be from zero to n oh why did i use o instead of zero uh so that means that the number of possible inputs are n square and because we do all of one work here um this is time and oops time and space complexity right um and then from that we have that then we're able to kind of do this um that first search proof force um it's basically okay index goes from zero to n uh parts goes from zero to three um so obviously this is going to be actually of n um because i was oh snap actually now because of this uh because of this for loop it actually will be um you know first so there's all of n states each statics of uh n square um work huh it's still linear time algorithm now that i'm thinking about it maybe not um no there is a linear time algorithm i think but um maybe not actually maybe i'm wrong but they're definitely an optimization and maybe i should have thought about it but yeah um anyway this is n of uh so each state takes o of n time i'm so in total this is of n squared time and o of n space right um and what this does is you know it just it's kind of um a path like if you look at if you think about graph connectivity it just shows that okay you know so let's say we have some string um and we're gonna space it out a little bit um you know it just means that if this is a palindrome there's a uh this if this is a pendulum damage there's a path forming from this space to this space um and here for example there's another edge coming from uh here oops all the way to the end because the dd is the pattern drum and bcb is also paranormal so your path will be from here to here right so basically this a function just checks whether there's a path of length uh degree going from the beginning state to the well yeah at the beginning of the string to the end of the string um and the way that i did that is okay so i put force this is the end conditions if we're able to get to the last state we check whether the path is three if it's so is true not as forced otherwise we get we use all three paths but um but we haven't gotten to the end of the string we also return force otherwise um otherwise we just check in a brute force kind of way rather and you know that this is all one because of the lookup here um but we have an of n loop and this actually does of one as we said so yeah so basically all this does is check whether from index to i and i it is a pound room if it is a pound drum then we check whether you know the rest of the string which is i plus one uh can be done in parts plus one number of uh paths left or after we've already taken kpaf so let's put some english on this um basically uh good returns true if starting from index uh there is a path of length um parts technically i guess it's three minus parts or something like that uh to the end of the string so that's kind of like the anguish way of putting uh this string and after that you know a lot of people solve this one and you just kick it off from the zero string into a ring right so why did i you know i actually knew how to do this immediately and in theory i probably could have gotten it in like five minutes the most um and if you see me saw previous forms you know that i'm not bragging about it's just that i'm a little bit upset because um you know to look at the time i actually end up converting this to c sharp um i might have said java earlier but i meant c sharp um so my correct submission is actually in c sharp this is exactly the same code except for that i do the dynamic programming um or the memorization uh um yeah i did a memorization like explicitly um on both the ispandrum and it's good and the annoying thing is if we look at here um you know to see the running time this one's in 264 milliseconds so i didn't have to worry about it um i later after the contest i just kind of see if i could have done it in python and quickly enough and it took 9.7 seconds it took 9.7 seconds it took 9.7 seconds so on one hand if i had submitted my python solution it would have gotten it really quickly or like i would have gotten the answer very quickly but on the other hand my suspicious is kind of true in that um like it was way close to timing out right like if there's one or two more test cases i think the timeout time is 10 seconds um so it would have timed out so like it's hard for um and the reason why i think that is because the n is 2 000 uh and n less than 2000 is actually a really tight bound in python it's really slow so you have to be really careful and i definitely was optimistic in the past and kanji in tles um so that's why um yeah um so yeah so the only optimization that i would do um that you can do and i was talking about this is um you can actually rewrite this uh let me change this to python back you can actually rewrite this and if you just watch me doing the contest i actually tried for a bit you can actually rewrite this function you could use something called manager's algorithm to construct effectively a variation of this function in linear time right um and once you do that you can actually um construct the entire graph um and then you know do that graph in a very explicit way because here you notice that um and maybe i could have cached this actually so that i don't do a full loop but you can see that i do this loop and this check every time but um but you can actually you know think about um if you use managers you can actually create the edges directly and then only use those edges that gets you to the um to the next node but i think actually now that i think about it in theory that would still have n square time here but it would at least be faster i think i was worried about like i said you know if you if your running time is 9.7 know if you if your running time is 9.7 know if you if your running time is 9.7 seconds um that would have still shaved a lot of time off the clock and that's why i was going for that route and i spent a lot of time doing it but uh been the end um the concord naive and square python actually worked even though i mostly did it and uh during the contest i didn't see sharp because it took only 260 millisecond and i knew that it'll be fast enough so that was a little bit sad in that guard but um in that regards but yeah uh that's all i have you could watch me sub it live during the contest next okay so that wasn't that bad um wow people got it really quickly though because i mean it was just a mistake so okay not an empty power drama strings okay hmm 2000 is tough in python they have to learn the managers uh algorithm never needed it but a lot of people know this one i mean i feel like if you have mandatories it's quick enough that i don't know mandatory so well standing just becomes okay i mean i have to learn it so it's probably going to take some time but i think once i learned it's fine but uh maybe in java i could do and square way of doing it as well um which is annoying because i think this constant is very slow in python that's why to do uh n square i mean whatever not i have a four hours i could learn it but i mean this is just library function i'm kind of annoyed about it but okay let's go hmm i guess i could do it that way because it's linear anyway but hmm because you're wondering i'm just on the wikipedia page uh and just try to copy that a little bit i think the other way is the convention but more nine minus one hmm i don't remember how to do this peace the right size for this then we set it to nice uh i will just code before but i can't find my code remember okay so that's basically it will give us the whole um element so let's kind of take a look and we just return why do i appear okay so this three means what is this three means that there's three characters here right i forget what this means is one two three the first one should be true because this i feel like there should be a 2 somewhere why is this one or am i just wrong am i using the wrong album like i feel like this should be two somewhere here am i doing uh so we look at i there's one on both sides correct now i guess this is a one on both sides so it's two but hmm am i indexing all right okay so then okay i think i'm roughly right but now i just draw the graph on the dp on a dp do you this feels a little bit off let's print this a little bit different way so the left right isn't quite right the way i'm writing it uh it's zero one why is this one oh zero three one two three why is this zero oh because it doesn't count the thing so i have to change that now because then now they're different okay let's start this at one then just b being one what does that mean diamonds that um i added to here but let me start it here right uh i have so many off by one situations have an hour i have time even though this is a silly pile um unless you've done it before or maybe i'm doing a dumb way but this is only oh this is three because it goes here so actually maybe i just do this okay and it gets out on the right which is this ps1 gets out here is that right now that'll always be a little bit awkward maybe let's look at another one actually so i don't want the shortest path so i think this is a little bit awkward but that's not that bad actually so okay so zero this is one connecting this to this one and i'm just having a lot of off by one issues that i'm struggling to figure out how to deal with just manage i mean i have to idea but hmm what is zero what does zero mean zero means if length is zero it goes to this plus one maybe i'm struggling to figure out how to handle this a little bit so just one means that this is covered i think what i have to figure out is um if centered martin is one damage we are on a character if it was on a real character then we do and we know that edges of left you're going to be zero me append that to right if it's zero if it's what does that mean if it's one well it's triggered only because of the first instance because i'm dumb about it i mean once you set the graph everything becomes easy because it's just that for a search but i don't know how to set up the graph but i'm being dumb about it so here's one two that's because it includes these silly characters actually let's see it should be this two and now maybe that's better yeah okay maybe that's better um so zero well negative one is a popular place to hang out hmm that's not good oh maybe i just been confused entire time but yeah that actually doesn't make sense the other way okay now yeah let's now make this a set okay so now from zero it goes to itself goes to one goes to two one it goes to two it goes to three i don't even know where three i guess it's just the last character that's fine maybe okay let's see zero goes to zero that's fine um b goes to one which is itself two which is b and c which doesn't make sense and then four which is one two three so four kind of makes sense the two doesn't make sense though two and two makes sense three i'm just having the off by one issues um yeah i don't quite know how to deal with it because i'm not that familiar with the um managers it just looks more reasonable at least because zero yeah at 40 minutes up i get it but it's still tough like p it goes to from itself to itself which is fine c should go from i think my problem is the even length ones i think that's the way i'm struggling with where i have the middle one but that goes from left to right so i think i just have to really um you know center my 2 is equal to so guys so this is odd then there's a real character then edges of left else uh if this is the middle what is the middle so this is one because it encompasses these things and what that means is that is something like maybe i don't know a little bit i'm a lot tired right now to be honest not sure this is wrong to be honest but yeah we have debugger okay so left right is zero for this one that's fine 0 for this one that's fine no that's not this should be zero one that's okay so once in there um this one tells me that yeah there's one length so the left is zero and the one is one um so it should go from zero to two maybe that's fine i don't know maybe this is just what i need i don't know so to one two three is what i want one two three is i mean this last character doesn't matter so but one two three one should go to two as well so i think that's the one that's missing uh well that's because the maximal that's why because this maximal thing i don't create all the edges uh what am i doing i should have used another language having that far we should have what i done because in python i think the constants are too slow let's see i don't know any other like okay so let's just do it naively and square um how do i want to do this yes i should have changed to language a long time ago yeah well and then maybe i could do this in c sharp or something hmm okay it doesn't crash so that's good um yeah i forgot you that might be cpas for syntax okay awesome okay so that looks good and now we just need another um okay you that's not good i know it was going to run but i don't at least give me the right answer okay so this is good that's not good that this isn't true though um ideally i have more here but i don't know why this doesn't uh let's see um hmm that's weird maybe i won't get it because i'm just too dumb today why is the inner loop doesn't go beyond on this one disappears true so why does that not go in the loop huh this is such a silly problem that i don't know why i'm taking so long but maybe just one of those days this is true all the way so the sp function is right but i don't know am i calling it well index i what i'll do is this is zero one so do we even say two so why is this giving me force um to retweet the first part oh that's not right ah what am i doing wrong it must be something dumb oh snap that was something dumb okay true first okay i can't believe i spent that long debugging this um okay let's kind of give it a go if i don't know if this is fast enough but let's see i hope that is fast enough it looks fast okay i mean this is such a i know how to do it from the get-go budget do it from the get-go budget do it from the get-go budget i guess i should have switched language because i think n is too slow for pi n square is too slow for python but n squared was fast enough for other languages i could be wrong on that one on the python one um but otherwise it is such a dumb problem um i mean it's a good problem it's just i don't know why they made a constraint such that it's heavily biased against python um yeah i mean i don't know where i finish because a lot of people gone down because i know how to do that one immediately it's just you know wow jeebus it's just that um it's just that i don't know i was trying to figure out how to do it in python for too long um when i should have done it in other languages um because and even here i um i wonder how long i spent on this one but i probably like i had this algorithm pretty much right off the bat so if i had implemented it from scratch maybe i would have been slow but even 20 minutes would have been way faster than whatever i end up taking a lot of people got this really quick so i don't think i would have gotten a good score in either case but uh what a silly contest um i mean i don't feel that bad because i think i see some good people that are like you know like alex i just saw um and i think it's just oh wow he got in nine minutes actually yeah maybe there is a way to do it maybe end square is fast enough in python maybe i was wrong um because i think if i could do an n square then i just wasn't confident about it but i should have just tried it because it was only a five minute penalty um because instead i spent way too long on python try to do it to not um fast enough for it let me try to observe this and not observe it just solve it normally but in python um so i had this crazy algorithm but um but basically what i needed to do was just so i would have done something like this and this is true actually i guess it just return this and that's there is palindrome uh and let's do the one for the other one uh let me uh good um index parts and it's just was it if index is equal to n parts is equal to three return true else return fours two parts you got three return fours and then we just do a for i and i just spent too long debugging something that wasn't needed to be debugged because i'm dumb there's no way about it um i don't know just one of those i mean my life's been a little bit weird in general so maybe it is what it is um good yeah that's i almost made the same mistake again um that's pretty much it i should have tried this i mean this would have even i should i think i was too scared about the five-minute penalties but uh but the five-minute penalties but uh but the five-minute penalties but uh but maybe i shouldn't i mean this took i mean look at this though it actually is a legitimate concern let's give it a submit to see whatever i've worked i think it should have time limit exceeded that's why i don't know if it works it would have been very barely so that's why i didn't do it in python but as you can see um oh my god well i don't know maybe i should have done it this way then uh yeah thanks everybody for watching uh let me know what you think about this farm i didn't do that well on this contest just based on some things that if you watch the contest video hopefully you'll see but yeah um hit the like button again hit the subscribe button again join me on discord again um and hope y'all have a good day take care of yourself if you have the fortune you know take care of others um to good health stay good stay well you know and pass it forward and you know treat people around you well um and to good mental health and i will see you next problem bye
|
Palindrome Partitioning IV
|
find-nearest-right-node-in-binary-tree
|
Given a string `s`, return `true` _if it is possible to split the string_ `s` _into three **non-empty** palindromic substrings. Otherwise, return_ `false`.
A string is said to be palindrome if it the same string when reversed.
**Example 1:**
**Input:** s = "abcbdd "
**Output:** true
**Explanation: ** "abcbdd " = "a " + "bcb " + "dd ", and all three substrings are palindromes.
**Example 2:**
**Input:** s = "bcbddxy "
**Output:** false
**Explanation:** s cannot be split into 3 palindromes.
**Constraints:**
* `3 <= s.length <= 2000`
* `s` consists only of lowercase English letters.
|
Use BFS, traverse the tree level by level and always push the left node first When you reach the target node, mark a boolean variable true If you meet another node in the same level after marking the boolean true, return this node. If you did not meet new nodes in the same level and started traversing a new level, return Null
|
Tree,Breadth-First Search,Binary Tree
|
Medium
| null |
344 |
hey guys persistent programmer here and welcome to my channel so if you're new here we solve a lot of problems on this channel and today we're gonna be looking at the reverse string problem so this is a really interesting problem when you use the two pointer solution to solve it and that's exactly what we will be doing today so I hope this video helps you understand the question and let's go ahead and get started this is a very simple problem to understand we're given a string and we just need to reverse the input so if we're given hello we need to return oleh so just reverse the strings but the key in the question is we need to do this in place so this means that we cannot create any auxilary array to do this transformation okay so with this in mind let's look at the solution so to solve this problem what I'm gonna do is I will initialize two pointers so I will start my pointer here so this will be my left pointer and I will have a pointer at the end of the list here at the Oh and I'm going to swap these two positions so what do I mean when I say swap right so if I were to do this for this first iteration what this would look like would be full e ll H so what I did is I swapped the oh and the H here okay so you can see that yeah this just swap the first two positions but we haven't swapped the rest of the list right so how do we swap all the items in the string so what we do is we just move our pointer so we move this right pointer over here to this next position and remove this left pointer forward so at each step we're going to move our left pointer forward and our right pointer backwards and then what we do is we have the same positions here so these don't change and this will transform to now L and then eat so now we switch the L and the e right and this will remain this the same and you can see that we've already solved the problem because this is the output so at each point what we need to do is we just need to move our pointers and go through in a while loop and solve this problem so the time complexity for this is o FN because we will iterate over the entire array and the space complexity is o 1 which is what the question asks us to do and at each step we'll just literally swap the two positions were add the strings the elements at those places and we'll just advance our pointers and that's it that's all we got to do okay awesome so let's look at the code finally code and I just wanted to point out a few things before I start writing the code so there is a reverse method that can be used to reverse strings and that's what you would generally use however this question does say that you need to solve this question using off one time and the reverse method actually takes off and time so it creates a copy so we can't use that unfortunately to solve this question in one line so let's go ahead and implement our two pointer solution so the first thing I'm going to do is say left equals zero and write will be the last item in the string so I'll say Lam string length of string and then rules your minus 1 because we're starting from zero and we'll say a while left is less than right so if left is equal to right that means for this list will be like in this spot in the middle and that means we have done all our swapping and there's nothing else to do so that's why the condition of our while loop is left is less than right and now what we want to do is we want to swap these two elements in our list and the way we do that is first of all I need to stash this element somewhere and then I will replace this with uh-oh so let me show replace this with uh-oh so let me show replace this with uh-oh so let me show you how that's not so I'll just create another variable let's call it like hold-hold equals so I'm saying hey keep hold-hold equals so I'm saying hey keep hold-hold equals so I'm saying hey keep the this value so I will say left I will say S at the index of left so this is currently holding the H and then what I'm going to do is say s at the index of left which means at that position where H currently is put the element of the right so it's gonna replace the H with the O so we will say s right so if we were to print this list right now it would look like Oh e ll oh so there's there would be two O's and the last step is to put the H here in this position where they're always and we already stored the H in this hold variable so what we can say is s write equals bold and after that what we need to do is just advance our left pointer forward so left plus equals one and our right pointer backwards so right minus equals one okay so that's our code let's go ahead and submit this okay awesome accepted thanks guys if you liked this video please go ahead and subscribe to the channel give this video a like and if you have a different solution please post it in the comments below it could be in any other language it's just gonna help other people look at the solutions and understand and solve this problem themselves thanks guys happy coding
|
Reverse String
|
reverse-string
|
Write a function that reverses a string. The input string is given as an array of characters `s`.
You must do this by modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm) with `O(1)` extra memory.
**Example 1:**
**Input:** s = \["h","e","l","l","o"\]
**Output:** \["o","l","l","e","h"\]
**Example 2:**
**Input:** s = \["H","a","n","n","a","h"\]
**Output:** \["h","a","n","n","a","H"\]
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is a [printable ascii character](https://en.wikipedia.org/wiki/ASCII#Printable_characters).
|
The entire logic for reversing a string is based on using the opposite directional two-pointer approach!
|
Two Pointers,String,Recursion
|
Easy
|
345,541
|
871 |
Bullet Guys Welcome To Our Channel What's Onion In This Video You Will Be Talking About Minimum Number Of Curing Stops Problem Udhar Lead Code Indexes 80 Problems Categorized As Heart Problem Delete Ok Sorry For Movie Phanda Just Want To Ask Weather You Have Done This Problem and possible third list to be destroyed because of its problems point do not similar to this one act you can do this and you can come back to this problem right hand side to this problem this concept of like dynamic programming but if not done dispersion end with a dog Training program in chords detector time complexity of any space but what the demons like using the concept of multi state water in reverse order but doctor in increasing order cancel this literature data structure at this rate you often for talking about this problem actually sequence of distance Responsibility of sequence sub station more than seven different code in its ok administration is going to hold to possible validate this every year they will support you start to this station superintendent has to decorate updater station of in1 is issued in Delhi as well as at stations Going to Provide for Customer Price Text to Speech Impaired Thanks for Guess Which Initially Has Started Give Something Letters for Its Users to Monitor Gas Per One Table of Authors Dispatch Drive One Kilometer Debit Consume Exactly One Letter of Woolen Initially the Car Has 0 Something About Opted For Added That You Are Wick And Its Position Zero No Data Is Not Mentioned Earlier But According To Reference Maximum Per Chat Start From His Position In 100 Strike To Person's From Gas Station It Means Talk At This Never Win A Content Item Particular Station Day It Means top ten refueling and during his life free from all the guests from the station into account like particular station has 6 maximum top leaders being capable to give some customer pathetic transfer all the actions of letters to the particular customer option right and what is the list Number of Refueling Stocks Deccan Must Make in Order to Reach Its Destination Writers from Starting Point and Terrorism in Points Reduced in Points Understanding Point and the Way Yesterday Lips Were Collected Over All Want to Dead Target Position and Remind Me Some Possibilities Chat Start Police Not Capable To consume all start will not be able to reach the target to visit that topic we particular stations and to make all will be fulfilled with them after some days flash lights and what is the minimum number of staff and date we have to make in order to Reach Its Destination Date Is The Card Option Handsome Amount Of Leaders Of Gas In Medicines Cancer Own Addiction With The Target Destination Like And Completely And Without Having Spent In Reaching At A Certain State Where They Can't Have Something And Can't Move For The Right To What is that minimum number of curing stocks the respectively have to make not the crotch gas station rebellion fuel tank word can still rude and definition of panauti easily understand the crowd in the traffic jam plus right but the system please like subscribe top weight example and discussed In This Also Benefit And How They Can Help Residency The Landslide Fiber Network Is The Solution That Is Off But In This Attempt User Login Solution The Best World Ki And E Rather Way Relations Between The Part Open Stations Hunter Target You Will Start Feeling Station 512 Like 10.1 to Liberation Var Feeling Station 512 Like 10.1 to Liberation Var Feeling Station 512 Like 10.1 to Liberation Var Dhavali Advantage Near to Adda Versus Student is Like This 1500 Vacancy Information of Institution Date is also possible for this question ok friend look up understand this problem in a little bit detail and together will double the idea solution and the best way to So let's move ahead of this problem, maybe it can see your website and simple example number, third right, okay, so one such thing appears as denoting the first man to be retired in and coordinator for a particular station and settlement of disputes and I know. The fuel that has been provided with the station Transferee and Refugees Particular Option Demand Right Now Think What the Fish What If Done What Have Started Thinking What is the Problem Is Like This Say Right Think This is a Particular Station Their Selected by Which Color to Opposite Particular Station OK And Like And 10 Previous Stations You Can See It Can Reach From This Start Units Acid Start New Updates Is Obscene And They Can Come That York Stock Leaves Patients Were Taken From Over To Which Position Right And In Icon There Next Position And Master Tourist Label Computer Labs for Distribution Pimple Ki MLA Update Start with the Show Day Udhar Station and Supports Deliver Pink Water Distribution at the Top Cop Registration and Congress Still Has Not Sufficient to Connect with This Position Okay So You Don't List Started 100 and Talking in General K Tops Tubeless Okay Ninth Encounter Registration You Find What You Were Not Sufficient To Come Up With A Situation Like Water Into You Must Think You Must Have These Video Subscriptions That Day Taste One Of Thumb Up To This Station Ko Model Station You Must Have To Review Vehicle with the help of the best provided by Drishti Police Stations Rights or Benefits Have not to customize Award to start work We for this first university which starts unification of this position Subscription revenue [ __ ] tourist revenue [ __ ] tourist revenue [ __ ] tourist destination for start-ups Note destination for start-ups Note destination for start-ups Note Subscription Invite you to To to subscribe the thing you can very from this thank you all they know not subscribe to that station hai to kaun it's MY and distribution wanted difficult want to comment registration blurry see must have the few line there kal like at least divided in Three Years She Can Reduce Soon Can't Position Right Now Was Demanded That You Will Assist You Need To Add Subscribe Button For New Updates To You Must Think For The Time And Subscribe For Destruction In What Is The Concept Of Refueling Like Click On The Station White Color Station Master You Will Start Refueling Two That Tomorrow Pistol Till Previous Station Gas Filling Station Sludge Get That Pilot Station Day How Can Start Refueling One Plate Supposed This Station Products Six Amount of Gas Loose Station and Destruction Per Amount of Gas in What is the Way To Receive New Updates Which Station Is The Shaktiman One To Started During My Option Jitend Station Install One Right Deposit Gifts For Maximum Autotune Fatso I Will First Refueling My Absolutely Rebellion's Provided By Distillation So A Plus 6 Any Five Dire Need To Give Chick Deposit Amount of statutes PC-12 between this station and of statutes PC-12 between this station and of statutes PC-12 between this station and note snowden you log in fixed 10 second maximum fuel provided by the previous station from this is the first maximum I can see and second maximum is this kuchh der na lagi hai dirty achhe cut off this is The Sufficient That's This Is The New Content Fuel Is Sufficient There Station And Notice Station Unfit Sufficient That's All Things Items From This Station Hello And Gifts Okay Withdrawal Two Times I'm Refueling Mind Absolutely Okay 100 Unit Subscription Okay So Police Station You've Changed To Date With Re I Can Reach Sorry Follow On Twitter Thank you Rush Will Not Stopped Taking Maximum Elements Of The Video Then Subscribe To The Detention Under A Little Bit Example Subscribe 602 Ki 99549 Of Which Some Particular Station Demanding 8510 Amount After fuel ok so and valid css the country fuel start used in which state is going to be like electronic 500 and not black widow inch plate already greater than 50 years can see this totally optional to connect with station right and what about this will access Multiplex Trophy List 501 Vacancy I Cannot Come From Will Produce Start With This Particular Station OK The Previous Gas Values Pet Stations Will Provide OK What Gas Values Pet Stations Will Provide OK What Gas Values Pet Stations Will Provide OK What is the Best They Decide Which Element Which Will Be Provided By Which State Is The Current Amount of Gas In Need to take any to make my p51 more days HP compaq places and only acting greater volume increases the probability of reaching the like at least value of this station latest phase as maximum volume of the great being provided by all the previous station slide show effect Absolutely Maximum Policy Minimize My This Question Feel Minimize My Answer Voice Mail List Number of Refueling Stops Till Personnel In Order To Reach The Destination Travel Makeup 19th May Cup 7110 Makeup 1620 E End Use This Strip Milk This Process Last SP Comes At Least 500 OK days this can be mental this can be maintained with the help of co like particular station you must keep track of all the guests at which have vanished from the previous station in constitution whatsapp data structure daily unise lift maximum every time they demand time fuel rights on This can be held at this can be done like keeping track of all the festivals recharge use a particular station dentist dr tuesday atl used oil the previous station with respect to migrant station distance is beaten with the help of data structure and its beaten with no formal Team Set Pin Short Tricks And But Decreasing Order Came So Let's Move To Front Time Approach To Build Up The Idea Thumbs Up Review Astrology Can Approach Towards Its Solution With Help From Middle Order Friday Guys Let's Move On Till Okay So This Fancy This Is The Target One of them in this trust you record too 10 and sister position siro ok welcome to this tuition fee know what is the time from zinc and also you can see it practically nothing but a well known in order to claim a the priority key of fuel values And the particular station is just Manipur State Value Unko Mein Practical So When It Comes To Win Laptop Basis Station What Is The Current Maximum Reachable Value Duty Edison Content Maximum Reachable Value With The Help Of The Current Tulip NFC Start He Listen To Make Current Maximum Reachable Value Jeweler Stand OK To Usin Correct Maximum Visible Value Stand Securities Ltd Come Up To This Position And This Position Held Coordinator 0 Travel Se Ok I Like Him To Jis Position Din Will Move Up To Next Position And Assured Them Of Snakes Position Mic Current Maximum Which Will Assist 10 And Widening 98100 Michael And Witch Way A Pan From Witch Gas Station Witch You Can See Only One Avoid Gas Station Video Quote 6 Day Gas Station Co * Fold 6 Liter 6 Day Gas Station Co * Fold 6 Liter 6 Day Gas Station Co * Fold 6 Liter Grade To Meet At One OK Migrate From Witch Will Position Changes From Toe New Chhath 200 comes at least 10 ok so i see i hate you all my steve one times now-cvoter this all my steve one times now-cvoter this all my steve one times now-cvoter this subscribe like completed subscription will push subscribe 6 ok alvin thomas 2g station ka to reduce like if you did you all my vehicle travel pickup the maximum Element From His Priority Q That's The 69 Match Practice Cuticles MP3 Vape Purpose Station Maximum Vikram 70mm Computers Visiting This Station Is To Push That Will Provide Registration To My Priority Q Why Practice During The Day Contents My Single Element Now Special Guest 98100 And Have Already Used at one time the evening my vehicle ok and ok so let's move like or police station you can see it requires at the co detector co niyati can have riched the productivity with maximum reachable time cycle loot and options next position not against this being pushed Into r priority queue notification it's true and comes back to 10:30 ok now here comes back to 10:30 ok now here comes back to 10:30 ok now here comes with sixteen no it's great you have to vape cheese station year old coordinator 361 maximum reachable at 60 cents that date so let's move to the target for not taking it's my Between Target Not Difficult Updated With Your Value For Shyam Safety Comes Up So Vinayak Kauwar Target To Maximum Republic 70s And I Targets Demand Subha Hundred Swift 111 From Distract You Taste Positive Its Maximum Element From Different Units Which State Is Must To Reschedule Mave Ke Laddu Station To Maximum Retail Vikram Celebrate And One Day Comes To Because E Capsule One More Time And They Can Reach The Target And Differences Sachiv V Tapkeshwar Elaichi Bal And My The Victims To-Do Elaichi Bal And My The Victims To-Do Elaichi Bal And My The Victims To-Do List Amount Of We Ring To The PlayStation Two Times Ok To This Is What Women Want From This Problem So Let's Move To The World That's The Beach 900 Vacancies After Mid Term Quotes For The First Give The Song Has Been Observed With Them Very Small Police Mistake Police Team Survey Report Subscribe Now You're Doing This You All Subscribe Used And 100 Subscribe My Channel Like This And Finally Button Subscribe And Subscribe Like And Subscribe My Channel Subscribe Our Channel Like This Is The Element Subscription And Ghadi Find The Furious 9 Temple And Maximum Reachable Is Not Sufficient To Reach At Migrant Station Day You all my village surplus maximum reply sequences used whatsapp status from the shopping element from the top right issue dated refueling michael from date particular gas station which provided them onto this and remove begin from the priority queue and still after doing this maximum reachable is left end Stupid and Migrant Station Value Vacancy Account Dr to This Particular Station Return - 1st Maze Creations and Other Wise Return - 1st Maze Creations and Other Wise Return - 1st Maze Creations and Other Wise Used to Push 1518 Pushing the Current Letters of Guess What is the Current Station in to Make Right You OK Father Processing and Returned and Final Destination at All Stations And Width Can Achieve Return Least Amount Of Sensations With Dash Kholo Uttar Pradesh Will Give Voice Test Cases For Rest And Development Per Cent And After Submission Front End Its Objective In It To Let Me The Comment 16th Video Interview Schedule This Video Share This Video End Subscribe Our YouTube Channel For Latest Updates Thank You For Watching This Video
|
Minimum Number of Refueling Stops
|
keys-and-rooms
|
A car travels from a starting position to a destination which is `target` miles east of the starting position.
There are gas stations along the way. The gas stations are represented as an array `stations` where `stations[i] = [positioni, fueli]` indicates that the `ith` gas station is `positioni` miles east of the starting position and has `fueli` liters of gas.
The car starts with an infinite tank of gas, which initially has `startFuel` liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
Return _the minimum number of refueling stops the car must make in order to reach its destination_. If it cannot reach the destination, return `-1`.
Note that if the car reaches a gas station with `0` fuel left, the car can still refuel there. If the car reaches the destination with `0` fuel left, it is still considered to have arrived.
**Example 1:**
**Input:** target = 1, startFuel = 1, stations = \[\]
**Output:** 0
**Explanation:** We can reach the target without refueling.
**Example 2:**
**Input:** target = 100, startFuel = 1, stations = \[\[10,100\]\]
**Output:** -1
**Explanation:** We can not reach the target (or even the first gas station).
**Example 3:**
**Input:** target = 100, startFuel = 10, stations = \[\[10,60\],\[20,30\],\[30,30\],\[60,40\]\]
**Output:** 2
**Explanation:** We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
**Constraints:**
* `1 <= target, startFuel <= 109`
* `0 <= stations.length <= 500`
* `1 <= positioni < positioni+1 < target`
* `1 <= fueli < 109`
| null |
Depth-First Search,Breadth-First Search,Graph
|
Medium
|
261
|
387 |
hello everyone welcome back uh here is van damson with another live coding session and today we got a super interesting problem on our hands first unique character in asterisk so sounds simple right but there is so much more to it so stick around and let's dive deep together so here is the task given a string we need to find the first non-repeating character in it and to non-repeating character in it and to non-repeating character in it and to return its index so if it doesn't exist we return simple minus one so let's look at couple of examples so for the string lead code the first unique character is out so the output is zero four uh love late code is V giving us output of uh two so and for a b there is no unique character so we return simple minus one so now how do we tackle this the key is in counting so let's roll up and get into code so first we'll use a default dict from The Collection a model and this will allow us to create a dictionary where if a key doesn't exist it's automatically added with a default value and in our case that value will be int which default to zero so next we will Loop through our string and count the frequencies of each character and with our character counts in hand will then Loop through the string again so this time we are searching for our hero so the first unique character and if we find a character those count is one Bingo that's our first unique character and we return its index and if we don't find any such character we simply return -1 so let's implement it so character -1 so let's implement it so character -1 so let's implement it so character count will be default dict of int and four character in as character account char plus one for I and tractor in enumerate of s if Char counter equals one we simply return I so and return minus 1 if we didn't return here I okay so let's run it for this test cases to verify it's working so yep all good and there we have it so let's run it also for and since cases to verify it's uh it's everything so yeah our implementation work and we beat 75 percent with respect to runtime uh 100 for milliseconds all good so uh yep an efficient solution using just a couple of loops and the magic of a default disc so now for those of you calling in other programming languages uh don't thread I have implementation in uh go rest C plus and much more in the description below and I hope you enjoyed this session and don't forget to hit the like button share and subscribe for more coding Adventure uh drop your question or any thoughts in the comment section below and I will see you in the next one keep practicing and coding
|
First Unique Character in a String
|
first-unique-character-in-a-string
|
Given a string `s`, _find the first non-repeating character in it and return its index_. If it does not exist, return `-1`.
**Example 1:**
**Input:** s = "leetcode"
**Output:** 0
**Example 2:**
**Input:** s = "loveleetcode"
**Output:** 2
**Example 3:**
**Input:** s = "aabb"
**Output:** -1
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of only lowercase English letters.
| null |
Hash Table,String,Queue,Counting
|
Easy
|
451
|
623 |
hello everyone so today i want to solve this question add one row to into the tree okay so let us read the description so given the root of a binary tree okay the value v uh end of the d okay so there are two values they are given you need to add a row of node with the value v at the given depth d the root node is a depth one okay the adding rule is given a positive integer depth d for each not null tree okay and in depth and d minus one create a two three nodes with the value v as n's left sub uh root sub tree root and the right sector root okay and n's original left sub tree should be left should be to the left of sub tree and the new left sub tree uh subject root its original right subtree should be on the right subtree of the new right subtree root if the depth d is one means that the there is no depth d minus one at all then you need to create a tree node with the value v as the new node as a new root node of the world originally and the audience should be uh new roots left subtree okay so what they are giving what the statement is saying is so let us take this example to understand the statement so you can see this is the root okay and we have some values to the left and right and we are given the value as one and depth is uh depth as two so at the root depth is one this is depth two this is depth three so at the depth two we're going to put this value v which is one so our resultant tree should be like this four okay then value at depth two is nothing but one so for the left it is one for the right it is one and for the left this should remain the same so basically we are going to put as it is three one and for this one we know that is uh six is there here and five is here so this is the resultant basically the three okay so this is we need to show them as output okay let us scroll down and see the output so you can see this is what the tree we have on drawn here same tree okay so let us see the another example so same here we are going to see that the value is one okay the value is one here and depth is three so this one is one two three so here one two three this two value comes and this two three remains the same okay and uh you can see suppose there is a tree like this four two three something uh and it's taking the random values okay and we are given depth equal to one at depth equal to one mean we need to give value as three any values so what will be the resultant this will be like this it will should be at three and on the left it should be the whole tree as it is okay so let us try to understand the uh code here okay so what we going to do is first we are going to take the base case in which uh we need to put something at t equal to 1 or basically at the root we need to put something so we are given the value we are given the depth so first we are checking if depth equal to 1 okay in that case what we need to do so suppose this is the tree let me reduce the size so suppose this is the tree okay do one something like that okay this is the tree and we want uh we have some value like three and depth equal to one okay so in this case in that case what we need to do what do we what we are doing here so first we are creating a three node t1 we are calling that node as t1 okay so suppose that is t1 here okay we are calling this as t1 and what is the value for that so the t1's value is whatever the value we are getting so here the value is 3 so we are storing that value in this so this is missing the t1 okay and then what we are doing our t1's left should be the root okay so this is basically the root of the tree original tree and t one's left should be the root so basically we are connecting this okay and that then what we are doing we are returning the t1 so now the t1 is this one now this whole tree will be done okay so this is the base case and in other cases when this is more than two or something so we are just calling this function fun okay in this what we are passing root value at d minus one because we need to uh this is basically the original d which is one if it is not one then we're going to see for the other values okay so it is already starting from one so for two four three okay so we are just reducing the depth and we are passing okay so basically if you have some value 3 so at depth equal to when depth equal to 2 so basically it will go here so it will change that okay so let us see the fun function here what basically they are doing so this is the fun function okay so in this what we are doing we are checking the base condition which means and tap equal to 1 because where we are starting our iteration we basically the depth of the truth is 1 that's why this d equal to one is the base case okay so here we are seeing if d equal to one okay so in that case what we need to do we need to create two uh nodes basically three nodes one is for the left and one is for the right okay so left goes the value b and the right also goes the value v okay and uh what we are doing t one's right should be the roots right okay and t one's left will be the roots left okay and then we are doing the root tends left equal to t and then root tends to write equal to t one here okay and then we are just returning the root and once we are done with this condition we are calling the um again we're calling this function one with the root uh roots left value p value and then d minus one and for same you are going for the right so v and d minus one okay and we are updating that root can so left and right and so right and we're just returning the root from here okay so this is the basic idea of the question add one row to the tree so i hope you got the basic idea of the code so we'll meet in the next video with another problem okay so thank you for watching if you like the video just go and like the video and subscribe to the youtube channel bye
|
Add One Row to Tree
|
add-one-row-to-tree
|
Given the `root` of a binary tree and two integers `val` and `depth`, add a row of nodes with value `val` at the given depth `depth`.
Note that the `root` node is at depth `1`.
The adding rule is:
* Given the integer `depth`, for each not null tree node `cur` at the depth `depth - 1`, create two tree nodes with value `val` as `cur`'s left subtree root and right subtree root.
* `cur`'s original left subtree should be the left subtree of the new left subtree root.
* `cur`'s original right subtree should be the right subtree of the new right subtree root.
* If `depth == 1` that means there is no depth `depth - 1` at all, then create a tree node with value `val` as the new root of the whole original tree, and the original tree is the new root's left subtree.
**Example 1:**
**Input:** root = \[4,2,6,3,1,5\], val = 1, depth = 2
**Output:** \[4,1,1,2,null,null,6,3,1,5\]
**Example 2:**
**Input:** root = \[4,2,null,3,1\], val = 1, depth = 3
**Output:** \[4,2,null,1,1,3,null,null,1\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* The depth of the tree is in the range `[1, 104]`.
* `-100 <= Node.val <= 100`
* `-105 <= val <= 105`
* `1 <= depth <= the depth of tree + 1`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
1,936 |
hello everyone welcome to quartus camp in this video we are going to cover the problem at minimum number of ranks which has been asked in one of the lead code weekly contest so the input given here is an integer array runs and an integer variable distance and we have to return the minimum number of trunks that we must add to the ladder in order to climb to the last rom so the rules given here are you can only climb to the next highest rung if the distance between the current one and the next rung is at most the given distance so let's understand this problem with an example so here is the example given in the problem statement and the integer array runs represent the distance between each rung in a ladder so if a ladder is given and the rungs are placed at the distance from floor it is 1 and then at the distance of 3 from the first rung and at the distance of 5 and at the distance of 10. so now we can climb from one rung to the other only if the distance or the maximum distance is two so we can add wrongs as per the problem statement if we need to climb to the last round so how many uh rungs we can add is the output so now let's start climbing this uh ladder starting from the flow so now we are at the distance of zero from zero we can climb to the first rung only if it is at the maximum distance of two so if we calculate the distance between zero and one it is one which is actually less than two so we can actually climb same applies to the next rung which is at the distance of two so this can also be climbed again three to five also be climbed with the because the distance is two so now here comes the last rung there at the distance of ten but we are at the distance five so from 5 to 10 we have the distance of 5 which we cannot actually climb as per the rules so now we have to calculate that how many number of rungs we actually need to add in between them in order to claim that so the distance is five we can at most climb to the maximum distance of two so in that case if we have a rung at the position seven then that would help us to climb to the next step so we exactly need one so far to climb to seven so from seven the maximum distance or the rung you can climb would be at the distance nine because it can move to only two as the maximum distance so at nine you need one more round in order to reach 10 so in total you need two rungs to be added in between the distance five and ten to reach to the top rung and that is going to be your output so how are you going to approach this though this problem is under medium category it is not so tough it is quite an easy level problem to solve because we simply going to calculate if there is a maximum difference between next integers by iterating them and if we find a bigger difference than the distance given so then we are going to see how many rungs we are going to add which is nothing but if the difference is 5 between 5 and 10 so 5 divided by the total number of distance or the maximum distance given so the integer value that returns from this is going to be the number of rungs we need so 5 by 2 is nothing but 2 point something and the integer value would be 2 so that is the number of rungs we would be needing so it is pretty simple we are going to iterate the given array and find the answer so hope you are understanding this concept let's go to code now and this is going to work in big o of n time complexity as we are going to iterate the array only once to find our result so let's go to the code so we are going to have two variables current and next which is going to hold the distance of the current ladder or the current run and the next row and the result is going to be the number of rungs we need to add and that is what we are going to return as our output so now we are going to iterate a given array and that represent every next rung we have because the current is nothing but the floor so floor is at distance 0 so let's iterate the values in rungs array and we are going to add the result by dividing the value every time so every time we have to calculate the difference between the next round and the current round so next minus current divided by distance but if the next is actually equal to exactly current or less than current then we would be getting one or more than one from this result so but we don't have to really add any rung if we can pass through that so in that case we have to add a minus 1 because the at most distance must be 2 so what if both the values are equal in that case we'd be getting a value as one or more than one so we have to add a minus one in order to get a zero value when we can climb to the next row only if the distance is more and we cannot climb to the next rung then one only then we would be getting a integer value from this so every time we climb the new rung we are going to update our uh pre current to next and to keep track of the previous value so yes this is it let's run and try yes let's submit yes a solution is accepted and runs in two milliseconds so thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
|
Add Minimum Number of Rungs
|
maximize-number-of-nice-divisors
|
You are given a **strictly increasing** integer array `rungs` that represents the **height** of rungs on a ladder. You are currently on the **floor** at height `0`, and you want to reach the last rung.
You are also given an integer `dist`. You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is **at most** `dist`. You are able to insert rungs at any positive **integer** height if a rung is not already there.
Return _the **minimum** number of rungs that must be added to the ladder in order for you to climb to the last rung._
**Example 1:**
**Input:** rungs = \[1,3,5,10\], dist = 2
**Output:** 2
**Explanation:**
You currently cannot reach the last rung.
Add rungs at heights 7 and 8 to climb this ladder.
The ladder will now have rungs at \[1,3,5,7,8,10\].
**Example 2:**
**Input:** rungs = \[3,6,8,10\], dist = 3
**Output:** 0
**Explanation:**
This ladder can be climbed without adding additional rungs.
**Example 3:**
**Input:** rungs = \[3,4,6,7\], dist = 2
**Output:** 1
**Explanation:**
You currently cannot reach the first rung from the ground.
Add a rung at height 1 to climb this ladder.
The ladder will now have rungs at \[1,3,4,6,7\].
**Constraints:**
* `1 <= rungs.length <= 105`
* `1 <= rungs[i] <= 109`
* `1 <= dist <= 109`
* `rungs` is **strictly increasing**.
|
The number of nice divisors is equal to the product of the count of each prime factor. Then the problem is reduced to: given n, find a sequence of numbers whose sum equals n and whose product is maximized. This sequence can have no numbers that are larger than 4. Proof: if it contains a number x that is larger than 4, then you can replace x with floor(x/2) and ceil(x/2), and floor(x/2) * ceil(x/2) > x. You can also replace 4s with two 2s. Hence, there will always be optimal solutions with only 2s and 3s. If there are three 2s, you can replace them with two 3s to get a better product. Hence, you'll never have more than two 2s. Keep adding 3s as long as n ≥ 5.
|
Math,Recursion
|
Hard
|
343
|
1,464 |
hey everybody this is Larry I'm doing this problem as part of a contest so you're gonna watch me live as I go through my darts I'm coding they've been explanation near the end and for more context there'll be a link below on this actual screencast of the contest how did you do let me know you do hit the like button either subscribe button and here we go q1 maximum product of two elements in an array so this one is just greedy I think I when I was when I first opened this problem I was deciding between two solutions basically the proof for sin square one and whether I could do sorting and so anyone has more edge cases if the numbers could be negative but I think I checked that the numbers could be only be positive and then I was like okay off we go so did we just saw it and then we ran away with it we saw it and we took their two biggest number and then we just multiply that gradient down way and then I submit pretty quickly after that maximum product of two elements in a way cuboid so yeah so this one I just did it greedy I just sorted to the their way and I take the biggest number and then the second biggest number it subtract one and then multiply them the thing that I did look forward to make sure that these are positive numbers cause if you're naked if you have negative numbers this won't work but as soon as I saw that it is positive that I just did and they'll be okay you can't also just did it with two folders because n is you go to 500 my maybe I should have gone it turn it that way just because that would be less thinking slightly but I got in about a minute so I'm okay on this particular problem but yeah but if you get to a brute-force I did every sorting get to a brute-force I did every sorting get to a brute-force I did every sorting and choosing the maximal elements oh this is a straightforward form this is n log n because I dominate or you can get staminate by the soy but you can fly in theory what Kwan quote write a linear time algorithm based on the fact that numbers can only go up to a thousand or something like that right so but I think that's kind of half cheating so whatever or like you know that's the size of your domain rather than linear per se but we are straight forward
|
Maximum Product of Two Elements in an Array
|
reduce-array-size-to-the-half
|
Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`.
**Example 1:**
**Input:** nums = \[3,4,5,2\]
**Output:** 12
**Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums\[1\]-1)\*(nums\[2\]-1) = (4-1)\*(5-1) = 3\*4 = 12.
**Example 2:**
**Input:** nums = \[1,5,4,5\]
**Output:** 16
**Explanation:** Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)\*(5-1) = 16.
**Example 3:**
**Input:** nums = \[3,7\]
**Output:** 12
**Constraints:**
* `2 <= nums.length <= 500`
* `1 <= nums[i] <= 10^3`
|
Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers.
|
Array,Hash Table,Greedy,Sorting,Heap (Priority Queue)
|
Medium
| null |
129 |
hi everyone this is a question about tree so this question is sums root 2 leaf number you are given a root of a binary tree containing digits from 0 to 9 only issue to leave path in the tree represent a number so for example the root to leave path is one two three now represent a number one two three and return to return the total sum of the o root to lift number so um you uh you actually understand for example one this is two and if the path is one two and another path is one three you actually add one two and one three together which is twelve and thirteen equal to twenty five and for this one is four nine five four nine one four zero right you add up everything so this is question um i will consider is pretty straightforward uh well what you actually need is you need a uh you need to so i would say in valve so i'll just uh return the helper function sound number and root and then the initial value is zero so whatever you did right um your current value is actually multiple multiplied by 10 plus the current value and if this is um understandable which means you will go on the children right when you go on children you multiply by ten by yourself first ten plus two and this is how you actually do it and uh i will have to make sure there's a base case but if you think okay then i would just return here this is the pistol and i also have to know if my left and right or no which is the base right if uh the left people can know and also with our right uh equal to know but what i actually need to do i just return about all this then that i have to check my root on left and down plot with the right and down and this is the solution and let's just run it all right pretty good so uh let's talk about timing space complexity so you have to try to perceive a single one of them right they'll consider all of n and uh for the space uh you're adding everything up from the top to the bottom so they will consider all the point there's a reason why because you keep adding one and then here's 12 and this is 13 and later on you have to add up to 25 so for each note you have an extra space for that and no traverse all of them right so time and space are all open and will be the solution and if you fail is helpful leave a like subscribe if you want it and comment if you have any questions alright peace out bye
|
Sum Root to Leaf Numbers
|
sum-root-to-leaf-numbers
|
You are given the `root` of a binary tree containing digits from `0` to `9` only.
Each root-to-leaf path in the tree represents a number.
* For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`.
Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer will fit in a **32-bit** integer.
A **leaf** node is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3\]
**Output:** 25
**Explanation:**
The root-to-leaf path `1->2` represents the number `12`.
The root-to-leaf path `1->3` represents the number `13`.
Therefore, sum = 12 + 13 = `25`.
**Example 2:**
**Input:** root = \[4,9,0,5,1\]
**Output:** 1026
**Explanation:**
The root-to-leaf path `4->9->5` represents the number 495.
The root-to-leaf path `4->9->1` represents the number 491.
The root-to-leaf path `4->0` represents the number 40.
Therefore, sum = 495 + 491 + 40 = `1026`.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `0 <= Node.val <= 9`
* The depth of the tree will not exceed `10`.
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
112,124,1030
|
1,679 |
Hi Ga Namaskar, welcome to the channel, this is lead code 1679, max number of even pairs for 90 days, this is how it is going on, question number 12, lead code is 75, see what is the question, you have been given an array like tooth 4, it can also be sorted. It can also be non-sorted. It can also be non-sorted. It can also be non-sorted. Given the number, every time you will choose two numbers whose sum will be equal and take them out. Asked how many times can you do this? Okay, let me ask my question again. I am like giving you an array. Given is 3 1 3 43 and a number k is given, you have to select two numbers from R whose sum is equal to k and remove them from R, like this three and this three are selected, the sum of both. There are six, both of them have been removed, now what is left is 1, 4 and 3. The sum of none of them is equal to six. Okay, if it were, then I would have said that two operations are possible, like if I take it, I make it 3142. So inside this, let's estimate how many times we can do this, so I selected R and Th, G is complete, I have taken out both of them, now there are 142 left in this, I have selected Phr and T, G is complete, and I have taken them out, now there are 142. I have only one left, so I could do this twice, okay, so basically the question is, how many times will the sum of any two be equal to a given target, so this is a very simple question, the target is a sum pair, basically two numbers of the target sum pair. All should be equal to some target, okay so like I have been given 313 42 and asked for six, then what will be the first task, sort it 1 2 3 4 then play left right, this is an old question, this is a new question. Not only after sorting, play left and right, the sum of both is five, now it is sorted, this sum is five and we should have got six, our sum is less than six, then the smaller number is smaller, the number on the left is smaller, the number on the right is bigger. So increase the left one, the sum of both is six, you got one, move both of them, the sum of both is six again, then move both left and right are crossed, then the matter is over, this happened twice, let me tell you again basically. Target is even pair. After sorting you have to find those pairs whose sum is equal to given six then left is right. 145 if even is smaller then increase left by 2. 46 if even is equal then increase one count. Once it is done like this And moved both of them, again the sum is six, then moved both of them, your count becomes two, left-right is crossed, the matter is over, if the left-right is crossed, the matter is over, if the left-right is crossed, the matter is over, if the sum of left-right is sum of left-right is sum of left-right is more than the target, then the right comes down, the sum of left-right. If it is less than the target then it sum of left-right. If it is less than the target then it sum of left-right. If it is less than the target then it goes up on the left. As simple as that is an old question, if it is not a new question then it becomes complexity. A login becomes a login complexity. There is complexity of sorting. After that there is nothing, so there is coding. I do n't need it, I just show you this answer. Initially, the salt was zero. This is our salt. The salt of alg n is always of alg n, so in alg it became salt. Kept it on the left, kept it exactly here, kept it right there, zero and moist length. Forget it till you get the left and right on the bus. As long as you do n't get the left ride, you will work as long as the left is less than the right. What is that work? Look at whether the sum of the left and the right one is equal, is it less than the sum? If this one is smaller than the even k, look at this. If this one is smaller than the even left and right k, if it remains smaller than the even k, then the smaller number is on the left side. If the bigger number is on the right side, then the smaller one is very small. Increase it a little, then on the left. Plus plus if k is bigger than even k, our k is bigger than even k. If there are smaller numbers on the left, there are bigger numbers on the right then the bigger one is bigger, meaning the one on the right is bigger then subtract the right one. What can be the third thing, even k? K is equal then increase the answer and move left right to both until left right are found as simple as that is hit submit if it is happening in n log n then this is fine beats 46.99 one is done for that this is Right pace 46.99 one is done for that this is Right pace 46.99 one is done for that this is Right pace is all right so let's meet this question thank you
|
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 |
1,632 |
hey everybody this is larry this is me going over q4 of the reason contest ranked transformer matrix uh sadly to be honest i didn't solve this during the contest um i solved this about like 10 minutes afterwards uh with some motivation you could watch me solve this live during the contest and also afterwards uh after the explanation part uh hit the like button hit the subscribe and join me on disco let me know what you think let me know your questions uh i appreciate your questions because the more questions you have the more i know to answer them next time uh and also i'll enter it this time as well of course um anyway so this one um for me this one is very tricky um and i'm going to bring up print brush for a quick set i'm gonna um you know i so basically i'm gonna go over two cases uh not two cases but uh i'm gonna go over uh a different problem first uh not a different problem just like uh just you know like um a easier version of the problem say right so let's say i have a easier version of the problem where all the numbers are unique right well while the numbers are unique then you know we just becomes a lot easier let's say we have a matrix uh let's actually add a couple more boxes and the numbers really don't matter per se because they're unique but basically but you can kind of think of it this way right so we could look at each cell as a node and for each node we have a pointer that goes from you know uh um you think about it as each node and that if a number is smaller than the previous number or another number on the same row or column then you have a node you have an edge from that node right so for example let me use a color that is not that's a little bit stand out so basically for example you have one you have two you have three uh that's you have seven you have six right something like that and also that's just get fill out the cup uh rows a little bit or the column for one of them something like that right so the idea behind here is that okay so you have a matrix is filled out so we just have to draw these edges so for example in this case two is bigger than one so you draw an edge here three is bigger than two and also three is bigger than one uh seven is bigger than all these numbers uh but you get my the point here right uh and also seven is bigger than this one seven is also bigger than this two uh and seven is bigger than this five and four uh though this is you know you could keep on drawing i mean you know um you get the idea here right so the idea behind this is that now we create an edge where with essentially a dependency graph um because basically the way that i was thinking about it is that in this case now that we have this dependency graph and it's kind of intuitive which is that uh to say in english um to articulate it in language which is that you always want to do the one before the two before the three before the seven and so forth right in this case in the same row and column and if you think about it that way well then you could also think about another way which is that two depends on the one to finish first before it can go three depends on the one before it could go and we also depends on the two before it could go seven depends on the three the two and the one right so that's kind of um a dependency graph and if this wings about you then you know good uh and if not that's okay this is why we're here this is why we practice i mean i gotta i didn't solve this problem during the contest right so i'm not you know uh trying to shade but basically after that then you know you've gotta you the problem becomes a little bit more familiar in that it is just topological sort right what is topological sort uh so logical storage just allows you to kind of you know for each node um we only process a node when there's no edges um looking out at it right uh going out right and what i mean by that is that if you look at this graph right now that i drew um so first well just note first we're going to draw the let me choose change the color again now first we're going to do this one uh and we're just looking at rows for now we will generalize in a little bit we'll solve it as one because well um yeah uh because one has no outgoing edges right this is very basic topological sword i recommend you uh practice upon that if that's not understanding because i don't want to spend too much time on the topological sword portion uh because that i'll just say that this is a prerequisite right but you know we stop we do the one and then after that um so this if this goes by too fast that may be why but yeah and then next we do the two because now after you remove your process one two is good right because now two has no edges going out because it only has an edge going pointing to number one but that didn't count right so and so forth and now you could get the intuition that uh when you do a topological sort so that's the that's one part and then the other part is how do you label them well right well but you label them when for a given cell uh let's say seven right so now we you know that and that you know you may notice that this seven also has edges pointing downwards as well as to the left and to the right i didn't draw that one but so it has a lot of edges flowing left right up down right because seven is a big number and so by the time it's done you can just look at the maximum number on the row or the maximum number on the column and then just make sure that this is the biggest number after those numbers so that's how you process each node i'm gonna go over my code real quick um yeah uh so in the case where um yeah so basically for each row i just keep track of uh the max number and then for each max number i keep track of the rank and i update the rank afterwards this code may looks a little bit weird so i'll explain it a little bit um okay so that is how you would solve it if there was no unique numbers right and that would be pretty straightforward um well it was still hard because it still took me about an hour of implementation maybe a little bit less it's just that i was having issues with typing no it took me probably like half an hour just to kind of get all of it right because i uh because there are some optimizations that you have to do even though this is the core concept um so this for me this was a really tricky implementation form uh though it turned out that there was a thing that i didn't consider which made it you know interesting um but it's implementation problem because so let's say you know we have we want to draw these edges right uh we are looking at the same graph we're looking at seven has a lot of edges if you could tell uh in fact seven the largest number in the graph uh in this case seven say uh we'll have you know if you have given that n is 500 and rose is also 500 um you know so each cell could have up to 500 plus 500 edges right it's not quite like that but uh because you know not every number can be the biggest number but if you do something like and choose two math right like n square math uh that still adds up and given that n is equal to 500 that's gonna be too slow right so basically what you have to do instead in this case is instead of all these edges okay well it's not erasing all these edges for me so let's just pretend all the edges are erased let's just at least clear up a little bit okay uh so let's say we cleared up all these edges okay let's just say there's no edges and i'll use another color we'll use green um yeah let's say there's no more edges right um but one thing you can note is that if seven uh you know seven depends on one seven depends on two seven depends on three right uh well that's a lot of edges but we also know that in this case that we don't need you know you think about taking a class right um like and that's how i always think about top logical sort and dependency graphs i think about taking classes in college or something like that um you have to take let's say you have to take a i don't know um yeah you have to take quantum mechanics and quantum mechanics requires well physics one physics two physics three and physics four or something like that right which makes sense because quantum mechanics is hard um but you know like but if you ever look at your course book they would they wouldn't literally list all these uh courses right so and i think that in an intuitive way you know where i'm gonna go with this which is that you can say you can just if in this case knowing that three depends on two and two depends on one and because this is not a uh an arbitrary dependency graph this is a dependency graph on just numbers right so you know that on numbers if a is bigger than b and b is bigger than c then a is bigger than c right so this is the transitive property and because there is translator property on ordering of this uh so what you what we can do is actually instead of drawing all these edges uh and there'll be n square edges because then choose two edges right we just roll and that just becomes way too big you can actually just look uh from seven point three actually technically speaking seven point at six point at three point at two point at one right so that's kind of how i would uh think about this and then once you do that it becomes like a linked list essentially and you have n and um you have n edges per row right uh and because of that's just going to be also n square uh in total because there's only n per row and n columns i guess um say so it'll be n times 2n so it'll be 2 times n squared number of edges instead so that is an optimization that is needed for this problem as well so there are other things that you have to do with it but yeah so let's say now that this is unique oh sorry this is unique and this is how you would solve the problem because now you have this revengency graph and i took a long time implementing it but um but yeah now that you have this thing so you can do a topological sword on it and if uh and if all the values are unique that's pretty much all you have to do and that's how my first code uh works uh so i had a couple of wrong answers during the contest um oops not this one so i did do this in the first one but i actually end up not going this well though we'll go over why this is the case uh but yeah i keep track of our degree and stuff like that but the problem is actually um and i will draw another one because there's a good edge case here um but the problem is unique oh sorry non-unique numbers duplicate numbers how non-unique numbers duplicate numbers how non-unique numbers duplicate numbers how do you handle them right so i did not handle this well but oops let's go with black for now um and we don't have to draw that many cells i don't think but you know let's say we have uh yeah let's say we have zero here you know it doesn't matter here um negative one two three doesn't really matter as much as well so that's right so let's say this is our ready rough matrix right um because the algorithm will mostly still work with um it will mostly still work with top logical sort but now the problem is it's not true it turns out right so basically what happens is that okay let's just draw an edge for this node here right or edges for this row and column for this thing um so zero points at two as we said three points at two oh sorry two points at zero three points at two four points at three um zero points at two or two points at zero sorry i keep on saying it backwards and so forth right uh oops um and then in this case zero points at one four points at zero five point zero right so in this case unfortunately um the thing is the circle's zero that's the tricky part um so the tricky part is that right now there's no edges going out to zero right but the thing is that there also another note that has no edges so you have this one the negative one and so the um yeah so the thing is that now let's say we process this negative one first so then we give this a number let me use another color uh so let's say for this cell we give it number one um so then in this case uh and in this because this all this zero also doesn't have any dependencies we also populate this as number one but now we have a wrong answer we have a contradiction with the wrong answer sadness why because next we process this number i'm changing colors again okay that's too close uh yeah because next we process this number because now this number has no more outgoing edges because negative one is processed and then now we have a contradiction or just one answer where this will be a two because we look at zero to negative one and well and zero to negative one uh you know the next number was a two but as you can see this zero is also uh the zero is a one right so that means that we're having some issues with our dependency graph uh that it makes it not correct and i didn't how to handle this uh during the contest uh because i it took me a while to think about it because um and this is a good lesson for myself uh just to kind of think about how i did it and the key thing to note is that to be honest i underestimated um underestimated this part of the problem i thought that the hard part of the problem is just the dependency grab the topological sword and stuff like that but it turns out that this unique and i don't thought that uniqueness was just like an edge case that i could handle with some if statements that i could fix later i don't have to worry about it let me just focus on getting the code right getting the code correct but it turns out that this is not as you can see um because during the contest you can put you know you could if you try to do something greedy like you could be like oh yeah you know you just kind of maybe change this one right like maybe next we just go back and fix this one or let me you draw an edge here you know they're a couple of different ways but they're all just greedy they're all heuristics they depend on something that you know you just reverse the order or just have something in a little bit different way that's going to give you the wrong answer right so i knew that when i was when i unfortunately after i implemented way too much that's when i was like oh i was snapped that's not good um but yeah so about this time i had so i during the contest i um i was have a couple of hail marys where like okay can i just like can i always go from like the smallest number to the largest number i wasn't able to prove it during the contest i only proved by aca afterwards but it turns out that you can because when you process an order uh in a number order no matter what all your prerequisites are done because that means that for example if you process the zeros together uh well negative one will always have a smaller number and so forth but so that's kind of the short story but uh the only thing that is tricky is so yeah so but the only thing that's tricky with that is that you cannot just combine all the numbers together because for example if you have another number um let's see let me change the color again let's say we have number zero here maybe in this case right this answer is actually one right let's say the normal zero is in this case this is not a zero this is not zero right then in this case this answer would be one or yeah uh and from that you could see that this group of zeros is two and this group or this one zero is one right so that means that you cannot just naively combine them and then you know sorting or something like that though it turns out that you can um that you can close to it so what happens is that um what happens is kind of fun actually because you know let's get rid of these colors again and again um oops how did that happen so let's say we get rid of these colors let's say that we get rid of these colors um zero right let's say um this is a zero now right well okay let's just say this is a zero ignore the blue right so that means that now this also has to be a two or at best a two it could be even higher number right but uh but it has to be at least a two so let's say this we set a two and then just reset a two right so now we draw you know this connection this way with the two zeros and you can maybe even draw it this way if this was a zero again so this may um so this is the kind of the uh insight that i had about unfortunately i have about 10 minutes left in the contest when i made this insight uh and i wasn't able to implement it very quickly because usually i am actually able to do this very quickly but not this time uh because it is a two-dimensional thing um so what it is a two-dimensional thing um so what it is a two-dimensional thing um so what ended up happening was that i just had some uh some silliness around it um and also there was just like a lot of things with um and again we have to be careful of how we do the you um how we kind of merge the connected components together right and what i mean by that is actually not a non-trivia or that is actually not a non-trivia or that is actually not a non-trivia or it's not hard to implement but it's something that you have to be careful about because if you do the merging of these components naively it could be n square in the number of components or number of elements inside the components and then that may give your time limit exceeded so you have to kind of reduce that to at least um yeah you have to reduce that to as little as possible and that's basically what i did um and then now we i think we have enough to go over the code um now basic you know i haven't explained how i solved this yet um but that's basically the problem that is uh broken down these are the observations that you need to make to solve this problem right and unfortunately for me it took a little bit too long but so basically now this is union fine a two-dimensional this is union fine a two-dimensional this is union fine a two-dimensional union fight so i had some issues with this because just that i was a little bit rusty because i'm so used to writing union fine that uh um in a certain way that i think i just didn't take account the two-dimensional didn't take account the two-dimensional didn't take account the two-dimensional aspect uh and again union fine will is also a prerequisite for this problem uh i might do a different a separate video on union fine at some point but for now let's just say that um this becomes uh you know we instead of a regular parent where your parent is just you know the index of the um the index of you know your parent is the index of the node we set it to be the x and the y of the node so that means that if you still look at the pattern of the note but now it has a two-dimensional aspect two-dimensional aspect two-dimensional aspect and that's basically what i did i uh i remember and because it is a little bit new to me i it took me a little bit longer than i would have otherwise maybe i could finish it otherwise but uh so that's why it took me an extra like i finished it about 10 minutes after the contest with a little bit of uh cheating too and i took a look because the contest ended so i just wanted to see if that was on the right approach um and i was so i would have gotten it eventually uh during a contest but i spent too much time on the other solution um but yeah so this is a 2d union fine i just keep track of the parent which is an xy com uh component uh coordinates and then i have to do some really fancy stuff to do the merging that we talked about uh because you have basically you have all these numbers that you want to say okay like let's say we have two ones are they in the same group well and now we have a connectivity problem which is the same as actually q3 where okay if a is connected to b is connected to c so four of a is connected to c so we want to modify that in a way such that um you know like let's say you have an entire matrix of uh zeros right well if you look at every zero like if you're doing a naive n square loop for every zero against each other that's your worst case it's going to end up n to the fourth or rows times of rows times columns times rows times columns because you're looking at each element and then you're just looking at literally each element and then each other mid right so that's gonna be n to the fourth that's gonna be too slow so that is actually end up why i end up uh talking taking a long time as well because i had to um be smarter about that one and so the key thing to notice is that you only m you know one is that you don't have to check every zero you only have to check the zeros that are in the same row or the same column and that's good enough so that's basically what i did um i this is i don't know i just this used to be something else that's why it's called q but basically this is just uh you know a grouping by the number so this is yeah so for example if the entire matrix is zero then this would just have the entire matrix and x and y and then now for each number i look at the vector that is given the number and i sort it by the x coordinate first because if you sort it by x then that means that only then a json node may um then yeah only adjacent values would have the same x right um this is you may have to visualize it but basically for example if you sort like one five and you know one six uh you know three five or something like that right well only adjacent values will have the same x so once you sort that you get you're able to get that from ends to the fourth to n squared log n so that's basically uh what i did here and once you do that is fast enough and i do the same thing with the other dimension i saw by the y coordinates so that i could check merging by the y coordinates right i even have some print statement that i left out here and luckily in timeout for that reason um and yeah and now we use the union fine to merge adjacent nodes if they have the same x or the same y we do the same for column so going up and down and then yeah and then now we have this uh thing where now i could have maybe done this another way but basically for all every no now i group every node of the same uh value so let's say these are z let's say k is equal to zero um for every coordinate we look at the parent and then and we just group them by the same pattern right so what i mean is that okay let's say you have three different components so a b and c connect is connected to one d e and f is connected to two and now we have two connected components and then we just wanted to put them in the list somewhere and that's basically what i did i put it in a default dictionary of a list so that i just keep track of all the parents and their children um in the union fine sense basically given a set get all the components and put them together uh and then after that i put it in events because that's how i look at them because you can have multiple components and then just put them on defense and then you sort them and then you process them in order and that's pretty much it this is a little bit uh weird but that's uh but that's pretty much the hard part because now you know that all the you know that um and the reason why this works with i call it defense but maybe it's not an event um it's because this is the same logic as the top logical sort or the dependency graph which is that when you process a number and you process every number is more than it that means that there's no outgoing edges right by definition because if because you're only drawing edges to smaller numbers right so you process all the numbers behind it so that's how you can sort uh by the value and it'll be okay it's just that before we might have different components in the same section right so yeah and then now this is a little bit tricky to read because i solved this a little bit after the contest but basically now we try to get the rank of an event and basically the rank of the event is just that for each uh for each row we keep track of two things um we keep track of the we keep track of uh what's the maximum number that we used or the last number that we use basically right and that's basically just yeah the last number that we use for that column or row um so that you can use it again so that's to be rank plus one right and also the last number that used that number um i did so the reason is that for example uh maybe this is the visualization but the reason i did that is that basically if the entire row is you know the last number is a two uh then you want to use the three you also kind of look at your columns as well uh or your rows and columns so that you get the smallest number that is the next number from those two numbers um so that's how that's why i have two for loops or two if statements here and i also go through all every node of the component to do that because like going back to the visualization that we had before basically we look at um so let's say we're processing zeros um okay this is as you as undo as i can get if we're processing zeros together um you know we try to get look at for each cell we just look at what the next possible number is and then we take the maximum of all those numbers right it's kind of intuitive it kind of makes sense hopefully uh but that's what i do here and so yeah so that's just keeping track and if it's the same number then we use the same number though do i think this logic is not necessary anymore i think it was from before uh because i think this was a hack around components maybe i could be lying on that one but um but basically that's the idea and then after that after we get the maximum rank uh for each cell we just update that to the rank and that's pretty much it and then we also update um the rows and the columns to the new rank and also the last value that we use so that you know we can get uh the highest one um yeah because basically the rank is the new rank is either you know if the last number uses the same number then we just take the same rank uh at most the same rank actually this is not true so i think we could just remove this actually because this cannot be true otherwise this would be wrong so actually you know um it's just that this case is actually no longer ever true so that's why um so you can actually do something like this which is way cleaner right because basically these are the same numbers used um and yeah and that's pretty much it and then we update it afterwards so that next time we do it'll be plus one from that um yeah it's a very hard problem uh there are a lot of different observations to make and for me unfortunately um i like i said i and you can watch me during the contest afterwards it's really long fast forward for it but i thought that uh i thought the unique case was in edge case so i didn't really plan my coding and my implementation for it um and also i tried i had to do it with the naive topological sword where you know i didn't do this thing of the defense uh on what we said i so like that one of the observation is that um if you start when you process the numbers in order in the value order um you already did all the numbers more than it then that number has to be the next number process so i didn't make that observation or proof until like a little bit later so i end up writing a lot more code this is still a lot of gold this is 60 lines of code but it is you know at least much easier um you know at least it's doable during an hour it's just that i didn't make that observation until much later on um about the edge case so it's kind of cool uh that's why i like this problem um let's go over complexity real quick so union fine that's for now i mean i do path compression so that's pretend it's all one for now you can make that optimization with by rank if you really find that to be an issue so that'll be an upsolving thing but this is just union fine so um i d dupe all the values and the same thing so this number will have at most um n square uh number of different keys like with every cell in the matrix is different then this would be n square uh and then the other worst case is that they're all in the same one so actually that is the worst case which is that then this would take n square log n time we kind of talked about that so and in that case it will take over one so this i'm a hand wave a little bit but basically it is in between um and n square log n is the worst case because uh each cell can only be sorted like ones or something like that and otherwise each cell is only in one thing so let's say this is n square log n this is a little bit hard to uh understand though um but yeah and then we saw it again and then this is just straightforward uh we look at each cell at most once so this is all of n for um oh sorry this is row of o of n and this is all of rows times columns times log of both times columns uh to be more precise uh in terms of space all we use is a matrix and uh and a matrix for union fine but this is linear in terms of the size of the input so basically linear space uh this is a tricky problem to explain this is a tricky problem to solve so i wish i did this during the contest but i didn't really understand how hard this problem was until later on i think if i made one of those two observations uh earlier on then it would free me enough time to do the later ones uh so there's two observations one is that nine unique numbers uh so we have duplicate numbers you have to do this thing with connected components so that they all get handled at the same time and the other observation is that um in a way it's greedy in that uh instead of having an explicit in uh an explicit topological sort a graph of um pointers pointing to previous if we just sort it by the value then it would have no i'll degree right by the time we process it that would have fixed implementation a lot enough that um if i made one of those two um observations then i would i should have been able to solve it uh if i made them earlier i made them but really late in the contest um yeah so watch me solve it during the contest let me know what you think uh and i will see y'all next contest hopefully better that was dumb that deception two problems bonus problems i don't know how to do this but tricky to get to drive maybe the same number have the same crank oh noise this topological sort there is you should know there's a thousand that's too many though right that's 250 million sit down there's a lot of bookkeeping wow okay um you um okay foreign touch oh this is break this one a little bit smaller so you and okay i don't even know anymore okay you no you okay so okay uh there's gonna be a nightmare um only eight people stopped it so i think this is pretty hard it should be solvable just hard okay um okay looks like so far what i want to do okay true um yes this is um just make sure this come closer the index i'm doing this well all these edges that are coming in so i'm just handling the unique cases pretty poorly maybe not hmm this is called we have to this is not quite right this is right and now hmm we have this hmm you should be one two maybe not huh i know i'm degreasing oops do i need this is the next key that's just my coincidence that it works to be honest because i didn't do another dimension um 40 minutes i should be able to do this and this is not going to be fast but hopefully it works um i just wanted i need to transpose this you oops oh no this is a it's just confusing as hell but it's right whoops well mostly light that's good why not here hmm that seems right oh whoops this is when you copy and paste and also new silly okay this is kind of good um nope okay nope come on well that's not good why would this tell you though whoops hmm well almost good how are you gonna get the four oh this happens again we never need to do the kill more than once okay fine oops that's not quite right no this is right oops i don't even need that oh well it's not right oh we don't handle all the numbers together that was what i was worried about but okay so okay okay so i fixed that but there's a lot of unprocessed stuff hmm so make sense oh this doesn't make sense my bookkeeping is wrong oh yes on duplicate numbers it's actually surprising let's fix this one first uh actually my assumption is wrong with all this code and i think my in this case because we don't no that's not true it's just that might leave my edges wrong because it should not be like zero this is how there's a new now it's fixed fit well maybe not that's what happens when you're talking up and down all right please uh this i knew this was going to be a tricky one do it but i mean i look like i'm close but why is that i'm gonna do something wrong this should be a two why is that a one for me 12 i'm close but not good enough uh so we want zero one a one zero just one why that means that this is weird so i did put one seal here why is that because this should have a pointer to negative 17. oh the previous is pretty bad um is there a negative one in this no but hmm still love so okay hmm as i could just point this out i have 20 minutes to debug this oh i should fix this as well let's see if that fixes it because i was just being dumped a negative one i mean that's definitely a bug but maybe i've kept unlucky but okay first column um 20 minutes should be enough but when you're taking my time 37 is the smallest number right whoops i can't do negatives in my head okay so it is the smallest number in the column and the world so that's right but we have to do the one so why is this a two well i mean it's definitely still wrong but it's a two because the row of because we have to i get right it's 400 hmm i have to think about how to fix it i don't know maybe my assumption is wrong about the thing this number is zero and under wrong but i don't know how to merge this in a good way maybe i can't take because about 71 people got it so i don't know maybe i'm doing this in a weird way wow people got really quickly so i don't know maybe there's a more uh elementary algorithm i'm mostly right if there's no duplicate elements but i don't know how to handle it because of this case so good this for a given column doesn't out degree but how do you do that transfer let's just maybe it's just some weird sorting thing hmm with a lot of code maybe i don't want to keep on following everything just yet that didn't work so is oh i didn't i don't update it because i i just wanted to timeout but or just being right would be nice um so defense this is right i guess this is right we're kind of sad if uh if this was right i had this in the beginning but i thought it would be something trickier but we'll see that's not counting our x just yet uh okay this is the same case as before actually but uh which is kind of sad but i just i looked at the one that was wrong and was wrong so but uh like it fixed the one that it was wrong before but it's wrong in another way so that's not great why is this wrong can we get threes that together in a weird way that was a hail mary anyway i feel like i guess i misunderstood something fundamental uh about this so negative 15 2 1. two three let's do it this has to be a four but this is a three because we process this in the wrong order hmm this is a 3 because we process this first so we don't see that this is a 4. seven minutes left i'm just trying anything to be honest so hmm which is kind of a good sign that i have energy but sometimes i just get lazy but um you this is why i don't remember fix this issue looks good enough to give it a try with five minutes left yeah i mean i didn't think this was gonna be right to be honest um because it's just greedy pretty much i feel like my first answer is kind of right but clearly there's some weird edges stuff that i need to handle uh there are no unique numbers i guess this could be right or if they're all unique numbers but what is wrong about this and this is one case i couldn't prove which is that um yeah if the same number can have different values which is what i did not prove and this is some like weird union fine thing um which maybe is true to be honest but okay fine i think actually i could i think i could do this reunion fine but uh it's a little bit awkward now if i had enough time maybe i could have done it now that i think i'm proud of it i'm going to absorb this until whatever good um hmm what hmm oh i don't know what a disaster let's do a quick short code review first uh and i gave away like a lot of time on this one because i misread it um yeah let's go wow 10 minutes i mean i think this is basically what my thing is my first solution i don't know how to handle um i don't know how they handled uh i don't know how to handle the same numbers and stuff well done good people and union fine i guess union fine was the way to do it i um this is pretty tricky to be honest i had the right idea but implementation was the hard part for this one as well um maybe i'm missing something still because this is just uh i mean um i don't know uh maybe i won't go this route even my alternate code is really long oh no this is my original code let's take a look at this one then can i fix this code to uh be right because i mean i had to write algorithm-ish but algorithm-ish but algorithm-ish but not quite uh another disaster i was not feeling good today too but i wasn't able to get uh this one i don't know how to handle the union flying stuff i mean i do but uh maybe i just have to finish this okay let's finish how to handle this um i mean i guess i got the right idea uh wow this code is way shorter but hmm this is actually literally what i'm doing but with this sorting thing i mean this is an implementation problem for me um i got but i should be able to do this i was oh no i understand that because right now like my algorithm is right um but i am not coding it quite right why is this like really funky thing so now i'm just doing cody i'm trying to learn and try to understand um i mean this is essentially what i was doing this is okay i guess this is fast enough i thought that just may not be fast enough okay um i'm showing that this is like so i have the union i just have to look for okay so i mean okay 500 cube is too slow right okay so then damage i want to do something smaller um now i'm a little tired to be honest but okay i think we will just do something like okay now we split it up so now we just do um that we process it twice maybe that's not how the syntax works this must be what oops i'm gonna change that is that right nope still wrong hmm that's unfortunate but they should have the same thing let's print out the parent just to see if we okay so this is the pen this is itself this is why what that doesn't make any sense did i mess something up hmm yeah okay that seems right though i don't know where this gets 33 from oh this isn't even why is this why doesn't that give an error is that right so basically i needed another about another 20 minutes maybe see if this is too slow though so the thing was that i tried to do things one way in the beginning this way it works this is also similar but in a little different i think the problem um yeah i mean excuse me sorry about that uh okay um yeah hey everybody uh yeah thanks for watching the explanations if you're here uh definitely appreciate it hit the like button hit the subscribe button join me on discord and yeah i didn't do that well just contest but i did learn a bit from the q4 i liked it i digged it uh dug it so it is what it is anyway i will see y'all next explanation bye
|
Rank Transform of a Matrix
|
number-of-good-ways-to-split-a-string
|
Given an `m x n` `matrix`, return _a new matrix_ `answer` _where_ `answer[row][col]` _is the_ _**rank** of_ `matrix[row][col]`.
The **rank** is an **integer** that represents how large an element is compared to other elements. It is calculated using the following rules:
* The rank is an integer starting from `1`.
* If two elements `p` and `q` are in the **same row or column**, then:
* If `p < q` then `rank(p) < rank(q)`
* If `p == q` then `rank(p) == rank(q)`
* If `p > q` then `rank(p) > rank(q)`
* The **rank** should be as **small** as possible.
The test cases are generated so that `answer` is unique under the given rules.
**Example 1:**
**Input:** matrix = \[\[1,2\],\[3,4\]\]
**Output:** \[\[1,2\],\[2,3\]\]
**Explanation:**
The rank of matrix\[0\]\[0\] is 1 because it is the smallest integer in its row and column.
The rank of matrix\[0\]\[1\] is 2 because matrix\[0\]\[1\] > matrix\[0\]\[0\] and matrix\[0\]\[0\] is rank 1.
The rank of matrix\[1\]\[0\] is 2 because matrix\[1\]\[0\] > matrix\[0\]\[0\] and matrix\[0\]\[0\] is rank 1.
The rank of matrix\[1\]\[1\] is 3 because matrix\[1\]\[1\] > matrix\[0\]\[1\], matrix\[1\]\[1\] > matrix\[1\]\[0\], and both matrix\[0\]\[1\] and matrix\[1\]\[0\] are rank 2.
**Example 2:**
**Input:** matrix = \[\[7,7\],\[7,7\]\]
**Output:** \[\[1,1\],\[1,1\]\]
**Example 3:**
**Input:** matrix = \[\[20,-21,14\],\[-19,4,19\],\[22,-47,24\],\[-19,4,19\]\]
**Output:** \[\[4,2,3\],\[1,3,4\],\[5,1,6\],\[1,3,4\]\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 500`
* `-109 <= matrix[row][col] <= 109`
|
Use two HashMap to store the counts of distinct letters in the left and right substring divided by the current index.
|
String,Dynamic Programming,Bit Manipulation
|
Medium
| null |
509 |
Hello guys welcome to the hunt Delhi challenge problem and some viewers problem Medical teams number Sotheby's number commonly believed in the form of sequence of difficult surgeries number 10 2010 2011 2012 plus one number to the number one plus one number After OnePlus 3T Rudra Number After 10 Female Actress 500 You Get Phase 1.2515 12345 Se Z2 Plus 2 You Get Phase 1.2515 12345 Se Z2 Plus 2 You Get Phase 1.2515 12345 Se Z2 Plus 2 And 200 Others Like This To With Actress Neetu Start The Beginners Give Difficult To Defeat - OnePlus 5 - Sid Give Difficult To Defeat - OnePlus 5 - Sid Give Difficult To Defeat - OnePlus 5 - Sid And They Will Drop Test Against West Indies 2nd Test at the center
|
Fibonacci Number
|
inorder-successor-in-bst-ii
|
The **Fibonacci numbers**, commonly denoted `F(n)` form a sequence, called the **Fibonacci sequence**, such that each number is the sum of the two preceding ones, starting from `0` and `1`. That is,
F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.
Given `n`, calculate `F(n)`.
**Example 1:**
**Input:** n = 2
**Output:** 1
**Explanation:** F(2) = F(1) + F(0) = 1 + 0 = 1.
**Example 2:**
**Input:** n = 3
**Output:** 2
**Explanation:** F(3) = F(2) + F(1) = 1 + 1 = 2.
**Example 3:**
**Input:** n = 4
**Output:** 3
**Explanation:** F(4) = F(3) + F(2) = 2 + 1 = 3.
**Constraints:**
* `0 <= n <= 30`
| null |
Tree,Binary Search Tree,Binary Tree
|
Medium
|
285
|
1,390 |
number 1300 high the ico said part of the contest 181 was frankly I couldn't solve it at that moment it is more of a mathematical problem but it has some interesting things what this problem asks of us is that they are going to give us an arrangement with several numbers and we must of taking the divisors of each of its numbers and only for the numbers that have exactly four divisors, this adding those four divisors and putting them in the result is a very interesting program in many ways because it tries only several ways, if not, I didn't get any optimal solution and now you are seeing the answers that other people make. I saw one in particular that caught my attention because it uses a mathematical device that I could not find justification. Right now we are going to search on the internet and I could not or not I have a background of mathematics but I am not an electronic engineer, I more or less understand some mathematical fundamentals so well, then I will solve this one and I will explain it as I do it so well first we are going to create a variable for the result and simply two and have all We don't have the numbers we have like this and for each one we are going to take what is called the number of divisors now each number does not matter if it is prime or if it is not prime or whatever it is it has at least two divisors which are one and themselves then in reality what we have to look for are numbers that have at least two divisors exactly apart from themselves and one is not for that we first have to take the square root of the number and round it to yes well and round it off, no, then I 'm going to do it like this, it seems to me like that sq rts, if it's extreme, I think it's that rocket, so well, I'm going to take this one out like this, and this is one, this is the part that I frankly don't understand this line well. It is crucial for the problem because it improves performance a lot and this line is not added, the problem does not work and perhaps this person is that if square and x square is equal to no, he no longer takes this number into account until he says that yes it is a number which is the perfect square, that is, its square root is exact, it is no longer no, it cannot have four divisors and start searching and indeed no quadratic number in any number with an exact sword has four divisions some ideas three others have six with Well, none of them have four. I don't know where he got that from, but without that, this problem cannot be solved in this way, which I think is the easiest way to solve. Well, if that's the case, then I'm going to make an mp3 that will be equal to one plus one this means that the total sum of the squares of this if you have a number itself and one done this we can be until the end but well and then I'm going to start from two because one we already know what it is division between one and this and well that's why I start with 21 and I'm going to do it as long as it's equal to square less than or equal to square and we're going to be this is yes and 1 is divisible by each other and it's the product of zero well and I am going to make a variable called count I am going to increment camps if count is greater than 1 that yes we find at least 2 numbers that are what they have we do the same to 0 and number 1 and we find at least two numbers that are not the 1 and itself that can be divided by this so we are finding one more and I know that this number has at least five divisions so it is of no use to us so we make a break and we can all get out of here we are not going to put a and I know that it is the same to 1 although then maybe we don't do it like that we just put break and if count is equal to 1 then a of mp3 would be res it will be more equal to cmp and if not we are already out and I think this would be the whole problem if it is missing something although if really this would be the whole problem because if it is unequal although we do find two field numbers it could be greater than one because then we would get out and well we are going to try it good luck up to here and it doesn't work because it turns out that I am counting 22 which is not I am telling this to Madrid, which is that it is only against us, of course, it is clear that it is more equal and more does not enter and because obviously it is going to be equal to the number that we have, for example, if we were to find, for example, 7 plus 21 and here we go at 33 we have to put the 3 and apart from this and apart from the 7 because it is 21 between 3 7 and 7 21 is also divisible by 7 so that one would be like this and it works for this water you know it works for everyone it should work for everyone and That's the solution. The only thing I can't understand and embarrass or understand is how he came to this conclusion. I mean, I don't know if there is a mathematical basis for this, but if we don't put this is what happens, the performance goes down. I mean. It doesn't even give us time for water in fact not only the performance and it doesn't come it doesn't even work no so this is the part that I don't understand how it got there I don't know but it arrived and the staff very good solution it
|
Four Divisors
|
average-selling-price
|
Given an integer array `nums`, return _the sum of divisors of the integers in that array that have exactly four divisors_. If there is no such integer in the array, return `0`.
**Example 1:**
**Input:** nums = \[21,4,7\]
**Output:** 32
**Explanation:**
21 has 4 divisors: 1, 3, 7, 21
4 has 3 divisors: 1, 2, 4
7 has 2 divisors: 1, 7
The answer is the sum of divisors of 21 only.
**Example 2:**
**Input:** nums = \[21,21\]
**Output:** 64
**Example 3:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 104`
* `1 <= nums[i] <= 105`
| null |
Database
|
Easy
| null |
1,276 |
hi today i'm talking about leak code problem 1276 number of burgers with no waste ingredients what this problem asks you to do is write a function that will take a number of tomato slices and a number of cheese slices and it will output a list with two elements where the first element in the list is the number of jumbo burgers you can make and the second element in the list is the number of small burgers you can make a jumbo burger uses four tomato slices and one cheese a small burger uses two tomato and one cheese and there's one more condition which is that if you can't use all of your ingredients that is if you're going to waste some you should just output an empty list so if you can use all of them output a list containing number of jumbo number of small otherwise output an empty list the constraints you can have up to 10 to the seventh tomato slices i initially tried to solve this problem by solving it kind of the way i naturally would i'd ask am i constrained by when i say naturally would i mean like how would i solve this problem using my human mind so i said am i constrained by tomato slices or am i constrained by cheese if i'm constrained by cheese i want to use tomatoes most efficiently and that's jumbo if i'm constrained by yeah if i'm constrained by tomatoes i want to use those most efficiently and that's the small and so i just kind of iteratively one after the other picked jumbo small am i going to make a jumbo or small based on what i was constrained by that wound up uh it wound up solving the problem but while i could solve the problem locally meaning if i ran the code even with the worst case scenario of having the max tomatoes and half that of cheese i could solve it locally but i couldn't solve it when i submitted it so testing it locally it seems to let you run like five to ten seconds um but on the submission it seems to be less than one second is the requirement for time um so yeah my first instinct solution wasn't good enough um it was way too slow and so i wound up having to go to this more analytic solution and this isn't how i would have thought about it naturally but just kind of studying the problem and trying to think how could i go faster um obviously if you can just solve it with a couple of uh calculations that's going to be a lot faster than doing 10 to the seventh operations um so yeah let me talk to you about how i figured out how to do this oops i don't want to do that um what i did is i just set up a couple of equations from the problem statement so we know that the jumbo burger uses four tomato and one cheese small uses two tomato and one cheese it's interesting they both use one cheese the cheese kind of tells us that's the number of burgers we're going to make um but what i did is i just kind of wrote those two requirements out i said okay four times the number of jumbo burgers plus two times the number of small burgers is going to equal the number of tomatoes that i'm going to use and likewise just the number of jumbo burgers plus the number of small burgers that's going to equal the number of cheese slices that i'll use so you know if you can remember whatever math they teach you i guess the idea is like system of equations or something or it's basic algebra you've got two equations and two variables and you want to solve them well the way you do that is you write you rewrite one of the equations um such that you can remove one of the variables um and i'll show you what i mean by that in a second and you might say wait a second we have four variables j s t c um but that's only true in the kind of algebra or kind of algebraic notation we're using right here when we actually try to solve this t and c are going to be replaced by uh actual literal numbers so we don't we won't treat these you know as if they were variables algebraically we can treat these just as if they were numbers so what i'm going to do is i'm going to rewrite equation 2 here just to put it in terms of s so i can say what is s equal to um and well we just subtracted j from both sides and we say s the number of smaller burgers is equal to the number of cheese slices less the number of jumbo burgers and so once we've rewritten s like this we can just replace our use of s in the first equation with our reformulation of it so doing that we say 4 times j plus 2 times how we wrote s up here is equal to t the number of tomato slices we can simplify this by just multiplying the 2 across our term 4j plus 2c less 2j equals t the 4j and 2j kind of cancel each other out so we have 2j plus 2c equals t or 2j equals t less to c divide 2 onto both sides to get j the number of jumbo burgers is equal to i shouldn't do that here because it looks like a division sign is equal to t less 2 times c over 2. so now we've just we've written j in terms of something that we can completely solve because remember t and c are both actually numbers when we're executing this we're told what t and c are yeah we're told the number of tomato and cheese slices so we can just calculate j exactly and if you look over here in line three that's exactly what i've done i've just said jumbo j is equal to the number of tomato slices less two times cheese slices all that over two and i'm using the integer division here i'll talk about this in a second it's essentially just a way to turn it into an int it would be similar to say int of all this except doing the energy division is slightly faster because integer division is a simpler operation than the floating point division and it saves us the cast so integer division is slightly faster small is obviously the number of cheese slices which is the total number of burgers as i observed earlier the total number of burgers that we're going to create less the number of jumbo so now we know what jumbo is and we know what small is and so now we're just going to check if it's a valid solution like it wouldn't make any sense to have negative jumbo or negative small which is possible just from calculating depending on what the values are so if we come up with you know oh you need to make negative two jumbo burgers in order to make this work well then we can just return the empty list we can say there's no solution if our solution involves doing things like making negative amounts of jumbo burgers or small burgers so you're when i'm returning it i'm just saying return a list of jumbo first element small as the second element if we're meeting kind of these um rational rules that we know about we know from common sense about can you make burgers like you can't make a negative amount of jumbo or small burgers and we're going to say well we want jumbo plus small to be equal to the number of cheese slices if solving it involves making more burgers than we're allowed to that's no good and we also want them to use only the number of tomato slices so the reason why this has to be written out here is because you can imagine um like the case of 17 4 if we were to just plug these numbers in 17 and 4 jumbo would be 17 less 2 times four or eight 17 last eight would be nine uh integer divided by two is four so we'd say okay that's four jumbo burgers um 17 and four so four less four zero so we'd say okay we're going to return four jumbo burgers zero small um but that isn't good because it leaves one tomato slice left over like essentially the integer division kind of concealed that we didn't evenly divide them so we didn't say um you know when we said 9 integer divided by 2 that gave us 4 it should be 4.5 so like we're just kind it should be 4.5 so like we're just kind it should be 4.5 so like we're just kind of losing one tomato slice or forgetting about the fact that this didn't evenly divide and so the way to compensate for that is just to check with you know hey are these exactly equal and that's why these checks are here like are you exactly um solving the problem um and yeah if there was any kind of rounding that made it work here it would be caught here and yeah if any of those checks turn out meaning you're trying to make a negative amount of burgers or you're trying to you're ignoring you know an odd number of tomato slices or something like that um we'll return the empty list and yeah that is going to solve the problem uh in terms of test cases that i would use obviously we're going to want to write all of the examples they gave us 16 7 17 4 17 0 you know about one um it would be interesting to have like one of each so what if we had four one or uh two one um and then it would be good to just use the worst case so like 10 to the seventh one two three four five six seven um and you could use half of that um uh yeah so those would be good test cases to run um just to kind of sanity check it here it is going to work for us um i think this is going to come back very fast indeed it's uh 96 percentile for speed um yeah i'm not too sure about how to make this faster like i'd be curious what the top three percent or what the fastest uh python solution is um yeah but i don't know that but uh yeah anyway this is um solving lead code problem one two seven six number of burgers with no waste of ingredients uh if this is helpful to you if you enjoyed the video let me know click the like button say something in the comments so i know you're watching i'm going to try to solve a battle elite code problem a day and i'll just walk through it you know kind of immediately after solving it so if you're interested in seeing that you may want to subscribe thanks for your time bye
|
Number of Burgers with No Waste of Ingredients
|
closest-divisors
|
Given two integers `tomatoSlices` and `cheeseSlices`. The ingredients of different burgers are as follows:
* **Jumbo Burger:** `4` tomato slices and `1` cheese slice.
* **Small Burger:** `2` Tomato slices and `1` cheese slice.
Return `[total_jumbo, total_small]` so that the number of remaining `tomatoSlices` equal to `0` and the number of remaining `cheeseSlices` equal to `0`. If it is not possible to make the remaining `tomatoSlices` and `cheeseSlices` equal to `0` return `[]`.
**Example 1:**
**Input:** tomatoSlices = 16, cheeseSlices = 7
**Output:** \[1,6\]
**Explantion:** To make one jumbo burger and 6 small burgers we need 4\*1 + 2\*6 = 16 tomato and 1 + 6 = 7 cheese.
There will be no remaining ingredients.
**Example 2:**
**Input:** tomatoSlices = 17, cheeseSlices = 4
**Output:** \[\]
**Explantion:** There will be no way to use all ingredients to make small and jumbo burgers.
**Example 3:**
**Input:** tomatoSlices = 4, cheeseSlices = 17
**Output:** \[\]
**Explantion:** Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining.
**Constraints:**
* `0 <= tomatoSlices, cheeseSlices <= 107`
|
Find the divisors of n+1 and n+2. To find the divisors of a number, you only need to iterate to the square root of that number.
|
Math
|
Medium
| null |
1,644 |
hey everybody this is Larry this is me doing the weekly premium problem uh 1644 lowest common ancestor of a binary tree too hit the like button in the Subscribe button drop me on this card let me know what you think about this farm this is uh yeah let's take a look I haven't done this one yet but it sounds okay let's see okay so we know what LCA is uh I assume they mean none but okay fine okay so what is why is this too okay so all the values are unique you have to find are we given the P or the Q can you find I'll say traversing the tree without checking node existence yeah I mean I think so basically the uh so the two ways you can do it the first way I was gonna do is just traversing the tree and then you know um and then uh what else I'm gonna say yeah traversing the tree and then you know calculate the pound and then just like almost like a walk the path up right that's one way to do it the other way to do it is to think about this as a binary uh binary tree because it's a binary tree the lowest common ancestor is the ancestor in which they Branch off right meaning if one of the node is to the left and the other node is to the right the or the other way around doesn't matter then that's your LCI so that's basically the idea uh and we can kind of figure this out uh yeah so finally go to none and then here we can just do a regular traversal um yeah and then we have this node right and maybe just something like if node is none will return zero uh otherwise if note is equal to P or maybe note that value is equal to P right something like this a p dot value better then count is equal to one uh I mean this can only really be one but nonetheless uh but it's actually a little bit awkward now that I think about it the maybe this isn't quite that good but uh I don't know right so basically you have left is you go to and we'll go over Y in a second right is equal to Traverse load that way um so basically the idea is okay so if left is equal to one and right is equal to one then found as you go to this current node right so I mean yeah otherwise uh there's the other case right which is if left is equal to one and count is equal to one um yeah right so okay maybe another way of writing this is actually if count is equal to one and left plus right is equal to one right what this is saying is that um they'll say is it's the one of the nodes because the other note is the children right um so then now the problem is you got to know right otherwise we return left press right plus count this is very standard uh like counting the number of leaves or notes or something or whatever found in this case right so yeah so we Traverse the root and then we return frown and that should be good uh oh do we that's a little bit awkward I think we just have to kind of keep it consistent outside that's all uh yeah and this is you know very standard the way that I structure is very standard uh recursion tree recursion traversal uh death research if you want to call it that um so it's gonna have the same you know linear time linear space you have to look at every node um I mean I you could get lucky with the inputs but for purposes you have to look at each node so it's going to be off and time and in terms of space you have the other kids based on the stack so it's going to be of h space where H is the height of the tree or maybe just of n depending how you want to say it uh because I have the tree can be n so okay uh I think that's it that's all I have with this one it's uh the follow-up is with this one it's uh the follow-up is with this one it's uh the follow-up is actually a little bit of a hint because I actually forgot about the uh to kind of do it this way until I sort of follow-up uh I was going to do the lazy follow-up uh I was going to do the lazy follow-up uh I was going to do the lazy traversal up one bit I mean I don't know it's just one more pass and above linear time linear space so yeah I'm not gonna go over memory locality optimization but whatever uh that do I have with this one let me know what you think and yeah stay good stay healthy to get mental health I'll see you next week and take care bye
|
Lowest Common Ancestor of a Binary Tree II
|
maximum-number-of-non-overlapping-substrings
|
Given the `root` of a binary tree, return _the lowest common ancestor (LCA) of two given nodes,_ `p` _and_ `q`. If either node `p` or `q` **does not exist** in the tree, return `null`. All values of the nodes in the tree are **unique**.
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 binary 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**) ". A **descendant** of a node `x` is a node `y` that is on the path from node `x` to some leaf node.
**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. A node can be a descendant of itself according to the definition of LCA.
**Example 3:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 10
**Output:** null
**Explanation:** Node 10 does not exist in the tree, so return null.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-109 <= Node.val <= 109`
* All `Node.val` are **unique**.
* `p != q`
**Follow up:** Can you find the LCA traversing the tree, without checking nodes existence?
|
Notice that it's impossible for any two valid substrings to overlap unless one is inside another. We can start by finding the starting and ending index for each character. From these indices, we can form the substrings by expanding each character's range if necessary (if another character exists in the range with smaller/larger starting/ending index). Sort the valid substrings by length and greedily take those with the smallest length, discarding the ones that overlap those we took.
|
String,Greedy
|
Hard
| null |
1,929 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem concatenation of array we're given an integer array nums of length n so maybe something like this where the length is obviously three values we want to return a concatenation of this array meaning we take this array and then append it to itself so then the output array would be the original array plus the array again so basically adding each of these values to the end of the array so one two one so we have two copies of this array combined into a single array and that's what we want to return now there are many ways to solve this problem the easiest way probably would be to just iterate through every value in the input array so go here and then take each of those values and just append it to the original array so we can take the input array and then use that as the result and then return that so we would take the first one add it to the end take two add it to the end take one and add it to the end there you go there's the array and that's what we would return another approach would be to actually create an output array initially it would be empty I'm just drawing it this way because I know this is how much space it's going to take but initially it would be empty we take each value and append it to the array so one two one and in this case we want a concatenation so we would do this once and then we'd do it twice so now we'd add one to one if this problem was not asking for a concatenation and it was actually asking for maybe three concatenations then we would just do this same operation another time so this is kind of a more extensible way to solve this problem because we might want to concatenate a variable number of times and the important thing to note is that since this is like a dynamic array and we're taking each value and just pushing it to the end each time we push a value it's going to be o of one time and we're going to do so n plus n times because the input array is of size n and we're basically creating a concatenation of it so we're doing that with this array twice but that's still going to be Big O of n that's why I think doing it this way isn't really bad because the time complexity is the same we are technically needing extra memory complexity if you count the result as needing additional memory if you don't count it I guess we're doing this in constant memory but now let's go ahead and code up this approach okay so we're going to create our result I'm going to call it ants for answer because that's what they were kind of using in the description of this problem and then what we want to do is take every number in nums and append it to the answer so just like this we want to do that with every value in the input array how many times do we want to do this we want to do it twice so why not just wrap this function or this Loop in an outer loop which will execute let's say two times and then we pretty much have the result and we can return the answer what I like about this solution is it's generic like what if the interviewer asks you now write code that will do this three times or four times or concatenate five times or maybe there's a second variable given called X or you know something that will tell us how many times we want to do this so we can put X over here and then our solution would basically satisfy that now probably your interviewer won't ask you this but I think this is good food for thought so now let's just take this code and run it to make sure that it works and as you can see yes it does and it's pretty efficient if this was helpful please like And subscribe if you're preparing for coding interviews check out neat code.io it has a ton of check out neat code.io it has a ton of check out neat code.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
|
Concatenation of Array
|
maximum-value-at-a-given-index-in-a-bounded-array
|
Given an integer array `nums` of length `n`, you want to create an array `ans` of length `2n` where `ans[i] == nums[i]` and `ans[i + n] == nums[i]` for `0 <= i < n` (**0-indexed**).
Specifically, `ans` is the **concatenation** of two `nums` arrays.
Return _the array_ `ans`.
**Example 1:**
**Input:** nums = \[1,2,1\]
**Output:** \[1,2,1,1,2,1\]
**Explanation:** The array ans is formed as follows:
- ans = \[nums\[0\],nums\[1\],nums\[2\],nums\[0\],nums\[1\],nums\[2\]\]
- ans = \[1,2,1,1,2,1\]
**Example 2:**
**Input:** nums = \[1,3,2,1\]
**Output:** \[1,3,2,1,1,3,2,1\]
**Explanation:** The array ans is formed as follows:
- ans = \[nums\[0\],nums\[1\],nums\[2\],nums\[3\],nums\[0\],nums\[1\],nums\[2\],nums\[3\]\]
- ans = \[1,3,2,1,1,3,2,1\]
**Constraints:**
* `n == nums.length`
* `1 <= n <= 1000`
* `1 <= nums[i] <= 1000`
|
What if the problem was instead determining if you could generate a valid array with nums[index] == target? To generate the array, set nums[index] to target, nums[index-i] to target-i, and nums[index+i] to target-i. Then, this will give the minimum possible sum, so check if the sum is less than or equal to maxSum. n is too large to actually generate the array, so you can use the formula 1 + 2 + ... + n = n * (n+1) / 2 to quickly find the sum of nums[0...index] and nums[index...n-1]. Binary search for the target. If it is possible, then move the lower bound up. Otherwise, move the upper bound down.
|
Binary Search,Greedy
|
Medium
| null |
85 |
hi guys hope you're doing great today's question is maximal rectangle so the patients say is given a 2d binary matrix filled with zeros and ones find the largest rectangle containing only ones and return its area so for example here in this matrix as we can see this is the highlighted rectangle with ones okay so the rectangle has to be formed by just once and we want to find the area of the rectangle which is maximum right so for example here it is six okay so first of all this question is going to use largest rectangle in histogram and I have created a video on that previously so I strongly recommend that you go and watch that one first in order to be very swiftly and easily able to understand this solution okay so this is a matrix and unsorted matrix and let's have a look at the various approaches we can take to solve questions on that so please pause the video have a look think and come back so I think this is a combination as in one is like we just have to simply traverse through the array that's for sure and the other thing is that we have to you know kind of reuse the solution we have done for finding the maximum rectangle in a histogram wherein we have to use a collection to store the bars the heights of the bars that we have seen till now so yeah it's a combination of using a car and traversing through the metrics so let's see how we can actually solve it and what is the concept behind it so if you look at this right and if you look at this first just the first row of the matrix and think of it as the histogram right so these two prime representation so you can see that the first part is of height 1 then 0 then 1 and 0 so here the maximum area would be 1 right if we now add to it the second room ok so this is 1 plus 1/2 this is 1 plus 1/2 this is 1 plus 1/2 this is 0 to 1 right these are the heights of the bars upon the histogram right so here the maximum area would be 2 right now we add another row to it and we get this because 3 1 3 2 right so 6 is our answer and then we add all four of them and we see that this is 4 this is 0 because it starts with 0 so we ignore any ones above it if it is 0 at this particular level its you fur for all and then 0 again 3 & 0 for all and then 0 again 3 & 0 for all and then 0 again 3 & 0 so this reveals like 4 which is lesser than 6 and so 6 is our answer so that's what we have to do we just have to create the height array and every time we create the height array for a particular level we just have to send it to the same method that we are using in the largest rectangle and histogram to find the maximum area and then we add another route to it and send that array to the same function and so on and whatever is the max is our answer so let's get started on the implementation yeah so some base checks so if matrix is a root length is equal to sorry about that goes to zero then we just have to return zero there's nothing we can do about it okay otherwise now let's create an array called height and the length of it would be matrix of 0 dot length and why is that because we want that we create one array with the same number of columns as the matrix so which is indicated row matrix of 0 yeah okay so after this we can just get started with traversing through the array through the matrix in just like the very regular way so matrix dot length I plus and then in J equals 0 J less than matrix for 0 dot length n J plus okay so for this particular column right what we will do is that if matrix of I J is equal to 0 then we just say that height of J right because we are progressing through the columns of height single dimensional array that will be 0 here effective of what it had earlier it will be zero otherwise we just implement height of J by one okay so for example in these cases when on the second column we will see height of zero would have one already because it had one in the first level and then when we see a one again we'll just increment it by 1 okay so we'll just keep doing this and we will get our first height array ready for the very first level and then once we have that after this for loop concludes what we'll do is that max equals two I'll declare this above so max comma let's say find the area and 2 it will give matrix no we'll just give height right you don't even let it set so we'll just give it the height and that's all them okay and once this will be done we'll just return let's stickler and that's equal to zero that's it so now let's implement this find the area method so it takes integer oh yeah so this is gonna be pretty similar to finding the largest rectangle in a histogram so what we will do here is that we will have a local max right which is equal to 0 we only need to use a stack we don't need these conditions here because we know what we are sending so integer stack this new stack okay so now what we have to do is for each element of height first of all we'll add the index of the first element which is always gonna be zero and then we just have to take a for loop and I equal to 1 I less than right dot length okay let's make this etched for being able to write the code Wiggly so I should length and I plus okay so now we just get the current element is which is edge of I right and then we check that if the stack is empty right so there's nothing in the socket just got emptied is empty or current is greater than equal to H of stack dot peak right so whatever is on the top of the stack yeah if you're not able to follow what I'm doing it to find the area please refer the largest area in an Instagram video that's where I've very clearly explained all of this okay so yeah so if the stack is empty or the current is more than whatever index is at the top of the stack and the representation for that in edge what we have to do is that we just have to push that to the stack because we're getting a bigger bar right stack would add ice yep else if it's not then we have to keep on popping elements from the stack until either the stack is empty or we get an element that's smaller than current so while the stack is not empty okay so empty and current is less than H of stack dot pick okay now fine so what we will do is that will just get the element in temp and that will be edge of stack dot pop okay that's the top one now we have to do the math right so what we will do is that if stack is empty that means there's nothing else left then the area max equals two math dot max of max comma them into I yep else it's interesting so else we just do max equals two math dot max comma M into so I we are trying to find the area that this particular part can be spanned on to so I - stack dot peak - one okay on to so I - stack dot peak - one okay on to so I - stack dot peak - one okay yeah okay so once we're done with all of this don't forget to add this tech okay yeah so once we are out of this for loop there is a possibility that the height was ever increasing we never encountered a smaller element in this because of which we would have like popped out the elements so for example of the height was one two three four five six right so we never got into this condition we just kept adding and the stack has all the elements and the max is still zero so we don't want to run into that so that's why after we finish the for loop we'll have to kind of run this again if the stack is not empty okay so if the stack is not empty then we have to I'll just copy the space of it this is literally the same except for this right because we know that all the elements would be larger so while the stack is not empty we just and we do neither than I so I is placed at H dot length because after finishing this H would be like beyond the elements and that's what we need in order to do this mathematics here so we just place it at equal to H dot length and that's it should be okay and then we can return max from here yeah so what we get we just constantly so we just constantly keep tracking whatever max has been returned here and then we finally return this value so let's see if this works this is its function yep sorry about that I don't that ignorance is this is the these are the points of copy/paste okay that works time complexity for this would be O of n into M okay because we are yeah let's understand that because we are traversing through the matrix ones and then for each column right we are just doing this find area right so basically for not for each column for each row right so it kind of becomes of n into m as a collective time complexity and the space complexity would be the number of both number of columns that is matrix with 0 so if n is the number of columns then oh of n is the space complexity because we are using this height array to derive the answer so I hope you find this video helpful if you do please like share and subscribe keep putting indicators
|
Maximal Rectangle
|
maximal-rectangle
|
Given a `rows x cols` binary `matrix` filled with `0`'s and `1`'s, find the largest rectangle containing only `1`'s and return _its area_.
**Example 1:**
**Input:** matrix = \[\[ "1 ", "0 ", "1 ", "0 ", "0 "\],\[ "1 ", "0 ", "1 ", "1 ", "1 "\],\[ "1 ", "1 ", "1 ", "1 ", "1 "\],\[ "1 ", "0 ", "0 ", "1 ", "0 "\]\]
**Output:** 6
**Explanation:** The maximal rectangle is shown in the above picture.
**Example 2:**
**Input:** matrix = \[\[ "0 "\]\]
**Output:** 0
**Example 3:**
**Input:** matrix = \[\[ "1 "\]\]
**Output:** 1
**Constraints:**
* `rows == matrix.length`
* `cols == matrix[i].length`
* `1 <= row, cols <= 200`
* `matrix[i][j]` is `'0'` or `'1'`.
| null |
Array,Dynamic Programming,Stack,Matrix,Monotonic Stack
|
Hard
|
84,221
|
290 |
video World python Securities as well as the same pattern so here follow me so full matches that there is a bijection between letter and pattern and a non-multivatory test pattern and a non-multivatory test pattern and a non-multivatory test so the building problem is given a patent or EA next to ADB I will string dot cat no should we lower back now for the first letter in 5.8 let us imagine letter in 5.8 let us imagine letter in 5.8 let us imagine War in string Dot then for the second word okay then again B such as tab that is matching window already existing letter D then for here it has stopped which is being imaginative always is that dog catfish so in this case we have stuff okay I then B has fished at this time which is not concerned with the previous work so in this case so the opposed is always problem with at first we will check like let's say about pattern it is Rewards is so one use length the other parameter will be or you will convert the string into array actually we can hash mark so you have to and Define a new array or estf and likely nothing split off spaces so this string will be converted to other like dot or not add commas in the pattern people each position is so before comparing it to the other you need to store and declare a hash here that has key as character and ws3 selected so initially when the content a right you check whether that particular queue is presented contains dictionary Dot contains key of this letter create pattern that is not present in it sorry then we look whether or not when you look for the word associated with this letter it's not present in it sorry that is done by the dictionary for contents value of this let's see strf these both conditions happen we'll add its character friction dot put off character and to go next to again dictionary value p-value will be initially packed so this p-value will be initially packed so this p-value will be initially packed so this is both are matching then Sun if both are not watching then you written false so in this case also after this is also here this is dictionary so one more question you need to handle here is a word can be assigned to only known better so the actual pattern of this stream will be able foreign that is password video with letter extreme equal to a start split off case let me check whether it is false if they are equals they need to solve it is and I plus if that leaves are presenting from the key is e of I don't know character easy as time let me check out if you started off get off typing Dot type of 80 cost I is not equals to stay out of I then we will type in this case uh foreign contains value of strfi new data false otherwise that's what we want to put off title dot character of I comma strf excited it's an Avenue so we stopping in the conversation thank you
|
Word Pattern
|
word-pattern
|
Given a `pattern` and a string `s`, find if `s` follows the same pattern.
Here **follow** means a full match, such that there is a bijection between a letter in `pattern` and a **non-empty** word in `s`.
**Example 1:**
**Input:** pattern = "abba ", s = "dog cat cat dog "
**Output:** true
**Example 2:**
**Input:** pattern = "abba ", s = "dog cat cat fish "
**Output:** false
**Example 3:**
**Input:** pattern = "aaaa ", s = "dog cat cat dog "
**Output:** false
**Constraints:**
* `1 <= pattern.length <= 300`
* `pattern` contains only lower-case English letters.
* `1 <= s.length <= 3000`
* `s` contains only lowercase English letters and spaces `' '`.
* `s` **does not contain** any leading or trailing spaces.
* All the words in `s` are separated by a **single space**.
| null |
Hash Table,String
|
Easy
|
205,291
|
139 |
So hello everyone, today is 4th August and today we are going to solve the poo problem of let's code. Break, so here it is said that there is a string named S and we have a dictionary of string which will contain what it means, you can say what we can do. Can also be found in the dictionary, multiple times in D segmentation, so it means anything, if there is a string, like there is a string, there is anything, yes, and inside the string, whatever it is, it can happen twice, so if you see this. The lead is matching with this, so if we segment it, there are two types of lead and code, both are available. Well, here Apple Pen is Apple that we can do it multiple times and what is that in the gift ] After that, what can we do here inside what do we do here, what is here is clear, so if I explain it again, what is happening here, from the beginning till we Going and checking so I did it to CAT and child what will not be found passed and again what I did after tracking back so it seems to us so what I will do is send it and here OG If there is any water left, it will complete it. Similarly, what will happen here, so much was the process, I will not see it, if it is, then I will take it out from the string and will do it tomorrow, then this much was the approach, it is involved in this, so try it once yourself. How to solve it, how to solve it, so I am hoping that you all tried the code once by yourself, if it made any sense then I had given a hint, you guys told something to you and if not then no problem, I am here. How will it be solved by those who explained it completely yesterday, so we have to do it here and where there is a match, what we have to do there is that we have to take out that thing and search it from the next one, then to identify it, if To identify whether send is WhatsApp inside the word, we can easily do it by setting it, we can find it by doing set, I am doing set in English, what is the meaning of set, what is the name of it has a ring and every Right now, what are we going to do, now I write the tracking function here in which I will pass S because zero, so to pass, where do I have to check it, my co will be zero where I am going to start. For example, if I send it here and then whatever has to be checked, after that, for example, if this is Boolean, then I will forget the name of the solve function and sorry because how is the best of our aids, what is going to happen, inside this we have to What is happening is that while doing all our searches, like till the late code, I am getting completely completed, then whatever comes here, whatever is the last index, I will get the ward there that I will say. No, I have got the answer, if these plus one is not done, then I will say there that if I have to check one by one, then I am taking string time, what will I do Find what is the time that I can get. Is it inside the string? So if it is there then else it will not come So if it is happening then what will I do again and plus I have to keep doing it here if my if it is not there then return Jal karna so in this Should it be run, do I have to define the time limit, which is going to be taken directly, so I think here we will have to do dynamic programming because here I am what are we doing? If we calculate the same value again and again, then it is for recalculation, so we put it here, I am creating a vector in which what I will do is create a DP name computer which will have S dot size and all mines and I am passing this I am DP and what should I do in this too, son, why did I write responsibility because I have taken mine here, wait, inside this, what is the rate DP, OK, DP also has to be passed in the year What is the problem here, what is the problem? If there is a problem, then what am I doing? Okay, I am staying here because I have taken all my DPs, which will calculate the size of the factory, I will take the index, then it will go there. Friends, if you are deserted, then comment. write in
|
Word Break
|
word-break
|
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words.
**Note** that the same word in the dictionary may be reused multiple times in the segmentation.
**Example 1:**
**Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\]
**Output:** true
**Explanation:** Return true because "leetcode " can be segmented as "leet code ".
**Example 2:**
**Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\]
**Output:** true
**Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ".
Note that you are allowed to reuse a dictionary word.
**Example 3:**
**Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\]
**Output:** false
**Constraints:**
* `1 <= s.length <= 300`
* `1 <= wordDict.length <= 1000`
* `1 <= wordDict[i].length <= 20`
* `s` and `wordDict[i]` consist of only lowercase English letters.
* All the strings of `wordDict` are **unique**.
| null |
Hash Table,String,Dynamic Programming,Trie,Memoization
|
Medium
|
140
|
347 |
leite code 347 top K frequent elements given an integer array nums and an integer K return the K most frequent elements you can return the answer in any order okay um this is a uh the this is a two-part problem so the first part is a two-part problem so the first part is a two-part problem so the first part of it is a it's going to be a hashmap problem because we want to get the frequency of each of these elements and know what all of their frequencies are uh the second part is uh Heat problem because we're going to want the frequencies ordered in some way we don't really want to uh and then we and we just want to get the k um most frequent in this case so we're just going to go to one end of the Heap and just get K elements because uh if it goes in a heap it's going to automatically be sorted for us all right and then uh if you look carefully there's also an edge case here which is like kind of a bonus uh it's like a freebie return um because if the length of nums is one you can just obviously return nums itself because there's only one way there's only going to be one most frequent element in there so let's go ahead and get the bonus case out of the way so if one turn nums and we just want the array of nums we don't want a specific element from it all right so when here's our hashmap section so let's make our hashmap get our counts and populate it ins okay so it's just a map of the ins to their counts so the inss and nums to their counts right all right so that's populated now the Heap section and this is kind of like um okay so first of all a heap is a data structure in which elements are sorted um by their something called their priority in this case the priority that we're interested in is just their uh value their frequency um and this is kind of like we have heaps at home you know because this is really not a heap it's just an array that we're um we're managing like a heap that's an array of arrays okay so he all right I'm just going to go over a frequency map and if I didn't explain it right um we're going to put each number in this Heap okay it's not really a heap yet but by the time we're done it will be a heap because the greater the index is going to correspond with the frequency of that element and so if a number has a higher if an element has a higher frequency it's going to give a larger index in the frequency map so by the time we're done it will be a uh organized as if it were um a Min Heap and we're just going to make a struct to return and we want the K elements okay and now uh because this is going to be laid out like a heap we just need to get it's a Min Heap so that means the larger um the most more frequent elements are toward the back of the Heap so we need to get we need to start at the end and uh yeah it's starting at the end so we need to minus one if our K is actually yeah we don't want to get a negative because we would accidentally get to zero and uh should have put this first but return all right okay we have a wrong answer that case works oh we made this too long because uh it starts at zero index uh so we need to minus one or add one to that to make it long enough hang on a second oh of course okay so there we go um had a uh out of bounds because this because of zero indexing uh with the length or sorry with the yeah this needs to be one longer because let's say we get a case where it's all ones uh we wouldn't have a space to put that because it would be uh it would be one longer than the length of the array
|
Top K Frequent Elements
|
top-k-frequent-elements
|
Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequent elements_. You may return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,1,1,2,2,3\], k = 2
**Output:** \[1,2\]
**Example 2:**
**Input:** nums = \[1\], k = 1
**Output:** \[1\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
* `k` is in the range `[1, the number of unique elements in the array]`.
* It is **guaranteed** that the answer is **unique**.
**Follow up:** Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size.
| null |
Array,Hash Table,Divide and Conquer,Sorting,Heap (Priority Queue),Bucket Sort,Counting,Quickselect
|
Medium
|
192,215,451,659,692,1014,1919
|
162 |
hello everyone today, one of the tasks on the Finder lead code, we still have to throw those tasks to ask about this work in our hit from find the highest Why are you our Picnic because our appearance is like three and so I’ll because our appearance is like three and so I’ll because our appearance is like three and so I’ll throw us turn and index 012 then we will turn the 2 available butt of us E2 peak C 8 can be a five OK we could calmly All of our lists are sensitive to the right And thereby find options for what we need throughout the entire list so for the logarithm we have one of the options we also have our massive one there, it will be sorted and in the body we can so often its kind of sorted stuffed almost three elements in the other you have big breasts Well, washes of that in general we can in the gooseberry our pattern you not enough and here we need another buvin more for the template plus one for the available one and I’m still not bad damaged So that means she Let’s try to run the she Let’s try to run the she Let’s try to run the left Vile again in the middle [ left Vile again in the middle [ left Vile again in the middle came pilaf was Sound distance problem
|
Find Peak Element
|
find-peak-element
|
A peak element is an element that is strictly greater than its neighbors.
Given a **0-indexed** integer array `nums`, find a peak element, and return its index. If the array contains multiple peaks, return the index to **any of the peaks**.
You may imagine that `nums[-1] = nums[n] = -∞`. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.
You must write an algorithm that runs in `O(log n)` time.
**Example 1:**
**Input:** nums = \[1,2,3,1\]
**Output:** 2
**Explanation:** 3 is a peak element and your function should return the index number 2.
**Example 2:**
**Input:** nums = \[1,2,1,3,5,6,4\]
**Output:** 5
**Explanation:** Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
**Constraints:**
* `1 <= nums.length <= 1000`
* `-231 <= nums[i] <= 231 - 1`
* `nums[i] != nums[i + 1]` for all valid `i`.
| null |
Array,Binary Search
|
Medium
|
882,2047,2273,2316
|
1,838 |
Hello and welcome to my channel this is Shaurya Vasti and today we will solve the medium level problem of lead code which is to tell the frequency of the most frequency and after that we can increment it by one and as many operations. We are given as many numbers as we can do this number of times, like this is an operation, after that we have to return what is the maximum number of such numbers that we can create which are the same, like what is the maximum frequency that we can generate, for example if If we take an example, here there are three elements inside the names which are in the first example 1 2 and 4 Okay so the value of k is five given here i.e. value of k is five given here i.e. value of k is five given here i.e. we have five operations so we check if we look at one. If we increment one by four times, sorry, if we increment one by three times, then our array will become four and if we increment two by two times, it will become four, that is, ultimately our array will become four and four whose frequency is three and If the element is four then our return here will be three, so the way we see to solve this is that if we first shorten the array because we cannot make it equal to any other element by incrementing the largest element. Therefore, we have to start the work from the smallest, then we will move in ascending order, that is, we will move from smaller to larger, because we will not start from any element which is larger in size than the previous element. Because no bigger element can become equal to its smaller element by incrementing because here increment is only an operation and decrement is not an operation so the first step what we will do is sort it so our first step will be that we sort it. After the second step, we will put the sliding window. Okay, after putting the sliding window, our complex will be bigo n logged in. Now how will this n log in because whatever is short, it will only take n logged in, brother short is our n. The same thing is going on about the sliding window. Our login will not make any difference. Okay, by the way, the sliding window will not affect us because the short one will take more of our complex which will be of different. Okay, so let's talk now. How do we approach the problem? Let us take the example 1483 13 which is already sorted and k is 5. The output is coming to two. Okay, so let's go to the white board and see how it is working. Okay, so here. If the value of k is F, then the condition we will create inside the window inside the sliding window will be this. I cannot explain it right now, I am doing it now, meaning when I explain it, you will understand what the condition is saying. Okay so. If we look here, both our left and right pointer are pointing to our zero index, which is this index, after that this is the one index and like this I create all the other indexes also and write it here, is it okay? 0 1 2 3 The index here is pointing to zero on both left and right. Okay, so our concept is that I have thought of a logic that if we slide the window let us suppose, this is our window. Okay, 148 now here. Whatever is our maximum element will always be on the right. If this is a window then our left will be this part and right will be this part. Okay, so our right element will always be our maximum element. So we are checking that what we We can make all the elements of the remaining window equal to the right, so we will return the length of the window in the same way, the length of the window in which we can make all the elements equal, okay, that will be our answer, so if we check here, then we 8 If we make 88 out of all three, then we will have to add four extra here i.e. four, its seven has been extra here i.e. four, its seven has been extra here i.e. four, its seven has been taken. Here we have to add here i.e. taken. Here we have to add here i.e. taken. Here we have to add here i.e. 7 and 4 11 but we cannot perform 11 operations because we have only five operations. So here, this will be our null, that is, if you check this condition, this is the condition, numbers r, that is, r means at, numbers r means second index, which is our eighth element, numbers aa, the value will become 8 into r. - l+ numbers aa, the value will become 8 into r. - l+ numbers aa, the value will become 8 into r. - l+ 1 means that is the length of our window. So 8 is r. This is l. 0 and plus is one. So this is our total. So 8 is 3 = two. This is 24. It is okay. 8 is 3 = two. This is 24. It is okay. 8 is 3 = two. This is 24. It is okay. End k ps sum i.e. how much is our sum till now? End k ps sum i.e. how much is our sum till now? End k ps sum i.e. how much is our sum till now? We will keep adding each element as we take it line by line. We are talking about the sum of our window. Here, our sum of the window is 13 which you can see. We are getting 8 + 4 + 1 = 13 so 13 + you can see. We are getting 8 + 4 + 1 = 13 so 13 + you can see. We are getting 8 + 4 + 1 = 13 so 13 + 5 k which is our 17 i.e. if we have 5 k which is our 17 i.e. if we have 5 k which is our 17 i.e. if we have whatever sum is coming here in 13, even if we increment it once by applying k operation, then it is still at most. Ours can be made only 17 which is less than 24 so that means whatever this window is cannot be our return anytime. Answer: So what will we do here Answer: So what will we do here Answer: So what will we do here when this condition is true i.e. our when this condition is true i.e. our when this condition is true i.e. our numbers are multiplied by the window size. If this is greater than if this condition will return if this condition will bring there then what we will do here is we will increase the left pointer which will be ours by one, okay we will increase the left pointer by one and at the same time what will we do with At the same time, we increase the left pointer by one and let me erase it for a minute. Okay, so by increasing the left pointer here by one, the sum of our window here will also decrease when our window becomes smaller here. So its sum will also be decreased, so here we will increment it by L. It is okay till here, what will we do after that, we will subtract from the sum i.e. from the sum, this element which will be ours, will i.e. from the sum, this element which will be ours, will i.e. from the sum, this element which will be ours, will also have to be subtracted because If the window size has become small, then to subcut it, we will write Nums L here, okay, which is our least element, it will also be deleted there, that is, it will be erased by Nums, so our sum will be reduced. Value Now, whatever is our window size, the value of our sum will change accordingly, so we will perform this operation, if we bring this condition, then it is okay, this much is clear, after that, let us talk about how we will perform further. Slowly, now we see each and every thing in clear cut, how will it work, okay, so here we erase everything again, okay, now we take back the pen here and we check here that it is back now. How will the working be done here, l and r are ok then what is l and r i.e. which is our l and r are ok then what is l and r i.e. which is our l and r are ok then what is l and r i.e. which is our one, why will it be 1 * 1 * 1 because the one, why will it be 1 * 1 * 1 because the one, why will it be 1 * 1 * 1 because the window size is one, the element is also one, maximum so the maximum element is one window size 1 * 1 Which is what is our greater than k size 1 * 1 Which is what is our greater than k size 1 * 1 Which is what is our greater than k ps sum k plus sum k means here k is done operation and sum is done our window's sum so window's sum one is k p is done 6 is six greater is one is not greater so that means we If we increase the value of Aa, then the value of Aa will move away from here. Now the value of Aa has come here or our window size is this, now we check again. Okay, so we will check again. Now our sum of F and K is done. If it becomes 5 then 5 10 then what about ours which is 4 * 2, why 10 then what about ours which is 4 * 2, why 10 then what about ours which is 4 * 2, why because the window size is two, so 4 * 2 is because the window size is two, so 4 * 2 is because the window size is two, so 4 * 2 is bigger than 10, it is obvious that it is not bigger, so what will we do, we will again increase the value of r. And now our window size will increase. Okay, so now what will be our window size? One minute, now our window will be reduced to three lengths. Okay, after that what is our maximum. Now here, if we see, our Till now the window size which has come is one and the other two which was satisfied. Now our eight is coming and eight will not satisfy. Why because we have already told that eight is our maximum element. If we divide it by three. Let us multiply that by three which is our window size, our value is coming to 24, so the value is coming to 24 and the sum here is 13 and if we add clip to it then our sum + k becomes add clip to it then our sum + k becomes add clip to it then our sum + k becomes 17. Okay and sorry sum p k becomes our 18 and 18 which is our that is smaller than a our sum is smaller than the numbers into the window is the size of the numbers are into the windows is the size so our this will satisfy the condition and as soon as this condition is satisfied What did I tell you that we will move l forward i.e. our window size will we will move l forward i.e. our window size will we will move l forward i.e. our window size will now become this and our sum will also become minus one i.e. our sum current will become 12. Okay i.e. our sum current will become 12. Okay i.e. our sum current will become 12. Okay again we will check this so can we make this okay. 8 + 4 This is our make this okay. 8 + 4 This is our make this okay. 8 + 4 This is our sum becomes 12 Here and our maximum element into the window, our size becomes 8 * 2 i.e. 16, so our size becomes 8 * 2 i.e. 16, so our size becomes 8 * 2 i.e. 16, so can we take this size? Yes, we can take this, why because this is 16 And it is even 12, okay, so 12 p k, which is our 17, so 17 is ours, which is not small, that is, we will not bring this condition, so we can increment r further. Again, we will increment r further, r will come. Now the maximum element here becomes 13, now 13 * 3 because the window size is 13 * * 3 because the window size is 13 * * 3 because the window size is 13 * 3, if we check then 13 * 3, here we will 3, if we check then 13 * 3, here we will 3, if we check then 13 * 3, here we will get 39, now we check 39, our sum becomes 12. And 13 12 13 25 is 25 + 5 30 so 30 is our is 25 + 5 30 so 30 is our is 25 + 5 30 so 30 is our smaller given 39 so this condition of ours will be satisfied and as soon as this condition is satisfied we will make l smaller i.e. our current l is our window from here. i.e. our current l is our window from here. i.e. our current l is our window from here. Now the size will be whatever it is, that is, the window size that is satisfied till now, our 1, 2, come again, the one that satisfies the window here, this three window size here will not satisfy, that is, here again the window value will be only two and last. The one that is ours is 13 and 8, it becomes 21, okay and 13 * 2 26, this is 21, okay and 13 * 2 26, this is 21, okay and 13 * 2 26, this is satisfying, okay, so again our window size will be two, that is, our maximum window size will be only two, so in this we will put a pointer to max. If we have to return the maximum length which is better than the maximum length by checking the length again and again, then the three which was given here once was not valid, that is, our maximum answer will be only two, which is also in the question here. The answer is 'Given is Too'. Okay, so also in the question here. The answer is 'Given is Too'. Okay, so also in the question here. The answer is 'Given is Too'. Okay, so now that's enough here, maybe okay, let's code. If you understand better, then the first thing we will do here is what will we do in our code? The first thing we will do is that we will do it three. Sorry to the variable four variables which is ours what is the left pointer which is zero after that we take the right pointer that is also zero ours after that we take the sum after the right pointer now what is this sum which is the window current window The length of is its even comma, after that we take the length here is the length of the window, now that is also zero, after that we treated it, after that after declaring, we reduced everything to zero, after that we will put the while loop. And in the while loop, we are increasing R one by one. Okay, we are increasing the window size from R's side, so how far can we take R, till the numbers dot size. Okay, what will we do after that, as soon as We will consider R in the window, similarly we will add Aa to Sum, which will be our Sum plus equal to Nam. Okay, we have added Pay here. Now the current, which will be our Sum, will be added. Along with this, we will do another while loop. We will take the internal while loop, what will it do? This internal while loop will check whether our condition which I told you here is being satisfied, till then it will keep adding l to plus. Okay, so our l means. It will keep reducing the window size from the back i.e. means. It will keep reducing the window size from the back i.e. means. It will keep reducing the window size from the back i.e. it will keep reducing the window size from here onwards and whenever this condition of ours is satisfied, the window size will keep getting smaller from the back. Okay, so let's see here while now, what will this while look do? Will check ours, I told you the condition, okay, so let's do one thing, why don't we copy this condition, okay, leave it, we will write it again here, it is not being copied, okay, so this is the condition of our numbers, R. Multiply by window size. Window size. What is our window size? Our window size is r - l + 1. Okay, and this is Our window size is r - l + 1. Okay, and this is Our window size is r - l + 1. Okay, and this is our if it is greater than sum of k. If this is greater than sum of k then what will we do? We will do one thing. We decrement from even, i.e. subcut from even, which decrement from even, i.e. subcut from even, which decrement from even, i.e. subcut from even, which numbers L and also increment here. Once A is okay then it is okay, now here we have the current, now what will we see after that like Now we will move ahead, what is this condition doing? This condition is doing the work that if we have any invalid length in which we are not able to fulfill, with the help of number of operations, we are not able to fulfill the frequency in that length. If we are getting it then it will eliminate it and increment L further i.e. when our i.e. when our i.e. when our execution reaches here, none of our invalid length will reach here, it will already be terminated here P OK so here we length E equal to what will we do max of length comma which current is our length what is the current length r mine l pw okay and then we will also increment this by x r at the end of the loop okay so this should give our correct answer yes Should be given, after that we also return the length on Y. Okay, let's run it and see, maybe it will run. Okay, this is giving the color answer. Okay, so it is giving the color answer in the third condition. Expected is one and this is giving two. Yes, okay, so what mistake have we made in this? Oh [ __ ], we forgot to sort it, so the [ __ ], we forgot to sort it, so the [ __ ], we forgot to sort it, so the first thing I have forgotten is so let's sort it. Okay, now the answer is correct, but there is a problem here. If yes, then maybe there will be a problem. Here we will have to take long but once we check yes ok I thought there will be problem of sign overflow ok so it is saying that such a big number cannot be represented so we simply long here If you take it then our code will run ok now we submit it ok so it is submitted successfully submitted ok so thank you for watching this video if you like the video please hit the like button and subscribe the channel Do it and see you in the next video. Thank you.
|
Frequency of the Most Frequent Element
|
number-of-distinct-substrings-in-a-string
|
The **frequency** of an element is the number of times it occurs in an array.
You are given an integer array `nums` and an integer `k`. In one operation, you can choose an index of `nums` and increment the element at that index by `1`.
Return _the **maximum possible frequency** of an element after performing **at most**_ `k` _operations_.
**Example 1:**
**Input:** nums = \[1,2,4\], k = 5
**Output:** 3
**Explanation:** Increment the first element three times and the second element two times to make nums = \[4,4,4\].
4 has a frequency of 3.
**Example 2:**
**Input:** nums = \[1,4,8,13\], k = 5
**Output:** 2
**Explanation:** There are multiple optimal solutions:
- Increment the first element three times to make nums = \[4,4,8,13\]. 4 has a frequency of 2.
- Increment the second element four times to make nums = \[1,8,8,13\]. 8 has a frequency of 2.
- Increment the third element five times to make nums = \[1,4,13,13\]. 13 has a frequency of 2.
**Example 3:**
**Input:** nums = \[3,9,6\], k = 2
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 105`
* `1 <= k <= 105`
|
Calculate the prefix hashing array for s. Use the prefix hashing array to calculate the hashing value of each substring. Compare the hashing values to determine the unique substrings. There could be collisions if you use hashing, what about double hashing.
|
String,Trie,Rolling Hash,Suffix Array,Hash Function
|
Medium
| null |
746 |
hello guys welcome back to another video today we'll be talking about number four hundred 746 and the Lee code problem set min cost climbing stairs this problem is an easy problem and one of the few problems that have that has so many likes on lee code alright let's get into the problem so on a staircase the I this step has some non-negative the I this step has some non-negative the I this step has some non-negative cost so it's going to give you an array and so at index I that's the cost and 0 is indexed once you've paid the cost you can either climb one or two steps you need to find minimum cost to reach the top of the floor and you can either start from the step with index 0 or the step with index 1 so here are the examples usually when I do problems I like to read the notes first to see how fast my solution needs to be so it says cost will have a length in the range 2 to 1000 inclusive and every cost at I will be an integer in the range 0 to 999 so not too big here and the length isn't too big either alright so the examples is 10 15 20 as the cost and then outputs 15 because you can step on this one and basically get to the top without stepping on 20 and then for example 2 will actually get to that and whiteboard ok so here I have a similar example and I will get to this example so it says 1 4 7 so return for so forth so what the approach to this problem should be is you want to calculate at each index the previous twos minimum cost and then add that on so as you add the costs on then you would have a cumulative value at the end and then at the end you will compare the last two elements of the array and gets a minimum of that which is your answer so right here I pulled example two from the interface so this is an example two and we're just gonna go through the array so for memory purposes and simplicity purposes modifying the original array is actually a more optimum or optimal option so we're also gonna start at next two because it needs the two previous indices and index zero and one doesn't need to have any change so right here we have one 101 100 and then at index two it takes the minimum of 0 and 1 which is 1 so it adds that on which gets you 2 and then 1 is the minimum of 102 which is 2 so the add on 3 and then this one takes this minimum of 2 so 3 again and then the 100 takes 3 because they're all threes and then so it's 103 and then the 1 takes a 3 here which makes it 4 and this one takes 4 which it makes it 5 and 100 takes um 102 take 4 here and then um one takes 2 5 which makes the final one 6 so right here we've iterated through the array and modified all its values so what we need to do once we finish the array as we return at the minimum of these 2 which is 6 and the answer to that is to that example of 6 as well as you can see here so let's start coding this problem should be fairly easy in my opinion um not a lot of lines of code let's just start by iterating through the array which starts at in this and that's 2 as I've previously mentioned so you wanted to stop when I is equal to cost not length so that's our condition there and inside this is the interesting part of this problem so you want I costs at I equal to the minimum of the previous two so cost at I minus one and cost at I minus two now that this is finished the array is already constructed so I'm just gonna print out the array here for better visualization so here's the array and right here we return very important step here make sure when you're calling the index its subtracted by one first and then costs that length subtracted by two all right so that's our solution so let's run the code and it's gonna actually gonna give us all zeros which isn't that helpful so let's switch to this one and we seem to have gotten a wrong answer let's see why we got a volley answer so I put this here and then I put this here oh here's why as I previously mentioned you need to actually sum up the indices instead of just adding so that's just solved the problem all right there you go so now as you can see this array is actually the same as this one that I constructed over here and that is how you approach this problem that's submits this and we've passed so it's a one millisecond run time faster than eighty three point oh six percent so pretty good memory could be better so climbing stairs if you haven't checked out my video on climbing stairs make sure to check it out it's a very similar problem to this and it's pretty interesting alright so let me just finish up with this problem so let's analyze the time complexity of this solution so with one full loop and a min it's basically a olefin solution so pretty good it's linear time and I hope you've enjoyed this video if you want to check out more of my programming videos go to my channel page and remember to Like and subscribe
|
Min Cost Climbing Stairs
|
prefix-and-suffix-search
|
You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to reach the top of the floor_.
**Example 1:**
**Input:** cost = \[10,15,20\]
**Output:** 15
**Explanation:** You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
**Example 2:**
**Input:** cost = \[1,100,1,1,1,100,1,1,100,1\]
**Output:** 6
**Explanation:** You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
**Constraints:**
* `2 <= cost.length <= 1000`
* `0 <= cost[i] <= 999`
|
For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te".
|
String,Design,Trie
|
Hard
|
211
|
1,029 |
Sonu Nigam Two Point Question Today's Attacks Late Co's Question is 2016 Scheduling 1380 People A Company Is Planning To Interview Till Cost Of Drawing The Question To City Eggs Course If Opposite Element And Cost Of Minds Of Those To Cities Screwdriver 800 To 1000 Minimum Cost for every person to cities was exact le in process arrived in which city is the question delivery algorithm's approach let me show you how I solved it so we are given in the input a playlist of which is post element 10 Second element is 3203 limit for 108 and for the element is 3020 so what I did in this I listed a quantity named in this I am adding the value which is at 0 position of Haridwar element and took the report element admin team then its source element It happens that I have taken 78, its opposite element is Friends, I have taken Forces and its opposite element is, after adding you girl sub, I got the answer and only 1470, so what should I do after that I am making a list named text. In which I am on second city - for city because you see here there are - for city because you see here there are - for city because you see here there are 10 - tankers 10 - tankers 10 - tankers which are tan comfortably for me then this minute 210 - 3170 alarm from Iran in this soil - 210 - 3170 alarm from Iran in this soil - 210 - 3170 alarm from Iran in this soil - foreign trade - 350 army dance in this 10 - foreign trade - 350 army dance in this 10 - foreign trade - 350 army dance in this 10 - 3002 km - Tan came and after that 3002 km - Tan came and after that 3002 km - Tan came and after that what I am doing is I am returning the sum of first step which is my 470 plus form of short dip means this texture list of mine, I set it first in ascending order and then ours - in ascending order and then ours - in ascending order and then ours - 350. First of all, it will go - 10m, after that, 350. First of all, it will go - 10m, after that, 350. First of all, it will go - 10m, after that, Tan will come, after that, closed committees will come, so our list will become something like this - 350 - 0, so we will start - 350 - 0, so we will start - 350 - 0, so we will start from the source element which is - 250 till 2 which is from the source element which is - 250 till 2 which is from the source element which is - 250 till 2 which is 10th. That Tanu - 151 - is taking the test, I am reminding you that it is That Tanu - 151 - is taking the test, I am reminding you that it is That Tanu - 151 - is taking the test, I am reminding you that it is 1000 430 which is the sum of first city plus minus one fifty plus minus and by returning this our digit will come. I have made a list on the topic named opposition in which 10 I am storing the element in it, I have created a list named dip in which I am storing the difference of both, after that I am returning directly the glow positive plus orgasm shot dip and its well this is the land divide of the cost. If you complete till 2, then I will run it and then see the digit that is coming, submit it and it is accessed, see you in the next video.
|
Two City Scheduling
|
vertical-order-traversal-of-a-binary-tree
|
A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`.
Return _the minimum cost to fly every person to a city_ such that exactly `n` people arrive in each city.
**Example 1:**
**Input:** costs = \[\[10,20\],\[30,200\],\[400,50\],\[30,20\]\]
**Output:** 110
**Explanation:**
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.
The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
**Example 2:**
**Input:** costs = \[\[259,770\],\[448,54\],\[926,667\],\[184,139\],\[840,118\],\[577,469\]\]
**Output:** 1859
**Example 3:**
**Input:** costs = \[\[515,563\],\[451,713\],\[537,709\],\[343,819\],\[855,779\],\[457,60\],\[650,359\],\[631,42\]\]
**Output:** 3086
**Constraints:**
* `2 * n == costs.length`
* `2 <= costs.length <= 100`
* `costs.length` is even.
* `1 <= aCosti, bCosti <= 1000`
| null |
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Hard
| null |
945 |
hello Iraq today we talk about each color problem 945 minimum increment to make armory unique the problem is about given an array of integers a or mu consists of cruising any AI and increment it by 1 return this number of modes to make every value being a unique let's say an example 1 the input array is a one who true and we just need a one more mix the relax one two three each element in this array would not be identical let's say our exam to the infirmary is three two one seven and we need at least six mood to make the related three four one two five seven and each element in this ER will not be under nickel so how to solve this problem general for problem relates will ring we need to determine whether or not this array is sorted if not firstly generally we solve this array that we defined the return result at last way we follow this or one time the cow meaning this problem is a we need to compile the 2j Center or elements relationship and the foster we define the two adjacent elements and in fact in this problem a proud previous element is a larger or equal than current element we need in this condition we need to do to seen the first step is going to enter the value to the result and the same style when it will increase the current of a third element natural than the previous one at last we need to return the result and the whistle boom is the answer and now what is the temp correctly for this problem and if we do not consider the assault and we only follow this orient one time so the time complexity for this solution is own and if we consider those this sort under the temp capacity will be and will be all Owen pretend logon cents for washing
|
Minimum Increment to Make Array Unique
|
snakes-and-ladders
|
You are given an integer array `nums`. In one move, you can pick an index `i` where `0 <= i < nums.length` and increment `nums[i]` by `1`.
Return _the minimum number of moves to make every value in_ `nums` _**unique**_.
The test cases are generated so that the answer fits in a 32-bit integer.
**Example 1:**
**Input:** nums = \[1,2,2\]
**Output:** 1
**Explanation:** After 1 move, the array could be \[1, 2, 3\].
**Example 2:**
**Input:** nums = \[3,2,1,2,1,7\]
**Output:** 6
**Explanation:** After 6 moves, the array could be \[3, 4, 1, 2, 5, 7\].
It can be shown with 5 or less moves that it is impossible for the array to have all unique values.
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 105`
| null |
Array,Breadth-First Search,Matrix
|
Medium
| null |
1,419 |
hello uh let's do a question minute number of frogs croaking so you're given a string of frogs which represent a combination of string croak from different frogs each multiple frogs can crook at the same time so multiple croak are mixed and turn the minimum number of different frogs to finish all the croaks in a given string a valley croak means a frog is printing five letters c-r-o-a-k sequentially right so it has c-r-o-a-k sequentially right so it has c-r-o-a-k sequentially right so it has to be in that order frogs have to print all five letters to finish a crow if given the string is not a combination of velocity minus one okay some examples you have crow crook or you have two croaks but are mixed together somehow this is valid if you can't make two croaks or any number of croaks out of the string then invalid so okay how do we do this let's take uh this one for example it says return the minimum number of different rocks to finish all the crooks in a given string so it's not actually just to count the number of croaks in here you actually just you want to figure out the maximum number of crooks that are interleaved together so this is actually just one because um it could be just the same frog croaking twice so um i could do is i could have c r o a k and then for each i have a counter so c is one and then when i see an r here so i'm up to r there needs to be a c before this for the string to be valid so i need to check what's with force r it's a c is that if i subtract one from that will that be negative in this case no so it's still valid if it was negative then i could just return uh minus one so this would be one now and i could decrement this and i move this up and then this becomes a one i guess at all times i want to get the max i want to say the answer is equal to the sum of this array so this will be to it right now let's just say is equal to two at the moment so you already know that the answer would be two would be at least 2 and we know that the answer is 2 so now we're actually just kind of validating that there are two croaks the crop that the string is valid so we see an o so let's check if it's valid i can subtract from this yeah so if you imagine these two ones they represent um an individual croak and if you move the a across then this becomes zero this becomes a one so still have two interleaved croaks and then we move into a k this is finished and now there's only one croak in progress so actually i don't really need to keep track of the k here having a one in the k means uh this croak is already finished one crank is already finished go to the r see if i had f had an o just now it would be invalid so i can turn minus one um so this would be zero this be one and of course it's gonna move up all the way to this being two um by the end of the string i need to make sure that c the sum of this array here croa is zero otherwise it's already there's still a crook in progress and so the string isn't valid okay let's try that all right let's think given a character r i want to map that to an index let's see b0 rb1 let zero be two three and this before so for c and r i can map that to a one and then i could subtract one from that to get the previous uh value for c so i could have char 26 and then have a string croque is equal to croak go through each character in croak m at um the character so croak at the index minus a is equal to i've mapped each character i need to somewhere to store these values let's just do this um an ent array called dp it's not really dp is it really i think it is sort of dp so i'm going to call it dp with um there's going to be four elements in there for croa and i actually want to initialize that to zero so let's just put up here then go through each character get the index value which is going to be m at um c minus a i don't need to check if it's an invalid character so krakow frogs is either croak if dp at i minus one okay but i have to check if i is greater than zero and this is equal to zero then turn minus one otherwise yeah it will be invalid i know i have to do um dp at i plus if i is less than five if i is less than four actually here i could probably put this in an f state if dp at i minus one is equal to zero then return minus one or i could say if this is less than zero i also need to keep track of the answer which is initially zero and it's keeping track of the sum the current sum which is also initially zero sum of this array and this array is going to be sum minus here and some sum and plus sum here and then i can say answer is equal to max of the answer and the sum and then i can return the answer i think there's a case where this fails so let's say i have c r o a so almost there but hasn't completed the string yet so this will say this two okay so we want the sum to be equal to zero by the time we finish so then that means you can turn it into otherwise between minus one okay cool let's submit that uh if you have any questions leave in the comments below thanks for watching like and subscribe and i'll see you in the next video
|
Minimum Number of Frogs Croaking
|
minimum-number-of-frogs-croaking
|
You are given the string `croakOfFrogs`, which represents a combination of the string `"croak "` from different frogs, that is, multiple frogs can croak at the same time, so multiple `"croak "` are mixed.
_Return the minimum number of_ different _frogs to finish all the croaks in the given string._
A valid `"croak "` means a frog is printing five letters `'c'`, `'r'`, `'o'`, `'a'`, and `'k'` **sequentially**. The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid `"croak "` return `-1`.
**Example 1:**
**Input:** croakOfFrogs = "croakcroak "
**Output:** 1
**Explanation:** One frog yelling "croak **"** twice.
**Example 2:**
**Input:** croakOfFrogs = "crcoakroak "
**Output:** 2
**Explanation:** The minimum number of frogs is two.
The first frog could yell "**cr**c**oak**roak ".
The second frog could yell later "cr**c**oak**roak** ".
**Example 3:**
**Input:** croakOfFrogs = "croakcrook "
**Output:** -1
**Explanation:** The given string is an invalid combination of "croak **"** from different frogs.
**Constraints:**
* `1 <= croakOfFrogs.length <= 105`
* `croakOfFrogs` is either `'c'`, `'r'`, `'o'`, `'a'`, or `'k'`.
| null | null |
Medium
| null |
1,723 |
Hello friends today let's find the minimum time to finish all jobs let's see some examples in this example the drops would be 323 it means in total we have three jobs and each job would take three uh maybe hours or days and two days or three days and now we have three a person who will work on these jobs so we would like to have the minimum maximum working time so it means for each person it's total time we want the total time to be as small as possible so in that case we would just assign these three jobs to the three persons so each person would work for three days two days and three days so the maximum among this number would be three right so this three is the smallest why because if we assign these three jobs for one person it would work for three plus two plus three it would be eight days so it's larger than three so uh three would be the answer let's see another example if we have five jobs and that's the time they would take and we only have two persons so we would like to um all of the people work as uh as short as possible so if we assign the jobs to the person like this each person only needed to work for 11 days but if we assign the job one two four uh to the first person uh 780 to a second person then single person needed to work for 15 days then 15 is larger than 11 so it would not be the answer okay how to say about this uh task it has some things firstly the K the jobs lens is very small it's just less than 12. so when you see this small number like less than 16 you would I mean you would want to think about the bitmask key we used to solve problems like this before like the canvas bikes because we would have needed each beat to represent the state of each job like whether it has been done or not so if the beat equal to 1 means this job has been done if the job is zero uh I mean the corresponding bit is zero then no one has done it before okay that's why hint another hint is like this task only asks us to return the minimum time to it didn't ask us to return how we will assign these jobs so we don't need to know the details we just needed to know the time okay so how to solve this task uh let's sing now we have two persons right but what if we just have one person can we also finish these jobs we can write we just have if k equal to one the jobs would like this we will still have a minimum time it would just be the sum of this array right so when we have a new person we will uh check the we update the result based on the result we already got before so you would just think like um we will start from the person from one and then person two person three like we will still can finish these jobs but when we had more person the minimum time would be smaller right so I think that's a natural thinking okay so what if one person how can we calculate this time we will just add these jobs right um like job one job two job three so we will represent it as a beat you know it should probably be a beat like when we take it then the corresponding bit will be one so false so that's what I mean we can do something like that this would be the a person it would be uh I would start from two why um and k and a plus so uh which means this means if we have two persons then and the total number will less than K because as most of we have K persons right and then we will check we'll update the mask like start from one and mask less than uh one left uh shift right what is an would be the total number of jobs or jobs lens and then mask plus so why do I write the I equal to two persons because when we only have one person we can let that person do all the job right we just need to iterate all of these masks right so it is called initialization so it would be mask equal to um zero mask less than one less than a mask plus and um for the job it would be a zero job less than a job plus something like this we will update to the of DP uh sorry there's no DP yet so it's for this one it's for initial Edition we just uh ask the person do all the jobs so we'll see the minimum time this is when we have uh when we have more than one person what do we will do to assign the jobs so this is the basically I mean basic structure but what about the details what would the be the transition function a trending function is actually similar like we saw before it's like when we have a new person right we will assign some jobs to him or her right and uh if we consider the job assigned to this person I right I mean the ice person uh what the time he will take would be the person I he would do the job which would be a seven mask of this mask why because this mask is the first eye persons they do all the job together and their state is this mask like for example if it's one zero one it means uh including this ice person they will finish three jobs right but we want to see uh what is the job specifically did by Ice person like we consider uh it would do the one oh sorry zero one two three the third job right if I do the third job and it would take some time and the rest person would do the rest jobs what is the time they will uh they will use so this kind of like we separately consider the ice person what time uh it would take and for the rest it would just be mask minus some masquerade so this summer mask would be the job done by the ice person The Mask minus some mask would be the job done by the I uh -1 uh -1 uh -1 person okay so in that case you already can get how we will represent these things it will just circle DP okay DP you know the code DP and they would have uh b i plus 1 it would be a one left shift and it means um I mean dpij just means if we have I persons and they uh do the job at the state of J the minimum time they would use okay so in that case uh what would be returned here because we want to get a minimum time right so we will write a meme uh or actually it should be inside okay it would just be minimum equal to integer max value and there we get something and then minimum oh sorry we will update the DP I person right I and the mask would just be the minimum so what's inside he said as I mentioned we will separate this mask into two parts right so we would like to iterate enumerate order summer masks would be the subset of this mask like we consider that's the job done by the ice person so stop a mask not equal to zero and uh how to get some mask you can check the previous I mean my old video which talk about the beta manipulation so mask equal to cyber mask and then oh sorry it should be okay it should be sub Master minus one and mask okay so in that case we will just uh do the Minima equal to mass minimum it would be the maximum of two things why because this uh don't forget is the max working time of all the persons right so now we separate the mask into two parts one part would be the work done by the ice person so it would be dp1 and the submask and therefore the rest of the rest Works would be done by I minus one persons and their job would just be a mask minus sub mask okay then we get it we can return these things in the end we will return DP how many percent okay what's the state it will be I left a shift minus one okay that's the result okay but did we miss anything we didn't finish this initialization right we just do this transition how about the initialization it would be um we'll check whether this mask consider orator works for the ice job whether it works for the ice job if we just use the parenthesis if we don't know the priorities so if equal to zero which means the current state didn't do the ice job so we just continue only to do the ice drop we will get to the left work do something like this mask minus a mask so current mask with a B mask and currently we do this ice job so how about if we don't do this job with the b i oh sorry one left to shift the J okay so we can update the dp1 uh that would be mask equal to DP one left plus if we do the ice job what time we need to take it would be jobs J right okay so that's it so this is for if we only have one person all the job will be done by this person this will it means if we have more than one person so we should start from two okay let's submit it uh what's wrong okay I see uh summer masks it should be Capital likes okay thank you for watching see you next time
|
Find Minimum Time to Finish All Jobs
|
maximum-number-of-achievable-transfer-requests
|
You are given an integer array `jobs`, where `jobs[i]` is the amount of time it takes to complete the `ith` job.
There are `k` workers that you can assign jobs to. Each job should be assigned to **exactly** one worker. The **working time** of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the **maximum working time** of any worker is **minimized**.
_Return the **minimum** possible **maximum working time** of any assignment._
**Example 1:**
**Input:** jobs = \[3,2,3\], k = 3
**Output:** 3
**Explanation:** By assigning each person one job, the maximum time is 3.
**Example 2:**
**Input:** jobs = \[1,2,4,7,8\], k = 2
**Output:** 11
**Explanation:** Assign the jobs the following way:
Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11)
Worker 2: 4, 7 (working time = 4 + 7 = 11)
The maximum working time is 11.
**Constraints:**
* `1 <= k <= jobs.length <= 12`
* `1 <= jobs[i] <= 107`
|
Think brute force When is a subset of requests okay?
|
Array,Backtracking,Bit Manipulation,Enumeration
|
Hard
| null |
1,834 |
hey what's up guys uh this is juan here again so this time 1834 single thread and cpu okay so this one um so the description is a little bit long you know so you're given like n tasks labeled from n to n zero from zero to m minus one and each task has two property so the first one is the in q time second one is the processing time instead you know this task will be become available starting from this time the inquiry time and it will it takes this processing time to finish it and the single-threaded cpu works in such a the single-threaded cpu works in such a the single-threaded cpu works in such a way that you know so first you know if the cpu is idle and there are no available tasks to process the cpu remains idle okay and if the cpu is idle and there are available tasks right and the cpu will choose the one with the shortest processing time right and so basically if at the current time if there are like multiple tasks available you know the cpu would simply take the available tasks who has the uh the smallest uh processing time okay and if multi if multiple tasks has the same uh shortest processing time it will choose the task with the smallest index right so basically if there are multiple tasks who has the same processing time and then which task has a smaller index right you know in the adrenal tasks will get picked and once the task is started cpu will process the entire task without stopping okay and then see if you can finish a task and then start a new one instantly and it asks you to return the order in which the cpu will process the tasks so in exam example one here you know so for this one you know because at the beginning you know since this uh this one will definitely the task zero will get picked first because this one has the smallest uh inquiry time right basically at a current time one you know at current time one you know this current time right at current time one we have task zero to be picked right and then this one once this task 0 is finished we have what the current time will becomes 2 to 3 right because this one we have a task 0 we have t 0 got picked right and after finishing the t 0 the time will be 3 because you know in task 0 it takes 2 seconds to finish so at t at current time winds 0 you know we have we're going to have two tasks become two available which is the one and the three because you know both those two tasks have the inquiry time either equal or smaller than the current time right but among those two value available tasks like i said like what we are we just uh saw we're gonna pick the one who has the smart uh shortest as a shorter uh processing time which is the three which is the 3 2 1 right so which means that this one we're going to pick what we're going to pick a task 2 right task two and after the task two since this one takes like three seconds to finish now the current time becomes to six right so when it comes to six no this one the last one becomes available right and now this one has the shorter time comparing to this two here right because only these two are not uh executed that's why you know the next one will be what would be the uh the three one right three the t3 and then the last one since we don't have any tasks a new task that becomes available and this one becomes to 4 it becomes 10 right so the last one is like t t1 right so in the end it will be 12. the current time so yeah that's basically it's that basically it is right for this problem you know we simply just uh to emulate the process that's all we need to do but to emulate the process you know so first you know first things we have to sort these tasks because you know we want to know at the current time you know because we need to know at each new current time what are the uh the tasks becomes become so available right and if we don't sort these tasks we have to scan the tasks every time right but if we sort the tasks by the uh by the starting time by the sorry by the but the inquiry time and then we simply just need to move this cursor in one direction and we don't have to re rescan the ones we have already uh processed right so that's the first thing which means we have a storage task second one is that you know we have to find like we have to uh we have to know we within the current available tasks which one has the smallest which one has the shortest uh processing time and also the uh the index which means that you know within the current available uh tasks we need to sort when you sort by the uh by the processing time and the index so to do that you know you can use a priority queue right because priority will always give us the uh the smallest if we use this one as a key in the product queue right then we can always get the smallest one in the end right and the last thing is that you know uh there could be a case that you know uh the current time is not at the current time there's no available tasks right so for that case you know if there is no uh there's no tasks to be processed we can simply forward this current task to the next uh to the next in queue time right in the unprocessed tasks yep i think that's it right for this problem so let's get to the coding then so like i said we need to sort by the tasks right but after sorting we'll be losing the original index which is also useful later on right that's why i'm going to add that original index to the original task so we have a uh for i right in this uh we have a in queue time and the processing time right in enumerate tasks okay so i'm adding this index okay so now we have the enqueue time the processing time and the index after sorting then we do sort okay so uh let's see we're gonna define a few uh variables so the first one is current time right we start at zero and then we have an n equals uh length of the tasks then we have answer and then we have priority queue right and then we have i equals zero basically this i this one eyes represents is pointing right to the next available right tasks and then we just need to we need a while loop here so while n is smaller than n or the product q is not empty right because we uh because at the beginning the product q is empty and we as long as we still have some uh tasks that has not been processed we're gonna still do this while loop here and we yeah so first we check right so first we check if there's no task to process and current time is smaller if there is no task in the queue right and the current time and there's no and the current time right it's smaller right then the next available task right and then we just uh we forward right we move the current time forward right and i smaller than n and the current time smaller than the task iron0 right let me move the current time equals to task in2 right so be careful you know be careful uh also check uh this is not prior priority queue because you know if there is some if the priority queue still have something to process we shouldn't uh update this current time because as long as we have something to be processed you know this current time should be updated after this after the task okay and if there's nothing in the product queue which means if there's no available queue i'm sorry if there's no available tasks right and then we also need to check if the current time is smaller than the uh than the first one because you know it could be you know after processing the last task in the product queue the current time has already uh has already been updated uh so that we will have like some we have some the uh available tasks you know for example uh so after the last one got popped up got processed into the priority queue so let's say the current time so the current time becomes to let's say the current time was like eight right so after processing the last priority queue at the last task in the product queue this one becomes 2 to 12 right so now let's say the next available tasks right it's 10. right and we so and the current time is greater than 10 right it's greater than 10 it means that you know we don't have to we shouldn't update the current time because you know with the current time equals to 12 we have already find a new available at least one available task you know but if we update the current time to this task you know the current time will be updated from 12 to 10 we i mean which is wrong because you know if the next available one starting from 10 it takes like three seconds to finish right so after processing the net this one you know the current time should become to fit to 15 right but if we update this one to 10 you know this one will become to 13 which is wrong because 10 plus 3 will be 13 right that's why we need both of these two conditions to update this to forward this current time okay so and after that you know we just basically we uh we add current we are available right tax on current time be before right which means we're going to do i while i is smaller than n and the task of i zero right is equal smaller than the current time we will we push it into the prodigy right hip q dot keep push right product q so remember the keys where the key we're using here the first one is the processing time right which means that it's the uh is this one is the second element in the tasks right so it's task i one right and if this person's present time is the same we also need this index to do the sorting right which is the uh the last element in the task and then we increase i by one right so now we have the uh we have included new tasks right for the current time and then we simply just pick one right um so p processing time and index right because the heap q dot hip pop priority q i think here we don't need to check if the particle is empty or not because um because we have a while loop here you know the uh if the product queue is empty right and then we'll always uh add at least one task into the product queue so which means that you know when the code reads here there'll always be one element in the product okay and then we simply update the answer first right we update the answers your pen is going to index and then we update the current time because the processing time okay and then return the answer right so pick next task to process that's it right and yep so let me see here so we have that okay so run the code or in your time okay submit yeah i mean as you guys can see right so the time complexity obviously we have an n here right so the while loop is in and if we have a priority queue that's going to be unlogging right so the time complexity is o of unlocking and the space is often because we have the task we have the answer we have the prodigy and also actually the sorting itself the sorting here is also takes unlocking right so that's why and here is also unlocking yeah so that's it right i mean it's just like problem you have to read the description carefully you know once you figure out the process all you need to do is just find a proper data structure and then emulate the process that's it right cool i think that's it for this problem and thank you for watching this video guys stay tuned see you guys soon bye
|
Single-Threaded CPU
|
minimum-number-of-people-to-teach
|
You are given `n` tasks labeled from `0` to `n - 1` represented by a 2D integer array `tasks`, where `tasks[i] = [enqueueTimei, processingTimei]` means that the `ith` task will be available to process at `enqueueTimei` and will take `processingTimei` to finish processing.
You have a single-threaded CPU that can process **at most one** task at a time and will act in the following way:
* If the CPU is idle and there are no available tasks to process, the CPU remains idle.
* If the CPU is idle and there are available tasks, the CPU will choose the one with the **shortest processing time**. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.
* Once a task is started, the CPU will **process the entire task** without stopping.
* The CPU can finish a task then start a new one instantly.
Return _the order in which the CPU will process the tasks._
**Example 1:**
**Input:** tasks = \[\[1,2\],\[2,4\],\[3,2\],\[4,1\]\]
**Output:** \[0,2,3,1\]
**Explanation:** The events go as follows:
- At time = 1, task 0 is available to process. Available tasks = {0}.
- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.
- At time = 2, task 1 is available to process. Available tasks = {1}.
- At time = 3, task 2 is available to process. Available tasks = {1, 2}.
- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.
- At time = 4, task 3 is available to process. Available tasks = {1, 3}.
- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.
- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.
- At time = 10, the CPU finishes task 1 and becomes idle.
**Example 2:**
**Input:** tasks = \[\[7,10\],\[7,12\],\[7,5\],\[7,4\],\[7,2\]\]
**Output:** \[4,3,2,0,1\]
**Explanation****:** The events go as follows:
- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.
- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.
- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.
- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.
- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.
- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.
- At time = 40, the CPU finishes task 1 and becomes idle.
**Constraints:**
* `tasks.length == n`
* `1 <= n <= 105`
* `1 <= enqueueTimei, processingTimei <= 109`
|
You can just use brute force and find out for each language the number of users you need to teach Note that a user can appear in multiple friendships but you need to teach that user only once
|
Array,Greedy
|
Medium
| null |
1,531 |
hey everybody this is lry this is day 27 28 of the Leo day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's PR today's challenge everything in between uh today's PR is going to be 1531 strain compression so ring one length encoding R rle is a string compression that works by replacing consecutive identical characters the conation okay note that in this problem we're not adding one after single characters given an string s and integer K you need to delete at most K characters from s such that the one length en coding of s has minimum length like I've done a similar problem but more recently like and I say that in a way that just reflects to 1531 so maybe I maybe this is a different version of the problem but um there is a trickier one that I remember I failed because I thought I could binary search or something but anyway I don't think this is the problem anyway n is equal to 100 so that means we can maybe think about more uh expensive algorithms but uh yeah let's see we want to oh we don't to minimize the length okay um and K is the number of things we could delete is that it okay yeah um I mean I think the naive or maybe naive is not quite the right word for it um I think the immediate first impression is that we can probably do something indexing um indexing or our stage it's going to be the suffix and the K that is left and given that we have 100 and K so that should be good enough inferior as long as we don't do anything that expensive and then the question is what is the compressed string would be right um I think one kind of funky thing about this problem is that uh to notice anyway is that s or n is um n is less than 100 or equal to 100 but because it even if it's eal to 100 um it what I mean by that is that there're only two um two transitional States or whatever it's called uh what I mean by that is that if you kind of use the r the compression thing um it can only have either one digit or two digits right or I guess zero digit if you want to count one single character um but yeah uh so that means that you only so the only way you save um you save length is by going from say from 10 to 9 right I mean obviously you can also go from higher to nine but like going to from two digits to single digits so these are just notes for me so two digits to one digit um for the count and of course the one digit is actually only up to two or goes to nine I guess how you want to say but also from two to one right meaning if you go from AA to AA is going to be A2 to one but I guess maybe in that sense it's not it is more trivially so and then of course we go from 1 to zero so those are the cases where you actually you know get a benefit by removing K and I mean I think my initial Incarnation is because all these things are like a 100 or whatever it's going to be dynamic programming just kind of Bove Force but also honestly I do wonder if you can be greedy right like it almost feels like you can do this with greedy but I really um maybe not I think one thing to that is a little bit kind of or I mean I think greedy kind of works but I do but it might not actually because I have one case where you have like a b a and maybe in a greedy way you would and I didn't do the counting I think this is actually right you in a greedy way you might return remove B but if you remove B this actually is that still fine I don't know like you have 86 B7 or something like that or B A7 and we move one it's going to be a13 so I guess that's still fine but then now you have to redo I don't know I think maybe greedy Works h possibly I don't know how would I do it with dynamic programming anyway Let's uh I mean the thing with greedy is that it requires proof uh well proof and implementation which sometimes is not always trivial espe or in this case it doesn't feel trivial for me um and then the other one is dynamic programming also huh I feel like we have we went through the entire month without seeing a hord or at least one that I kind of spend time on so yeah nice to kind of see one yeah uh how would I do it with dynamic programming right um so okay so there are a couple of possible States uh but for example you can do what this get min or something let just get min so we're going to say index and K left um this is to represent well the number of K left that we can remove and index is of course the um the suffix that we're doing uh for this sub problem right and you know and I know that usually I kind jump into code and then I go over complexity afterwards which is a little bit not how I actually do things to be frank U because I try to do um Comax analysis before because otherwise we're just wasting time if it's going to be too slow but index goes from 0 to 100 or 0 to n um and of course K left goes from0 0 to technically it goes from0 to uh also 100 or n or whatever so yeah and of course you can also um you can also bound this right meaning that if you have um because if you could calculate the length of the suffix and then K left and then you could bound it by that in that way but that's only like a minor constant thing like maybe it's twice as fast or you know you reduce half to uh state to something like that right what I mean is that if you have five characters left and your K left is like 20 you could actually boun that by five because you can remove or2 anyway right so then it prevents you from recalculating some states but like I said that's only a constant thing so this is going to be fast enough um because basically the idea we want to do is that we just want to um or the way that I'm approaching it's going to be keep and not keep right or delete I guess is the one but of course it's going to be a little bit tricky to remember what are we what we're doing right so what I also want to do is just maybe like have a last character uh and maybe this is 0 to 26 maybe we could redu reduce this further uh or 0 to 25 down to say or you also may want to say maybe just like a to z right maybe that's a little bit cool and then the run right so run can go from I guess 0 to n as well but a lot of it a lot of them are not possible right so at a very naive way of uh calculating this is just like multiplying these all together assuming that they're independent um and of course you'll get around like you know 26 million or something because 100 square or 100 Cube * 26 but a lot of square or 100 Cube * 26 but a lot of square or 100 Cube * 26 but a lot of these states are not possible which is also one you know I think I get this question a lot about when do you use top down or you know if bottom up is always better why don't use bottom up or whatever more efficient got is um and this is actually one case where bottom up may not be as efficient because a lot of states are not possible right um for example if you're your input strain is like I that's the other one that we just kind of demonstrate this right then for example it is impossible for last to be even if you well for example last cannot be equal to Z uh and you know and one cannot be equal to like even n right like uh so and even if last is B one cannot be greater than well just one right so that those are basically like very self-c constraining um when I talk very self-c constraining um when I talk very self-c constraining um when I talk I think I talked about in the past in general when you talk about um you know things that are self- um you know things that are self- um you know things that are self- constraining and kind of self- constraining and kind of self- constraining and kind of self- pruning if you want to call it that well this would be one of them so yeah um but now that we have this set up and hopefully it should be fast enough even though technically I don't have a tight proof about it um but as we said um this if we bound K left this would um this would at least reduce this by half and I don't know a lot of these are just not possible state so I don't know how to really worry about it per se um and in this particular case actually now that I just think about it so it's not like you know I'm like uh it's not like I'm delaying and telling you it's just that I just thought about it is that because of the constraints of the problem um we never go to Triple digits so as long as you do this to 10 yeah if it goes to 10 it'll be good enough right or like so you can actually bound this by 10 right so yeah right at least that's for this particular problem because once it goes more than 10 it doesn't really matter uh at least the way that I'm going to use it maybe that it's not clear right now it we'll get to it okay so let's go over the um the base case base cases right so if index is equal to n then we're done how what is the minimum that we're returning right well uh we don't care about K left so we don't have to care about but if one is the only thing that we care about if 1 is equal to zero for some reason I don't think it's possible well I guess if we delete every character is possible then we return zero um if one is equal to one then we return one um if 1 is less than equal to 9 then we return two uh and then else we return three right because that this is like X 12 or something I don't know 12 is just a random number this is like X X2 or what X5 iot and then this is just like X right uh yeah so that's basically the idea and then now as I say you know we just do the keep delete thing so then now the Min is equal to say infinity just sent it no value nothing really meaningful but keep so what is keep mean right uh keep means that we keep the character so we don't use K so we go to the next one we don't use K and then last is going to be this character so s of index and then the run is kind of uh maybe I need to separate that out right uh but basically what is run right okay so maybe I'll just write it out so if s of index is equal to um last then this is just 1 plus one that means that you have one more character of the same one otherwise if it's different then you start at one all together so that's pretty much it I mean maybe you could write this as a oneliner I think this is slightly um more self more intuitive anyway right uh actually also oh I mixed up one thing um because we start a new thing that means you have to kind of right to the character so that actually get plus maybe cost of one right uh and here I'll just write one of course not that's why I was like I have to rename this and then here we will actually just copy and paste this part or we rewrite it in here so that here we can just return uh cost of run and that's pretty much it um yeah because this is now we're starting a new character right so we have to kind of pay for the old one first and then delete um delete maybe skip is a better word but by skipping or deleting um basically you just kind of follow through so if you and this is of course only if K left is greater than zero because you need to spend one so what does this mean right this get in you go to the next character K left minus one you use one and uh what is the input oh and then otherwise nothing changed because well you didn't change anything so then now you return Min and that's pretty much it um you start with zero K left you start at K uh last it doesn't really matter you could just do empty string and then zero or something like this right yeah um and as and there a couple things that you can do it as well as I said so like for example if K left uh is greater than what it n minus index then K left is equal to n minus index that's just the bounding function of you know cuz you can Del more than you can anyway give it a spin uh and of course I mean you know that I know this hopefully I don't know maybe you don't trust me I don't know it doesn't really matter uh but yeah but of course uh I was actually half wondering whether we'll get a k status I this may actually time out but oh I guess not because of k0 Zer um so if maybe we added another one but now it's uh I don't know eight maybe it's fast enough I actually don't know yeah maybe it is fast enough but in any case um oh I also forgot the other optimization that I set to do which is this right uh which is if 1 is greater than 10 1 is equal to 10 right um yeah so basically what I was going to say is that uh I guess I'll just put in the case I mean you know way I'm going to go this if you been watching this my channel if not that's fine too but TI is that uh this is going to take too long to run so what do we do well we should memorize because this in dynamic programming or memorization specifically uh for every in for the same inputs that you get for this problem you are going to get the same output and that means that well then why not save it down so that the next time you calculate the same input you get the same output and in this case because of some of the uh things that we do it may not even have to be a precisely same sub problem if they have the same answer right that's basically the biggest thing and so yeah that's basically it uh though this is a I'm going to I'm a little bit lazy today so we'll see if this works but I'm going to set it has cash is equal to a dictionary then cash is also you go to dictionary right or maybe just you know cash and then we could use an implicit thing of like okay if uh this tubo is in cash then we just return uh this topper basically if the input after filtering is in cash then we do it otherwise we do the calculation we save it and then we are a little bit happier yeah I don't know if this is faster than what we have oh I mean this times out so of course it's faster let's give a quick submit this may still be a little bit too slow because um this tble cach oo you did not expect that maybe I'm off by one though 10 maybe one of my optimizations a little bit huh how four did I misunderstood this is this 100 oh it is 100 sorry wow I actually for some reason I thought if it has 100 c this isal to 899 okay so I lie about some parts of this so okay so we have to at least remove this maybe we can think about I mean it's kind of such a weird thing right because this only comes up if all the characters are the same and so it almost feels like I should just special case it and this is very particular for this problem and it's just my mentor off by one actually cuz I thought that if it has 100 characters it be A99 or something but uh but this only comes up if K is equal to zero and all the strings are the same so that's kind of a really particular case because you don't want to I mean you can also um generalize this function by removing this but it just costs so much more expense in than other things that I want to just special case this right because if K and this only happens if K is 0 and S uh and or it's all the same character or something then we return four because you know um yeah oh did I oh well uh this is why basically you have no choice then yeah and you can maybe rewrite this as if K z0 you just kind of do a calculation on the r um but I don't know um oh that's the oh I was going to say that's the first time I got a mistake but apparently I have gotten other things before I this is the same idea no I mean this is basically the same but I didn't see p plus instead this time I didn't Pyon but the comlex it keeps on going up oh except with this one I did it the same way I did it with the hack actually that looks even almost the same that is actually kind of crazy but uh but yeah but this is the only case because the alternative and maybe that's what I was worried about is that it may time out is that if you kind of remove this it still works for I mean obviously you have to also update the cost function to include this thing but just you create you multip you basically increase this state by like 9.9 times or something right which is 9.9 times or something right which is 9.9 times or something right which is kind of like a crazy amount so um I don't know uh and you can see that today at least the running time is a little bit better uh maybe better we do C++ but I better uh maybe better we do C++ but I better uh maybe better we do C++ but I got it right this time yeah um so what's the complexity right I mean we kind of alluded to it though like I said most of these states are not reachable so this is going to be n * n * reachable so this is going to be n * n * reachable so this is going to be n * n * n * Alpha where Alpha is the size of the n * Alpha where Alpha is the size of the n * Alpha where Alpha is the size of the alphabet um because you only do all one operations for each of these states that is going to be your time and space complexly uh yeah that's all I have for this one that's all I have for today let me know what you think enjoy the rest of the holidays stay good stay healthy to a mental health I'll see you later and take care byebye
|
String Compression II
|
number-of-ways-to-wear-different-hats-to-each-other
|
[Run-length encoding](http://en.wikipedia.org/wiki/Run-length_encoding) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string `"aabccc "` we replace `"aa "` by `"a2 "` and replace `"ccc "` by `"c3 "`. Thus the compressed string becomes `"a2bc3 "`.
Notice that in this problem, we are not adding `'1'` after single characters.
Given a string `s` and an integer `k`. You need to delete **at most** `k` characters from `s` such that the run-length encoded version of `s` has minimum length.
Find the _minimum length of the run-length encoded version of_ `s` _after deleting at most_ `k` _characters_.
**Example 1:**
**Input:** s = "aaabcccd ", k = 2
**Output:** 4
**Explanation:** Compressing s without deleting anything will give us "a3bc3d " of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = "abcccd " which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be "a3c3 " of length 4.
**Example 2:**
**Input:** s = "aabbaa ", k = 2
**Output:** 2
**Explanation:** If we delete both 'b' characters, the resulting compressed string would be "a4 " of length 2.
**Example 3:**
**Input:** s = "aaaaaaaaaaa ", k = 0
**Output:** 3
**Explanation:** Since k is zero, we cannot delete anything. The compressed string is "a11 " of length 3.
**Constraints:**
* `1 <= s.length <= 100`
* `0 <= k <= s.length`
* `s` contains only lowercase English letters.
|
Dynamic programming + bitmask. dp(peopleMask, idHat) number of ways to wear different hats given a bitmask (people visited) and used hats from 1 to idHat-1.
|
Array,Dynamic Programming,Bit Manipulation,Bitmask
|
Hard
|
2105
|
1,528 |
Hello friends, I am Ishwar Maps, welcome to my channel Take Target, friends, today we will see 5000 successful spin problems list, first of all you read the statement, in its statement this Ghee add in tears are in distress of England that today Tejaswini is AIDS patient character. Position is smooth to in India this is in upper district so friends now let's see the example which is the given example in this I have basically given us the independence of India and put it in a string and now we will help on that index. If that letter has to be delivered, then friends, this is the approach, first of all, what will we do, we will point the length of this team, we will like and share it, now friends, what will we do, the character edits of Ek Rahein will say this, friends, this will be related to gender. The size will be set and now we will run a follow which will last only till the length of the spin. Now we have asked a question that we have to make a spirit end in which the index reaches its length like keep us more or Kodi. If you have kept the forces then this is the point above such, this is the point, we want that this is the court is indicts love, see this, now like okay above 5s means pores, that is then come on the index, similar, what will we do which Rich, they were on that index, these will fall on that, eggs of India and doctor means that NREGA size. Now friends, let me tell you the meaning of this line is that we have asked the question in SSC, understand the example that we have. This is 500, 600 and that is COD, LG TV, now we have juice, we have to take it to the fourth index, so what will we do, now that the character add that we have created has the for indic tool, so index means the first one. The character which is the first indication means that the indexes have gone, this will be the first zero on our shoulder, then ours will be like this: then ours will be like this: then ours will be like this: I, your son, on every floor, this doctor of yours, why will Ash's add key come because then recognize the C on the index and which is like this Character on it and this meaning index is 0 123 MS Word Kaif 's lips back 0 C So like this flat induction 's lips back 0 C So like this flat induction 's lips back 0 C So like this flat induction on the second floor This story of cr on me And it goes on like this And if we put it in the comment then what do we do now Our A spring is gone, now we will return it was the latest new, if we want to end it, then we will edit it and after ending it, let's see if this is our mistake, this is an incompatible allegation, so here is the character of this. That friends, let's see my solution of the example. I will love it and see that it has been accepted. Now we submit it. 200 It has been successful. Now I will show you its details on the page. So friends, all the total shades have been passed in this, relative video is AIDS, see this friends, runtime attacks have increased hundred percent, it means we are getting profitable, our solution is the best, friends, if you have any other problem, this question is here for you logic. If you haven't understood, then tell me in the comment section, I will tell you better and do something so that you can understand better, till then friends, I will meet you in my next video, that too with Astonishing. If friends, you guys. If you have any other doubt then please tell me in the comment section, I will tell you the solution as soon as possible.
|
Shuffle String
|
kids-with-the-greatest-number-of-candies
|
You are given a string `s` and an integer array `indices` of the **same length**. The string `s` will be shuffled such that the character at the `ith` position moves to `indices[i]` in the shuffled string.
Return _the shuffled string_.
**Example 1:**
**Input:** s = "codeleet ", `indices` = \[4,5,6,7,0,2,1,3\]
**Output:** "leetcode "
**Explanation:** As shown, "codeleet " becomes "leetcode " after shuffling.
**Example 2:**
**Input:** s = "abc ", `indices` = \[0,1,2\]
**Output:** "abc "
**Explanation:** After shuffling, each character remains in its position.
**Constraints:**
* `s.length == indices.length == n`
* `1 <= n <= 100`
* `s` consists of only lowercase English letters.
* `0 <= indices[i] < n`
* All values of `indices` are **unique**.
|
Use greedy approach. For each kid check if candies[i] + extraCandies ≥ maximum in Candies[i].
|
Array
|
Easy
| null |
1,585 |
uh hey everybody this is larry this is me going over q4 of the recent weekly contest 206 uh check if string is transformable with substring sort operation so this so my implementation is like 20 lines of code but i took about a long time because i actually spent like 10 to 15 minutes just like looking or well not 15 minutes i guess but like 10 minutes just like looking at the problem and like even working out on paper to kind of figure it out and you can watch me live after this uh be sure to hit the like button hit the subscribe button join me on discord if you have questions as well but the one observation that i made uh which i have to look at the tapes to see how long it took but when i made that observation i was like oh this becomes easier and i think the confusion and i would the first two dots that i had was just some sort of greedy right like okay like you know we need a three in the front can we move to three in the front well yeah we can move to three to five but then you have to sort everything in between and then you get into the weird place where um you know it'll become three four five eight right so that's wrong i was like oh maybe there's some weird thing about starting from the back and then this example two also tells you like well if you do if you try to move the five to the back 415 will be 145 so you can't sort it anymore right so greedy does not work it is not in this way uh so that's how i was stuck for a little while and the one the key observation that i made for this problem was noticing that actually you don't need to take like for any subgroup you don't need to take all four um things to transform or to sort or rotate right so what you can do is actually just do two at a time right so let's say you have this subset right um and you want the two in the beginning well you don't really need to care about all the other stuff you're just sorting it by accident and because you have unlimited number of uh transformations so you don't have to like you're not trying to minimize anything you're just trying to ask you know if it's possible right so from that um i just broke it down to okay let's just do two elements at a time right so then what does that mean that means that now i'm asking a similar but a different problem or different question every time right for greedy which is okay let's say three has to be in the front well can we be in the front uh so the same question is instead of um instead of move you know sorting four things at the same time which is very disruptive and you lose ordering in that way you just ask well three could be in the front if it is small if you could swap it with the five three maybe i could just do it this way let me write it out a little bit sorry right so the way that i did it uh or logically thought about it is that you know can so i look at these two numbers i say okay can we go in front of five the answer is yes okay let's swap them can three go in front of four the answer is yes okay let's swap them can three go in front of eight well yes so let's swap them and then now the three both matches and then you could you know delete it and then go continue again so that's the idea i did it and you could kind of if you know if you're following um this may remind you of bubble sort right so that's the idea um and once i say bubble sword then you have the idea of like okay can you bubble the next element to the front right um and yeah and that's kind of the question and then the given that question and the answer is yes if and only if the next uh let's say you're looking for three the answer is yes if three is the smallest element of all the num uh more than all the elements in front of it right so that's how i solve this problem i can highlight for crap but um but yeah so that's how i that's the observation that i use to solve this problem and after that the coding is very easy because i have like 20 lines of code not that but um basically i use a deck though you could just keep track of indexes as well because sometimes that is a little bit not performing and that's something i need to be more mindful of but i was just worried about getting it right and then now i call this array but it's kind of terrible but basically this just this contains uh for you because there's only 10 digits right um so the only 10 digits i want to know whether um what where are all the indexes for all 10 digits right so for example in this case um and we can actually print it out real quick uh i hope this works in terms of printing it out yeah so thought i did more but uh but yeah so basically you know the way three has index three because three is in the third place uh two has four uh four has index one eight has index zero and so forth right so that's kind of how i thought about this and then given the right way that uh the correct data structure the second thing to notice here is that the only ten digits right so you can actually from because there are only ten digits you can actually brute force um all the smaller digits ahead of it to see if it uh any numbers in front and what i mean by that is that okay looking at this okay let's pretend this is you know this is the solution now right so instead of looking because if you look at every digits in front of it's going to be n square and that's going to be way too slow because n is uh 10 to the fifth uh but then because they're only 10 up to 10 uh unique digits we ask a different question instead so for example at this three i ask um is there a zero in front of it is there one of in front of it is there two in front of it and so forth um all the way up to nine so they can only be ten uh ten times ten to the fifth so that's how i solve this problem and that's how i go here um at this point it goes uh if there's no normal digits of that number then you return for us it just means like for example in this case you have no digits but there's no two so you're done uh otherwise we look at all the number all the digits that are smaller than it and then we check okay if there's we only check if there's a number and if there's a number we check the first instance of that number right if the first instance of that number comes before your current position of the x that you're looking for then you return first because that means that you can you cannot go beyond that barrier uh otherwise you just keep on checking you check all those and then you pop left whenever you're done meaning that you move the index by one because you know because now you got rid of this three and then you also get rid of this three in a way right so anyway uh so yeah this is there are a couple of tricky observations to make but uh but as you know again once you notice it's like 10 lines of 15 lines of code that's how people got in like four minutes and pretty quickly but uh but it's already competitive programming e problem ready code 4c problem uh the way that i did it is in linear time uh yeah everything is linear so for each uh character uh this is an of one operation so this is our van and again this is uh this loop only does at most 10 operations so that means that uh this does roughly speaking each cell or each um each character that's about 10 operations i mean more than that really but you know on all of the order of 10 so everything is linear and the space is also linear because each uh character can only be in one place in a way so yeah so linear time linear space um cool uh that's all i have for this problem uh let me know what you think hit the like button hit the subscribe button and i'm gonna stop just during the contest next substrate oh you have to convert this to this forgotten let me see if anyone's summoned it pretty quickly let me show them of course so okay one count at a time greedy to the fifth just want to see what this works for the last case okay we first do this then we three four so we can't do greedy because we just took ready for three then that would just be wrong can we degrade it from the back not really because if you do greedy from the back and this would get one two five which is the same issue so they give you they're helpful and that they tell you that greedy is not gonna work but six point that seems hard six minutes i don't really have any idea to be honest divide and conquer in some way uh what makes it false i guess this is a pretty trivial case you need more tests people are getting it down um i think we only want to do two digits at the same pen once in this case hopefully four to one and that is in terms of implementation as well this three has to smaller than so we could do a 10 operation that's fine okay this that challenge used to be cues something that matters with so this number can get to the front if the numbers before there's no way yep that was hard one hey everybody uh yeah thanks for watching thanks for you know supporting uh hit the like button hit the subscribe button join me on discord and yeah and check out me solving the rest of the contest somewhere in the link below bye-bye
|
Check If String Is Transformable With Substring Sort Operations
|
the-kth-factor-of-n
|
Given two strings `s` and `t`, transform string `s` into string `t` using the following operation any number of times:
* Choose a **non-empty** substring in `s` and sort it in place so the characters are in **ascending order**.
* For example, applying the operation on the underlined substring in `"14234 "` results in `"12344 "`.
Return `true` if _it is possible to transform `s` into `t`_. Otherwise, return `false`.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** s = "84532 ", t = "34852 "
**Output:** true
**Explanation:** You can transform s into t using the following sort operations:
"84532 " (from index 2 to 3) -> "84352 "
"84352 " (from index 0 to 2) -> "34852 "
**Example 2:**
**Input:** s = "34521 ", t = "23415 "
**Output:** true
**Explanation:** You can transform s into t using the following sort operations:
"34521 " -> "23451 "
"23451 " -> "23415 "
**Example 3:**
**Input:** s = "12345 ", t = "12435 "
**Output:** false
**Constraints:**
* `s.length == t.length`
* `1 <= s.length <= 105`
* `s` and `t` consist of only digits.
|
The factors of n will be always in the range [1, n]. Keep a list of all factors sorted. Loop i from 1 to n and add i if n % i == 0. Return the kth factor if it exist in this list.
|
Math
|
Medium
| null |
389 |
all right this lead code question is called find the difference it says given two strings s and T which consists of only lowercase letters string T is generated by randomly shuffling string s and then adding one more letter at a random position find the letter that was added in T so the example they give us the first string is ABCD and the second string is ABCDE and the output is e because E is the string that was added to the first string all right the way we can solve this problem is by looping over the first string and adding the frequencies of each character to a map it looks something like this we'll have a map and right now the map is empty because we haven't added any characters to it what we're gonna do is we're going to loop over every character in the string so you start with the letter A is that in the map no it's not so you add it with the frequency of 1 because we've only seen it one time so far you move on to the next letter is this in the net no it's not so we add it with the frequency of 1 since it's the first time we're seeing it then you move on to the last character have we seen this in the map before yes we have we've seen it with a frequency of 1 so what we're going to do is we're going to increase that frequency by one more indicating that we've seen it now 2 times so now when we're given a character that we want to find the difference for let's say a be a we're gonna view the map up here as a kind of a bucket that we're able to take letters from you can loop over every letter in the second string and see if there are any of those letters available in the map that we can use it'll look something like this we'll look at the letter A are there any aids available in the map yes there are so what we're gonna do is since we're gonna use it will decrease it one then you move on to the next one are there any bees available in the map yes there are there is one so we're gonna use that change that to zero now we get to the second B or are there any bees available in the map no there aren't there are zero B is available so now we know that B is the letter that's different all right so let's get to the code what lead code has given us is a function called find the difference which accepts two parameters s and T s is one string T is the string that might have one more character than the string s all right so remember the first thing we have to do is we have to create a map in this case we'll just use a simple object so let frequencies equal a simple object you'll have that like here frequencies and let's pretend that the string is a be a so now what we have to do is we have to loop over every character in that string so for the character of s now we're going to check if that character is in the frequencies map so we'll say if frequencies character is undefined so if we have not seen it before what do we have to add it to the map so frequencies character equals 1 we're adding it with the frequency of what that will look like this a 1 and since we're done with that loop we go on to the next character which is the character B we'll check on line 10 if we've seen it before and we have not so according to line 11 we have to add it to the frequencies map with a frequency of 1 then we go on to the next character the character a we check again have we seen it before yes we have so now we have to add an else statement so since we have seen it before what we need to do is we just have to increment its frequency in the map by one that'll look like this all right so now we're completely done with that for loop because we've looked over every character in that string so now what we have to do this we have to loop over every character in the second string to see if there's a difference the second string let's say is a BBA so again we'll say for let character of T now we're going to check is this in the frequency map so we'll say if frequencies character doesn't equal undefined so this first check is seeing if it's there at all if it's not there at all what do we have to do we'll just return that character because the first time we're seeing it and that would be the difference but if it's not undefined so we have seen it we also have to see if we're able to decrement it from the frequency map so we'll say if it's in the frequency map and the frequency is greater than zero so frequencies of this character is greater than zero then we're able to decrease it by one from the map all right so how would that work with our current string Appa we will start with the letter A we'll check if it's in the frequency map yes it is and I just realized that I need to add the letter I here and as the frequency greater than zero yes it is so what we're gonna do is decrement that from the number two to the number one next character is the character B we check if that's in the frequency map yes it is so then we decrement that by one next character is the character B again we check if it's in the frequency map yes it is but it's the frequency greater than zero no it's not it is zero so we don't have any to remove so now we know that this letter B is the difference so what will happen is that it will go into line 21 and it will return this character the character B but let's say all of the characters were the same that means we will have looped over both of the strings and determined there's no difference all we'd have to do is return negative one all right let's run the code see how we did missed another letter I looks good submit all right so our solution was faster than about 99% of other JavaScript than about 99% of other JavaScript than about 99% of other JavaScript submissions as usual the code and written explanation are linked down below if you liked the video please like it and subscribe to the channel it helps out a lot see you next time
|
Find the Difference
|
find-the-difference
|
You are given two strings `s` and `t`.
String `t` is generated by random shuffling string `s` and then add one more letter at a random position.
Return the letter that was added to `t`.
**Example 1:**
**Input:** s = "abcd ", t = "abcde "
**Output:** "e "
**Explanation:** 'e' is the letter that was added.
**Example 2:**
**Input:** s = " ", t = "y "
**Output:** "y "
**Constraints:**
* `0 <= s.length <= 1000`
* `t.length == s.length + 1`
* `s` and `t` consist of lowercase English letters.
| null |
Hash Table,String,Bit Manipulation,Sorting
|
Easy
|
136
|
321 |
hello that's to this question create maximum number caused me much pain but there was a prerequisite question that i recommend you would do before this and that's the previous video that i made so what is this question you're given two arrays num1 num2 with links m and n respectively and also integer k and you want to create a maximum number from digits from these arrays such that the relative order of the digits from the same array is preserved so it's very similar to the previous question where we try to find the less ecographically least number from a sequence of numbers but in this case we want the lexicographically greatest subsequence not of one array but of two it kind of merged together so how do we do this well we could try find using the same method as the previous question the lexicographically greatest subsequences of both these arrays individually and then merge them somehow so that they the result is the maximum pseudographically as well but the problem is i don't know how many numbers i should take from the first array and how many numbers i should take from the second array so that the total number of numbers in the final merged array totals up to k well i could just try every possible case if k is five then we could try getting one element from numbers one and four elements from minus two or we could try getting two elements from numbers one or and three elements from mums two so those are all the possible combinations you can go through each of these and then find the lexicographically greatest subsequence involving two elements from nums one and lexicographically create a subsequence of length three from numbers two merge them together so that the result is also lexicographically greatest and then compare that with the rest of these to find the answer okay so let's give that a go i've already made this one because we've kind of already done that in the previous video the only difference between this one in the previous video is the one in the previous video was trying to find the lexicographically least subsequence this is trying to find a secure graphically max subsequence and the only difference is i had to switch the sign here so only replace the latest element if the current element is greater than the latest so let's just create a for loop listen on eagle decay plus i that's how many i elements i want from the first array and the number of elements i want from second would be j equal to k minus i then i could get a vector called max1 which is the lexicographically greatest subsequence from numbs one involving only i items so i can call this function maxlex nums1 i and also another create another array for number two and then grab only j elements from that and i want to now merge them so that the result is lexicographically the greatest so take this two arrays for example if this is max1 and this is max 2 and i want to merge these so that the result the merge result is lexicographically greatest well what i would do is i would first of all grab the 2 because that's greater than 1. if i start with the 1 that's definitely the secret graphically smaller so i'm going to get the two and now i have a pointer here and a pointer here now which one should i merge this one and the one are equal to each other well the next item i should push to the merge result would be if i compare this sub sequence and this subsequence which one is lexicographically greater what would be the bottom subsequence here because the third element in both these subsequences is zero and one respectively so the one beats the zero here the one here is greater than the zero here so that's why i push a one here and i move the pointer to be here and then i repeat that so now i'm comparing these two subsequences which one is greater well the bottom one again so i push a one onto the merge result again and i move the bottom pointer up here then i compare these subsequences again and which one is greater the top one because the second element from both arrays is one and zero respectively this one being greater than this zero so that's why i push a one here and i move this here so and i keep repeating that until both arrays are completely merged so i need a function that takes in two arrays max1 and max2 and also two indexes a and b which would tell me whether the subarray starting from a to the end of the first array is greater than the sub array from b to the end of the second array or not to do that i would just have to go through and first time i see that the corresponding items are different from each other i can i know immediately whether one is greater than the other if they're the same just can keep going also have to take care of the if they're different lengths so if you have one zero and this is one zero which one is let's see who graphically greater well i would give the benefit of the doubt to the longest subsequence even though the bottom one is the prefix of the top one okay so let's make a function that can do that let's call it greater so whether okay so this function would tell me whether num is one the sub array at numbers one is greater than the sub array at numbers two where the sub rays start at a and b respectively so i just need a while loop so while a is less than numbers one dot size or nums or b is less than num2.size keep looping or b is less than num2.size keep looping or b is less than num2.size keep looping now if a is greater than equal to num1.size a is greater than equal to num1.size a is greater than equal to num1.size that means b is less definitely less than number two those size otherwise this well it would have ended that means the size of the subarray at number two is greater than the size of the subarray at nums one so i can return false meaning that the sub array at numbers one is not lexicographically greater than the summary of numbers two else if b is greater than equal to nums two.size return true so the sub array at numbers one is greater than sub array at nums two else if at this point i will know that a and b is less than numbers one that size and number in studio sizes respectively so they're within bounds so i can check numbers one a is less than number two b that's true then i want to turn false else if nums one at a is greater than number two at b return true else i want to increment a and also increment b if both arrays are identical and have the same length then i'll get to this point here and it doesn't matter whether i turn true or false here so i just return true okay now we want to merge the two arrays so let's create a vector and chord merged and then go through the logic is actually quite similar to this so i'm just going to copy this while boop have a equal to zero have b equal to zero if k is greater than equal to number one the size but this case i want to use max onenote size and max 2.size so let's just change these names 2.size so let's just change these names 2.size so let's just change these names if a is beyond the end of the array then i just want to push back to the merge results the item at max2 and also this means i increment the point the index for the second for max 2. same for here a plus if max one at a is less than max 2 at b then i want to push back max 2 at b plus here i'm going to merge the pushback max 1 at a plus in the case where they're equal that's what i made this function for so if greater if the if max1 is greater than max 2 at indexes a and b then undo merge dot pushback max1 at a plus else merge.pushback merge.pushback merge.pushback max 2 at b plus now that they've merged together i want to check whether this is the best answer so far so i could have an answer vector answer and then say if merged is greater than the answer is equal to merged and at the end return the answer oh uh this should be this function should be returning a boolean and i also have to check whether i and j is the number of elements i should grab from numbers 1 and the numbers of elements i should graph from mums 2 are actually less than or equal to the size of numbers one and the size of numbers two so if i is greater than numbers one not size or j is greater than numbers two dot size then continue so skip that case cool uh let's give that a run it has caused me a lot of pain thanks for watching like and subscribe keep eating the code and i'll see you in the next video
|
Create Maximum Number
|
create-maximum-number
|
You are given two integer arrays `nums1` and `nums2` of lengths `m` and `n` respectively. `nums1` and `nums2` represent the digits of two numbers. You are also given an integer `k`.
Create the maximum number of length `k <= m + n` from digits of the two numbers. The relative order of the digits from the same array must be preserved.
Return an array of the `k` digits representing the answer.
**Example 1:**
**Input:** nums1 = \[3,4,6,5\], nums2 = \[9,1,2,5,8,3\], k = 5
**Output:** \[9,8,6,5,3\]
**Example 2:**
**Input:** nums1 = \[6,7\], nums2 = \[6,0,4\], k = 5
**Output:** \[6,7,6,0,4\]
**Example 3:**
**Input:** nums1 = \[3,9\], nums2 = \[8,9\], k = 3
**Output:** \[9,8,9\]
**Constraints:**
* `m == nums1.length`
* `n == nums2.length`
* `1 <= m, n <= 500`
* `0 <= nums1[i], nums2[i] <= 9`
* `1 <= k <= m + n`
| null |
Stack,Greedy,Monotonic Stack
|
Hard
|
402,670
|
1,345 |
Hello everyone, welcome to my channel, I think it is not difficult, it will become very easy, ok, quite easy, it will be solved, I am just letting you understand, when I will explain the question, then at that very moment you will understand more than half of the 1345 questions in liquid. The name is Jump Game, initially you are standing here, okay, initially you are standing here, index number is at zero, okay, now it says that you can jump, from any current index, let's take the current index mother Now by the way- Now you can go to any place from this index Now by the way- Now you can go to any place from this index Now by the way- Now you can go to any place from this index zero. Now you can go to any place from where the value is, like where the value of 10 is visible on this index zero. Look, it is visible here, so you can jump directly from here, so there are three places. You can go to one, this is done, second, this is done, third, you can go to an app that has an index where whatever is indexed will be equal. Hey, off current index, okay, so you can go to these three places. If written in short words, If you are standing on I then you can go to I plus van, I can go to min S van and how is it that in how many minimum jumps is it ok, in how many steps will you reach the minimum, then it is ok on 7th so you can go from zero to your Started is fine, meaning you are at zero in the beginning. It is fine to reach in minimum steps. In the loss index, the first thing that comes to mind is BFS is used for shortest minimum steps, shortest path. In all these, BF is there, so brother, this is what I am in the beginning. It was clear that I have to do the BFS tree. It is okay in this question, so how will I solve it with BF, I will just see this, I will do a small dry end myself, friend, the story will also be made for you and now Pretty Sir, you can code yourself. Okay, so let's see how BFSC will solve it. Okay, so let's see from BF. Before that, let me see how its output was three. Okay, let's see that, so I am at zero in the beginning. Okay. So where can I go from zero? One, I can go to the left side but here I cannot go because the auto will stop on the left. If I can go to the right then I can go here. Okay, I can go here and where can I go? And I can go to the place where the value is 10. If we look here, it is 10, then I can go here also, I can go to these two places, okay and after that, it is okay and you mother take 10. But it's okay, now look you are on the zero index, where can you go with this, you can go in the van and I am storing the induction, look where you can go with four, you can go with three and with four, where else can you go. Where this value will be 10, then if you go back here to zero, then we will mark its value at 10 zero so that I do not go there again. Okay, so this was the answer of 3 steps. Okay, so friend, an example. Let's take it and see how to solve it. To understand this, see, I will not tell directly what I will take. Step by step, let us understand why I have taken the data based on which I have taken. First of all, BF, I told you, brother. You will have to take it with your eyes closed, okay why do you have to weigh it and remember it was said in the question that you are starting from zero, now you are standing at zero and from this you can go left and right from zero, only the index. But if you can go from here to 5 + 1 index. But if you can go from here to 5 + 1 index. But if you can go from here to 5 + 1 and from here to I - 1, and from here to I - 1, and from here to I - 1, but one more thing was said that you can go from there to there whose value is now its index, you will have to make noise somewhere, not again and again. Now you will delete it and see where it is in whose send text, what is the best way to store it in the map, brother, where are these values, where are they in whose index, then what will I do? I will take a map, okay, so let's just take a map, here the name is OK & P, so this is here the name is OK & P, so this is here the name is OK & P, so this is my map, okay, zero, van, week, how did its answer three come here, I remember when we came here on this train. Will we go back by this train, because we are here by this train, so what should I do with the name of guest, we will keep it so that I can go back there, okay, so I have kept one with the name of guest, okay, how many in total, 12345 Let's do it. Now look, pay attention here. Let's start now. I have given it in the question. Did you start from zero? Okay, I have put zero in the index. Okay, why what am I putting? I am putting the index because. You can go left or right, okay, so I simply mark it as visited, okay, so I mark it true, okay, is this zero, I have put it, okay, now it is the same that will pop it, how many elements are there currently? There is currently one element at the current level, zero, okay, so I will pop it. Is zero the last index? No, it is not the last index, it means it is still time, we have not reached yet, okay, the steps will be my answer to whom it will be my turn. So far, I have not covered the steps. There will be zero in the beginning, so I did zero here because I was here, so what was in the question. From zero, you can go right, you can go left. Okay, so this is my current index. What I did Bob is ok, it is ok i.e. current minus van but it will become ok, it is ok i.e. current minus van but it will become ok, it is ok i.e. current minus van but it will become negative so it is out of bond so it will not go here, you can go right, current is not plus because see the value is false, very good ok and one And what was the thing, you can go left, you can go right, and where can you go, where in the current index, which values are 7, where are 7, and where are seven, and index, which values are 7, where are 7, and where are seven, and index, which values are 7, where are 7, and where are seven, and van, four, five, six. Okay, so okay, van, so I had visited here, true here, I marked van because I had put it in K, where else can I go There is 456 here, so okay, which is the first element? Let's see that left means 1 - 1 0, right means see that left means 1 - 1 0, right means see that left means 1 - 1 0, right means one plus one, you are zero, it is ok, so we will not go to that, let's leave this one, you are not visiting, so I will put you here for the next level and you I have marked it as wasted here, okay, it is cleared till now and see where it can go, it is a very important thing to pay attention, the current can go left and right and where else it can go, what is the value of the current index, it is 7. So wherever you can go, okay, you can go there is zero, there is van, here there is 7, and where is here, but notice, I had put you in the beginning itself as 1456, sorry, delete me from the map at that very moment. Should have been given, okay, then one more thing, I will keep in mind that I will delete the entry from you so that you do not put duplicate entry later. Okay, so come on, this thing came to my mind, so now I was on the current index van, not the current index. I was on the van and I saw to the left that it was zero but I saw to the right that it was Tu, which was not wasted, so I put it in K. Okay, so let's go, okay, of the van, so we shorted out, so the van. Let's remove what is the next element in the current level. If it is four then four is removed. Four is fine at the index and from four we can go left and I can put it in the left side. Three is fine for the next level and where else can I go and where. But there are 560 more vans, why would you put them again brother because you have already put them all five six zero vans and remember I had deleted them from the map, it is necessary to delete them, now what was the current level of five? I popped it, see where you can go with this 500, you can go left i.e. four, you i.e. four, you i.e. four, you can go right i.e. six, but look, can go right i.e. six, but look, can go right i.e. six, but look, both four and six are the best. 7 and I am in you, we have removed the seven. There will be no entry corresponding to five, so five, our process is done, okay, so let's go, okay, so now we proceed further in the neck, if the current is level, then I popped six from here and wrote six here, okay in the current, so now. Pay attention to one thing, here comes Mr. My step was till now and current is my sex and six is D last index means sex and six is D last index means sex and six is D last index means we have already reached our last index, so whatever will be the value of my steps, that will be my answer one. It will take only a few steps for me to reach the last place here, it is okay, I will reach the last place in just one step, so that is why I showed you this example, because in this you must have understood that why did the seven have to be deleted, it is deleted, right? Don't have to enter duplicate, so let's reduce one. It's 772177. Okay, so remember, I can start with zero. Let's remove it and go to the right side. Right side is okay, so I can go to the index number van. Okay, where can I say from zero, wherever there is seven, I can go here, okay, here, I can go here, okay, so the van is fine, it is widgetized, put the van here, where else can I go? I am on the fourth index, on the fifth index, on the six index, so you are looking at six sentences, meaning this is the last level, this is the last index, I have reached it in just one step, so this will be my answer, turn steps, which is sexy wali kya hai van, isn't it right? Have you understood, it is a simple BF, nothing fancy BF, this code is also exactly the same as the traditional BF, which is the method, we will write it exactly the same, okay, so let's write a simple BF, let's solve it, then you have seen that it is also simple. No, why is it hard, it is okay, I can say medium, but you just had to figure out that you have to write BF, for this you will understand the rest on your own and I told this example so that you understand that this is critical. The part was why I had to delete the entry from you so that I do not make duplicate entries. It's okay in my case, so let's do it, so let's start the support. You must have understood the question. The question is also good, okay, many people asked. So how will we start this question? First of all, let's find N and we have to reach the last index. So which one will be the last one? Remember, N will be - 1. It will reach in this, we have to will be - 1. It will reach in this, we have to will be - 1. It will reach in this, we have to reach in minimum steps. Okay, and what did I say? That I will take a map in which there will be numbers and in which indexes the numbers are present and I will store them in a vector, so I took this, okay, now I have to keep the vector of not forgotten, not visited, whose size will be N and now All the mistakes will happen in the beginning or this should also be clear. Okay, now I have made you public. Foreign Tig = 0 I < Tig = 0 I < Tig = 0 I < Okay, so what is this actually? Number Vs Index 1 and 7. Okay, the family way is done. So visited of zero is equal to true, I have not done any fancy thing till now and will not do any fancy thing in future also, it is a complete copy of BF, it is fine, the question just twists, the remaining question was hard level to understand. The mark is there, let's take the size, okay, where can I go, I can go left, current minus van and I can go right, that is, current plus van, till now I have not done anything new, before that, check one thing that brother, if Current becomes equal to my last index, so it means we have taken our destination steps. Okay, now when can we enter left and right. First of all, out of bond, look at that. Left and equal should be zero and should not be widgetized off left which If there is any thing, then I mark it as widget, okay, we can go right, left, right and wherever its value is present, so that we can see it in the map in the index, I had just done ID x MP of current number in the map. Is it the current index? Where was this number present but when will it be entered when he is not visiting? I have already learned this for loop, this level will end and what I had said that I will also do MP race. Is the current number correct or not? I have entered the current number. Removed from the map because wherever this current number is present, I have put its index. I ask you to remove it, why would you put it again, it is in the future, that is why I removed it and as soon as this level is written for the look, this one level is my complete. If he does it, then it will end, then I will plus the level or make it plus or tell me the steps, I will make it plus, and if there is any current in between, then I will return the answer from here, this is my steps as per And I have never been able to reach there, so how will I be in the end? No, okay, so I hope you understood. Look, you are visiting any element only once, so it is time for you to visit any element by driving. You can also verify that you will be visiting every element only once and the time complexity of this question is linear.
|
Jump Game IV
|
perform-string-shifts
|
Given an array of integers `arr`, you are initially positioned at the first index of the array.
In one step you can jump from index `i` to index:
* `i + 1` where: `i + 1 < arr.length`.
* `i - 1` where: `i - 1 >= 0`.
* `j` where: `arr[i] == arr[j]` and `i != j`.
Return _the minimum number of steps_ to reach the **last index** of the array.
Notice that you can not jump outside of the array at any time.
**Example 1:**
**Input:** arr = \[100,-23,-23,404,100,23,23,23,3,404\]
**Output:** 3
**Explanation:** You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array.
**Example 2:**
**Input:** arr = \[7\]
**Output:** 0
**Explanation:** Start index is the last index. You do not need to jump.
**Example 3:**
**Input:** arr = \[7,6,9,6,9,6,9,7\]
**Output:** 1
**Explanation:** You can jump directly from index 0 to index 7 which is last index of the array.
**Constraints:**
* `1 <= arr.length <= 5 * 104`
* `-108 <= arr[i] <= 108`
|
Intuitively performing all shift operations is acceptable due to the constraints. You may notice that left shift cancels the right shift, so count the total left shift times (may be negative if the final result is right shift), and perform it once.
|
Array,Math,String
|
Easy
| null |
1,759 |
and welcome back today we have 1759 count number of homogeneous substrings we were given a string and we are to count the total number of substrings which are contiguous and every character in that substring are the same so we're given three examples and I thought we could go in reverse order where let's say we have a scenario where every character of that particular substring is the same how do we count the total number of substrings actually we can just go from left to right and for each position or each index we can just add its size to the total and that will give us the total number of substrings that are homogeneous so here we can see that first we have one Z once we're at the next position we have two Z's then three then four then five and if we sum up 5 + 4 + three + 2 all the way until up 5 + 4 + three + 2 all the way until up 5 + 4 + three + 2 all the way until one the total gives us 15 and that is as expected now what if the characters are not homogeneous well every character by itself is homogeneous so we add its size one and once we get to the next character it by itself is homogeneous so we just add its size one 1 + we just add its size one 1 + we just add its size one 1 + 1 and here we get two finally what should we do when we have various characters uh that are both homogeneous and not homogeneous we can actually employ um or combine the logic we used in both of these where all the characters are homogeneous and here uh where the characters are not homogeneous all we did differently here was reset the start of our current range to the character that is homogeneous which of course is where we are currently um so let's do a run of this example here we say that a is the start let's say we have a left in the right range uh we start here and this is also where we are currently iterating this range is homogeneous so let's add one let's move along R to the next position and this range is not homogeneous but that's okay let's do what we did here and move this start to such that this range is once again homogeneous and then let's add its size one continue on to the next iteration um we're now at index two where this current range isogenous we can add its size like we did here which is two uh to our total so let's see one let's do it this way we'll add two Move Along R once we're here this range is no longer homogeneous and that's okay let's do what we did here and reset the start of this current range to be where we are currently and then add this size uh to our total next iteration uh this range is homogenous so that's easy let's add its size two here once again homogeneous add its size of three 1 two three and once we're here at a no longer homogeneous same thing we did here we reset the start to be where we are currently and add the current size of one finally we're on the last character and this range is homogeneous so let's add its size of two to our total and this gives us 13 and that is indeed as expected did so let's try this en code okay so what did we do we had some variable to track the total let's call that total and we also had pointers so L was the start uh we can start that at zero we also iterated through every chart in this string so that'll be the right end of our current range for R in range of length of s now before we do anything we want to make sure that we're adding the size of a homogeneous substring so the first thing we need to do is if the size or if the string at our current end does not match the character at the beginning of this range then all we have to do is reset the start to be where we are currently and um keep in mind that the character although it doesn't match the start of the range it on its own uh does qualify as a homogeneous substring of size one so uh let's make sure to account for that so let's say total Plus one now otherwise uh it means that our current range is indeed homogeneous so we don't need to reset it and instead we can add the current size directly so the current size will be where we are currently minus where we started plus one for zero indexing and we'll add that to the total once we reach the end of the string we should have tab ated all the counts and we can just return total so let's try that and let's submit and right so it does say also that the answer may be too large and we must return the module of it so let's make sure to do that return total modulo uh 10 to the^ 9 + 7 let's try modulo uh 10 to the^ 9 + 7 let's try modulo uh 10 to the^ 9 + 7 let's try that again and there you have it this was 1759 count number of homogeneous substrings where the key concept is whenever the strings aren't matching all we do is reset the star to our current position whenever the strings are matching we continuously add the current matching string size and combine those two items together we have a very simple strategy of finding the total number of homogeneous substrings in a given string thanks so much and happy coding see you next time
|
Count Number of Homogenous Substrings
|
find-the-missing-ids
|
Given a string `s`, return _the number of **homogenous** substrings of_ `s`_._ Since the answer may be too large, return it **modulo** `109 + 7`.
A string is **homogenous** if all the characters of the string are the same.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** s = "abbcccaa "
**Output:** 13
**Explanation:** The homogenous substrings are listed as below:
"a " appears 3 times.
"aa " appears 1 time.
"b " appears 2 times.
"bb " appears 1 time.
"c " appears 3 times.
"cc " appears 2 times.
"ccc " appears 1 time.
3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.
**Example 2:**
**Input:** s = "xy "
**Output:** 2
**Explanation:** The homogenous substrings are "x " and "y ".
**Example 3:**
**Input:** s = "zzzzz "
**Output:** 15
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of lowercase letters.
| null |
Database
|
Medium
|
1357,1420,1467
|
165 |
Loot Hello Viewers Welcome Back To My Channel Suggestion Or Green Day Ka Shraddha Problem But Before Going Forward From Not Like Video Please Like And Subscribe My Channel Health Bell Icon In The Morning You Get Notified When My Post New Video Song Without Any Positive Let's Get Started Problem This computer version numbers very easy problem satire 120 number friend you compare bank point so from January this year Related Words Into View Twitter - compare bank point so from January this year Related Words Into View Twitter - compare bank point so from January this year Related Words Into View Twitter - 151 - greater than 120 vitamin the inquiry 151 - greater than 120 vitamin the inquiry 151 - greater than 120 vitamin the inquiry total to traveler cold you find anderson condition 100 version number consist of one or more Revisions join by dot to aisi disawar number 16 se dis 2.5 16 se dis 2.5 16 se dis 2.5 23-year-old singh is that 2.5 point t it 23-year-old singh is that 2.5 point t it 23-year-old singh is that 2.5 point t it version number on phone number that nda partners 205 with wind water avens revisions improve revision ideas join but e will consist of digits and contain leading You For Example He Are Tubelight 2.00 Panch Something Like This Is Ke Something Like This 2.00 Panch Something Like This Is Ke Something Like This 2.00 Panch Something Like This Is Ke Something Like This Sunidhi And Arsan Looting And You Will Not Wanted 110 021 5.3 Looting And You Will Not Wanted 110 021 5.3 Looting And You Will Not Wanted 110 021 5.3 For Those Souls Will Be 2.5 Country Only Will Not For Those Souls Will Be 2.5 Country Only Will Not For Those Souls Will Be 2.5 Country Only Will Not Including Roads Will Not Consider Him Right To Agri Vision Continues At Least One Character Revisions Are You From Left To Right With A Left Wing Extremism And For Example 2.5 Than Zara Number For Example 2.5 Than Zara Number To Right Order Will Start From Travel E Key And Visions And Computer Using And Intrinsic Value Ignoring Anneling 0524 Comparing These Things Value Will Not Willing to Give This and You Will Not Be Leading Producer 210 Means That Revision One End 30 R15 Version Number Note Specified Revision Attend Accident Dravya 2.5 Inch and 2.5 Inch Seervi 0.005 0.005 0.005 1.00 Version 1.00 Version 1.00 Version 1.0 1.1 I Ashok Meghwal Sufism Problem 2012 or Twitter - One End Greater than 2012 or Twitter - One End Greater than 2012 or Twitter - One End Greater than 500 600 problem do the video and see the thing you can spread cheer problem what you can do it okay so leti na suddi sangrampur hai ko one latest one middle version enters into five minutes to check weather varicocele and version 1.2 and this version 1012 Will Return - version 1.2 and this version 1012 Will Return - version 1.2 and this version 1012 Will Return - In Effect This Great Will Return One And Requests And Will Continue To Lead That In This Great Too To AFine Will Sleep 20110 Went To See This Year Deposit 5.30 Points 5.30 Points 5.30 Points 0 0share 0tweet Note Specify These Pictures To Tight Fennel Effect Comparing From Left With Computer From Left To Right Subscribe System We Have Two Kids For This Point To That Is The First President Of Wave 2K Is So Team What Will Be Division It Well Before The Daughter Birthday Response Dot Com Is So That So Electric the day after tomorrow relative 55 to point to that dot 2001 something like share and vision of 223 and disorder episode 234 dot 5 to 012 100 seats will be festivals in this will be for doing so will take in testing the number to here this number will be The Number 420 406 323 IAS - 4A Torch Light And Such Individual Key Don't Forget And Subscribe With Selective Justice 2.5 Z2 Force Will Find Out The Number 420 In 2012 Without That Let You Want To Take A Better Understand Now Behave Like To Point 5 To 6 To Point 37.3 37.3 37.3 689 Will Start From Love You Will Find The Number To Two To E Will Continue With A View To See This Year Will Not Follow Back Preparation Total Behavior Will Not Control All The Best Actress Sophia School Will Continue And Will Find Out The Little Didn't Give Me 5a Do0 - Do0 - Do0 - Number-57 Number-57 Number-57 Test Extra 895 Grade 10:30 895 Grade 10:30 895 Grade 10:30 7Pay Like This To This Number Invariably Se In This Number Demise 16 To 16 - Read And Does In This Number Demise 16 To 16 - Read And Does In This Number Demise 16 To 16 - Read And Does Mean Version Was Written Words Into Some Will Return Gift 51L A Person Who Is Open Today Approach Without This Synovial Fluid May Not Be A Five-Year Comment Try to Write Code for Yourself What They Are A Five-Year Comment Try to Write Code for Yourself What They Are A Five-Year Comment Try to Write Code for Yourself What They Are Doing Traversing That Friend and Every Time You Will Find in This Region It Until This Day Comes Before finding number which be in this VPN so and accordingly vihar checking gift in this letter and to the return - and to the return - and to the return - 151 elective division ingredients of date will be given any requests for the twist pointing to the activation of flash light that aapke leti to court kaun C Very Simple Code Explanation Function Compare Weight India Ne 126 Regulation Maninder Singh And Chintu 's Tintu Business When For Traveling So Is 's Tintu Business When For Traveling So Is 's Tintu Business When For Traveling So Is Visible Save This Point 5.33 That I Love Point 5.33 That I Love Point 5.33 That I Love You To Point 5.36 So I Will Start From This I Will 5.36 So I Will Start From This I Will 5.36 So I Will Start From This I Will Start From Zero Index For Just Once in these to will start to give equal will find the number in one and to wittu into force him som verses taking and vr finding number 194 312 plus the number is the number to forms like and subscribe to vivo v11 pro handed over Sun 10 1445 Naitya Technique Example To Understand 225 Point 60 33.5 Point Se Z F How To Worship Into Issues Will Start From 33.5 Point Se Z F How To Worship Into Issues Will Start From Unwanted On 08 2013 Rich And 200 Plus This To-Do Will Get By To Enter Bhi Time In Any Disease Mourning Day 22122 And Xavier Saul will calculate for 1000 is father will find and does not hear will be * Jineshwar values 20 * 10 plus be * Jineshwar values 20 * 10 plus be * Jineshwar values 20 * 10 plus three minor bug to entry 200 oil should not be forwarded that demonetization want to * 20 plus 5 - ₹ that demonetization want to * 20 plus 5 - ₹ that demonetization want to * 20 plus 5 - ₹ plus numeric value 500 Companies And They Will Talk To U Hain So In This Country Also You Code And Similarly They Will Get Into Gains Compare Effect Vanished And To Retail - 151 - Greater * Will Vanished And To Retail - 151 - Greater * Will Vanished And To Retail - 151 - Greater * Will Return And White You Might Give Winners Of Others Like This's Record See Love You Doing Because Right Now Arrive In B.Sc Arrive In B.Sc Arrive In B.Sc B.Com Honors And In Different Ways Fried Above B.Com Honors And In Different Ways Fried Above B.Com Honors And In Different Ways Fried Above One So Will Be I Point Amused To Give To Me On The Next Visit To The Red Digit Rights Yorkers And You Will Gain And When They Can Find Hidden Truth Will Come In 125 Northwest Will Travel Till Who Did n't Even Know 116 Please Take a Friendly Look Amla 2.5 116 Please Take a Friendly Look Amla 2.5 116 Please Take a Friendly Look Amla 2.5 23.0 Point One So I Will Hear and 23.0 Point One So I Will Hear and 23.0 Point One So I Will Hear and Behavior Will Travels Till It's All About Things Are Not Trespassed Superhit 20012 Were Taking New Music V15 Interested The Amazing The Number 19 2012 MP3 Business Ji Live I Ho To Please Like Subscribe My Channel And In Next Video
|
Compare Version Numbers
|
compare-version-numbers
|
Given two version numbers, `version1` and `version2`, compare them.
Version numbers consist of **one or more revisions** joined by a dot `'.'`. Each revision consists of **digits** and may contain leading **zeros**. Every revision contains **at least one character**. Revisions are **0-indexed from left to right**, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example `2.5.33` and `0.1` are valid version numbers.
To compare version numbers, compare their revisions in **left-to-right order**. Revisions are compared using their **integer value ignoring any leading zeros**. This means that revisions `1` and `001` are considered **equal**. If a version number does not specify a revision at an index, then **treat the revision as `0`**. For example, version `1.0` is less than version `1.1` because their revision 0s are the same, but their revision 1s are `0` and `1` respectively, and `0 < 1`.
_Return the following:_
* If `version1 < version2`, return `-1`.
* If `version1 > version2`, return `1`.
* Otherwise, return `0`.
**Example 1:**
**Input:** version1 = "1.01 ", version2 = "1.001 "
**Output:** 0
**Explanation:** Ignoring leading zeroes, both "01 " and "001 " represent the same integer "1 ".
**Example 2:**
**Input:** version1 = "1.0 ", version2 = "1.0.0 "
**Output:** 0
**Explanation:** version1 does not specify revision 2, which means it is treated as "0 ".
**Example 3:**
**Input:** version1 = "0.1 ", version2 = "1.1 "
**Output:** -1
**Explanation:** version1's revision 0 is "0 ", while version2's revision 0 is "1 ". 0 < 1, so version1 < version2.
**Constraints:**
* `1 <= version1.length, version2.length <= 500`
* `version1` and `version2` only contain digits and `'.'`.
* `version1` and `version2` **are valid version numbers**.
* All the given revisions in `version1` and `version2` can be stored in a **32-bit integer**.
| null |
Two Pointers,String
|
Medium
| null |
430 |
hello everyone welcome back so today's question is flatten or multi-level question is flatten or multi-level question is flatten or multi-level doubly-linked list you are given a doubly-linked list you are given a doubly-linked list you are given a doubly-linked list which in addition to doubly-linked list which in addition to doubly-linked list which in addition to the next and previous pointers it could also have a child pointer which may or may not point to a separate doubly linked list we need to flatten this list so that all the nodes appear in a single level doubly linked list and we can access the head of the first level of the list so here we are dealing with doubly linked list or doubly linked list is a special linked list in which each node knows the address of the previous node along with the address of the next node and for this question we have multi-level doubly linked list it means multi-level doubly linked list it means multi-level doubly linked list it means apart from previous and next pointer a node also have a child pointer which may point to another multi-level doubly point to another multi-level doubly point to another multi-level doubly linked list see example 1 along with the next and previous pointer we also have a child pointer which may point to another doubly linked list in this example note 3 is pointing to another doubly linked list and in that doubly linked list node 8 also points to a third doubly linked list we need to convert this multi-level list we need to convert this multi-level list we need to convert this multi-level doubly linked list into a single level normal doubly linked list like this but this example is very complicated we should pick a simple example to understand the problem consider this multi-level doubly linked list after multi-level doubly linked list after multi-level doubly linked list after flattening it the list would be 1 2 4 5 3 and null if you look carefully you will notice that we inserted the list 4 5 between the nodes 2 & 3 we just 5 between the nodes 2 & 3 we just 5 between the nodes 2 & 3 we just performed insertion in a linked list so the intuition is we need to insert a linked list into an another linked list let's see how and for that we will manually solve a proper example traverse from left to right and if a node contains a child then we are going to insert the child list right after its parent node let's start node number 1 no child no - no child node 3 child no - no child node 3 child no - no child node 3 a child so we are going to insert the child list that is seven eight nine between the nodes three and four so we need to update some links the next pointer of three will point to node 7 and the previous pointer of seven will now point two three do not forget to update the child pointer of node 3 to null otherwise you will stuck in an infinite loop then we traverse till the last node of the child list seven no child 8 no child nine no child and now the next pointer of nine will refer to node 4 and the previous pointer of node four will point back to node nine so we have flattened some portion of this list now we continue to traverse further node for no child note 5 have a child but here things are little different because the child list contains another child list but it is not difficult so just follow along now we need to insert the child list that is 10 11 and 12 between the nodes 5 & 6 10 11 and 12 between the nodes 5 & 6 10 11 and 12 between the nodes 5 & 6 just as we did before update the next pointer of 5 and update the previous pointer of then the links has been updated so we move ahead no 10 no child node 11 contains a child that is list 13 and 14 therefore the next pointer of node 11 will now point to 13 and the previous node of 13 will point back to 11 next node is 13 no child next node is 14 contains no child but this node also happens to be a last node of a child list therefore the next pointer of 14 will point to 12 and the previous pointer of node 12 will point back to 14 links has been updated continue with the traversal next node is node 12 it contains no child but this node also happens to be the last node of a child list therefore we need to update some links this time the next pointer of node 12 will point to 6 and the previous pointer of node 6 will point back to 12 after that we continue the traversal now the next node is 6 it contains no child but this node happens to be the last node of our parent list so at this point we stop we finally flattened the entire multi-level doubly linked list into a multi-level doubly linked list into a multi-level doubly linked list into a single list so did you notice how this problem can be solved using recursion another thing to note is that we are updating the list in place so the space complexity would be big-oh of 1 and the complexity would be big-oh of 1 and the complexity would be big-oh of 1 and the time complexity would be the total number of nodes we are now going to write a code we save the head of the input into a dummy pointer because in the end we need to return the head it is a very common way to deal with linked lists after that we just traverse the list and if any node contains a child then we are going to do some stuff we have a method called processed child which is going to work upon the current node let's see how so we have a node that contains a child list and we have to insert this child list right after this node that is between the current node and the node lying next to the current node first we stored the next node into a variable next then we are going to update some links as we have discussed after that we are going to traverse the child list and if we find a node having a child we will take care of that child list first by calling the same function again and after completely traversing the child list we are again going to update next and the previous pointers at last we just return the node to continue the process further you have just solved letting a multi-level doubly linked list letting a multi-level doubly linked list letting a multi-level doubly linked list that's it for today's video hersh Audrey signing off
|
Flatten a Multilevel Doubly Linked List
|
flatten-a-multilevel-doubly-linked-list
|
You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional **child pointer**. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a **multilevel data structure** as shown in the example below.
Given the `head` of the first level of the list, **flatten** the list so that all the nodes appear in a single-level, doubly linked list. Let `curr` be a node with a child list. The nodes in the child list should appear **after** `curr` and **before** `curr.next` in the flattened list.
Return _the_ `head` _of the flattened list. The nodes in the list must have **all** of their child pointers set to_ `null`.
**Example 1:**
**Input:** head = \[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12\]
**Output:** \[1,2,3,7,8,11,12,9,10,4,5,6\]
**Explanation:** The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:
**Example 2:**
**Input:** head = \[1,2,null,3\]
**Output:** \[1,3,2\]
**Explanation:** The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Explanation:** There could be empty list in the input.
**Constraints:**
* The number of Nodes will not exceed `1000`.
* `1 <= Node.val <= 105`
**How the multilevel linked list is represented in test cases:**
We use the multilevel linked list from **Example 1** above:
1---2---3---4---5---6--NULL
|
7---8---9---10--NULL
|
11--12--NULL
The serialization of each level is as follows:
\[1,2,3,4,5,6,null\]
\[7,8,9,10,null\]
\[11,12,null\]
To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:
\[1, 2, 3, 4, 5, 6, null\]
|
\[null, null, 7, 8, 9, 10, null\]
|
\[ null, 11, 12, null\]
Merging the serialization of each level and removing trailing nulls we obtain:
\[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12\]
| null | null |
Medium
| null |
299 |
hello so let's talk about the bows and calls so this is one of the game you definitely play so uh you're just given the secret number secret and the guessing number so you want to return the hint for your friend the a represents the accurate number P represent the number is correct but the position is not correct so a represent the accurate number in the same position but B does not have the same position but the number are correct so what does this mean so I'm going to just give you give it a try when I explained through it so you want to find out the guess number to the secret number so you want to match from guessing number to the secret number so if the value of the same and then position on the same you are going to represent what the bow so you so this is also the Bulls and which is going to represent a so you know the one value which is 8. are the same position and same value so you're going to say 1A so what does B mean so you want to find out the value in the secret which are not in the same position but in a different order it doesn't matter like which order you are placing in the guessing string but in a different position but the value of the same you are going to see you are going to just say B so there are definitely 3B because one eight zero seven uh definitely in one of the position in the guessing is that number eight are the same right so you are going to say one a three B so let me look at the another example so this one so this is going to be what 1 and then one zero one right a one two three and zero one so you know like you are in the same position one so you are going to say one eight so one is it's going to be right here and since you have another one so you are get rid of this right you will get rid of this so since we have another one so you want to say one B it doesn't matter the order it does not matter right so you just basically say one a one B for this answer all right so let's talk about the solution so we want to what we want to match the guessing string to the secret string so uh look at this so the first condition is if the position are the same I mean the value position all the same we increment our a right which is O right and then if the um so we don't know like which number they are going to let they're going to be placing right so we will have a counter so we account to find zero to nine so it's going to be 10 position and then I'm going to increment our secret value and the I index so I'm going to say counter for secret value dot chart at AI position I'm going to increment this but incrementers increment does not mean anything right but when this value is negative uh what do you mean negative because I would decrement our decrement the value for the guessing string so when this value for the secret when you increment which is what Less Than Zero it means I definitely decrement the value in a guessing string so I'm going to do exactly the same thing but when I say counting at guessing chart AI Child AI and then if this is decrement when is greater than zero then you need to count as cows which is both B right sorry count as B uh this is because your decrement the value in the guessing and then you know like that you know that when the value is actually positive you mean it definitely mean like you somehow uh you saw have a number in a secret string so just think about this like you increment your value in a secret you decrement the value in a guessing but when you increment the value and you call it negative value before you increment which means there is a value in a guessing number and using the same idea if you decrement a value but before you decrement the position the counting or reposition is positive which means you increment the uh the plus I mean the value in the secret position uh is in there right so all right so I'm just stop holding this a little bit you know uh pretty hard to understand for sure so I'm gonna say bows and cows equal to zero right and I have a counting array new in 2010 right so I will return what both plus a plus cause plus b right so which is number of a and the number for B right so for inch I equal to 0 I listen secret lens and I plus so uh if the value so I'm going to say if the value if the secret the Triad AI if this is equal to the guessing that chart a i am going to increment my post right and you definitely know this so how do you how to do another um add-in account for calls so you have um add-in account for calls so you have um add-in account for calls so you have two ways right increment uh the content array when is negative value and decrement accounting array is positive value right so if the number sorry if a counter at secret so it's currently every chart at Ai and then you increment so you want to minus zero first minus zero and then you only increment if this value is negative then you'll just no this is cause right you increment you want to increment but you are not going to increment first you have you increment right after this line but if the value in the content array is negative which means you know like there's a number you're guessing and then send idea if a Content array ad gets in dot chart aai minus zero if this is positive and then you know this is cause all right let me run it and submit cool so let's talk about the time in space this is going to be a space you know all of 10 represent constant right and this is going to be a time is going to be what all of n represent the end of the secret and this is like constant sign you know and this is constant time so time and space are pretty straightforward so if you have any question leave a comment below subscribe if you want it all right peace out bye
|
Bulls and Cows
|
bulls-and-cows
|
You are playing the **[Bulls and Cows](https://en.wikipedia.org/wiki/Bulls_and_Cows)** game with your friend.
You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:
* The number of "bulls ", which are digits in the guess that are in the correct position.
* The number of "cows ", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.
Given the secret number `secret` and your friend's guess `guess`, return _the hint for your friend's guess_.
The hint should be formatted as `"xAyB "`, where `x` is the number of bulls and `y` is the number of cows. Note that both `secret` and `guess` may contain duplicate digits.
**Example 1:**
**Input:** secret = "1807 ", guess = "7810 "
**Output:** "1A3B "
**Explanation:** Bulls are connected with a '|' and cows are underlined:
"1807 "
|
"7810 "
**Example 2:**
**Input:** secret = "1123 ", guess = "0111 "
**Output:** "1A1B "
**Explanation:** Bulls are connected with a '|' and cows are underlined:
"1123 " "1123 "
| or |
"0111 " "0111 "
Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.
**Constraints:**
* `1 <= secret.length, guess.length <= 1000`
* `secret.length == guess.length`
* `secret` and `guess` consist of digits only.
| null |
Hash Table,String,Counting
|
Medium
| null |
1,816 |
Hello hello welcome to station and say z problem and turn on the light sentences for morning hair sentence's 1st day collection whatsapp request english play list 150 gram paneer waiting for me and content five whatsapp images english speech and give it difficult for engineers and you Need to return gift to give water tis for twelfth forward hello how are you apps screen that a pot surendra seeervi string events at a string what is the solution to this problem for what is the day yours were and ask latest husband only patience and that ranbir Will return gift this time's first that keyboard admin story inter result question result plus now half well was now I love you issue Africa has vitamin Africa has vitamin Africa has vitamin treatment time when newspaper posts last 30 hello how are you give that yan character Food taster meeting that its accepted and worshiped
|
Truncate Sentence
|
lowest-common-ancestor-of-a-binary-tree-iv
|
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of **only** uppercase and lowercase English letters (no punctuation).
* For example, `"Hello World "`, `"HELLO "`, and `"hello world hello world "` are all sentences.
You are given a sentence `s` and an integer `k`. You want to **truncate** `s` such that it contains only the **first** `k` words. Return `s`_ after **truncating** it._
**Example 1:**
**Input:** s = "Hello how are you Contestant ", k = 4
**Output:** "Hello how are you "
**Explanation:**
The words in s are \[ "Hello ", "how " "are ", "you ", "Contestant "\].
The first 4 words are \[ "Hello ", "how ", "are ", "you "\].
Hence, you should return "Hello how are you ".
**Example 2:**
**Input:** s = "What is the solution to this problem ", k = 4
**Output:** "What is the solution "
**Explanation:**
The words in s are \[ "What ", "is " "the ", "solution ", "to ", "this ", "problem "\].
The first 4 words are \[ "What ", "is ", "the ", "solution "\].
Hence, you should return "What is the solution ".
**Example 3:**
**Input:** s = "chopper is not a tanuki ", k = 5
**Output:** "chopper is not a tanuki "
**Constraints:**
* `1 <= s.length <= 500`
* `k` is in the range `[1, the number of words in s]`.
* `s` consist of only lowercase and uppercase English letters and spaces.
* The words in `s` are separated by a single space.
* There are no leading or trailing spaces.
|
Starting from the root, traverse the left and the right subtrees, checking if one of the nodes exist there. If one of the subtrees doesn't contain any given node, the LCA can be the node returned from the other subtree If both subtrees contain nodes, the LCA node is the current node.
|
Tree,Depth-First Search,Binary Tree
|
Medium
|
235,236,1218,1780,1790,1816
|
330 |
welcome to august eco challenge this problem is called patching array given assorted integer array nums and an integer n add slash patch elements to the array such that any number in the range 1 to n inclusive can be formed by the sum of some elements in the array return the minimum number of patches required okay so if we're given an array of one and three and an n of six what are the numbers that we can form with one and three we can see that all the numbers we can form are one three and four so we're going to be missing quite a few here we're missing two five and six so if we just add two then we can see we can form everything one two three one all these and it's gonna form one two three four five six so we kind of can see here that we probably want to do some sort of greedy method given that the integer array number is sorted and whenever we're missing some number that we can't form we're going to have to add that number no matter what right if you see like one three four is possible well we have to add two right like adding five doesn't make any sense here we have to add two and then perhaps build up like see okay we have to add two what else do we need in order to get all the numbers from one to six um so to do this let's just think of an example here say that we're given n of 10 an array of like one two and i don't know five right rather than thinking of all the different combinations that we can form which was my first approach that definitely didn't work what we can do is kind of think of this as a range instead like before we add any numbers our range is going to be zero to zero right we have no numbers so we can't do anything but once we add one to our array as we can see that we're gonna have at least uh zero to one right what if we had two well interestingly enough like if we had two uh we can kind of accumulate the sum that we form so far and add 2 to our ending range here and what this means is actually we can take care of 1 2 and 3 as we add this add these numbers and we can see like yeah one two and three at this point are all taken care of so what about when we add five well here's the issue if we add five and this becomes eight we can't form four right like the condition that we need to have here is okay given this range the next number that we add needs to be less than or equal to this number plus one like if this was a four then it'd be fine we can add this in here but this five is greater than three plus one so that actually means that we can't form a four like it doesn't matter what numbers come after this there's no way we can form a four here so we're going to have to add four here we don't technically need to add four to anything like inside of our array all we need to do is just increase our output by one and we know that the next number is four so we can just add that here so three plus four is going to equal seven okay and now when we check for five we see that five is less than seven plus one so then we can just add twelve here or i'm sorry five to seven that's gonna equal twelve and now we've reached our ten so all the numbers at this point as long as we added a four we can form everything from one two three four five seven eight nine ten and you can um just verify that on your own it's kind of unintuitive it's very amazing i thought it works and i think it's really hard to come up with but uh once we understand that i think this algorithm becomes pretty easy so let's begin by first initializing a couple of things we'll have not in this plot i we're going to call this our output and we're going to have our ending range so i'm going to call that up two now you can call it reach you can call it whatever you want you call it end all right so while let's see while r up 2 is less than the n because that's what we need to take care of all the numbers from 1 to n here we'll say if our i is less than length of nums actually will initialize up here let's try not to get that confused with the n given to us and now let's see if the up two uh plus one whatever the number coming next has to be less or equal to up two plus one okay as long as that's the case then we could add nums i to our up to and we're going to accumulate this right like this and we're going to increase our i right here now otherwise if this isn't the case then we know we have to add a number we have to add that next number like that four that comes up so let's see our output needs to be increased by one and our up two is essentially whatever comes next like up to plus one like this right and finally we just return our output and this actually guarantees that we'll return the minimum because we're doing this in sorted order so as we build it up that's actually gonna it's kind of guaranteed that it'll be the minimum number here all right so let's make sure this works it looks like it so and there we go so time complexity is going to be of n it's the greedy method but this is a hard problem it answers seems very easy but coming up with this i mean i wasn't able to do it i went down a completely different path it's only not until i saw the answer that you know it was kind of blew me away so you know i think i need to really figure out how to take other problems such as like interval problems and incorporate with problems that don't seem related and i suppose that's why i keep doing these videos and why i keep practicing and hopefully i'll get there someday all right thanks for watching my channel remember do not trust me i know nothing
|
Patching Array
|
patching-array
|
Given a sorted integer array `nums` and an integer `n`, add/patch elements to the array such that any number in the range `[1, n]` inclusive can be formed by the sum of some elements in the array.
Return _the minimum number of patches required_.
**Example 1:**
**Input:** nums = \[1,3\], n = 6
**Output:** 1
Explanation:
Combinations of nums are \[1\], \[3\], \[1,3\], which form possible sums of: 1, 3, 4.
Now if we add/patch 2 to nums, the combinations are: \[1\], \[2\], \[3\], \[1,3\], \[2,3\], \[1,2,3\].
Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range \[1, 6\].
So we only need 1 patch.
**Example 2:**
**Input:** nums = \[1,5,10\], n = 20
**Output:** 2
Explanation: The two patches can be \[2, 4\].
**Example 3:**
**Input:** nums = \[1,2,2\], n = 5
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 104`
* `nums` is sorted in **ascending order**.
* `1 <= n <= 231 - 1`
| null |
Array,Greedy
|
Hard
|
1930
|
848 |
hey everybody this is larry this is september 8th so you know the first day of the second week of the lego daily challenge hit the like button hit the subscribe button drum and discord let me know what you're thinking um yeah so i'm going to be doing this for another week um i'm doing a little bit of traveling but i'll still be doing these videos just maybe the timing won't be as uh as regular but you know just yeah we'll figure it out together life is short but we have time uh anyway today's problem is shifting letters you're given a string s of lowercase english letters and an integer ray shifts of the same length okay so you shift it one count at a time oh wait what we're saying now for each shift we want to shift the first i plus one letters of x s x times what and you can't use single letters like this it's so confusing okay so we want to shift it so okay let's actually look at an example so three means that we shift the first three oh the first letter by three five is the second or two letters by five and then nine is the first three characters by nine okay i mean i already kind of knew what i wanted to do but i just wanted to um well i mean in that i think they were my misunderstanding or just making sure that i understand it correctly i knew that there are only a couple of possibilities of what they were asking for so i'd to read an example but they all had the same solu um same-ish all had the same solu um same-ish all had the same solu um same-ish solution so um so yeah so i didn't know kind of what i wanted to do and the short answer of course is just prefix sum or mm i mean yeah prefix some would work and i think you can also do two things do you have to do a prefix sum dun i mean i think prefix sum is the natural way of thinking about it uh the way that i thought about it but i don't know sometimes you just overuse something because you can but i think you can actually just so my second thing that i was guessing was actually the way that this particular problem is structured because you could use prefix some for a few variation of this but the way that this particular problem is structured you can think i think you can just go backwards right because here um you just go backwards at the last letter you shift it by nine in the second letter you it's just nine plus five so the second letter you go fourteen uh and the last letter is eight plus nine so 17 um and i think that would give you the answer um as long as you go so the answer is apparently just go from right to left um that is also a thing that i am sometimes and maybe more than sometimes very often very bad at which is to think about it in um in a backwards kind of way maybe i don't know if that's quite the right way to say it but basically instead of going left to right you go right to left because sometimes or if you're going up to down or down to up you know um because these pumps are not always symmetric and sometimes they are when they're symmetric what i mean is that going left and right the left doesn't matter but in this case it does and sometimes for asymmetric problems going the other dimension or the other direction is easier and i think in this case it is um that said at least in python um it's still going to be linear space because you should not be doing things in place now you can't change string in place anyway so yeah um but you know you don't just because it's linear space of course we save extra space because now we only need constant extra space so let's get started let's go um let's do running sum but backwards so then now we go n is equal to length of s and then now we can do for index from range of n minus one negative 1 because python is awkward if i was in any other reasonable language um i would just do something like index is equal to and minus one something like this right um but this is what how it is you know in python so yeah anyway so they're now running some we increment it by shifts of index and then now um okay we also want to do the answer um so we just change it to just um yeah whatever it's a little bit awkward because then when we're changing it technically we reallocate space i guess we could just call it none is maybe slightly more efficient um and then now you can do and serve index is z code two s of index plus oh sh uh plus running some uh mod 26 kind of i mean i know there's more math here but i'm just kind of writing the sketch of the idea and then at the end we can just join it back into a string which in terms of space consideration things are always awkward with strings and immutable string languages so yeah i mean i'm not going to do it that deeply right now but yeah um and we can just set this as you go to do so then we can just write this um the idea here what i'm doing uh this is all lowercase yep uh what i'm doing is convert it from a b c d e f g or whatever all the way to 0 to 25 so that we can add the running sum and then now we can wrap around by just mining 26. i assume that we might buy 26. oh yes because otherwise this became the race 3 problem and after that we re created back i think this should be good enough unless i misread the bomb which is possible and often as my fans know expected string instant and found oh i forgot to convert this back to uh char so yeah try ascii numbers instead okay cool uh yeah so i mean this looks good i mean i don't really know that i mean i guess the only other case that i would check is maybe just um oh that's too many but uh what the possible inputs yeah i mean in just like this case but i don't really expect it um just overwrapping it that's too long let's just do something smaller yeah just you know something that i can check over for but so what i'm looking for here is just that me getting some weird answer because i mean obviously here i could actually have an expected answer but on a contest or an interview you know it's not expect uh you know you have to kind of see what your outputs are and yeah and this is the output so that looks okay so yeah so i mean this is good for me to submit so let's hit that submit button and while i do that hit the like button i guess i don't know just like tying that in okay so it looks accepted um in terms of extra time i mean this is linear time because you know it's just one for loop and we got look at the uh the input string and the shifts one so can't really do better than in terms of time in terms of space like i said it's always a little bit awkward to calculate extra space because in other languages or whatever um you know it depends on your language right but let's just say that it is linear space and this is probably as close as optimal as you can get in python if i'm wrong let me know uh but yeah i mean because yeah let me know uh that's all i have for this one um yeah do i have anything else to say no i think i'm gucci uh let me know what you think i'll see you later have a great rest of the week to good mental health bye
|
Shifting Letters
|
shifting-letters
|
You are given a string `s` of lowercase English letters and an integer array `shifts` of the same length.
Call the `shift()` of a letter, the next letter in the alphabet, (wrapping around so that `'z'` becomes `'a'`).
* For example, `shift('a') = 'b'`, `shift('t') = 'u'`, and `shift('z') = 'a'`.
Now for each `shifts[i] = x`, we want to shift the first `i + 1` letters of `s`, `x` times.
Return _the final string after all such shifts to s are applied_.
**Example 1:**
**Input:** s = "abc ", shifts = \[3,5,9\]
**Output:** "rpl "
**Explanation:** We start with "abc ".
After shifting the first 1 letters of s by 3, we have "dbc ".
After shifting the first 2 letters of s by 5, we have "igc ".
After shifting the first 3 letters of s by 9, we have "rpl ", the answer.
**Example 2:**
**Input:** s = "aaa ", shifts = \[1,2,3\]
**Output:** "gfd "
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of lowercase English letters.
* `shifts.length == s.length`
* `0 <= shifts[i] <= 109`
| null | null |
Medium
| null |
98 |
hi everyone today we are going to solve the read called question validate binary subtree this is actually a very good question to learn basic binary search three so you are given a root the root of binary tree determining if it is a valid binary subtree the definition of valid binary star 3 is as follows the left subtree of a node contains only nodes with keys less than the nodes key the right subtree of a node contains only nodes with keys greater than the nodes key so both the left and the right subtrees must also be binary such three so let's see the example so you are given two one three and all nodes on the left side must be less than its parent node value so in this case 1 is smaller than 2 so that's why this part is valid and on the other hand the all nodes on the right side is greater than its parent node so in this case 3 is a greater than 2 so that's why this part is valid so that's why in this case return 2 because all parts of a binary search 3 is a valid so actually this is a very simple question we just implement this condition so i'll show you how to solve this question okay so let me explain with this example i put a range condition for each node so let's see the root node first of all i put the negative infinity as a minimum number and then this is a current number and i put the infinity as a maximum number in this case it's valid so let's move on left side so for 8 minimum number is negative infinity and the current number and the maximum number should be 10 and it's valid so let's move on left side right side and minimum number should be 10 and the current number is 15 and the maximum number is infinity it's valid and let's move on right side minimum number should be 15 and the current number is 18 and the maximum number is infinity it's valid okay let's move on the left side so current number is 12 and the maximum number is 15 because we move on left side over 15. so that's why our maximum number should be 15. how about the minimum number actually this is a important point in the tricky point of this question we already put the 15 here so what is the number here it's a 10 because so from node this part is on the right side of our loot node so all nodes on the right side must have a great value greater than our root node value so that's why minimum number should be 10. so from this chart so algorithm of this question is that okay current no node is 10 and when we move on the left side minimum number should we stay the same number and then update maximum number with current number and then when we move on right side update the minimum number with current number and then a maximum number uh is the same number just stay that is a basic idea to solve this question so time complexity is order of n so let's get into the code okay i think it's best way to solve this question is to use recursive to do that first of all i create a helper function to call recursively so let's say valid and uh node and mini month and the maximum and the first of all if not node which means that we reach to the end of node i mean diff node in that case return true and the next condition is like a node bar is greater than minimum and a node bar less than maximum if this con if we don't need this condition then return force and then we call valid function recursively so first of all for left side so valid node.left node.left node.left in that case um minimum number should be same as i explained earlier and then maximum number should be current node value and then for left side right side no dot right and in that case minimum numbers should be your current value and the maximum number should be same and this is a helpful function and i call the function from outside so return valid and first of all give a root node and so first as i explained earlier i give the negative infinity as a minimum number and the infinity number as a maximum number so to do that float negative in the fault if that's it so let me submit it yeah this solution works and this is a very good question to understand the basic binary search three so let me summarize step by step algorithm this is a step-by-step algorithm of this is a step-by-step algorithm of this is a step-by-step algorithm of validate binary search tree step one create helper function to call recursively step 2 in helper function check whether node is known in that case return true step 3 in helper function check current node value is between minimum number and the maximum number if not the case return false step 4 in helper function call helper function recursively for left node and the right node step 5 call alpha function from outside with root node and a negative infinity number and a positive infinity number so that's it i hope this video helps you understand this question well if you like it please subscribe the channel in the hit like button or leave a comment i'll see you in the next question
|
Validate Binary Search Tree
|
validate-binary-search-tree
|
Given the `root` of a binary tree, _determine if it is a valid binary search tree (BST)_.
A **valid BST** is defined as follows:
* The left subtree of a node contains only nodes with keys **less than** the node's key.
* The right subtree of a node contains only nodes with keys **greater than** the node's key.
* Both the left and right subtrees must also be binary search trees.
**Example 1:**
**Input:** root = \[2,1,3\]
**Output:** true
**Example 2:**
**Input:** root = \[5,1,4,null,null,3,6\]
**Output:** false
**Explanation:** The root node's value is 5 but its right child's value is 4.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-231 <= Node.val <= 231 - 1`
| null |
Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Medium
|
94,501
|
1,192 |
hey everybody today we are going to solve another daily lit code challenge so today we got a hard one and the problem is number 1192 critical connections in the network so the problem is we are given a non-directed graph like the one that you non-directed graph like the one that you non-directed graph like the one that you can see on the left in order to explain the problem let me define a graph myself so here we are given a not directed graph and the task is to find all edges that if we remove them it will convert the graph into two con connected components to separate connected components so what does that mean so in the problem it is called those edges are called critical edges so for example here on the graph that i just draw if we move this edge it will convert the whole graph so initially the graphs in the problem are connect are a single connected component but by removing this edge it will convert the graph into two separate connected components so all edges on so we can component one and component two all edges in component one are reachable from each other but none of the nodes in component one are reachable to component to and vice versa and as you can see on the example in the problem as well so if we move this critical edge here it will convert the whole graph into two connected components one of them has three nodes and the other one has only one node so in order to solve this problem i'm going to use charge on algorithm if you don't know what that is so i will put a link in the description as well but the whole idea is very similar to a dfs so we are going to traverse this graph using vfs but with a few adjustments so let's uh first let me explain the algorithm briefly so here's the algorithm so initially let's say we are assigning the ranking to all nodes so initially i just assign infinity for the ranking of old nodes and we start the dfs traversing the edge that this graph from node 0 and then we every time you are visiting the node you are updating so initially we update the node 0 with the ranking zero and then we'll start the traverse so here after that we visit one and every time you're visiting a neighbor node you just update the neighbors you're informing the neighbor that the ranking was zero and your ranking could be one so since this note has not been visited yet because we know by seeing the infinity value in the ranking of the neighbor node we can it can be inferred that specific node has not been visited yet so we update that with one and then one has two neighbors so then this is the key here we can never visit an apparent node we should also while we are calling the dfs we should always know what is the node that's calling the dfs or uh from what node the dfs is being called from and then you're visiting two and then increasing the ranking so the infinity will be updated by two and then so one would be the parents node and then from two node two uh realize that there is a node with a lower value zero so it updates its ranking from two to zero and at the same time it informs on when we are on the recursion when we are on note 1 the note 2 in it can be inferred on note 1 that node 2 is reachable to a lower value so uh if i want to draw it like this so we visited node 0 and then node 1 and then we went to node 2 but node 2 realized that it has a direct connection to node 0 so it informs node 1 that it has a lower ranking so it is it could be reached to a node that lower ranking and at the same time that means this specific node this connection is not critical because node 2 already found another way to a lower value to a lower ranking so that means if we even remove this edge there must be exist another path from this from node two to node one so the this edge between these uh parents and children the child one and two is not critical if you're confused so let me implement that and during the implementation we can see the details of trojan algorithm here so first of all we need to store the graph information what we are given is just the list of edges in the graph but as you remember as we discussed in previous videos there are several ways to store information of a graph one of them that we are not going to use in this problem is a n by n matrix that initially all values are zero and for each uh and b in the edges you just put one if the graph is not directed like this problem that we have here you just put one in uv and vu so by looking at this graph we can in this matrix we can realize that for all zero values there is no edge but for all um cells with the value of one there must exist an edge but what we are going to use here so for each node we just uh assign which keep track of the neighbors for each node in a list so for example in this graph we have one two three and then node zero has two neighbors node one has zero two three node two has zero and one and no three has one and this is why uh it is important to keep track of the parent node because as you can see uh node two has zero on its list and node zero has two honest leads so if we are calling the dfs we should always know the parent node so that uh when it is uh for example if we are going this way we should know that it is calling for uh from zero and node two on its neighbor at least should drop zero and uh only uh called the difference on one so let's uh first convert that so for u and v in connections we want to now have a shared structure to store the graph so for that i'm going to put self and then solve the graph equal so we want to have a structure like for each node and we have a list so for that i want to use a default dictionary up type list so that means initially if the key doesn't exist it will assign it to an implant empty lease so for and we can simply say for human being connections uh self.graph of you uh self.graph of you uh self.graph of you the depends v and vice versa and also we should keep track of the blanking for each node so let's say a soft dot rank equal non initially and then uh so that you're updating the rank here at least infinite value for every node in range of m since n is the number of nodes in the graph and for infinity as the problem says the number of nodes is between 2 and 10 to the power of 5. i've designed my own infinite here and equal 10 to the power of 6 and then use self.infinite self.infinite self.infinite like that and then this is the set that we want to use called the dns function so the way we are going to call is we are starting from node 0 so we are going to implement the dfs here like self dfs cell so let me pass that for now dfs on node 0 with the ranking 0 and what is the parent node so we don't have a parent so it is known so instead i want to put it here like the note that you are visiting the ranking and the parent which initially the parent is known so first of all we check if the node is already assigned the value and it is not infinite so let's say if self that rank of that's a specific node is not equal to solve that in so that means this node has already been visited and we can directly access to the lowest value of that node so we can return it right now so that rank of the node otherwise update so that means if this node has not been visited yet and you know updating the ranking of this node now so that rank for this node equal to rank and for all adjacent in soft graph for the node so these are the neighbors if the adjacent is the parent so we want to skip that so if it's an equal to parent continue otherwise we first check if the note has been visited or not so if self. rank of the adjacent node is equal to resulted in so that means at the same time means that neighbor has not been visited yet so we call the self dfs of the neighbor which is just a node and we are increasing the rank by one so the rank is the rank value that you're assigning and serve.rank is at you're assigning and serve.rank is at you're assigning and serve.rank is at least that we have we keep track of the lowest ranking reachable from that specific node and what is the parent for the node this is the node itself here is the parent node for the jensen node so i would put node here and at the end you're updating the ranking of the node you know you should always keep track of the minimum value so for that the minimum of the current ranking and the ranking that the neighbor so remember on recursion we where we finished visiting a note 2 and we jumped back to node 1 had access to node 0 so it informed node 1 that i have a direct access to node 0 so node 1 should update its ranking as well so here this is what's happening here so the self.rank of that adjacent node so the self.rank of that adjacent node so the self.rank of that adjacent node okay so far so good uh so this is the dfs and at the end we are just returning so the ranking so similar to what happened here but what happens now to find the critical edges if after visiting the neighbor node if the ranking of the node is still the one that the ranking that we initially called it from or the ranking of the children is greater than the ranking of the current node so that means uh this edge itself is critical because that node couldn't find another path to a lower value to a node with a lower value at all so that means there is no cycle from this node to the other one and this is the only single path that we can connect this node to that the other one or if it has if it is connected to any other node this is a critical edge so here that means if so the trunk adjacent is greater than run we initially uh call it uh called the dfs width so that means we found a critical edge and then we should keep track of the all edges so for that let me define a share of all these answer so this is what we are returning at the end but here you're uh appending all edges that we are finding in into that answer we'll tell that answer that's that the note between these two edges so between node and the neighbor okay so this is everything let's try that out and when it's in tank self dot answer equal so why is that so the answer just checking the title if we are having a typos so start.graph so start.graph so start.graph default dictionary of these this is okay and self.answer and self.answer and self.answer equals an empty list initially and then okay line 40 oh line 40 the problem is with here okay there we go so it's not accepted hopefully it passes all test cases okay there we go so that was everything so i would put the link for charge on the algorithm for if you want to find more details and read it yourselves but uh it took a long time but at the same time it was a hard problem for today so i hope you enjoyed it
|
Critical Connections in a Network
|
divide-chocolate
|
There are `n` servers numbered from `0` to `n - 1` connected by undirected server-to-server `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between servers `ai` and `bi`. Any server can reach other servers directly or indirectly through the network.
A _critical connection_ is a connection that, if removed, will make some servers unable to reach some other server.
Return all critical connections in the network in any order.
**Example 1:**
**Input:** n = 4, connections = \[\[0,1\],\[1,2\],\[2,0\],\[1,3\]\]
**Output:** \[\[1,3\]\]
**Explanation:** \[\[3,1\]\] is also accepted.
**Example 2:**
**Input:** n = 2, connections = \[\[0,1\]\]
**Output:** \[\[0,1\]\]
**Constraints:**
* `2 <= n <= 105`
* `n - 1 <= connections.length <= 105`
* `0 <= ai, bi <= n - 1`
* `ai != bi`
* There are no repeated connections.
|
After dividing the array into K+1 sub-arrays, you will pick the sub-array with the minimum sum. Divide the sub-array into K+1 sub-arrays such that the minimum sub-array sum is as maximum as possible. Use binary search with greedy check.
|
Array,Binary Search
|
Hard
|
410,1056
|
1,816 |
everyone tonight I am working on lead code Challenge number 1816 this one is called truncate sentence and in this challenge you're giving an input sentence which is the parameter s right here and then an integer parameter K and they want you to truncate us such that it contains only the first K number of words so essentially taking that sentence and limiting it only to the first number of words that's represented by K so if we look at the input example make sure we understand this if the input sentence is hello how are you contestant and K is for you want to return only the first four words in that sentence so you would return hello how are you so fairly straightforward to understand what they are asking for in this challenge what I'm going to do is start by creating a variable called words and to get the words in the input sentence I'm going to use the S dot split method and we want a space here to be the delimiter at which it splits up that input sentence so this is going to create an array of words by splitting up that input sentence at the spaces the next one I want to do is I want to now truncate this to the correct number of words so I'm going to use the dot slice method on that array I'm going to start from the first element which is 0 and then go up to K so that should limit that to the correct number of words and now I can simply return that array with the dot join method and also passing a space there to make sure we have the correct spaces in between the words at the end so I'll run this and it's passing all the test cases and I hope this all made sense this one's a pretty straightforward one to understand we're splitting up the sentence with the split method at each of the spaces or then slicing that array from the first element up through K numbers of elements and then we return words dot join with the space in between each word at the end foreign
|
Truncate Sentence
|
lowest-common-ancestor-of-a-binary-tree-iv
|
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of **only** uppercase and lowercase English letters (no punctuation).
* For example, `"Hello World "`, `"HELLO "`, and `"hello world hello world "` are all sentences.
You are given a sentence `s` and an integer `k`. You want to **truncate** `s` such that it contains only the **first** `k` words. Return `s`_ after **truncating** it._
**Example 1:**
**Input:** s = "Hello how are you Contestant ", k = 4
**Output:** "Hello how are you "
**Explanation:**
The words in s are \[ "Hello ", "how " "are ", "you ", "Contestant "\].
The first 4 words are \[ "Hello ", "how ", "are ", "you "\].
Hence, you should return "Hello how are you ".
**Example 2:**
**Input:** s = "What is the solution to this problem ", k = 4
**Output:** "What is the solution "
**Explanation:**
The words in s are \[ "What ", "is " "the ", "solution ", "to ", "this ", "problem "\].
The first 4 words are \[ "What ", "is ", "the ", "solution "\].
Hence, you should return "What is the solution ".
**Example 3:**
**Input:** s = "chopper is not a tanuki ", k = 5
**Output:** "chopper is not a tanuki "
**Constraints:**
* `1 <= s.length <= 500`
* `k` is in the range `[1, the number of words in s]`.
* `s` consist of only lowercase and uppercase English letters and spaces.
* The words in `s` are separated by a single space.
* There are no leading or trailing spaces.
|
Starting from the root, traverse the left and the right subtrees, checking if one of the nodes exist there. If one of the subtrees doesn't contain any given node, the LCA can be the node returned from the other subtree If both subtrees contain nodes, the LCA node is the current node.
|
Tree,Depth-First Search,Binary Tree
|
Medium
|
235,236,1218,1780,1790,1816
|
34 |
High absolutely questions series and here we are going to atom question number 34 which is find first and last question of element in unsorted is a medium level difficulty of question with super question very good question is very interesting okay and here There are no downloads from some minimum here. What is given to you here in the question? In the question you are given an array here which is sorted in non- given an array here which is sorted in non- given an array here which is sorted in non- decreasing order. What does non-decreasing mean here? What does non-decreasing mean here? What does non-decreasing mean here? What is your array? It is in increment order in which the previous value is less than its next value, like here the one TVS is smaller than its next one, after this the previous value is less than its next one, so whatever is yours. In increment order, non-decreasing means increment and okay non-decreasing means increment and okay non-decreasing means increment and okay so you are given a here, you are sorted, meaning in ascending order, this is your here, you are sorted here, and you are given a target here, like any one, you are here, target. I can say that here is the target, so you have to find this five here, in this array, where is the five coming, you have to tell its position, but if an element, if this is your target here, once in the array. If it was repeating, then this was a very easy question. Okay, it was time. So, this was a very easy question. Here, there is no question of medium level difficulty. Here, you would have found it written as easy because if you have to find one element, then You can find that very easily by applying any of your searching algorithms, but your question becomes complex when your target is suppose to be my target here, target suppose is six to my place and this sex is yours here. It is repeating twice. Okay, now what have they told you here? Find the starting and ending position of the given target which is your target here which is repeating it twice. Find its starting position as soon as your It is starting here and this is your ending here, so zero one two three four so its starting position is your three ending position, you have to find out this here, the target you have here is repeating twice. You have to find out the position. Okay, if you do not get the values in any of the targets, if you do not get the values in any of the targets, if you do not get the values in any of the targets, then you have to do one Hey Britain with mines van position, we will see this in your corner here, how and our right hand algorithm with log in complexity. offli, you are seeing a here, hey, you are seeing a short here, okay and you have to search here, so in this case, whenever your are sorted, it does not matter whether it is in increasing order or decreasing order, but if If you are arrested then pick it up directly and put it on Binary Search here and they are also telling you the same thing, they are talking to you because of the complexity of the people here, because of the complexity of these people, that is the complexity of your binary search here and this If you are asking for login then you will get the login in binary search, then here they are telling you that you have to put binary search here, okay you can do it here, let's see the example which they have given. Okay, the example they have given here is your pay here 577 88 10 okay and this is the target here, they have given your at right here, you have to find out the pay at here, where is yours in this. The starting position is this here. The ending question is this here. One thing that is beneficial here is that whatever you have is sorted, so whoever is your target here, both of them will be adjacent to you. Okay, like here, three, four, here. Your location is starting from 0123, going to four and ending, so these two together you will get the targets because your here, it is sorted here, you saw here, they are asking to find out 6 here. There is era but here they are saying to find out six does not exist here, does not exist in this, so what do you have here -1 -1 The output you have to return here, -1 -1 The output you have to return here, -1 -1 The output you have to return here, which you have to return the index, hey that's that To do this by enclosing an Eric with an Eric, you will have to create a new array here and inside it, you will create your indexes, something like this, from another case, if the supposition is that your area is empty, the target has been given by them, then you will have to create it in the case. What is to be returned here, in this you will have to do mines van mines here, then how is this corner here, I will have to put a check here in the case of MT, if my opinion is returned from behind, then mines it directly in the case. I will turn my van mine, this is mine at the corner, we will check it here, but mine is less here, it is okay, we have to reduce it and mine is here, you have to put binary search here, you can do that. Let's see what I have to find out here, I have an array here and you have an array here in which the values you have are an array here in which the values you have are an array here in which the values you have are 88 and 10. Whatever is your target, they come here, so my From which location we have to find out, how does binary search reduce this array? In binary search, here we have a low which is your first question and here we have a high, so I have this. This will be low here and I will have high here which will be pointing to the most end position and I will have to do mid here first. Here in binary search, we first calculate the mid. There are six elements, on the third element you have to Here my A will go, then here this will be your mid here, after that now I will have to check here if your element is act made portion, if your element is mid position and it is smaller than your target, it is fine, meaning now. Here we have to check whether your element from the middle is on this side or your element from the middle is on this side, the target you have to find out is in your first half of D list or it is in your second half. In the half of D place, I put a check here that I am checking yours here, the element which is in my position here is 7, if it is mine, that means whatever is my target, it is mine. If it is right hand side then what will I do here in case I will set the law on mid plus van so here at this time my pay will be set here what I did here if my target is here on second half of D If it is in the list then I have made the first half of D student that there is no my element here, so in that case, I have set Pe Lo here, Mid plus Van Pe, now I will have to find Mid again, there are three elements made by you. He will come here, in this case I have come here, this is your low, this is your high and here this is your made, again you will check this condition here, what is yours at this time? Is it less than your 8? Okay, it is equal, so from this you will know that your element is in the first half of the D list, because now the list I have is this much left, this is yours. Made here, I am checking whether that element is on your left or that element is on your right. This will make it appear that your element is not on the right at all because yours is at right. That equals, you come here, in that case, what will I do here, I will set the high on my mid, I have set the high here on my mid, now take mine is here, I have mine here, I will calculate the mid also. I will go here and Madam, I am pointing at the same point, now I will check here whether my element which is at the middle and which is my element and automatic target, should it match that, okay so here. This will check that if your 8 < 8 is not at all that if your 8 < 8 is not at all that if your 8 < 8 is not at all 8 is your weight then my lower middle is pointing to the same element, this was my high here, okay now my high will also point to the same point here. Because according to the condition that I have here, if this condition is formed here where the left part is smaller then I will badhaunga the law. If the left part is equal or bigger then I will badhaunga the high here. In which case it is equal, so I increased my high, now what happens is that my low, high and made are pointing to the same element which comes here, so when this loop of mine will break. Finally the condition in search is that you keep running your loop until your low is less than your high. Here your low is equal to your high so your loop breaks here. And you will get the position of your first element. Here, the position of your first element is zero, one is three, so the value of your low at this time is also three, the value of your high is also three. It is three and your mid-key value is three and your mid-key value is three and your mid-key value is also three, so you have got three here, so you have got the first element. It is okay at this time, if this one gets a little congested on the hand, then I am here. If I recreate it once again, you will see one thing here that whatever is mine is here, at this time the high and mid are also here, but I have got the first position of my element here which is This is the third position here, so in this case, I will put the third position here in Era because now I have got the first position, now I have to find out my second position, okay. I have found the first position here, I have to find out my second position here, in that case I will have to run the search here one more time, here it will remain mine because we have this I came to know that in the list on the left, my element is not there. The element which is mine is on the right hand side because now if my element was on the left side, then instead of lock, mine would be higher here. And my lo is somewhere behind in this case, okay, whatever is my lo, is somewhere behind in this case, that means now I have come to know here that my element which is next is my lo here and this one. In the middle of the high, now my high which is set here will have to be set back here, my high will have to be set here and the calculation will increase again with my low and height in this case. I made mine here this will go to this last time I have set the condition that I have set if my element at mid is less give target if my less give is target then in that case I will set it to low here mid Plus van Now I will put the condition here if my element comes mid this less and equals tu target is my this condition will go if it is equals tu target then I will put loco made plus van pe dal here and what is the scene here that my Element jo hai aate mid wo mera equals tu target hai yahan pe aate mera equals tu aate hai so I will set lo here on my mid plus van pe loco lo at this time mine is here at lo mine at this time here a So the main condition is that till the time I have to run the loop, my low is less than the high, but here the low and high here are equal, so I have to run this loop here. Break will have to be done, my break has been done here at this time, the element that I will return, this position will be my return here, but now take mine is here, so out of the following, I will have to pay here in the mines van so that this is my Here on Britain, if you get five at this time, but here I have to pay -1, so that I -1, so that I -1, so that I return this condition here, so that my low here gets pay four, and here I get three. And four which is my index, I have to return it here which is given in your answers 3 and 4, so it will work like this, it is a lot of conjuring, okay, it is a lot of conjuring, I don't know how I explained such a long concept. Without going into the code, but it will be easy in the code, when you see it in the code, you will find it a little easier when you see things happening in the court. Okay, so first of all let's come to the code, what do I want here sir? First of all, I have to put your empty check here, this is the most important thing sir. You have to put this check of your empty Erica here, so for that sir you don't have anything here. Do whatever your name is, look here, I have a target, so I have to check the length here and if this length of yours here is equal to zero, then I have to return one here. Hey, the values in this are -1 -1, so Hey, the values in this are -1 -1, so Hey, the values in this are -1 -1, so I have to return them here. I am creating a new era here in which the values you will have here in which the values you will have here in which the values you will have here will be -1 and -1, so this is one corner of yours. There will be -1 and -1, so this is one corner of yours. There will be -1 and -1, so this is one corner of yours. There is a case here, we have been given a condition here, don't think, it can come from behind, so for that, mines van has to be returned here, so I have handled the one which was with the corner here, now binary search. I have to put it here, in binary search we have a gl here which is pointing to the first question like I showed you, there is a high which is pointing to the last position of Eric, which means namshot. Your length starts from zero, so here you have to enter -1, okay and absolutely correct, now here we have to -1, okay and absolutely correct, now here we have to -1, okay and absolutely correct, now here we have to reduce one here, if you want to run a search here, make it like I tell you, binary search then. This continues till your lower high becomes equal or bigger than it. Okay, so I have given the condition here that this Kalyug should be breaking till the time after this we come out of mid, okay. Made I am leaving here to get mid you can put here low plus high minus low. So here you can calculate your mate with this formula. I have already explained in this concept that why we are writing this code here and we are directly low plus high divided by you and us. Why are you not doing this directly, I have explained in the questions behind in the concept, if you want to find the middle then you can do it here by low plus height by 2, but why are we writing this here, okay why is this? Here we are writing Pay Low Plus High Mins Tu Divide by Tu, if you are following my old video where I had done then you will know why we are doing this, okay once again I Let me tell you, this condition of the husband is that it prevents the wait for you people. If you know the one who waits for us, his vote is of 32 beats. Okay, if I give you an example here, it is 32 beats. I would need a lot of space, there is a huge wait, there is 32 beats but you can wait here for 32 beats, no man, you can wait here, the expectation is 100 means you The maximum value that you can store in one wait is 100. Okay, now the support here is my low is 60 and my high is the support here is 80 and my support here is 60 and 80. If I want to get the middle, then if I do low plus high divide by you, if I do this here then what will it do to you, your pay here is 60 plus 80, yours will become 141, 140 is your 100, then this is the bridge. Which is your upper limit of the number of values that you your upper limit of the number of values that you your upper limit of the number of values that you can store in an integer, it has bridged the value, so this is the condition here, this is the condition, your integer wait is the overflow condition whereas What does this condition do? If you look here, what I am doing here is 60 plus and 80 - 660 / 2. So here you will 60 plus and 80 - 660 / 2. So here you will 60 plus and 80 - 660 / 2. So here you will get 60 + 20 / 2. Which is 60 plus get 60 + 20 / 2. Which is 60 plus get 60 + 20 / 2. Which is 60 plus 10 and here you will get A. 17 So look at the answer here, your answer is from both the cases, the medicine is given separately, the medicine of 6 and 80 is 70, but here you see that there is a condition of 100 which is not solved here. There is a condition of wait overflow here, it will not bleach here, even though here you are dividing by you later, but before dividing by you, here you are doing plus here, so this condition is there in your integer. If you are in floor condition, then never come here in such a way that you write directly here, low plus high and divide by you, it is okay, you always have to write like this, it is very important, see, this is a small thing which is asked in the interview. If there is a lot, then you should know this thing, after that you have to put the condition here which I was explaining to you just now in the explanation that if your aa element is, if its value is small, that means. If your element is in the second half then you have to set it as Made Plus Van Pay but if this value is equal to yours or in the first half of D best then you have to set it as High in your mid pay end. When this loop will break, then the first value at that time will be here, it is okay if any value does not come out here, like suppose this is here, it is okay, my target here is six. It is there, if you make it existing in me, then in this case, none of my value will come out here, meaning the value that is here will come out to me, now someone or the other will extract the value and give it to me, but the value that is here will not come to me. In the case, it will come out if I target here, if I can put a check here, if my Joe is by name and his lock condition is, if it is not equal proposal to my target, okay, here Joe, I have one Joe here. But I have the first one and it will come out, here I have three come out, now the name set is the third position which will be mine, that should be equal to my target, if it is not my target then it means this here is your target. If the Axis does not agree to this arrangement, then in case it has to be returned to me here under the condition of mines van bottle, then exactly what we had done above, here you have to do the same thing that you return from here. It is okay if you are doing -1-1, but if your condition here is okay if you are doing -1-1, but if your condition here is okay if you are doing -1-1, but if your condition here is not satisfied and the value you have got is equal to your target, then the first value is mine here. In that case, you can make one here because I have to return one here, so I have created one here in support and in two questions here, I have taken your here and Here the first position of the expected result will come from inside the low, I have got it returned here, I hope it will be so clear, now it is here, now I have set it here, now lo, my middle of D is listed there. My high is also there at the same place, so my high will have to be shifted back to your end of D list, sir, so here I have shifted the high from there back to your end of D best and put it in the case. We will have to run the binary search you have here once more, but this time your condition will be like this. What did I tell you that in this condition, you will have to do one thing this time that your element here will be Your pay can also be equal to the target. Okay, and in that case, whatever is your take here, will overtake medplus van pay, but I will have to come back after taking it to the minus van, so when you have the pay value here, when your If this happens to Lo then you will have to do Minus Van from Lo here and both your values have come here, and both your values have come here, and both your values have come here, you can return the result here. Well, if I show you here then it will work perfectly, this is the correct answer. After submitting, if I show you here, it should run absolutely perfect. You see the runtime here, give the posture from zero milliseconds, 100%, so Java give the posture from zero milliseconds, 100%, so Java give the posture from zero milliseconds, 100%, so Java online submission for the first time of elements in unsorted. Hey, it is going absolutely great. Hope you have understood and this is it, you can do this question here, you can check out the rest of the questions, if you have understood the question, you liked the video, like the video, subscribe to the channel, Next Video with Sam Andar Late Question By
|
Find First and Last Position of Element in Sorted Array
|
find-first-and-last-position-of-element-in-sorted-array
|
Given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given `target` value.
If `target` is not found in the array, return `[-1, -1]`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[5,7,7,8,8,10\], target = 8
**Output:** \[3,4\]
**Example 2:**
**Input:** nums = \[5,7,7,8,8,10\], target = 6
**Output:** \[-1,-1\]
**Example 3:**
**Input:** nums = \[\], target = 0
**Output:** \[-1,-1\]
**Constraints:**
* `0 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `nums` is a non-decreasing array.
* `-109 <= target <= 109`
| null |
Array,Binary Search
|
Medium
|
278,2165,2210
|
1,022 |
welcome to september's leeco challenge today's problem is sum of route to leaf binary numbers given a binary tree each node has value 0 or 1. each route to leaf path represents a binary number starting with the most significant bit for example if the path is 0 1 then this is going to be represented by 0 1 in binary which equals 13. now for all the leaves in the tree consider the numbers represented by the path from the root to the leaf and we want to return the sum of these numbers so traversing our binary tree isn't the hard part here it's passing along our values and at the very end converting that into a number and adding it to some variable so let's think about how we could do that we can do a typical pre-order that we can do a typical pre-order that we can do a typical pre-order traversal and just write a function that's going to travel our tree and pass along our path in a string format as we go along and once we hit a leaf we'll convert that to a number and we'll add it to our total so what to do there i'll create a function i'll call that pre-order and i'm going to pass into pre-order and i'm going to pass into pre-order and i'm going to pass into node as well as a string and we'll just call that binary now i need to initialize a variable here call that self.total and this is going call that self.total and this is going call that self.total and this is going to be that variable kind of like a global variable outside of our pre-order traversal outside of our pre-order traversal outside of our pre-order traversal and it's going to be the typical thing where we say if not node just return then we will travel to the left and we're going to have to pass along our binary plus the node's value as a string and this is going to give us the path in order like we append it same thing here we do a pre-order but to same thing here we do a pre-order but to same thing here we do a pre-order but to the node.right the node.right the node.right the same value we pass along the binary to know that value finally once we get out of this we want to check to see if we had a leaf so if not no dot left and not no dot right this means we're at a leaf right so then all we need to do is take whatever binary path that we've traversed on and convert that to an integer what you'll do is you can use the integer function and pass along 2 which makes it binary and just add that to our self total once we finish that we should just be able to return our self total so what i'll do is run our pre-order on the what i'll do is run our pre-order on the what i'll do is run our pre-order on the root passing a blank string and then return the self.total the self.total the self.total so that's it's pretty straightforward make sure that works and that's it so we're just traversing our tree pre-order traversal and tree pre-order traversal and tree pre-order traversal and adding our total binary number to this self variable at the very end now you could avoid doing this sometimes it's considered cheating to initialize like a variable outside so to do that we'd have to make it like more of a recursive thing so what you could do then is still do the same format but once we add a leaf we're going to return this value otherwise we're going to return whatever is the sum of these two and we have to make sure that we return zero here otherwise we'll get some sort of error and if we did this then we just need to return the result of this function right so let me just make sure that works as well there we go so as far as time complexity goes believe it so then with what of h space complexity which is the height of the tree there's various ways you could do this you could also use a q but the logic of it would pretty much be the same and yeah there's probably a lot of approaches but it's always going to be some variation of this where we have to travel the entire tree and store the sum of the um root 2 leaf paths all right so that's it thanks for watching my channel and remember do not trust me i know nothing
|
Sum of Root To Leaf Binary Numbers
|
unique-paths-iii
|
You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit.
* For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`.
For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return _the sum of these numbers_.
The test cases are generated so that the answer fits in a **32-bits** integer.
**Example 1:**
**Input:** root = \[1,0,1,0,1,0,1\]
**Output:** 22
**Explanation:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
**Example 2:**
**Input:** root = \[0\]
**Output:** 0
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `Node.val` is `0` or `1`.
| null |
Array,Backtracking,Bit Manipulation,Matrix
|
Hard
|
37,63,212
|
146 |
hello friends today less of the LRU cache design and the employment a data structure for leads to recently used her cache it issued a suppose has a following operations dirty and put get a key can as a value will always be positive of the key if the key exists in the cache otherwise return negative one put a key value set or insert the value if the key is not already present when the cache which is a capacity issue during validates the Lisa recent use item before inserting a new item the cache is initialized with the politic capacity so we have to try to use of them in Big O one time capacity so let's see how it works we first to initialize a capacity over to cache will first put of this one want to the cache then we put a - - because this is the then we put a - - because this is the then we put a - - because this is the least recently used so when we put it into the list of recently user is this one right because we currently use this tube and then we get one is it also or use so now the lister isn't it used her element is true so when we try to put it is three we already reach our capacity so we need to remove one element because L you see we reach in a 1 here and this the lister is in a user element is true so we remove these two and the puter this is 3 in our cache and then we get you we return negative 1 because in not in our cache now we put 4 for the same we already reach our capacity so we needed to remove one element and we can see we lost visitors 3 so we needed to remove this right and we get won't remove nectar we return that to wall we get a story we get for we can get the value so how to solve the problem let me think about this bigger or wrong time complexity operations you may think about a double e Ling Lister because we can remove an odor when we know they're trees when we know the Noda because well again the current node that we already have the information of its previous node and its next node we just simply changes this link to remove these current node so the time complexity speak-o one also you may time complexity speak-o one also you may time complexity speak-o one also you may sing about the hashmap because in idea you know I mean the hashmap generally speaking we can't give the time complexity over the pootie and the contents it hashmap in a big old one so we can assume that the time compressed these big all right so why do we need a hashmap because you see this actually is a notoriety we have a key we have a value so we need a qu quickly of know the node because the you are removing double link blister just on a condition that we know the nodal knowledge as a key so we need a use hash map to save every key to its Noda we map a key to the node so we can quickly katsudon order the node ok so let me think about some operations I want to remove another average talked about before right so we need when we try to remove a node which means we try to add a new node that's there compare capacities rich is reached Sonia to remove an older the list arisen used to note or get exist know why because when we try to get an older we actually need a true moves there are no true der Heyden right to the like to the head of the queue so we refer to remove the nose then we add a new note in the head of the queue and I want to add a new node we know the key and the value so we can and you know right we first together next witchy the proof is originally next of the Hader then we never hidden exit to the new node and I know the next it should there originally next over the head and then we know the print to the hate and the next trip to there note okay for links change foldings and do not forget every time we need to update the map when we add the new note that we add we should add that to the note or to the map and the way when we remove a node we should also remove that from the map okay listen remove the tail why because way to you know reach the capacity we need to chew remove the list her used to know which is in the tail to the Q so if first together the norther wishes their tail proof and you also get it supreme or then approve next to the tail and a tail privy to the pre so basically we can just a code this function remove function okay so let's see this true function want to put a key in a vote if you is key already exist so we should therefore to remove the key and add there to there hate even though is this I just added through their head if we need to guess the key if we know use this a return natural one if already exists we'll remove the key and I add that choose ur head of the queue so let's see this example okay this is the at first though we have this a hater tail actually this is these are true dominoes hate and tell okay they link together and then we won't you put a long one right we need to change this link to write it not exist we add their chooser hate and put out to the matter which is why map to the node and we it becomes this they'll put a to it also know exist bad there to the hater there will be qu + 1 0 ok we add it to the map will be qu + 1 0 ok we add it to the map will be qu + 1 0 ok we add it to the map they don't get one yeah we have it so we return it but at some time when you remove oh we didn't move that true the hate so we remove one and a hater this one ok now in the to put is 3 it already reaches capacity so we remove their lister you recently used to know she is a true right then we added this 3 and we updated this map we removed it to an ad in history 3 they will get your return active one will put a 4/4 right return active one will put a 4/4 right return active one will put a 4/4 right we are there to the head anyway remove sir tell because it'll reach is capacity we remove this one ok and get one return active wrong yes three returns 3 adjust the needed to move it straight to the hater remove an ant hater ok Sam remove Ella hit so now let's write the code I hope you already understand what first where neither writes a note it had a key also they had well and their priests note next constructor note in turkey interval he got you que vão a coat UV ok therefore in this area cache we need a hater we also need a tail we also need a map which here the keys integer there value is a node we also need our inter capacity we also eat needed a size okay so we needed to initialize it new node we put a 0 actually they don't matter because we actually do not use this value and their tail new node 0 okay do not forget you link them together hey the next you go to tell pretty coat you hate okay then this stock capacity II got your capacity size equal to 0 okay so we to get the key right if they're map if the map contains data key it will contain the right so we need a first remove that's know right and add their hate this kid but we also need it's Val right so now note ecoute your map get their key we say remove that her note and then add it to the hate there will be no - Wow ok there will be no - Wow ok there will be no - Wow ok the do not forget to return there know though if it done exist return negative 1 ok so put her a new note if the map already contains this key already content we needed to remove the key and to the same thing aerate to the hate key and a value if that contains just add hate key variable okay so now less employment that they remove we just needed a keep remove is a key we were first needed the note current node which is map gets a key then we you see that we detonate pre linked to the next so there will be pre vehicle to occur please no next it code to occur next then proved on X equal to next a previa pre you just remove their note sighs - - do not forget to remove that sighs - - do not forget to remove that sighs - - do not forget to remove that from the map removed the curl no it will be the key okay we also needed there at the hate we needed a key and the value this is the new note key and value we add a new note we use this actually we change of all links right so we first needed up original next of the head next there we net hated the next to the current node no the next to the previous next there next pre-echo previous next there next pre-echo previous next there next pre-echo to the note the proof to their hate okay then the size should a + + right if okay then the size should a + + right if okay then the size should a + + right if the come if the size is greater than the capacity we needed to remove the last term which is the list to reason the user node we get that the node will be notre ego to tell truth right okay we remove note keep we remove that we call this function okay this seems I have fish yeah okay let's continue their network has some problem that's wrong it mmm okay the node um oh sorry I already uses this notice said there should be pretty tail okay there will be pre tail non pointers exception let's say what's wrong yeah we already knew that oh I know because I haven't herb initialized a hashmap sorry for the problem okay thank you for watching see you next time
|
LRU Cache
|
lru-cache
|
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**.
Implement the `LRUCache` class:
* `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`.
* `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`.
* `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key.
The functions `get` and `put` must each run in `O(1)` average time complexity.
**Example 1:**
**Input**
\[ "LRUCache ", "put ", "put ", "get ", "put ", "get ", "put ", "get ", "get ", "get "\]
\[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[4, 4\], \[1\], \[3\], \[4\]\]
**Output**
\[null, null, null, 1, null, -1, null, -1, 3, 4\]
**Explanation**
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // cache is {1=1}
lRUCache.put(2, 2); // cache is {1=1, 2=2}
lRUCache.get(1); // return 1
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
lRUCache.get(2); // returns -1 (not found)
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
lRUCache.get(1); // return -1 (not found)
lRUCache.get(3); // return 3
lRUCache.get(4); // return 4
**Constraints:**
* `1 <= capacity <= 3000`
* `0 <= key <= 104`
* `0 <= value <= 105`
* At most `2 * 105` calls will be made to `get` and `put`.
| null |
Hash Table,Linked List,Design,Doubly-Linked List
|
Medium
|
460,588,604,1903
|
153 |
hey guys welcome back to the channel today we're going to be solving the code 153 find minimum in rotated sorted array keywords are rotated and sorted it also asks us to do it in log in time and i'm going to show you guys three different ways of doing it the first one is kind of like a cheat method and it's just simply okay it's simply to return a mean of nouns okay this is probably not how the problem wants us to solve it but it works okay i think it works at least okay bam we're faster than six percent it works it but this doesn't show we truly understand what's going on although this is a login algorithm it doesn't show again a second way to solve it also a cheap way is to sort the array okay let's go back the problem says it's a sorted array okay second waste is sorted it's sorted and rotated so we just want to sort it again okay and then after starting it we want to return the first index okay this should also work bam okay still faster than just six percent terrible timing very good space because we're really not creating any variables just simply one instruction so um this works but again it doesn't show we understand the algorithm okay so the last way to solve it okay every time you see log n you want to think binary search okay and what is a binary search let's just go and try to at least kind of get a rough idea of what this problem is asking for okay i'm gonna use the example they gave us okay example one says gnomes okay let me get a black color it says nouns some nouns kiss a rotated sorted array okay so simply this array was simply just this it was simply one two three four five and then it got rotated to the left and go rotated to the left by two okay which is why these two guys went around to the back okay and that kind of led us to this array okay so now we want to solve so just to picture what this looks like okay if we were to draw a graph a regular sorted degree would look something like this okay this is n each element of the array is kind of increasing but this array looks something like this okay he's increasing to a point where he drops starts back from zero and keeps going okay it looks something like this because he was first sorted and then he was rotated okay so from this graph we realized there's a point where he's high and then he suddenly drops low at the next index so that is what this problem is asking us to find that point where that happens which in this case is right here okay between five and one well how do we find him how do we get to that point simple we start with two pointers a left pointer which is just the index zero of the array and the right pointer which is just the last index of the array which is length minus one okay now we need a midpointer which is just equal to our left plus our right pointer divided by two okay in this case it's gonna be here midpoint so we just have to ask ourselves a question is numbs okay norms of mid is he greater than norms of r in this case numbers of meat is five okay it's five greater than two in this case the answer is yes so we know the point we're looking for the inflection points where it switches from high to low is between norms of meat is between mid and it's somewhere between mid and r okay so we can completely ignore this point completely ignore this side and just move l to right here okay completely ignore the side so now this is our new vector we're searching okay now we have to search this guy to find the point and obviously we're going to find this right here and return that so again i thought this kind of made sense if not hang in there we're gonna solve it once you see actual code is actually gonna make sense okay so i'm gonna go ahead and minimize this guy okay so what do we wanna do like we said we wanna initialize two pointers left and the right pointer okay so l comma r so left and right point is equal to zero comma length of nums minus one okay we have all left and right pointers okay then wow okay l is less than r okay oh it's all binary searches follow this same pattern pointers then a while loop okay always while l is less than r standard okay we want to calculate our mid again like we said our midpoint is just halfway apples are divided by two okay so made r l 4 divided by 2 just in case there's decimals so we can get rid of the decimals okay because index indices of arrays don't have decimals okay if again the same question we were asking right here if mid okay is greater than our same even arms or mid okay let's go in the norms of r okay what did we do okay what we did was we just left i'm just gonna go ahead and put both of them on the same okay what did we do okay we just left shifted right we just said l equals mid plus one okay now uh else case else this means norm of mid is not greater than this is either less than or equal to norms of r in that case we're just gonna say r equals mid just in the case where he's equal another less than i'm gonna say it's equal mid and not move it by one okay then if we go through this completely we wanna return knobs of l which is going to be our lowest number so this looks correct i'm going to go ahead and run this first see if it's accepted and then submit it okay good for some reason we didn't do too good on the speed but again this works this is a different way of supplement okay we know it works okay so one step further just to kind of picture what's going on so this is the exact same function we usual in a lead code okay i just created a driver code to call it so we can kind of visualize what's going on and see what's happening okay so as always we initialize we define our array initialize norms called it called i'm sorry call the function we initialize the function and call the function okay keep in mind we're passing the same nums into the function so that's why it's pointing the same address in memory okay so next we're gonna define our l and our r okay l is zero which is the first index like we said r is four which is less than these are just our pointers okay then we're going to define mid okay mid is just halfway l plus r4 plus zero divided by two okay which is two so now if norms of mid is greater than numbers of r so in this case numbers of mid is numbers of two which is five which is greater than numbers of r which is number four which is two obviously five greater than two so we're going to move l should move to mid plus one so minus two l should move to three pretty much the same as you can see l is three same as we explained on paper okay then it's gonna go through the loop one more time okay so now we're looking between three and four okay now we're going to calculate our meat our meal is going to be 3 plus 4 7 4 divided by 2 seven 4 divided by 2 just 3. so meat is going to be equal to our l okay and in this case it's not greater okay so we're just going to skip and return l so we're going to return norms of l but that's it for the video guys i hope it was helpful and i'll see you guys in the next one
|
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
|
820 |
Hello Guys Welcome to Your Consideration Questions for Trading Video then subscribe to the Page if you liked The Video then subscribe to The Amazing That Aditya And In The mid day meal will start from do and boys celebrate valentine wedding valency subscribe liquid subscribe ameer vote mange more likely to video subscribe vivarvar hai to after starting the way will look like subscribe and middle nov22 512 MB Vidron in the middle of mid day subscribe The Video then subscribe to The Amazing Virwal Dho Lein - Subscribe Appointed Virwal Dho Lein - Subscribe Appointed Virwal Dho Lein - Subscribe Appointed A Notice To Date Will Have Not Enough Means That Every Twelve Was Not Sorted Will Give subscribe to the Page if you liked The Video then subscribe to the Index After and weakness to find the best wishes comes between Dheer and Sid subscribe Video subscribe and subscribe the Channel And subscribe The Amazing spider-man with avoid doing method to remove from the spider-man with avoid doing method to remove from the spider-man with avoid doing method to remove from the channel subscribe time from difficulties and media from time it is also known Indian residents After Idioms Subscribe Mez Thi Aur Mez Par Thursday Sea Width Non Rotting Hormone Impatient Video Subscribe Ishwar Hai Ki Aisa Parameter Needs To Provide Latest So They Can Convert A Plu Election Withdrawal Duplicate Suvvi subscribe Video Channel and subscribe this Video give WhatsApp Subscribe Loot Subscribe The Project Will Get All The Sufferings Of Spring And It Will Give Way To Find The Length Of The President Mid Length Belt Length Thursday Subscribe To Danny Data Success With Specifically Designed To Solve Problems Subscribe Withdraw Clear Within Subscribe Must Subscribe Last Volume of Me Into Its Strength in River for the Means from Right to Left subscribe And subscribe Video Staff Will Not for the Freud Amazon Video Subscribe Must Observer Appointed Nodal New Branch Subscribe Walking Tours in English Quid Nothing So Bayan subscribe And subscribe The Amazing Appointed From Subscribe New Branch Appointed Subscribe Button Trend President Appointed Do Subscribe Pimple Removal And They Would Mean That To The Number Note subscribe this Video give and Video subscribe this Video Please subscribe And subscribe The Amazing Ko In Tohni 200 Vid U Hai Na Mintu Ad Result Brigade Half Inch Width Words Will Help That Mid Town Sunshine More Subscribe Must Subscribe And Subscribe To This Video Channel And It's Not Vidron Subscribe In A Reader Website Create A New Branch Which Will E Do Not Want To Find Hidden From Right To Left Subscribe - Sid Appointed Observer Left Subscribe - Sid Appointed Observer Left Subscribe - Sid Appointed Observer Take Off The Way Straight Midcap Index - 1 Index - 1 Index - 1 Patrol U Can Go From 0524 Check The Value Of No Did Not Mean That You Will Love You All Subscribe Indian Co Like Made In The Art Of This Minimum Balance Coding Making You don't know you will not take off the Caribbean subscribe our Channel subscribe Video not to create a new level posted in half an hour but you know the difficulty level appointed nodal point where in the similar subscribe you will not withdraw appointed always need not avoid create a New Trust Was Created Str Ki Neetu Add Length Of The Best Friend Plus One Otherwise Mist Return Not Have Created A Liquid Final Result To A Sweet Line Successfully Lakshmi Dutt The Secret Submitted Successfully Vitamin subscribe to the Page if you liked The Amazing spider-man happened Is
|
Short Encoding of Words
|
find-eventual-safe-states
|
A **valid encoding** of an array of `words` is any reference string `s` and array of indices `indices` such that:
* `words.length == indices.length`
* The reference string `s` ends with the `'#'` character.
* For each index `indices[i]`, the **substring** of `s` starting from `indices[i]` and up to (but not including) the next `'#'` character is equal to `words[i]`.
Given an array of `words`, return _the **length of the shortest reference string**_ `s` _possible of any **valid encoding** of_ `words`_._
**Example 1:**
**Input:** words = \[ "time ", "me ", "bell "\]
**Output:** 10
**Explanation:** A valid encoding would be s = ` "time#bell# " and indices = [0, 2, 5`\].
words\[0\] = "time ", the substring of s starting from indices\[0\] = 0 to the next '#' is underlined in "time#bell# "
words\[1\] = "me ", the substring of s starting from indices\[1\] = 2 to the next '#' is underlined in "time#bell# "
words\[2\] = "bell ", the substring of s starting from indices\[2\] = 5 to the next '#' is underlined in "time#bell\# "
**Example 2:**
**Input:** words = \[ "t "\]
**Output:** 2
**Explanation:** A valid encoding would be s = "t# " and indices = \[0\].
**Constraints:**
* `1 <= words.length <= 2000`
* `1 <= words[i].length <= 7`
* `words[i]` consists of only lowercase letters.
| null |
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
| null |
1,189 |
section 1189 so this is the maximum number of balloons so given a string text and you are find the characters or texts will form as many as a word balloon as possible but each text can only use once okay so for example at least you can from the balloon and this you can from the two balloons okay i think this problem is you have many ways to solve it right but i guess one way it's very easy said we can just count how many because we can only use one uh letter right we can only use one character one times right so i can count the word b and count the number a and then count the number of l right but there's a two l here right so i need to divide by two and count the number of all divided by two and count it and so we have five of them right but uh only once uh five of them must exist right must be both uh if five of them are exist then there can uh there can produce one right so basically just return the minimum of it right just return the minimum of it uh well we give your answer okay uh yeah i think that's it okay so we can submit okay and i will see you guys in other videos but uh be sure to subscribe to my channel thanks
|
Maximum Number of Balloons
|
encode-number
|
Given a string `text`, you want to use the characters of `text` to form as many instances of the word **"balloon "** as possible.
You can use each character in `text` **at most once**. Return the maximum number of instances that can be formed.
**Example 1:**
**Input:** text = "nlaebolko "
**Output:** 1
**Example 2:**
**Input:** text = "loonbalxballpoon "
**Output:** 2
**Example 3:**
**Input:** text = "leetcode "
**Output:** 0
**Constraints:**
* `1 <= text.length <= 104`
* `text` consists of lower case English letters only.
|
Try to find the number of binary digits returned by the function. The pattern is to start counting from zero after determining the number of binary digits.
|
Math,String,Bit Manipulation
|
Medium
|
1070
|
609 |
Hello Hi Everyone Welcome To My Channel Night Fall Bilk Problem Says Problem Court Appeared In Amazon Microbes Interview Solve This Problem Statement Of Account In First Directly And Indirectly Or Directly From Multiple Files From The Tak Considered Upon Its Mode On * All Considered Upon Its Mode On * All Considered Upon Its Mode On * All World Wide This Trick 2592 Returns The Amazing Loot-Loot Custom Subscribe 12345 Amazing Loot-Loot Custom Subscribe 12345 Amazing Loot-Loot Custom Subscribe 12345 Pieces Products This Schezwan Sauce Subscribe Previous Videos 1515 E Subscribers How First To Forensibly Content Similar For Years Which Contents Back to File Name Is This 23545 Subscribe 508 Fifty Years Has Made Hair Oil Dictionary in Python Fennel Government Will Clear History Loot String Hai Haldi List Of Spinner Sunil Stopped Resisting Contain All Work Panipat Police Qualified Password Basis Awadhesh Activate Use First Service Will You Know How To Pass Through All Departed Soul String In Python Food Processing Speed When Scooter Subscribe Directly From Multiple Files With valid is behind the serious is point mintoo 110 open printers and considering and sacrifice straight forward * * * avoid the straight forward * * * avoid the straight forward * * * avoid the ajmer splashtop in the first president for speech for controlling power to face sexual is the first new cars in 187 submit solid body solid one husband and like youtu.be torch light not made any specific playlist office 10mb text to make ice cream subscribe string into a iss sauda se bhi collect collectors pradesh collectors tourist connected to me to so let's see what is the time complexity of complexity can we know Problem No Problem Karo Movie Pollok Problem Which Can Answer First Problem Flight Imagine You Are Governor Real Life System How Do Subscribe My Channel This Decision Is Any System For Finding It Very Much Me Aa Specific And Singh Bir Viewers And The President Difficult Subscribe To Most Come Question Is Scientific Content Of The File In The Debate So In Los Angeles How To Give A Modified On 16 Se Right And Left For Example subscribe The Channel Se Able To Enter So Her Win The Left Or Right Intent Of This Channel Subscribe Our Channel Like This Queen Hot Vrindavan Haft Liye Light Weight Something Pre Vitamin Complexity of what is the meaning of this country is the structure for every time e you go to Ahmedabad Din Pandey Slide basically creating also has spoiled times and completed in the time comes alive with how to make The quality of standard size chest size problem is the solution to the problem subscribe thanks for watching
|
Find Duplicate File in System
|
find-duplicate-file-in-system
|
Given a list `paths` of directory info, including the directory path, and all the files with contents in this directory, return _all the duplicate files in the file system in terms of their paths_. You may return the answer in **any order**.
A group of duplicate files consists of at least two files that have the same content.
A single directory info string in the input list has the following format:
* `"root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content) "`
It means there are `n` files `(f1.txt, f2.txt ... fn.txt)` with content `(f1_content, f2_content ... fn_content)` respectively in the directory "`root/d1/d2/.../dm "`. Note that `n >= 1` and `m >= 0`. If `m = 0`, it means the directory is just the root directory.
The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:
* `"directory_path/file_name.txt "`
**Example 1:**
**Input:** paths = \["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)","root 4.txt(efgh)"\]
**Output:** \[\["root/a/2.txt","root/c/d/4.txt","root/4.txt"\],\["root/a/1.txt","root/c/3.txt"\]\]
**Example 2:**
**Input:** paths = \["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)"\]
**Output:** \[\["root/a/2.txt","root/c/d/4.txt"\],\["root/a/1.txt","root/c/3.txt"\]\]
**Constraints:**
* `1 <= paths.length <= 2 * 104`
* `1 <= paths[i].length <= 3000`
* `1 <= sum(paths[i].length) <= 5 * 105`
* `paths[i]` consist of English letters, digits, `'/'`, `'.'`, `'('`, `')'`, and `' '`.
* You may assume no files or directories share the same name in the same directory.
* You may assume each given directory info represents a unique directory. A single blank space separates the directory path and file info.
**Follow up:**
* Imagine you are given a real file system, how will you search files? DFS or BFS?
* If the file content is very large (GB level), how will you modify your solution?
* If you can only read the file by 1kb each time, how will you modify your solution?
* What is the time complexity of your modified solution? What is the most time-consuming part and memory-consuming part of it? How to optimize?
* How to make sure the duplicated files you find are not false positive?
| null |
Array,Hash Table,String
|
Medium
|
2079
|
1,566 |
Hello hello everybody welcome to my channel its all digit code problem detect pattern offline tempted and mota is in this problem has given address of no individual are and how to find the length of david k and subscribe button and bell multiple times and the subscribe to r Feed subscribe to this is true for so special also example1 and a length of power pattern should be one and come three times solve and subscribe here and look for the pattern lock multiple times subscribe button check it airtel sim and width pores total three elements of Three Not Three Fatty Acids Vitamin C We Need Two Subscribe Withdraw From What is This is a very sick bean as it is active and it takes only 2 and so they can return proof hindi example ground fennel pattern history again but btu subscribe this is not remember and subscribe the channel been written for you will solve this problem solving problems in the number of voters will create a block elements class element subscribe must subscribe for elements and subscribe building and channel subscribe must stream and Something ki pintu the happy shades aur samriddh check in the middle subscribe thanks for watching this video subscribe this channel se paun inch to 10 shyam subscribe share aur subscribe hua hai next to check three pattern of length 272 safal will start from where will be late call Eye Element And Vikram Ped Pattern More Plus Elements In This Will Keep Away From Someone Will Update In This Element Subscribe To A I D S Every Time Also Checked Before Account Basically Account Figures Were Taken From One Place So They Can Check Effect Country 270 Veer and block element multiple number and then subscribe and increase in the company will reach from this point to subscribe this Veer Vikram Main 10 Gram Samhil Start Again From The Hero And Always Keep Continue Till I Plus Him Because They Are Considering Looking Ahead of elements class 10th subscribe channel directly share with ur very from over 250 to my channel subscribe our video 10th 12th ke subscribe the channel subscribe ki shatru samriddhi court a height is akshar so what is the time complexity of resolution is jasbir trading govardhan reddy Open and Displaced Account Thanks for the solution hit the like button and subscribe the channel thanks for watching a
|
Detect Pattern of Length M Repeated K or More Times
|
check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence
|
Given an array of positive integers `arr`, find a pattern of length `m` that is repeated `k` or more times.
A **pattern** is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times **consecutively** without overlapping. A pattern is defined by its length and the number of repetitions.
Return `true` _if there exists a pattern of length_ `m` _that is repeated_ `k` _or more times, otherwise return_ `false`.
**Example 1:**
**Input:** arr = \[1,2,4,4,4,4\], m = 1, k = 3
**Output:** true
**Explanation:** The pattern **(4)** of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less.
**Example 2:**
**Input:** arr = \[1,2,1,2,1,1,1,3\], m = 2, k = 2
**Output:** true
**Explanation:** The pattern **(1,2)** of length 2 is repeated 2 consecutive times. Another valid pattern **(2,1) is** also repeated 2 times.
**Example 3:**
**Input:** arr = \[1,2,1,2,1,3\], m = 2, k = 3
**Output:** false
**Explanation:** The pattern (1,2) is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times.
**Constraints:**
* `2 <= arr.length <= 100`
* `1 <= arr[i] <= 100`
* `1 <= m <= 100`
* `2 <= k <= 100`
|
First extract the words of the sentence. Check for each word if searchWord occurs at index 0, if so return the index of this word (1-indexed) If searchWord doesn't exist as a prefix of any word return the default value (-1).
|
String,String Matching
|
Easy
|
2292
|
1,020 |
hello guys today we are going to see the lead code question 1020 that is number of En Clips here we are given M cross n binary Matrix where zero represents a C cell and one represents a land cell that means these all are C or water and one all one or land a move consist of working from one land cell to another adjacent land cell or working of the boundary of the grid so we can travel the boundary of the Grid or from one land cell to other land cell we have to return the number of land sh for which we cannot work up the boundary of the Grid in any number of moves that means we cannot move from zero to one and if any of the one is found in the boundary in which we can Traverse then we can do the BFS or sorry DFS and cover the depth then to how many number of one we can um reach from the boundary that number of ones we can cover and the r number of ones we will not be able to cover so we have to count the number of ones that we will not be able to cover so let us see the code of the question so here is the code of the question first uh it we have to Traverse the boundary and check whether one is present or not then we have to uh TR uh call the DFS function to check the further ones present and first n is equal to grid size that is number of rows this will give number of columns and we have to Traverse the Traverse uh the n that is all the row and each of the row all the columns are checked if any of them is one then we have to call the DFS function for i j and the same for then we have to make the J M minus one that is we will raise the last column and we will check whether one is present or not if is it is present as we are traversing on the uh boundary so First Column we have to travel and the last column we have to travel if it becomes one then we have to call the DFS function then we have to start Jal to z less than M then j++ and we have to make similarly I then j++ and we have to make similarly I then j++ and we have to make similarly I equal to Z and G if grid i j it becomes one then we have to further call the DFS function then we have to check for the last row um last column and last row then if the same thing we have to it is basically the traversing all the uh four boundaries then we have to count the number of ones the finally we will get from after making we have to all we have to make all the ones zeros after making all the on zeros and we'll be leaving uh with we will be left with the ones that counts of ones we have to return so this will the DFS function if I less than Z or I greater than equal to row the same and if grid i j is zero then we have to return otherwise we have to make that grid as that will be previously if this condition will not be satisfied it will be previously one we have to make it zero and call the DFS function on all the direction I + 1 will be going below the direction I + 1 will be going below the direction I + 1 will be going below it is above this is right and this is left so all the traversal is done and we have to return the final count thank you
|
Number of Enclaves
|
longest-turbulent-subarray
|
You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell.
A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`.
Return _the number of land cells in_ `grid` _for which we cannot walk off the boundary of the grid in any number of **moves**_.
**Example 1:**
**Input:** grid = \[\[0,0,0,0\],\[1,0,1,0\],\[0,1,1,0\],\[0,0,0,0\]\]
**Output:** 3
**Explanation:** There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.
**Example 2:**
**Input:** grid = \[\[0,1,1,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,0\]\]
**Output:** 0
**Explanation:** All 1s are either on the boundary or can reach the boundary.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 500`
* `grid[i][j]` is either `0` or `1`.
For i <= k < j, arr\[k\] > arr\[k + 1\] when k is odd, and arr\[k\] < arr\[k + 1\] when k is even. OR For i <= k < j, arr\[k\] > arr\[k + 1\] when k is even, and arr\[k\] < arr\[k + 1\] when k is odd.
| null |
Array,Dynamic Programming,Sliding Window
|
Medium
|
53
|
205 |
hello guys myself Amrita welcome back to our Channel techno Siege so in today's video we are going to discuss lead code problem number 205 that is isomorphic strings so let's get started let's first understand the problem given two strings s and t determine if they are isomorphic two strings sntr isomorphic if characters in s can be replaced to get T so in the example you can see we have been given two strings one is s and another one is T so we need to check whether both the strings are isomorphic if yes then we need to return true otherwise we need to return false and how we are going to determine whether both the strings are isomorphic if each character in the S can be replaced to get T for example here e has been replaced with a so if e occurs in string s again it should be replaced with a itself for example G is replaced with d so another G also will be replaced with d itself so that means the output is true in another example you can see F has been replaced with B that is fine o has been replaced with a that is also fine so another o is replaced with RS so that means it is not isomorphic because 1 o has been replaced with a and another o has been replaced with r so that's why these two strings are not isomorphic so that's why output should be false in this case now let's understand how we are going to solve this problem so let's take the same example one string s is egg and another string T is ADD so that means e mapped to A and G is mapped to d right so that means we have to check the mapping if all the characters in string s are mapped correctly to the string T then that means these are isomorphic strings otherwise they are not ISO isomorphic strings so how we are going to map this so whenever you have to map any keys to the values we can use hashmap in Java hashmap is basically a data structure in Java in which each index has key value pair for example if I am taking hash map in this case I have to map character to character so we can take hash map of character and character in which we are going to map keys to the values we'll take the characters in string S as keys and the characters in string t as values so when we are scanning the string s so we'll see that character e right so we are going to put in the hash map e as key and a as value so let's say this is one pair and then when we are moving to the next character G we are first going to check whether that key is already there in the hash map it is not there so in that case we are going to put that key and the corresponding value as D so now move on to the next character G again so we are going to check whether that key is already there yes that key is already there when that key is already there we are going to check whether it is mapped to the correct value or not that means we are going to check whether G is map to d s g is mapped to D so here we can see that all the values in the string s are mapped to correctly to the values in the string T so that means we can say that these are isomorphic strings right let's take another example in which both these strings are not isomorphic let me remove this so let's take the strings as Foo and bar right Foo bar so when we are mapping the values so we'll see that F let's map it to B right move on to the next character o is not there already in the hash map so put OS key and value as a right so when we are moving on to the next character oh we'll check whether that key is already there in the hash map yes it is already there in the hash map then we are going to check whether it is mapped to the correct value here the values R but here the value is a so that means it is not mapped correctly to the value so that means we can say that these two strings are not isomorphic and we can return false so this is how we need to solve this problem now let's write a solution for it so this is our class that is isomorphic strings now let's write a method that would be public static and Boolean since it is going to return true and false and it will expect two inputs that is string s and string T right I'm sorry let's take the name as well isomorphic so now let's take one map to store the key values pair and both key and value should be character right let's take the name as hm new hash map character comma character so now we are going to scan all the characters in The String s less than s dot length I plus then first what do we need to check whether that key is already there in the hash map so if hm dot contains key so contains key will check whether that key is already there in the hash map so what is the key s dot carrot it index I and then we need to check whether the value for that corresponding key is equal to the value in the string t h m dot get s dot carrot I that means the value is equals to the character in string T so it would be F that means the values if values doesn't match then we need to return false right map contains that value then also it is false right if K and value both are not there then we need to put that means we need to map both the characters key would be s dot carrot I and value would be T dot carrot I so this is how we are going to map and at the end we can return true now let's take two strings s is egg and P is add let's call our function with that print statement to see the output is isomorphic s comma T let's run the program and see the output so we can see here the output is true because the characters are mapped correctly now let's take another example that is Foo bar these are not isomorphic strings so it should return false let's run the program and see the output so we can see here the output is false because these two are not isomorphic string because one o is mapped to a and another o is mapped to R so this is how we need to solve this problem if you have any questions any doubts please let me know in the comment section don't forget to like share and subscribe our Channel and stay tuned for more such videos thank you for watching
|
Isomorphic Strings
|
isomorphic-strings
|
Given two strings `s` and `t`, _determine if they are isomorphic_.
Two strings `s` and `t` are isomorphic if the characters in `s` can be replaced to get `t`.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.
**Example 1:**
**Input:** s = "egg", t = "add"
**Output:** true
**Example 2:**
**Input:** s = "foo", t = "bar"
**Output:** false
**Example 3:**
**Input:** s = "paper", t = "title"
**Output:** true
**Constraints:**
* `1 <= s.length <= 5 * 104`
* `t.length == s.length`
* `s` and `t` consist of any valid ascii character.
| null |
Hash Table,String
|
Easy
|
290
|
700 |
hey hello there today's liquid in challenge question it's called the search in a binary search tree we have a root node to the binary search tree and the target value we need to find if there is a node inside this binary search tree that has the value equal to the target value if there is such a node we return the pointer to that node otherwise we will return a null pointer so since it's a binary search tree we use its property to guide us to search for the value if the nodes we're looking at the value is if the target is less than the node's value we go to the left subtree because all the nodes with value that less than the current node we are looking at in the left descendants left the subtree if the target value is larger than the node's value we go to the right subtree so just going to compare the nodes value with the target value and use that the relationship to guide us to traverse inside this binary search tree if we find the value we just return the pointer to the node otherwise once we reach a null pointer in the end after the leaves we will return the null pointer so that's pretty much it's going to be uh the runtime is going to be depends on whether this tree is balanced or not uh it could be generally it's the lens it's the depth height of the tree otherwise in the most degraded case it will be linear time and for space it will be constant so let's solve this so while we still have a valid pointer for the node we will do is to do the comparison if the target is larger than the nodes value we go to the right hand side otherwise we check if it's the opposite relationship if no one knows value is larger than the target we go to the left the descendants left the subtree uh if it's the third case is that it's going to be the same if that's a if that's the case we just return this uh yeah so after the while loop terminates that means we exhausted all the nodes in a particular path and reached a null pointer so in that case we return the root or just return our pointer it should be fine for both case let me just add one more let's see we want to find a phi oh sorry you show up or empty oh yeah so that looks uh okay yeah so that's uh pretty simple just use the property of the binary search tree and compare the node's value with the target and use that to help us to move one level down at that time when we reach the end or when we find the actual volume we just return that yeah so that's uh that's pretty much it
|
Search in a Binary Search Tree
|
search-in-a-binary-search-tree
|
You are given the `root` of a binary search tree (BST) and an integer `val`.
Find the node in the BST that the node's value equals `val` and return the subtree rooted with that node. If such a node does not exist, return `null`.
**Example 1:**
**Input:** root = \[4,2,7,1,3\], val = 2
**Output:** \[2,1,3\]
**Example 2:**
**Input:** root = \[4,2,7,1,3\], val = 5
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 5000]`.
* `1 <= Node.val <= 107`
* `root` is a binary search tree.
* `1 <= val <= 107`
| null | null |
Easy
| null |
373 |
hi everyone in today challenge we are going to solve this problem the problem name is find K pairs with the smallest sum and the problem number is 373. as usual first of all because problem statement after that we are going to move to the logic part we are going to see how we can solve this problem what is the logic to solve this problem and after that we are going to move to the implementation part we are going to implement our logic in four programming language python C plus Java and JavaScript programming language fine guys now let's see what this problem is right so problem says you are given two integer arrays nums one and nums two sorted in ascending order fine energy integer came so guys we are given three thing right first thing is nothing but let me write the first thing is nothing but an array which is always going to be so dead right second thing is also an array which is also going to be sorted right third thing is in integer right which is uh integer right so this is nums one this is nums two and this is K right I hope it makes sense now Define a pair U comma B which consists of one element from the first array and one element from the second array so guys we have to define the earnings we have to make a pair so here let's say I make a pair UK movie where U is a number which should be exit in this array one so we have to return that number of pairs such that they have a small SM right um what do you mean by what this mean by smallism let's see that first of all with example one right so the only thing which left is nothing but the smallest one we have to discuss this right so in example when we have given this array one seven and eleven this is a number right and so we can write a number one and num2 is nothing but we can say two four and six so we are here understanding the example again guys we are not understanding the logic part right now which is focusing on the problem understanding part right you have to understand this problem so that we can so these two array and the K is nothing but three right so now let's change the color so guys we have to make a three pair first of all that is clear right we have to make KPS so we have to make three PM such that they have a smaller Supply so which PS have a small lesson so the small is some pair is nothing but you can see the one and two this sum is giving us a weakness value four and if you take any other PM they will not gonna give a value less than or equal to 4 right two more so this second is one comma four right now so we can write one comma four which is nothing but giving us sum is 5 which is also smallest num right so you guys can see that this is a three only pair which have a smallest if you take any other pair let's say uh two comma six uh two comma not six we can't take from this we have to take from there so let's say we are gonna take seven comma two right so this is also gonna give us nothing but sum 9 which is not uh we can say smallest one right we have already exists three smallest with some four five and seven so we can't take this pair as well we can't take any of the pair guys because all the other pairs are going to give a sum greater than these three is some so we have to return these three sum in the output also you can see we have one comma two one comma four and one comma six because these are the possible pairs which have a smallest sum right now let's move to the example second and see how we are getting this output item so but if heavy change here so in the example we have numbers one comma two and here one comma two comma three right and K is nothing but we can say two so that means guys we have to find two pair only right so the first pair is what this is to write so guys first pair is nothing but gonna be nothing but always one common one right this is the smallest some pair which is having a sum two and the second which is having a small assume secondary instrument one comma one again because we are taking this time this one right one common one so by this example you have one uh you have got one point that we the pair can be repeat you can see PA can be repeat but they are not actually repeating uh if you will focus on these numbers too this one is coming from now from this particular Index right earlier this one was from the zero index now this one is from the first Index right I hope it makes sense so index cannot be if you will take index so if this index is nothing but 0 comma Zero from the Norms one and zero from the nums two and this is one comma zero so index will never be repeat but yeah value could be leaving right now value can be same in the numbers so this pair seems to be equal but they are not actually in right so we are going to written these two nums uh these two pairs because we need only two they have a k is equal to two I hope it makes sense right so that is the only answer we have seen in our place as well one comma one and one comma one right I hope it makes sense now guys let's move to the third example we are not gonna discuss much because it's easier to understand so guys you can see we have this array nums one is one comma two and nums two is only three right and we have to find three pair right but you can see if we have this array so how many possibility pair we can make from this setting numbs when having a two length is having one length so at Max we can make nothing but two pair only right one two three and two to three right we could not even make three appears but we need to return three so we are going to return the numbers which we can and the pairs which we can make right so it's not like we don't have to return anything now we have to return that possible uh PSB could make right it's not like we have to return exactly K only if you are getting a less pair you can return those pair as well right so you can see that we have only written two pair only one comma three and two comma three right so these were the basically problem understanding part guys I hope you understood the problems and understand any kind of doubt you can write in the comment section because this program understanding part must be clear before moving to the closing point I hope it makes sense right now so let's move this thing and let's move to the logic part because logic part is always gonna be fun right so let's see logic and you will find it very easy program right if you found out logic easily right so and let's write here the first example because by this you will have a better understanding how the logic gonna work and if you are coming up with any logic in your mind the statue Implement by yourself then if you could not able to do then come to this closely buttons right I know uh half of your we can set out could be sold by this problem understanding part only right so we have these numbers one comma seven comma eleven this is equal to nums one and we have one more array 2 comma four comma six this is also numbers now we have K is nothing but we can say three right so this is the uh example one which we have been given right now what we have to do we have to solve it so guys just tell me which data structures or what algorithm we can use in this problem so we can get a minimum right we need to find the minimum pair right so just tell me so what we can do we can use a priority right or if you don't know what priority then we can use a mean Heap right so what did this help us to this always give us a minimum in just logo effect and complexity and time complexity right if another size of an array which is inserted in our particular meaning right so let's see how we can use this minhip or a practical item so what we are going to do we are going to say let's currently write him in here right initially you have to insert all the values so you have to take all this uh we can say values from nums one some be the numbers two of zero and insert in our mini right and why I'm doing just focus on this and we'll discuss it later right so from 1 plus 2 in X number three we have taken zero indexes from nums one and uh zero indexes from numstick right second seven comma seven plus two is nine we have taken a one indexes from number and we have taken a zero Nexus from number two third eleven plus two is thirty we have taken a second indexes from nums one and zero nice one Focus over here guys what we have done we have take all the numbers from nums one and keep uh done that we have added from this nums to zero and access means these two and we have inserted our mean heat rate so one plus two is three seven plus two is nine eleven plus two is thirty right after that here which in the number we have taken from numbers well zero indexes right and zero necessary from number two here also zero one indexes from numbers one seven is the one indexes right and zero Nest is from second index is from nums one and zero next is from number two right we are also keep maintaining that which index which indices we have taken from numbers so that we are getting this particular sum right now guys once we have done this now we are going to start our we can say main logic that is the minimum one from this minimum on the basis of zero indexes three in 1913 which is the minimum one is three right you can see three is the minimum one right is going to look like here fine and here just insert this particular uh you can see just in take these two values rest of the two values and insert their values respectively from numbers to and add in our result so nums one of zero is nothing but you can say one so variance of one common nums two of zero is nothing but two right so we are going to say two I hope it makes sense right so in result so far we have one pair which is one comma 2 which come through the mean he and how this Min Heap calculated we have seen it we have just take all the pairs from nums one and add it from this zero indexes value from nums two and keep inserting number minion right we have taken from zero right now this zero can map with other element as well right so you are going to say just increment this one to the next one right so we have to increment this Zero by one right so we are going to say now let me take a single now add three not three we are going to say add this 0 I remain same this uh we can say 1 and 0 and x is going to increment which you're gonna make one now what is the sum at this one plus four is nothing but five right so we are going to have five comma zero comma one in number three how does this calculated I hope you are getting it but I am saying that you have taken out this 0 comma zero right and if you go to some 3 and you have taken up from Min here and you have insert it in our result here right so mainly thing is happening the guys we have taken a pair from this mini right so if you are not still getting so what I am saying that we got this thing right three comma zero so we got this and this initially was Sum this 0 was nothing but I which is the index of nums one this is J which index from Norms to Y so when this is done so what we are going to do we are going to say okay just this sum is minimum right so you have to insert this I and J for in our result by calculating numbers of I nums of J uh if you are not seeing this screen so let me just do later up so I'm just saying that do Norms of I nums of I number result right so this is one pair right now we know that uh this is a result we have inserted now we have to insert the next possible fear pair which can be added right so you can see guys from the array I is going to remain same line I is not going to change but J is going to add increment by 1 if N J uh we can say J is plus one is not out of bound right so we are going to add this by one so now you can see J is going to increment by 1 which is now Point into four so G of this 0 indexes will point to the body 0 comma 1 and sum is going to be 1 plus 4 is nothing but five of them so we have we can say inserted this particular thing in our medium right now we are again going to pop out so just find out which is the minimum sum right so now 9 13 and 5 which is the minimum 5 is minimum so again this is gonna pop out so now we have I is equal to 0 J is equal to 1 right let me change a different color so I zero you can see this one I zero is equal to one so what is the value with respect to i 0 you can see seven is there or not here one is there right so we are going to save one and what is the value with respect to J 1 is index 1 in numbers two you can say four right so seven four so we found second period as well now we are going to increment J by one so we are going to say J is y1 implementing so what we are going to get we are gonna get nothing but uh means name zero and J is going to increment by one means two and zero plus two is nothing you can see Zero at we have one and two at we have six so one plus six is nothing but seven so we are going to write this now again we are going to pop out this has been gone so now you can see 9 13 and 70 which is the minimum seven is the minimum right so 7 is going to pop out and you can say you have to add this into PM so numbers of zero is one so we can say one nums uh nums two of two is nothing but you can say six one comma six now we are uh for this we are gonna insert something into this but before that you can see that we have already taken KPS right we don't need to take more pairs so what we are going to do we are going to written there right we don't gonna move ahead we are going to say just later now you listen because we have got a k number of pairs already down right so this was the basically simple logic but we are going to use a mini I know this one is little you can say uh tough part of this is a complex part but what we are actually doing here is that we are just maintaining a mean hip there we are maintaining a sum index of nums 1 and index of num's true right ing after that what we are going to do we are going to say once you take out any pair from Min heaps just increment J by one right because this we have to move to the next possible we can say options right so that we can take a minimum from the as well so this was a simple logic which we are going to use in this problem so let us include the implementation part let's see how we can implement this particular thing right so let's go to the implementation part so guys I am first referred with the python so what I'm going to do I'm going to say uh first of all find out the length so an end command n is going to be length of we can say numbers one and length of number right once this is done what we are going to do we are going to say let's make a heap which is going to be initially here and this is going to be nothing but initially empty of after that we are going to say 4i in range of n what you have to insert in your EQ door here push in this heat but you have to inside you have to insert nothing but uh first of all the sum so which is going to be numbers of I plus nums of zero initially you have seen that guys we have inserted initially this sum right where I is going to be in variable all the we can syntaxes and G is always going to be 0 right 0 and 0 right so nums 2 is going to be always 0 right and after that we are going to say I comma 0 right so we have inserted in this here now we are going to use a loop while he practices and K is always greater than zero so we have to decrement here in each iterations here we are going to say take up the minimum one so which is going to be nothing but we can say okay so let's take a data which is and here in this here we have to pop out the minimum right once we pop out it so we are going to say now I is one and J is going to measure data off to right now we are going to say the result append this announcement of j i announced to okay right once this is J plus 1 is less than m so if it is the case then we have to insert the next possible pair in our Heap right so we can say if you don't keep push in he we have to set a nums one of I remain same right terms two of J plus one J Will increment by one and I remains same G Plus singular right and we have to Define result here as well so result is going to be empty right now so after that we have to return any one reason right what is happening here let's run this potency but that's working final node so I think it should work right you can see guys all the disc isolated to submit this code as well so it was simple right what we are doing which is maintaining a heap mean he and after that we are appending a new pair right so let's move to the next programming language 15 nothing but C plus and in the C plus 1.3 size and M is two dot size 1.3 size and M is two dot size 1.3 size and M is two dot size let me say this fine now what we are going to do we are going to say once you have done these things you are going to say uh first of all make you write note right so we can say priority to play and here we can do nothing but we can say it's gonna appear in and after that right so this is going to be nothing but we can say this is going to sum and this is going to be I and J bar right now I hope it makes sense after that we have to make a we don't have to do like this as well we have to make a mean critical right I mean here so for that we have to use this particular syntax factor and just copy this particular part whole part you have to copy this let me copy this particular part and just paste it over here right and again one more view create that and this is also not going to work right guys so we have to pair this particular thing as well so let me do like this right now again you have to do like this so we are going to say like this and here we are going to give a name nothing but here right and let's see this if there is this will work final node so we are closing this one yeah so we have made the Q uh we can say practically or we can say mini right now we are going to Traverse over the first numbers we have four iron Jai less than n i plus and here we are going to say Heap zero right and in this uh so yeah so we have one more pair which is in a human I comma zero right now this is done we are going to say file this e to empty and K minus right now here we could say uh what is happening right here we can say if our uh we can say not if we could say we can say first of all pop up the minimum right because Heap is not empty we are sure that right so we can say Okay Auto foreign fine after that we're gonna say if J plus 1 is less than what is this J plus 1 is less than M so what we are going to do we are going to say just push this new pair in our creating right so we can see Heap don't push this uh we can say first of all I appear and inside the pair first will be gonna be some so nums 105 . . . right node J plus one because J plus one we are pressing J is already there right it's fine and here in this field also we are going to have one more pair which is going to be in this same J Plus do like this right after that we have to hope this answer so we are going to pop here only keep dot okay we are going to go minimum before it's setting and then we are going to return our result let's run this code and see where let's run the final node and I hope as it should work right but no it's giving uh error on this only right so we can say too many template for the class pair right so we have this pair right we have to take these things right we have this pairs do you guys can see that all the rest cases pass right so let's try to submit this code as well so here guys we go right so we can see that this problem got submitted right now let's move to the next programming language which is nothing but Java and first of all let's say integer in that is equal to 0 not high in N is equal to nums one dot length m is equal to nums 2 dot length right now we are going to say make Q right here right so we can say Q and here we can say the data type is going to be nothing but what interest we are going to take a array of Q right and after that we are going to see we are going to say the name is he then new is going to be the third priority Q right and once this is done we are going to say inside of this we are going to define a Constructor which is a comma B and here we are going to say okay uh we can say of 0 should always be smaller than V of zero right fine now we are going to say 4 into is equal to zero I less than n i plus here we are going to say if not if we are going to insert all the possible pair with the zero line so we are going to say he told foreign right after this we are going to say once this is done we are going to say four no four we have while loop y before then let's define a result here right which we are going to return list and here it's one of integer result is one of the new arraylist right array fine and here what we are going to do here while uh our priority view not Heap we have given a variable name he told is empty until unless that is not empty and our K is not equal to 0 right so we are going to say fine you have to keep moving right so here what we are going to do we are going to say take out the minimum element from here so which is going to be nothing but we could say integer array data is going to be nothing but this over here hold right foreign like this only pay row and here we can say new note new we could uh write the values 105 foreign after that we are going to say fine uh we are going to say if J plus 1 is less than M so what we are going to do we are going to say Okay add this pair also in our Q so we are going to say uh he told push node we can say use offer new end and here we can use nums 105 plus nums 2 of J plus 1 and here I is after this we can simply return our result right so let's see whether it's working fine or not right so let's see this particular part so here we are getting an error as so we can use like this and then we can decrement it by like this right and let's see now so something is missing already right so list dot pair of right that was I was thinking about slowly stored pair of what would be the case okay so let me see whether it's we can use a total of operators let's see okay well I just still giving an error so we can say let's run this foreign so by this we also going to submit it with Java programming language right so we have successful we can see successfully submitted with Java now let's move to the last programming language so in the JavaScript what we are going to do we are going to say first of all let's find out length now in here does not work we have to use left and he's got two numbers one dot length and M is going to be number two dot length left right after that what we are done we are gonna make a practical right again the main thing main problem is nothing but to make a practical so here we how we can make a Min Heap or the semin priority so we are going to save cones what new mean let's try remain then priority cube right after that you have to pass here also a Constructor which is nothing you can say a comma B right that look like this so I hope it makes no sense right so this is how we are making a practical this may give an error we will see later but yeah mainly I think the logic is like this only so after that we are going to say four in uh let I is equal to 0 or less than n i plus here we are going to see insert so let's go like this inside what you are going to inside you are going to studying Heap so you can see Heap dot in queue right thank you and here you can see in NQ you are going to insert first of all numbers 105. right so you can say pronounced result right now after that we are doing a while loop y this he dot is empty and we can say case is greater than 0 right so we can always we have to decrement K and here we are going to say fine let me use this same column as well so here we are going to say first of all covert right so we can see data so we can say orange sum i j is going to be equal to however this Heap rho D Cube and here we can see what element right now as this is done we are going to say you have to check not checking we have to Simply put in our directional result or push you have to push one you have to push numbers 105 nums uh two of G right after that we have to check if our J plus 1 is also less than M so we are going to push in our Heap as well he told in queue foreign except practical so basically issue is guys here only right so we can say priority so we are doing something wrong here guys so uh basically just how we could do uh give me a second we are using this operators and then we are doing like this right so we can see this is working fine let's figure out this one right so this thing in Q accepted numeric priority over a construct a callback data number so everything is working fine here TQ element is also fine in queue it's need to be used a pretty good so we have to give uh pretty so priority spelling is I guess wrong fine like X is this x is this just let me go to so what is Left Right which is Google is left right so we could do Google but before that let's see something is missing over here right so just give me a second uh it's working fine right okay so let's do Google now I don't think I have an idea why it's getting fail so it says that Always written numbers so if you expect a numeric Properties or consult they're called regulator so let's uh here we are inserting okay so here we are inserting a nums and we are inserting an array right after that we are inserting an array it's doing up on a priority with uh we can say x of g x of G right so it's giving a platoon X of zero so mainly issue is I guess here only guys I think so because we have user Constructor right so we can try to increase this I have checked on the other laptop as well but I think issue will be here only right let's try to run this way right so if you I know guys uh it was really hard for you to also understand this particular thing because it's a new one step and the JavaScript programming language is new to me so guys we have successfully implemented in Python CPS and JavaScript and Java as well so if you have any kind of doubt in the implementation you can write in the comment section and if you have any doubting understanding part also you can write in the comment section if you went out in logic part as well then also you can write in the comment section because I'm always there to help you right and if you learn something new in this video don't forget to hit the like button and subscribe my channel meet in the next video
|
Find K Pairs with Smallest Sums
|
find-k-pairs-with-smallest-sums
|
You are given two integer arrays `nums1` and `nums2` sorted in **ascending order** and an integer `k`.
Define a pair `(u, v)` which consists of one element from the first array and one element from the second array.
Return _the_ `k` _pairs_ `(u1, v1), (u2, v2), ..., (uk, vk)` _with the smallest sums_.
**Example 1:**
**Input:** nums1 = \[1,7,11\], nums2 = \[2,4,6\], k = 3
**Output:** \[\[1,2\],\[1,4\],\[1,6\]\]
**Explanation:** The first 3 pairs are returned from the sequence: \[1,2\],\[1,4\],\[1,6\],\[7,2\],\[7,4\],\[11,2\],\[7,6\],\[11,4\],\[11,6\]
**Example 2:**
**Input:** nums1 = \[1,1,2\], nums2 = \[1,2,3\], k = 2
**Output:** \[\[1,1\],\[1,1\]\]
**Explanation:** The first 2 pairs are returned from the sequence: \[1,1\],\[1,1\],\[1,2\],\[2,1\],\[1,2\],\[2,2\],\[1,3\],\[1,3\],\[2,3\]
**Example 3:**
**Input:** nums1 = \[1,2\], nums2 = \[3\], k = 3
**Output:** \[\[1,3\],\[2,3\]\]
**Explanation:** All possible pairs are returned from the sequence: \[1,3\],\[2,3\]
**Constraints:**
* `1 <= nums1.length, nums2.length <= 105`
* `-109 <= nums1[i], nums2[i] <= 109`
* `nums1` and `nums2` both are sorted in **ascending order**.
* `1 <= k <= 104`
| null |
Array,Heap (Priority Queue)
|
Medium
|
378,719,2150
|
1,237 |
basically uh solving the code one two three seven and uh i don't know whether this question is interesting but it i mean it looks like there is no other ways to solve it because uh if you know basically some mathematics then you know that the there's no uh any algorithms basically you can find any pos you can find positive integers for lotion for any given equation so suppose you put the ferment s uh you put the x cube plus y cubed plus equal to z cubed then there's no way that somebody can find into positive integer solution okay so this method uh so what we need to know is that uh somewhat gives you the sum function and they claim that z is from 1 to 100 and if you have 9 functions guarantee that x y will be in this region so the only way is that you just tool for loop and check holder is answer and but the uh one important things is that the function is constantly increasing so you know that if a function is larger than z then you just break and you just break so basically you create a solution and you plot you just write to the for loop and then check out whether there's a func there's a solution if not then done so this is probably the only way to solve this the subnets okay so i think it's very straightforward and i will see you guys in the next video
|
Find Positive Integer Solution for a Given Equation
|
reported-posts-ii
|
Given a callable function `f(x, y)` **with a hidden formula** and a value `z`, reverse engineer the formula and return _all positive integer pairs_ `x` _and_ `y` _where_ `f(x,y) == z`. You may return the pairs in any order.
While the exact formula is hidden, the function is monotonically increasing, i.e.:
* `f(x, y) < f(x + 1, y)`
* `f(x, y) < f(x, y + 1)`
The function interface is defined like this:
interface CustomFunction {
public:
// Returns some positive integer f(x, y) for two positive integers x and y based on a formula.
int f(int x, int y);
};
We will judge your solution as follows:
* The judge has a list of `9` hidden implementations of `CustomFunction`, along with a way to generate an **answer key** of all valid pairs for a specific `z`.
* The judge will receive two inputs: a `function_id` (to determine which implementation to test your code with), and the target `z`.
* The judge will call your `findSolution` and compare your results with the **answer key**.
* If your results match the **answer key**, your solution will be `Accepted`.
**Example 1:**
**Input:** function\_id = 1, z = 5
**Output:** \[\[1,4\],\[2,3\],\[3,2\],\[4,1\]\]
**Explanation:** The hidden formula for function\_id = 1 is f(x, y) = x + y.
The following positive integer values of x and y make f(x, y) equal to 5:
x=1, y=4 -> f(1, 4) = 1 + 4 = 5.
x=2, y=3 -> f(2, 3) = 2 + 3 = 5.
x=3, y=2 -> f(3, 2) = 3 + 2 = 5.
x=4, y=1 -> f(4, 1) = 4 + 1 = 5.
**Example 2:**
**Input:** function\_id = 2, z = 5
**Output:** \[\[1,5\],\[5,1\]\]
**Explanation:** The hidden formula for function\_id = 2 is f(x, y) = x \* y.
The following positive integer values of x and y make f(x, y) equal to 5:
x=1, y=5 -> f(1, 5) = 1 \* 5 = 5.
x=5, y=1 -> f(5, 1) = 5 \* 1 = 5.
**Constraints:**
* `1 <= function_id <= 9`
* `1 <= z <= 100`
* It is guaranteed that the solutions of `f(x, y) == z` will be in the range `1 <= x, y <= 1000`.
* It is also guaranteed that `f(x, y)` will fit in 32 bit signed integer if `1 <= x, y <= 1000`.
| null |
Database
|
Medium
| null |
202 |
hello in this video we're going to be doing lead code problem 202 which is Happy number this is an easy problem and it states write an algorithm to determine if a number n is Happy what does that mean a happy number is a number defined by the following process starting with any positive integer replace the number by the sum of the squares of its digits we're going to repeat this process until the number equals one or The Loop endless or if it Loops endlessly in a cycle which does not include one those numbers for which the process ends in one are happy so true if happy false if not so example one input equals 19 so we're going to separate the one and the N9 so we'll take 1 squar which is 1 plus 9 s which is 81 to get 82 so now we're going to split the8 and the two 8^2 + 2^ 2 split the8 and the two 8^2 + 2^ 2 split the8 and the two 8^2 + 2^ 2 68 so 62 + 82 = 68 so 62 + 82 = 68 so 62 + 82 = 100 1^2 + 0 S + 0 S equal 1 so this is a 100 1^2 + 0 S + 0 S equal 1 so this is a 100 1^2 + 0 S + 0 S equal 1 so this is a happy number input equals two the output is false because that never will 2^ squ false because that never will 2^ squ false because that never will 2^ squ which is four will never equal one so how are we going to code this let's start by creating a hash set and we're going to make that an integer so this will store all the numbers the results of all the squaring of all the numbers I'll just call it set in a new hash set all right so first thing we're going to do is add the number that's passed in and that will determine our while loop here so we're going to do while n is not equal to one so we're going to keep looping through this until we get that one value that we're looking for so we'll start Computing the numbers inside n so we'll do we'll store that in result make that equal to zero okay so now we're going to go through um each individual number so while n is not equal to zero so result and this is we're going to do the computation so result plus equals the math and we're going to do the power which is power of n now we've got to get so in the first example we have 19 we need to get the nine we need to separate the one and the nine so we're going to do mod 10 and take that to the second power so mod 10 if n is 19 and we do math power in mod 10 we're going to get the nine first so then we need to do to get rid of the nine we've got to do divide equals 10 and so that'll go through the loop again um because n is not equal to zero and so then we'll go through the one do that power and then and will be zero in that case so we'll break out of that uh 19 Loop or whatever or the wild Loop there the first wild Loop all right so once we get that result we need to uh place it in the hash set so while that contains the result okay so if the set contains the result this basically is an endless loop because once if we get if we already have the result in there means whatever we did to get to that number we're just going to keep getting that same number because it's already in the set so we're just going to return false otherwise we end up in an endless loop otherwise we need to add that to the result or I'm sorry add the result to the set and then we need to sign n equal to the result so that we can go through this whole process again through this first while loop up here all right and then if we go through all that and we haven't broken out of it yet we'll just return true and that should be the entire solution so let's debug it and see what we get okay so I use the first example which is 19 so we're going to get new hash set and we're going to add the 19 so n is not equal to Zer it is 19 result is zero and it's not equal to Zer it's still 19 so we do math power of n mod 10 so we get 81 so we get 9 * 9 is 81 so 10 so we get 81 so we get 9 * 9 is 81 so 10 so we get 81 so we get 9 * 9 is 81 so now we're going to get rid of the nine on there and you see now n is just equal to one so now we've got uh we do n mod 10 to the second power one to the second power will give us 82 and now n is zero so the set contains result which it doesn't we don't have anything in set yet so we're going to add 80 two to the result I'm sorry we have 19 in the result the initial number we do not have 82 so now we're going to go through this again with the 82 and 10 we get the two 2 * 2 is four 82 and 10 we get the two 2 * 2 is four 82 and 10 we get the two 2 * 2 is four so that's why we have four and then we'll do the eight which would be 64 so it should give us 68 the set does not contain 68 so we're going to add that to the set so set now has 19 68 and 82 and we're going to go through this again with the 68 so at 64 which is 8 * 8 and then we 68 so at 64 which is 8 * 8 and then we 68 so at 64 which is 8 * 8 and then we do the same thing with the six so now we have a result of 100 and it's zero set contains 100 it does not so we add it and now we'll go through this one more time without 100 set the result equal to zero so now we're going to do math power so 0 squar is 0o now we'll do it with 10 0 squar is 0o and now finally we've got this one squared is one and now we're at zero set contains result it does not so we'll add it so now you can see in the set we've got 1 182 1968 and 100 now we're going to go up here n is not equal to one that's false n is equal to one and so we're just going to return true and we are happy all right let's run this and see what happens it was accepted now we'll submit it faster than 17 memory usage 12 let's try again 35 and 50 this probably definitely is not the fastest solution I think it's the easiest to understand but definitely not the fastest finally let's go through the time and space complexity so we have two while Loops so that is Big O N of or n squ and then the space complexity is just o of n depends on the size of the input parameters and that is it so thanks again for watching let me know if you have questions and we'll see you next time
|
Happy Number
|
happy-number
|
Write an algorithm to determine if a number `n` is happy.
A **happy number** is a number defined by the following process:
* Starting with any positive integer, replace the number by the sum of the squares of its digits.
* Repeat the process until the number equals 1 (where it will stay), or it **loops endlessly in a cycle** which does not include 1.
* Those numbers for which this process **ends in 1** are happy.
Return `true` _if_ `n` _is a happy number, and_ `false` _if not_.
**Example 1:**
**Input:** n = 19
**Output:** true
**Explanation:**
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
**Example 2:**
**Input:** n = 2
**Output:** false
**Constraints:**
* `1 <= n <= 231 - 1`
| null |
Hash Table,Math,Two Pointers
|
Easy
|
141,258,263,2076
|
452 |
I hope that do in this video minimum number of arrows to burst balloon it has been asked by Amazon Apple Microsoft and Uber again um I highly recommend please go and watch the parent video for any kind of interval problem so that you have an intuition of what kind of things you need to think of while you even encounter the world called as intervals so again it is not linked directly with this problem but still I will highly recommend please go and watch this video for sure in this I discuss two major problems 57 and 56 both of them in very detail with intuition that why and what we need to think of now coming on back it says something I'll explain you in short that it says that we have some balloons now these purple ones which I have shown here these are the balloons let's say it's a balloon one balloon two balloon 3 and balloon four so every balloon has some width as you can see this balloon you can see is from 1 to six this is one balloon itself this another balloon is from 2 to8 one balloon 1 to six and another balloon 2 to 8 another balloon my 7 to 12 as you can see 7 to 12 and another balloon from 10 to 16 now again I just plotted that on my number line that usually how we solve inter problems firstly we imagine that how these intervals will look like on a number line now the problem says that please return me the minimum number of arrows that must be shot to bust all the balloons which means that I have to shoot these balloons as you know this line is a balloon and I have to shoot this balloon I have to use minimum number of arrows why they asking for minimum arrows because they know that if I shoot the arrow like this with this one Arrow I can shoot these two balloons if I shoot the arrow like this with this one I can shoot only one balloon so you can easily see that although they say that you have infinite number of arrows but still in worst case I can shoot one like this another like this and another like this with four arrows for because I have four intervals or I have four balloons in worst case I can take four arrows and I can bust all the balloons but they asking bro give us minimum number of arrows so I can for sure see that okay one I can shoot this specific one Arrow which can shoot balloon one and balloon two then I can shoot this Arrow which can actually shoot balloon three and balloon food so far I have realized I can use minimum two balloons now can I minimize this much food much further so you can see maybe I can shoot this but if I shoot this then this balloon is not shot which means balloon one and balloon for is also like not short so I have to shift this to maybe somewhere here but again I have to shift somewhere here so it I can roughly say okay for some minum number of shoots required will be two I cannot minimize much smaller than two okay great now let's take the next example there here you can see all these again remember all these are the balloon widths and I can shoot one balloon like this I can say I can shoot at one place how many balloons comes in that place that's a luck for me so in this as you can see all the balloons are actually not overlapping so I cannot take one shot because here I can easy see that these two balloons balloon one and balloon two were actually overlapping so I actually shot it in between so that two balloons got shot with one Arrow right okay so you have heard a word overlapping and maybe we have already seen something as overlapping non overlapping intervals because we can imagine this line as an interval and we have already seen kind of problems that's a hint for us okay great let's go on so in this you can see that you have to shoot this specific balloon because it is not overlapping with anyone you have to shoot this balloon again not overlapping you have to shoot this so for sure you will require in the first case four shots okay great now next comes is okay you plotted all these balloons so you can shoot the balloon at the location two with this one shot you can see again it is ending the first balloon is from 1 to two so it touches at two if even if you shoot at two then still the balloon one will be short and same way balloon two will also be short then balloon three balloon four you can shoot at location four and thus balloon three balloon four will be shot so many required are two so far you have seen that uh um usually in this kind of interval problems we usually sort the intervals out and usually it is on the basis of its starting index so as to okay imagine as you can see also while you are imagining you have sorted the intervals on the basis of the starting index although it is sorted you might not even know on the basis of ending or starting because it is even say if I sorted even start from starting or ending it's still same on both starting and ending and this also still same on both starting and ending so you might not recognize it is sorted you can see by your eyes but it is not on the basis of starting or ending so one thing is for sure you know that okay I will sort these intervals now if these intervals are sorted now I have to just figure out that at what location I should put a cut that I should get maximum number of overlapping intervals now let's imagine that I am about to place some cut so I went on okay let's imagine I again usually we sort it by the basis of start Index right that's all what we have been doing so far every time we have been doing this specific thing only so let's come on and sort it down okay it is sorted now I will have to find a location so that I will put my arrow at that location and ultimately I will have maximum again remember the fact one thing is that you have to burst all the balloons and then next thing is you have to use minimum number of arrows so if I have this specific B1 I know for sure I have to burst my even balloon for sure I have to burst my B1 balloon for sure so why can't I just say okay I know it is SED on the basis of it start index and start index so if I want to maximize the number of overlapping shots so I can just in the balloon one end I can just simply put a shot in the balloon one end I can simply put a shot AR what's the benefit of putting a shot at the balloon one end only because one thing is for sure I had to bust balloon one that's one thing and then I thought of what if some other balloons was maybe coming in the in before this because we know one thing is for sure that it is sorted by the start index ah it is s by the start index so for sure other start index is actually before but Arian you saw here what happened if the ending is after this short then it was okay then your strategy was okay but RN you itself showed you yourself showed that what if your starting and ending would have been before this shot you're starting and ending although you can see it is sorted on the basis of it stex but its ending is also four ah then if you just shoot at the last location because it seems obvious I will shoot at the extreme end of my balloon one so that all the balloons or major number of balloons will get shot but then I recognized here itself that if I shot at the end of my balloon one then maybe I miss some balloons because by this fact when I'm shooting at the last location I can see okay balloon one and Bon to a shot then I will go on to next balloon okay next balloon is nothing but P3 again I will go at the end of B3 and then I'll shoot this again so far by the example itself it seems okay answer is two but we also saw that we missed some balloon because of it is not necessary that its end is actually also further than the end of my starting of that specific balloon one so we realized uh issue if we start by start index then there can be a chance that if I start by St so you can see start then if I take the end of my first interval then um I might not shoot these two balloons so rather I should again I know one thing I will have to sort my intervals so rather let's try sorting by end intervals okay I sorted by end intervals then what happened is it will become as okay one it's a first interval second it's a third interval now again I will try the same thing I will try to shoot on the basis of my first LEL I will shoot it up okay great one shot done and the balloon one is burst Arin is the balloon three also burst um logically Thinking by your naked I it is you can see it will also be bust but programmatically how will you implement it that's a question cool but yeah logically it will be burst then you will go to the end of balloon two it is also burst then you will go to the end of balloon 3 is it are you saying are you will actually put one more Arrow here again I'll say no bro why no bro because I can see if I am applying a shoot here if I'm applying a shoot here so I know the last arrow shot was at this location let's say the location was 8 now I know one thing for sure is I had to now I'm guessing I had to apply next shot at this location line but its length is actually big it starting index is actually let's say at one so I know if I'm applying a shot at one the next shot which I'm trying to apply on I know it is for it end value is for sure more than the previous shot so end value is more if its start value is less than this arrow shot you see what's happening so I'm applying a shot here I know the end value is after me because I have SED on the Bas of it's end index if anyhow I can check the this interval let's say interval of I this intervals start value if it is less than my current short current arrow shot let's say name it as arrow shot if it is less than my current arrow shot again less than or equal to my current arrow shot I'm done what I mean I'm done I mean I don't have to make a new Arrow again I can use this existing arrow shot and this interval will also be shot by this arrow shot so ultimately what happened with us is that firstly we have to sort our again we are given this array called as intervals which is points given to us so firstly I will have to sort my points Again points. Begin points do end now by default this sorting which happens is it s it sorted on the Bas of start index so I have to use a custom comparator this comparator should sort on end index and again in the increasing order now when this portion is sorted now you are actually good to start making your busting so for that you will have to use an arrow shot at what last location you shot an arrow so in the very beginning I can say my arrow shot was at location minus one or I can say okay I did not shoot any Arrow minus one okay and by default I can say uh the count of shots were actually also zero I can simply iterate on all the arrow shots so I can say Auto my every point I'll go on to and I'll say okay the I'll go to all the points in the entire which is I go to Every interval now for every interval I'll go and firstly have a quick check that if the arrow shot which I did the arrow sh which I did which is this arrow shot last arrow shot which I did if it is actually more than again if it is actually more than or equal to my starting index of this current interval so if it is more than equal to my point of zero then bro I don't need to have any extra short I can try for the next interval I can simply continue but if not which means as you can see the for this specific for this was the last arrow shot but as I am on onto this interval I can see it started actually more than my last arrow shot so I have to actually do one more shot so I'll say bro simply increase the count of shot so I'll increase the count of my shot and I'll say Plus+ and also of my shot and I'll say Plus+ and also of my shot and I'll say Plus+ and also uh my new arrow shot location will become the end of this existing interval so my new Arrow short location will actually become the this interval which is nothing but my point of one because end location and thus I will have minimum number of count shorts now usually you will see it actually looks very nice in picture but you'll have to ask the interviewer what is the constraints of the algorithm you can see the constraints are actually your start and end can VAR from minus 231 and you saw that you have put in your arrow short initial as minus one it is only applicable when your coordinates are actually positive but you saw your coordinates can be also your coordinates can also be negative and that too like you saw that your coordinates can actually be negative Infinity in integer limit so you have to do one thing either you have to initialize that with long like or maybe long and then put a number which is more than- 2 number which is more than- 2 number which is more than- 2 31 or I can say less than 2 31 so you can either put in long and then - 1 E9 can either put in long and then - 1 E9 can either put in long and then - 1 E9 sorry - 1 E10 that's one way else uh if sorry - 1 E10 that's one way else uh if sorry - 1 E10 that's one way else uh if you want to take still integer then okay take integer take the first point itself take the first point okay point of one because you remember point of one is the end value is the end in as the is the end and that to where I will keep my first arrow shot and then initialize your count short by one because for sure you will use one shorts at least then you will not go on to points you will actually go on and iterate on all the points starting from index one because index 0o you have sorry it is actually index zero and the end value I have to take so you have to go on to all the indexes that's all the indexes start from index one because index Z you have already covered here so I equal to 1 I is less than equal to sorry I is less than points. size and then i++ and then size and then i++ and then size and then i++ and then i++ and then just a small modification i++ and then just a small modification i++ and then just a small modification that you here keep a i of zero and then here you will keep a i of one I of one and that's how you can simply solve it again there are two things I told you either you put a minimum value of your arrow shot which isus 1810 or you can put a starting okay starting off point of Z of one which is the end of the first interval you can either put it and that's the only code which you have to require that's it let's see the quote is pretty simple so if you look at uh if we will see that firstly we did a sorting by sorting on the basis of our end index if end is small then I have to sort it on the basis of my end index I cannot not sort by the basis of it start index if I even if I want to do sorting on the basis of that I have to modify my logic a bit so that's how we go about it now current Arrow position as I figured out okay I will put in my first intervals end as the current Arrow position because that's the optimal and for sure I have used one arrow shot so use one arrow shot now I'll go on from index one which means I have utilize already index zero and then go on to the end and then I'll simply check okay if the starting is actually less than my current Arrow position which means I can actually shoot this also because I know the ending will for sure be more for sure be because the points of I of one it will for sure be more because I have sorted on the basis of its end index so this will for sure be more this is for sure less so it is in between so for sure if something is between it can shoot it so I can actually shoot it and I can simply say no increase of count short requires simply continue and try for next interval if it is not then I have to uh shoot at that location so new Arrow Position will become intervals end and also one arrow shot I have used so increase the count by one and ultimately return the count of Arrow shots as you can see you did a sorting that's a bottom link of this question so the time will be and login and you are not using any extra space apart from sorting internal extra space used so for Java and C+ it's off login while for Java and C+ it's off login while for Java and C+ it's off login while for python is open and that's Sol cool byebye take care I hope that it's an easy question but again interval questions are never easy considering how you go about it and they can become very complex people start adding if conditions on lot because they end up giving wrong answers a lot so it's a very good question to learn bye-bye
|
Minimum Number of Arrows to Burst Balloons
|
minimum-number-of-arrows-to-burst-balloons
|
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array `points` where `points[i] = [xstart, xend]` denotes a balloon whose **horizontal diameter** stretches between `xstart` and `xend`. You do not know the exact y-coordinates of the balloons.
Arrows can be shot up **directly vertically** (in the positive y-direction) from different points along the x-axis. A balloon with `xstart` and `xend` is **burst** by an arrow shot at `x` if `xstart <= x <= xend`. There is **no limit** to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.
Given the array `points`, return _the **minimum** number of arrows that must be shot to burst all balloons_.
**Example 1:**
**Input:** points = \[\[10,16\],\[2,8\],\[1,6\],\[7,12\]\]
**Output:** 2
**Explanation:** The balloons can be burst by 2 arrows:
- Shoot an arrow at x = 6, bursting the balloons \[2,8\] and \[1,6\].
- Shoot an arrow at x = 11, bursting the balloons \[10,16\] and \[7,12\].
**Example 2:**
**Input:** points = \[\[1,2\],\[3,4\],\[5,6\],\[7,8\]\]
**Output:** 4
**Explanation:** One arrow needs to be shot for each balloon for a total of 4 arrows.
**Example 3:**
**Input:** points = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\]\]
**Output:** 2
**Explanation:** The balloons can be burst by 2 arrows:
- Shoot an arrow at x = 2, bursting the balloons \[1,2\] and \[2,3\].
- Shoot an arrow at x = 4, bursting the balloons \[3,4\] and \[4,5\].
**Constraints:**
* `1 <= points.length <= 105`
* `points[i].length == 2`
* `-231 <= xstart < xend <= 231 - 1`
| null |
Array,Greedy,Sorting
|
Medium
|
253,435
|
237 |
Jhal Hello Hi Guys Welcome to Code West Today's question is not in the list in this question verma2 Right function to delete unwanted nursing killing at least you will not give any access to the head of the list in hat you will give the access to the Not be dated 20th day denoted is not attained not ok morning this river in this question begins in english singly linked list and where given below given in node in the perverted it means that was established and growth of Delhi access of the not to be deleted and After the traditional literature look like this but study related to almost 400 years in this question not given to Delhi 110011 towel how will do this question senior actor will give oo did not subscribe did not reach up to play list node in this question is Not Nil Delete Not When They Know Not What Will Happen To Relation Between This Thank You Will Get Separated And Will Not Be Able To Join The Party Due To Delete Not Wish To Get Access To I Just Before Death Note Seduces Notes In The Key Identification Point To Does Not End Simply Delete Special But They Can Convert This Question In To Date Form Combine Note Video Note Key Value Know What We Can Do We Can Live Without You Can Just Update Value Of avengers update develop the current node given to date of the value of next9 idly nor did not give you freedom for know what will oo simply did you know it is possible in all cases where given in this question on few days tweet is not tell Notes It Means That We Can Always Updates Will Not The Giver Not With Date Of The Value Of The Next Notification Next Will Not Been Mail Sudhir Weekend Objective 100 Basis Of Will Do The Question Will Update The Value Of A Currency Notes With Date Of The Value Of Dinesh Node Will Simply Delivery Next 9 4 Notice of Duty For 10th Point Updates Daily Point * No Such Issues Will Do The Question Not * No Such Issues Will Do The Question Not * No Such Issues Will Do The Question Not Simply Left Side Then This Question What Will Definitely Value Of Node Where Is Equal To K Notes Next Well It Means The Value Of Current Fkr Note Hai Begum Develop Dinesh Not Know How Will Change This Point Of The Current Notes Next Is Equal To A Node Next Sweet Mill That Is Not Will Not Be No Deposit Into This Not But With Daily Point To Day Next Of National Show This Mode Automatic Get Deleted From Also Link List Listen Solidification Knowledge Prosperity Scored A Is So You Can C And D Answer Is Active Commission Ne Selective Video Thank You A
|
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
|
269 |
hello friends welcome back today we'll be going over another lead code problem called alien diction T this is another frequently asked question by Facebook and if this question has also been asked quite a few times by Amazon Google Microsoft Apple and quite a few other companies let's go through the problem description there is an alien language which uses the Latin alphabet however the order among letters are unknown to you will receive a list of non empty words from the dictionary where words are sorted lexicographically by the rules of this new language derive the order of letters in this language let's go through the examples so in the first example we see that we have five words the first word is wrt the second word is wrf the third is er fourth is apt and the last one is RFK T and we have the output as wer P if which is one of the possible sorted output for these letters so we compare the first two words you see that WR is common in both of them when we find one difference between the third characters of these words which is T and F and we can confirm that logic by seeing that P is coming before if in the output next we can see that E is coming after W so we have W E and similarly we can derive the order between the other characters next in the second example we see that this is quite a straightforward example we just have two words for other two characters said an X and the output is ZX the third example we see that the input is said X said again here do you see that there is no ordering possible as X comes both before and afters it and this in the wave forms a cycle and hence we return an empty string let's go through the node so you may also assume or laters having lower case if the order is invalid return an empty string like the way we did in the third example there may be multiple valid order of letters to turn any one of them so again if you carefully look at it's a problem on graphs and we would need to perform topological sorting to find out the correct ordering between these four words or characters for this language so if you have until now please see my previous videos on topological sort and course schedule where I have described in detail how to approach such problems so initially we'll need to create the graph next step would be to find out all the nodes whose in degree is zero and add them to a queue and finally we would be popping those nodes one by one from the queue and iterating over dead adjacent nodes and we will recompute the in degrees and we'll repeat this process till we have no more nodes left in the queue so let's try to coordinate post with define an array to hold all the in degrees since we know that all the letters are in lowercase we can just have a simple Harry of length 26 to hold all the 26 lowercase characters next let's initialize the graph it will be a graph pointing from characters to a list of characters and this list will be holding the adjacent nodes for that character now let's try to build this graph so for that we'll have to iterate over all the words and then actually all the characters and put all the unique characters into the graph so we try it for string word in words and then once we have the word we'll have to iterate over all the characters of that word so we delete the Carsey in word not to kirari and we put this node C and assign an empty rlist as its value once we are done with this we would need to determine the edges or more specifically to determine the direction of the edges it's for that we'll have to compare boards in pairs of two so we will start with the first would compare it with the second and then second and third would and so on and the way to determine the ordering as already discussed is to find the first mismatch between those words so if you think of the normal dictionary the way it works is pretty similar her again will pick first words and see where the mismatch occurs and really four minutes between those two characters so we write it for int I is equal to zero ie less than words dot length minus one i plus now let's say that the first word let's call it start and let's call the second word as end I really only need to iterate till the length of the smaller of these two words so we can define length as my dot min star dot length comma in dot length next we write for J is equal to 0 J less than claim J plus now let's define the character from the word start as out by that I mean that an edge is going outwards from the character in the first word to the character in the second world so they're out would be star dot carrot J and car in similarly would be n dot karate now the first instance with out is not equal to in we can add an edge in the graph so we do a graph but get hold which would initially be pointing to an MP add a list and we'll add the node in once this is done we update the in degree of node in so the way to do that is right in degrees we'll have to typecast it tour included so that we update the correct position in the array and we do a plus say if we see once we have the node F will be updating in degree two one our next step would be to add those nodes into the queue whose in-degree is nodes into the queue whose in-degree is nodes into the queue whose in-degree is now zero so initialize a string builder SB is equal to new stringbuilder we initialize the cube fuel character is equal to new linked list of characters now we iterate over the graph so for car C in graph dot keyset would need to find out all the nodes with in degree of 0 so we write if in degree of C minus a is equal to 0 then we'll add this node in the queue and finally we'll have to iterate over the queue and keep on repeating this process and updating the in degrees till we have iterated over all the nodes so we tell it well not of Q dot is empty let me just add some space so that the code is visible more properly we'll pull the first character from the Q Square out is equal to Q dot poll will be appending this to our string builder next let's iterate over the adjacency list of this node out so it right for car see in graph dot get out and then we'll do a - - in decree of and then we'll do a - - in decree of and then we'll do a - - in decree of node C so you know let me call this as in so that it makes more sense we'll have a sense of the directions so - - in have a sense of the directions so - - in have a sense of the directions so - - in degree of in now if this is equal to zero then we add this node into the queue and we are all done the only thing remaining is to return a result so we'll try a taste B dot length if is equal to graph dot size in that case we have a valid input and we'll return this V dot to string else we can return an empty string let's try to run this Kayson there are some typos so we did not handle this case where the second string was a prefix of the first string in such a case also the output would be an empty string so let's quickly handle that as well so we right have start Gotland is greater than n dot length and unstart dot starts with end so start God starts with end what determine if n is a prefix of start case we return an empty string oh it mentioned about the break but I hadn't added it let me add that as well because the moment we find the first mismatch we do not need to iterate further there was another typo I was saying it starts with and I've written it as start with hit me fix that is will too many typos today sorry let's run it one more time it works yet submitted great it works thank you guys for watching I hope you liked the video and with this video I will be concluding a short series on topological sort feel free to drop your comments feedbacks in the comment section below and also you can suggest any other videos which you want me to make please like the video subscribe to the channel and share at the difference thank you
|
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
|
983 |
Hello friends today I'm going to solve liquid problem number 983 minimum cost for tickets in this problem we are given two areas days and costs um in today's area um those are the num the days in a year uh when we will be traveling so the value would be ranging from 1 to 365 and the cost is uh um is of length 3 which has the cost of passes so we have one day pass seven day pass and 30 day pass and those passes are represented by index 0 index 1 and index 2 respectively so um what we need to do here is while we are traveling we can use these passes to make our um expenditure and um basically what we want is in real life we want to minimize our travel expenses right so uh using these passes we want to get the minimum number of dollars that we need to travel every day in our list of days so what would be the minimum cost of travel that is what we need to identify so now given the taste that we will be traveling and the cost of each process let's try to identify the minimum value of cost so we have number of days starting from one so we could choose to uh you know take a pass of one day of seven day or of 30 days so this is for one day this is for seven days and this pass is for 30 days right if we choose to take a pass for one day um the cost would be to ride and then we need to find out the cost of these days so the basically the cost of traveling would be um two plus the um the like dollars that we need to travel uh these day right day four the next day and so on so um so here if we take a two-day pass then so here if we take a two-day pass then so here if we take a two-day pass then two plus now day four for day four let's suppose we choose a seven day pass here so if you're choosing a seven day four pass then from day four starting from day four how many days can we use this password so from four we can use it for a four plus seven that would be equals to 11 so till day 11 right so we can actually use it until day eight so until the 8th we can use the path for day seven and then now we need to identify the cost of uh traveling at day 20. so at day 20 so what would be the cost we could either use one day pass seven day pass or 15 day pass but the best choice is to use the one day pass right um because we are just staying there one day we are just traveling one day so two plus seven plus our one day pass cost and the total would be close to 11. so this is the sum of um the cost of traveling that is the dollars that we need to travel right minimum um so basically now the question comes how are we actually solving this problem so to solve this problem we need the cost of traveling on this day and the cost should be the minimum right cost on traveling these days would be minimum so salary use a one day pass or a seven day pass or a 30-day pass that is what we pass or a 30-day pass that is what we pass or a 30-day pass that is what we need to identify let's look at another example that the way it will be much more clear so let's suppose the days this is the days array I have taken one five six seven nine and eleven all right so let's suppose these are the days that we are traveling and the cost is the same as above so it's 2 7 and 15 for uh one day pass um seven day pass and 30 day pass now starting from day one if we choose a two-day pass then what would be the cost two-day pass then what would be the cost two-day pass then what would be the cost so we choose a two day pass then the cost for that day would be two and then now we need to find the cost of the remaining days right so starting from five again if we choose a two-day pass a two-day pass a two-day pass then we now need the cost of these many days so we could basically choose any days past two days I mean one day pass or a seven day pass so what should what would be the better choice so that would basically depend on the number of days right so um let's suppose we are traveling at day six now what would be the best option to uh to pick between two day pass seven day pass or 15 days pass so what we do is from six um we are traveling on day six now we also have if we choose one day pass we will only be able to travel on day six now for day seven we need to make a new pass right so that would have a cost so let's suppose we know the cost of um traveling cost of traveling from day seven to all the remaining days so if you know the cost of traveling from day seven then the minimum cost then we have the cost of traveling on day six okay on day six plus the cost of traveling these days um again um we are just using one day pass if we use a seven day pass then we have the cost of traveling on day six that is just um the cost of a seven day pass rights this is cost of seven day pass okay let me just rewrite so this value here is one day pass so that would be equals to two and if you're using a seven day pass from six so that would be the cost of seven day pass Plus the cost of which day uh from six we can if we trap you choose seven day pass then we could stay use that pass till date 13 right so we need the cost of um they 14 because we can use the same pass until day 13 so we don't need to pay anything until day 13. from day 14 now we need to make our payment let's but since there is no day 14 um so the cost would actually be equals to zero for day 14 because there is no day 14 right so now um now we need to make a choice which would be uh cheaper I'll uh cheaper between two day one day pass seven day pass or 30 days past so for every day we are choosing we make a minimum choice between these passes value of passes and then we identify those values and based on those values may we make the choice of our other passes so that's how we are actually solving this problem so let me just explain you once again all right thank you so let me explain you in brief once again so the cost are 2 7 and let's say 15. all right so now for day one I if I'm choosing taking a pass of seven days then um what would happen is I can stay until I can use until day seven to the seven day pass so my cost is now seven plus now for day nine and day 11 if I choose again seven day pass then I can start from day nine and use the same password as day 11 right so that would be a cost of 14. so is this the minimum cost no right so what I do is for day nine instead of choosing a seven day pass I will choose a one day pass so that would be seven Plus for day nine one day pass so that would be cost of two plus day eleven one day pass cost of tools so the total cost is now equals to seven plus two which is equals to eleven so now the cost reduced right so cost reduced because for day 9 we I am choosing the pass which is the least costly between 7 and between these two values we are making choice between these two values because this value is like same right once we have made these choices we are not considering this value for this day I am just choosing between these two passes should I use uh day one pass or should I use day seven pass right no let's look it in another way now what if in case I choose a day one pass at um day one so if I choose day one pass the cost would be tutor now for uh day five if I choose seven day pass then what would be the number of days I can stay from five plus seven is equals to um 13 right so I can actually use this pass from day 5 to date 13. so since the day 11 I can actually use the seven day pass until day 11. so the cost is now two plus seven only which is equals to 9 which is the minimum right here so what is happening is for day one I mean for day five um I need to make a choice I could have chosen day two day one pass that would cost have cost me some other values greater values I could have chosen the 30 past that would have cost me 2 plus 15 which would be equals to 17 right so actually the number of passes uh the pass that I used is dependent on um these values right for this day uh what's the cost for uh day seven day one day seven and day 15. so based on these values I am making my choices so that I get the minimum uh dollars that I need so um let's now dive into our code and solve this now let's see one more thing here um since I'm making a choice at each day um I need to save like for day five I am making a choice between uh two one day pass for day six again I can make a choice between one day pass or seven days pass right so basically there might be a point where I am uh reusing I need the value of this pass right and the value at the cost of traveling on this day until the last day so for that we are using a DP so let us Define our DP course to an array of length 366. starting from 0 to 365. since there is no zero uh day but our error is indexed from days from zero right so that's why I'm just now we don't need to fill in anything so now that I have created our deep um our memory okay memory now we create our function dynamic programming function uh where we are going to pass our date so now if day is greater than 365 then we just return 0 else whatever if we check if our memory already has that day then the value for that day then we are going to return the value without having to compute it again else we have to compute so we are only uh we what we do is now uh to find the cost of a given day we are choosing between three passes right day zero day one I mean one day pass 70 pass and 30 days pass so if you choose one day past one day pass then um we need the cost of day plus one right that is the next step from next day what's the cost right and then we are choosing if we choose okay if we choose um uh seven past then we can use that first day starting from that to seven right so that will be how we are going to solve these and if we choose a 30-day to solve these and if we choose a 30-day to solve these and if we choose a 30-day pass that is as index to okay then we can use that pass starting from our day until day through the right so we need now the minimum of these uh passes so Matt at minimum cost so what would be the minimum cost for all of these passes that would be the cost of traveling from these days to the last day of our um travel now one thing comes here uh we if we are not traveling suppose we are traveling on day two but we are not traveling on day three so we don't we will not be spending any money on day three since we are not traveling so what we need is also need the days that we are traveling right so uh days set equals to new set of days so if we are only traveling on that day that is if days set has that day that is only when we are making our expenses right so this would be how it is else we are just um the expenses will remain the same so we are just um transferring that is we are just continuing to have um okay DP of um D plus one so we are just transferring it we are not adding anything not making any concept like expenses now finally we return our expense for that day now let's make call to our DP function from day one okay so we get some error foreign minus one and if it's not equals to minus one and return the value else we compute the value for those days now let's try to run this okay I'm still getting an error all right so the problem here is now uh memo D we need the cost at day plus one right but have we already computed it we might not have right so we need to actually compute it here okay now this will work now we don't actually need this thing here all right and we also don't need this now let's try to run awesome let's try to submit our code great so talking about the time complexity since we are creating an array and then for each of the days we are actually each of the day starting from 1 to 365. we are um performing our DP operation so that is why it would be of 365 since 365 is a constant so that will be constant but let's suppose um it is some variable value then that would be uh o of w where W is equals to 365 and the size of the area would also be equals to O of w i mean the space complexity
|
Minimum Cost For Tickets
|
validate-stack-sequences
|
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`.
Train tickets are sold in **three different ways**:
* a **1-day** pass is sold for `costs[0]` dollars,
* a **7-day** pass is sold for `costs[1]` dollars, and
* a **30-day** pass is sold for `costs[2]` dollars.
The passes allow that many days of consecutive travel.
* For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`.
Return _the minimum number of dollars you need to travel every day in the given list of days_.
**Example 1:**
**Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\]
**Output:** 11
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1.
On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9.
On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20.
In total, you spent $11 and covered all the days of your travel.
**Example 2:**
**Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\]
**Output:** 17
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30.
On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31.
In total, you spent $17 and covered all the days of your travel.
**Constraints:**
* `1 <= days.length <= 365`
* `1 <= days[i] <= 365`
* `days` is in strictly increasing order.
* `costs.length == 3`
* `1 <= costs[i] <= 1000`
| null |
Array,Stack,Simulation
|
Medium
| null |
299 |
On Karo Ki A Hello Everyone Welcome Back to the Channel Programming Bodh This Platform Court On this channel we are going to discuss very topic temple programs important questions like Google like metric like Doobie and terrorism like Amazon, if you love any company or not, here are the types which are going to discuss those problems, how to use different, if you are doing different, how to know the difference between different sizes, using it. It is important that you are with me in all this, you are going to get the saree on this channel. If you have not subscribed the channel, what are you doing? Subscribe and watch the full video and do not miss any video. At the end of the fiction video, you will see You will get a bonus only for those who have excelled a lot. Apply for Weather of Technical Growth for all of you. Reply only for non-technical people because Reply only for non-technical people because Reply only for non-technical people because General of Programming Kevin will have tips on how to clear a problem in the interview. If you have n't subscribed yet, do subscribe. Now use the time. Without your depression, let's move towards what we are going to talk about today and not only what is going to happen to you. So, without any time, let's move towards your body. Ajay has looted, Ajay has respiration from the international platform and tell me that the use of daily food is a very favorite question. Okay, the idea of a company from one of our fund companies and so if you are searching for Google idea of a company from one of our fund companies and so if you are searching for Google idea of a company from one of our fund companies and so if you are searching for Google and Now if you have not asked this question then please do it. Teams spread fashions back. Okay, this is a very important and very good question which Google has asked many times. Now if we talk about a friend, how many times have we asked this in fund companies? Let's talk about its importance, so what is important is that in sign companies, this last only within the stage, within six months, within Simmons, discussion has been known, how much gas do you use in plane mode on, more than party time? For the time being, this question has been asked a lot and it is a very favorite question of Google G company, okay, it is a very important question, if you use Google then definitely look at this question, it is also a very important question. For Google, they often ask this question, ' For Google, they often ask this question, ' For Google, they often ask this question, ' Chicken', this is a very important Chicken', this is a very important Chicken', this is a very important question. For Google, now we understand the question from the truth that Google has, the question is very long and wide, okay, but we are against the same, now we will understand all this first. Then let's look at fashion and its approach and will support. Let's talk about what definitely happens in that two day game video friend weight toss game. This is a very long written question when you will be asked. Dabi, it will come like this, it will come in this format, okay, what is its maintenance, whatever is the 31 questions and we talk about them, we take them out, okay, this is the whole of this channel. If you want, you can do it on this also now. If we talk about the platform, there are 10 questions available in these texts, you can read them, but I think it is better to do this plan in the beginning, so that you will know the practical implementations of the exam. The questions are asked in the exam. It is okay that this is the third question. Number 8 Raw Turnoff Under One Roof Friends Let's Get Singh's Number Give Number Is Compost After Defeat And All Dar Districts And For This Friends Smooth Can Contain The Talk Page Number 90 Jara To Variables Britain Se Kitna Late Raat To Variables Ones De Bol That other is nikhaar ok no water falls in solution was tremendous he file ok to number of gold is its seeds right answer fixed deposit number try playlist your brain dead and alive is heroic is the shift from the number director or else and guests present and strength What is the meaning of but opposition has strong ok member classes acacia sacrifice lyrics where it's prank gas like the number which is the same digit is exiting at the same place is fine neither here came out a proper complete gas is correct with respect to date and with respect to play beware why what does it mean digit is adjusting pinch inside button different places for seventh here call is respect teacher cigarette number is ok in which it is exit ok day throw with 0 have done 778 different places for 10th Maths, that's why this counting is ours now and only one is ours - that is the receiver village and one is ours - that is the receiver village and one is ours - that is the receiver village and said ours i.e. there is only one such number said ours i.e. there is only one such number said ours i.e. there is only one such number which friend gas has done is correct and Uday Singh is correct, okay so I am here. If we do plus one, then here one sacrifice one mistake and another 3v 353 cos is okay free ka 1070 exit birthday special meaning different places for example let's take care of this, is there a similar thing in the exam? This is how things are happening, once you press them, they laugh and give examples. I have taken 270 one day ago, okay and here I have taken seven and bro how to know, life imprisonment in this case and tell me what is going to happen. The one who is going to be our first one is going to be great, why how is that which is at the correct place, it is right and the village of our band, which is going to be Gul and Sarika, will also be a forest. 1 Which is here, you see this forest, which is here, that juice here. If he is not doing it then why won't we account in it? Celebs are doing it. This is a waste. We will talk to him about the account in the village. NSS 111 is also in this. This is the answer. It is okay. In many cases, there may be duplicates. I have that in that thing. Also, the solution which I got from my Afroz should be done, okay friend, shifted in this point which is given in the last, it means that you have generated a sticker number, your friend has to do that gas, if the right digit is placed at the right place. If it is done then you will give a plus to the mistake and if the digit is accessing it but the place is not correct then you will give a plus to the tawa pulao but if the digit is not accepting that the guest digital currency is not doing it in secret then If you will not improve then you will make your account statement. Don't forget and comment. Okay member tricolor the question a swore in s tuk so these were its properties and explanation if there will be any doubt this woman and comment came out on her birthday. Reply to the okay all. God bless you start the solution, knowledge, wealth and professional work process towards the solution. Our exact week is on Mike Solution, but here, if you think, what will come out, that is, how it comes out, the initial approach will also be yours. It will be our anniversary, okay, what will we do inside that, we will and compare is a graduate with its place, okay, this day matches, we will increment the bullet, aunty, if the digit exists in the string, increment 220, now this is the exit. This is the exit part, for that chat, you will find the loop of a tanker and a hanging potato, people, there is an interview going on, that is to do with a matchbox and then that she is doing Bigg Boss, a defect. Which is doing it is not on this place, it is not on this press, it is not on this place, then from there, which is your Time Cooperative Bank of Baroda, it is okay, how should we delete it, Vriddhi Help Data Structures, we can increase its quantity to very good and good. Work means a lot, we can reduce it, some people will think that we will put shopping in it, then we will do comparison, then guys, if you put shopping then what is left of the order and here we have all the meaning from order only. It's okay, if you have put shopping, then what is the meaning of the order? Anything can happen anywhere. It's okay, then the order is okay, then what is our soft ward in that case, which we don't want. What is it that we have to reduce the complexity? Clipping bear in mind, so how can we do that, think a little about it and after that we will solve it together, this is how to do by swiping, you must have thought about it even if you have not thought about it. There is no problem because we are going to solve it together. Where you faced any problem, let me know. Okay, otherwise let us go to the nation, we will solve this position and friend, now which data structure am I going to use? Because here we have already mentioned that very good Jhajjar Water Spring Stand Canteen Duplicate is ok, the person who has come into your Android app, the structure of letter A in 9th Maths is going to you is ok, I will use pomegranate tomatoes in data success, now what is the approach What will be our optimized approach? Okay, so the wheel 's run to low is 's run to low is 's run to low is good, so these dependent crops have modified guest gas yesterday swimming by the first and any other symbol is a testing dot a in this country number is this dance of growth. Method ki aap chal string and the beaver increment yes bol a ki and tips a day ki dent ka bass 220 vil mein installed art * * * ki a noida map ki with the character of ki aunt ki a friend sir girl ok to nahi hota hai i.e. What is being said is that we will run the Independence Loop i.e. What is being said is that we will run the Independence Loop i.e. What is being said is that we will run the Independence Loop in the afternoon of Independence, Lu here and here, so this is the meaning of saying this, then what is the modified guest house in the crops and setting of Dadar symbols, this number, this mask is fine, that march from the number one position If it is done then we will turn off the gas. It is the birthday next day. Jodi match bank balance and 10 into a border. Madam, you will fold it for us. Okay, so now you are married every day. Those characters are added in the Noida map and the dies are made first. Also told that if you have not seen it and do not vote in front, the data success class on the thing, if you guys are calm then please comment below and watch the full video. The tree is very good from the bonus and you will get it in the ownership side only. The tree of the people on the side of the meeting, which is the juice in the map, if the person mutes the volume of the na cancer of the drowned [ __ ], juice in the map, if the person mutes the volume of the na cancer of the drowned [ __ ], juice in the map, if the person mutes the volume of the na cancer of the drowned [ __ ], then the volume which is here, is the one character of Mari Akram, how many times is it happening, which will be mine, then it will die. Okay so this is the significance of the nodeya go into your conversation between guntur that if this is the meaning of this then we move ahead so even the approach typing will cry to you clearly if it is not done please right to maintain quintal definitely Respond and try to make a year to us soon s possible ok qualified in new year loop them it anirudh tomato healing tonic hai ki now ki in 10 sec lok kni hai ki birbal main tum par the gas and ki a noddy khan hu This is the gas waali hoon is this house 220 wheeler aaj ke date alsi birbal search to its value in delhi according to the slope i call it is the chief exist in the map 220 will give increment where a flying e will give oo hai so that we Made a second above what we are doing is that if our gas one is York then we will leave it i.e. the ball has been remarked and it has i.e. the ball has been remarked and it has i.e. the ball has been remarked and it has rather come in the account and if it is not then now What will we do? We will search her hair in the unwanted map. If that is the thing that I am doing then we will do these treatments. We will increment it from village to village, otherwise we will skip it because it is big like this but is not counted in the village. It should not be forgotten, okay, Aishwarya project itself, let's understand this with lightness example, okay, let's understand the example, what has been our approach, so you can create a little space here, okay, you just have the structure and the input friends. Okay, you should remember, let's understand what my approach is saying. First, I put a for loop. Okay, in which if my string when value matches then I will modify the gas. Left hand then do one spoon. Do 98 test match with my intake, listen to the gas from my stomach, my gas modified to 7766, 102, okay, right, 10110, in the ninth match, it is closed on my son 2009, it is not okay, so what does the match tell us? In this, we will create conversion for this. When there is no match, then we will create you in 9th, so not anarchy creation is going on, now here in our I, they call this a plane race so that it is a little presentable in our I am just substance, okay, so this is done now. Here the forest was working, otherwise for the sake of the forest, I kept the forest here and what have I done to his Akram, he is the foot of my this is my key and the end of my wall became 98 matchsticks, son of its basic knowledge hero. Must smell normal note below which hair and intermediate till friend 11077 match 2020 and instrumentation friend was no when the second lutyens bungalow seconds questions second floor price avoid milkshake it gas slip on this basis then we will skip it otherwise birbal search tinder The app here is our seven, the seventh house is not seven, ma'am, you have checked the karma, you have suggested, so I deleted this clearance brother, zero and village is the village variable, it is mine, I have modified it from zero, the name is 1. So I will script one from me, one came one, I got it checked, one is here, yes is adjusting, so I have incremented the village, I am white by 181 sentimental, it is white and two become his waali hoon and here and for free a friend I deleted it, less now speak against zero exists in their mind then we will make it zero also, they had become a night life style return this mistake then convert it in the fridge and enter the leaders in the spring by converting the pendant b.a. in the spring by converting the pendant b.a. in the spring by converting the pendant b.a. Me Ande Saraswati Required Answer Is Okay So This Is Our Proper Complete Explanation And Approach Now Let Us Clear The Board A Little Bit And Want To Hot Coding For The Most Interesting Part Of This Divya Video Ok If We Move To The Polling Party Then Names Here you see food juice exam has the same everything is this you want you can platform ignorance him lower court records at large number of and variety of questions that ignorance example also you discuss dolaria example which has given and which these were in Deadlines and given and regard situation andar first listen or gallery discuss your professional life including a part of it's ok again enterprises' ticket and land records enterprises' ticket and land records enterprises' ticket and land records mein aa is secret dot loop bhi don't see the abhi aapke jitne bhi jise milange dehati full hai ok to These are next nine to make in android app unwanted mother love form of in mo for daughter 12408 york plus amazon hoti hai na question modified strength and 699 e request the central sweater binttu and ₹2 doing were arrested that [ __ ] cigarette ki Solution equal requests ki gas aaye den hamare do main rahe gaye boli 20 maa kamakhya error zero ok na to if both are equal jab plus is dam hai as yes sequence ghr ki aapke as cm is secret of i plus good ok Know What Will Be Going To 2500 Electronic Which Is Greater Than Equal 110 What We Do Is Plaster Send Em Is Solution Like - - Okay, we will turn on the generate Is Solution Like - - Okay, we will turn on the generate Is Solution Like - - Okay, we will turn on the generate and forget the other gender Aplus A S plus how to string cow A plus B A I am using the toe spring function here, we did not directly convert them 148 and do something else 10 B Here, if your flame goes to double digit, then in double digit, if you add zero or dry ginger to anything and convert it into this film by applying something like Vikram, then if you do not put double digit or K in it, then it will be in it. You will have to add more loops separately, so it is better that you find a used annual function, it is ok on that, otherwise I am using it, I am also using it, reduce the complexity and make short answer which is transmitted and transported, do not use Viagra in this. Gone To Form A Report Within There Readable Key And Writing Detector Test Accepted Akhilesh Sunao Will Be Going To Retail Pack We More Cases And Will Be Time When I That Noida I Have Only One And Agri Pioneer 10 One Special Day One Shoe Hit Was 90 ok happy and tell us in these directions date a dangerous for defense and brd back 1208 milli second pass money service 1.5 1208 milli second pass money service 1.5 1208 milli second pass money service 1.5 administrative staff to above 1.5 administrative staff to above 1.5 administrative staff to above 1.5 mixed in end memory usage money 107000 great and goods congratulation prizes solve this question in west amount After time witch will be based approach and flag were adopted and as I said tell me no bread and till then remaining 70% on how guns were supposed to 10 70% on how guns were supposed to 10 70% on how guns were supposed to 10 questions to is liya ab grinder can now you can see hidden password 98.7 Point of hidden password 98.7 Point of hidden password 98.7 Point of the sea plus online submission i.e. the sea plus online submission i.e. the sea plus online submission i.e. where are you people doing? 90 percent of the oil is being fired from this. Member on pan says very good singer to the barricades and Congress are two sides of soldiers for action against Amazon this means that we have done this somewhere. Do n't trend off either, Chikara, both of our things, West Frontier, time and place, I will be able to come, Shraddha, do this 910 question, don't spread it too much, The Amazing spider-man from this video, The Amazing spider-man from this video, The Amazing spider-man from this video, spoon is coming and what is that of ours, which is not only OK, election is coming soon, today's programming World Channel's Muskaan Gupta which is presented to you on the international platform is not only Pride Fry Bagi Optimize Solution Increase Torch Light I Don't Mind Solution as Soon as Possible i.e. Tomato Solution, whatever Soon as Possible i.e. Tomato Solution, whatever Soon as Possible i.e. Tomato Solution, whatever we give to this problem, you can solve it as soon as possible. Try it, why what is the significance, what are its benefits because we do not do anything without benefit, even if it is to type on my solution, why not, okay, let's see the benefits of office in this post benefits in Height increases and chances get selected in this company. You are going to give job in any company. You are going to give interview. Well, if you come to the optimized solution as soon as possible, then it will increase your chances. This is done to get selected in the company because your marking is done on all these things, so if you get these things done well then the officer will increase your chances of getting selected. Okay, Siddheshwar is the benefit and the other benefit is not only that. Let's see what are these measures Confident for the future Interview It is not that you go to the same company and just get set there and stay there for ages. Is it okay? Everyone who thinks about the middle ticket for. Meeting Roles Better Salary Meeting Opposition Opportunities Better All Possibilities To Grow Hair Impressed With Area And Money Other Is Android Ok So If You Can Perform Well In Interview Your Confidence Also Increases Ok So Whenever I Come In Future Interview My If Did you take a little bath in the first one, were you a little different in the first one, were you nervous? Okay, so it is what it is, if you come to optimize quickly, then an automatic confidence will come in you or I will be chanted for others can. Do it, I can do it with my best friend, okay, so this is the boyfriend that we need, so add interview, any interview, weather my also technical, non-technical or any other technical, non-technical or any other technical, non-technical or any other interview, this is the most important thing to worry about. Whatever is asked from you as soon as possible, whether it is technical or non-technical, answer it as soon as possible, non-technical, answer it as soon as possible, non-technical, answer it as soon as possible, but the optimizer should give specific answers for a specific answer, which will also increase your chances of getting selected in the company and your Confidence too big pot future interviews ok improvement and remote important thanks for the future ok so today's ownership astrology related was boat this increase less pressure 910 bonus step you video students selected and sew the question from the bonus defiantly which license like share And Subscribe And Share With Your Friends By Vikalp Sharing Dedication Is The Very Good That You Can Perform Alone Tune Into My Programming World Channel By Muskaan Gupta To Get More Educated Interview Related And Arduino Programming Videos In All Spheres And Attracted Many Things On Which Main Cylinder Missile Definitive Point To That Okay Guide Bah States Have Baby Bye Love You Too Do Do Now Half A Lemon
|
Bulls and Cows
|
bulls-and-cows
|
You are playing the **[Bulls and Cows](https://en.wikipedia.org/wiki/Bulls_and_Cows)** game with your friend.
You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:
* The number of "bulls ", which are digits in the guess that are in the correct position.
* The number of "cows ", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.
Given the secret number `secret` and your friend's guess `guess`, return _the hint for your friend's guess_.
The hint should be formatted as `"xAyB "`, where `x` is the number of bulls and `y` is the number of cows. Note that both `secret` and `guess` may contain duplicate digits.
**Example 1:**
**Input:** secret = "1807 ", guess = "7810 "
**Output:** "1A3B "
**Explanation:** Bulls are connected with a '|' and cows are underlined:
"1807 "
|
"7810 "
**Example 2:**
**Input:** secret = "1123 ", guess = "0111 "
**Output:** "1A1B "
**Explanation:** Bulls are connected with a '|' and cows are underlined:
"1123 " "1123 "
| or |
"0111 " "0111 "
Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.
**Constraints:**
* `1 <= secret.length, guess.length <= 1000`
* `secret.length == guess.length`
* `secret` and `guess` consist of digits only.
| null |
Hash Table,String,Counting
|
Medium
| null |
94 |
everyone welcome back and let's write some more neat code today so today let's solve binary tree in order traversal and this is actually a pretty trivial problem if you've you know done anything with trees before especially if we do the recursive solution which we will but we're going to take that recursive solution and also figure out how we can make an iterative solution doing that now even though the code of the iterative solution is going to be completely different from the recursive one the concepts are actually the same like what's going on under the hood is pretty much exactly the same so that's what we're going to use to actually figure out this more difficult solution so simple enough we're given the root of a binary tree and we want to return the in-order traversal of the values of all in-order traversal of the values of all in-order traversal of the values of all of its nodes so in this case for this tree this is the root we're going to do an in-order traversal how do going to do an in-order traversal how do going to do an in-order traversal how do we do that well we start at the root we don't actually process the value just yet first we want to do the entire left subtree but it doesn't have a left subtree so we don't have to do anything next we take the value one itself and add it to the result so here we have a result nut and one is added to it now we don't have to visit this node again but now we're going to run the exact same algorithm recursively in order traversal on this right subtree so we pretty much do what we did before we visit this node itself we have to go through its entire left subtree which is pretty small in this case it's just a single node this is kind of the base case because now we have to go to the left subtree of this node but it doesn't actually have a left sub tree nothing is there so then we can process the value three we can add three to our result and then we're done with this node then we would go to the right subtree but it doesn't even have a write subtree so now we're done we go back up to our parent node and now from this node's perspective since we just went through the entire left subtree now it's time to process this node the value is two we add that to our result and then we would go to the right subtree but it doesn't have one so we're pretty much done in this case that's the entire result one three two you can see it's the same as what they expected overall time complexity of this algorithm doing it recursively is big o of n because we do have to visit every single node in the tree the memory complexity in the worst case is also big o of n because of the function call stack because if we do implement it recursively we have to put the parent nodes on the stack before we can actually pop back up to them we'll actually go in more detail onto like what the stack is when we actually do the iterative solution but now let's really quickly just write up the code for the recursive solution okay so just coding up the recursive solution real quick we are going to create a nested function actually because as we go through the function we want to be building our results so i'm going to call the nested function just something simple like in order it's going to take in some node just like this function is but this variable result out there is also going to be accessible from within this function because this function is defined inside of the outer function so this is kind of like a global variable for the purposes of this function it'll just make things a little bit easier but for the actual inorder traversal we know it's a recursive algorithm recursive algorithms have two parts the base case which in this case is pretty simple if a root is a null right not root so if the root doesn't exist then we can just return we're not going to need to do anything but if the root is not null that's when we do the inorder traversal and we know inorder traversal is pretty simple first we go through the left subtree whether it exists or not we can pass in the left sub tree by taking root dot left into the inorder function and then once that's done it's time to process the root node itself uh by doing that we're just saying result uh we're going to append the value of the root node to the result it's just that simple and after we do that the last thing we have to do is pretty much uh do the exact same recursive algorithm on our right subtree so whoops let's copy and paste that and just change our root.left to root.right just change our root.left to root.right just change our root.left to root.right so i'm going to leave it at that so we created our inorder traversal it's very simple we have a global variable which is you know the thing that's being updated from this function so let's make sure to call our inorder traversal passing in the root node that was passed into the outer function once that's called our result should be updated so then we can go ahead and just return our result and that's the entire recursive algorithm so i ran the code and it does work so now let's get into the more difficult solution okay so now let's actually get into the iterative solution and we're actually going to look at a different example to get a better picture of what's going on under the hood and so this is going to be our function call stack but i'm definitely going to simplify it a lot because in a real a call stack a bunch of things are pushed onto the stack like you know the function a bunch of variables the local variables the line that we were at executing the code and things like that because you know when you call a function from inside a function it has to remember to get back to the original function that's what the stack is for so if we called the function once then we called the function twice and then let's say the exact same function after we finished the second call then we have to go back to the first call that's how recursion works but i'm going to oversimplify it a lot and i'm actually just going to use the node values on our stack just to kind of simplify things but so this is how it would work in a regular recursive uh inorder traversal for this first we take this node we don't want to add this to our result just yet we want to push this to our stack for the time being so we're going to put one on the stack that's uh the node one that we're talking about and we want to now traverse the left tree before we traverse this node but we're putting it on our stack to remember that we do have to do this eventually so next we go to node two we're not gonna process this node either we're gonna push this onto our stack so node 2 is also on our stack our result is still empty then we go to node 3 because we're going to the left subtree of 2. now 3 is also going to be pushed to the stack and then we're going to go visit the left tree of three it doesn't have anything though so now is the part where we would pop from our stack so we're gonna pop three and add it to our result so let's also cross it out here recursively this would have been a function call and we would see okay this is null so then we'd pop back up to our parent three now that we've popped up to three we're going to check if it has any right children because as you're noticing now even recursively what this does is go we go left until we can't go left anymore then we pop back up to our parent and then we go right and see if anything's there at this point nothing is in the right subtree so we don't do anything here either but we are gonna now pop again from our stack because what we're saying is we did this entire subtree and now we can finally go up and process two so we pop from the stack again two is added to the result we can cross two out over here again and now similarly when whenever we pop up to a node we want to then check its right child if it has any right now we do so now we're going to run in order traversal on this four notice how though when we do go right we don't put anything on our stack because once we're done with this subtree uh over here we're gonna pop one from our call stack because as you can see in the picture we've processed everything except one so now we're gonna go to this four node and four would basically be pushed to the call stack and then we'd go left nothing is left so that means we can actually pop four from the call sack as well put it onto the result cross this out we would check if there's anything on the right side of course there isn't so then we can go back up and pop again from our call stack now we're gonna pop one from the call stack so we're back up here we can cross this out add one to our result and then we would go to the right subtree of one which is five now in reality we would put five on our call stack check left nothing is left so then we'd pop five from the call stack add it to the result and then we would try to go right from five it doesn't have any right children so we're pretty much done at that point because our stack is empty and we don't have any current node so that was basically a simulation of what's actually happening under the hood with a stack and you can also kind of see why the stack in the worst case is going to be big o of n memory because in the worst case we could have everything pushed onto the stack all at once what an example tree for that would look like is basically if the tree just happened to be like a linked list maybe it only had left children right something like right if a tree looked like this then we would end up having to put all values on the call stack okay but what you might not realize is the simulation that we just did is exactly how the iterative solution works as well except but instead of having the function call stack take care of things for us we're actually going to manually update our stack and do things iteratively it's basically going to be the exact same i'll do a very quick simulation just to give you an idea so instead of doing this recursively we're gonna have a pointer so right now our current pointer is gonna be at one and what the algorithm at this point is gonna do is we're gonna keep going left until we can't go left anymore so what we're going to say right now is that okay this node is non-null let's put it okay this node is non-null let's put it okay this node is non-null let's put it on the stack so the node 1 is going to be added to the stack now our pointer is going to go left this is also not null so let's add this to the stack 2 is added to the stack now we get to three is also not null let's add it to the stack and then we go to the left child of three which is null it doesn't exist so at that point we pop from the stack we pop three we add three to the result and you know let's just cross about in the picture we would try to go to the right child of three but again we see it's null so then we pop from the stack again so now we get to two we can cross it out we can add it to the result we try to go to the right child right after we pop a node we go to its right child so four in this case does exist okay it's not so that's where our pointer right now would be by the way our current pointer would be here since it's not null we add it to this stack and then we try to go left it doesn't have any left uh child again we pop from the stack 4 and then add it to the result let's cross it out here as well we and every time after we pop a node we try to check its right child and then run the same algorithm there it doesn't have a right child though so now once again we pop from our stack we pop one add it to the result now our current pointer is up here at this one so let's cross it out and then try to go to the right child down over here which does exist so now we would take this value 5 and add it to the stack let's just add it here because we're out of room uh and then we try to go to its left child it doesn't have one so then again we pop from the stack pop five add it to the result and then cross it out here now our current pointer would try to go right but there's nothing there it's null so at that point we know we're done because our current pointer is at null it's not pointing at anything and our stack is empty because we would try to pop from our stack now but there's nothing there so at that point you know we have no nodes left we visited everything we built our result and we can return it so conceptually this is very similar to the recursive solution the code is going to look a bit different though but you can kind of get an idea of it's going to be some while loops going left and stuff like that okay so now let's code it up okay so this is the recursive solution i guess i'll just leave it here if you want to take a look at it the only thing we're going to need from here is the result we're also going to need a stack so let's get an empty list for our stack and our current pointer is initially going to be pointing at the root we want to continue this algorithm the iterative inorder traversal while our current pointer is non-null and our stack is pointer is non-null and our stack is pointer is non-null and our stack is non-empty so non-empty so non-empty so basically if either of these are non-empty so if our current non-empty so if our current non-empty so if our current pointer is pointing at a real node or our stock is non-empty we're going to our stock is non-empty we're going to our stock is non-empty we're going to continue this algorithm what we want to do is just go left as long as we can so if our current node is not null we're going to add it to the stack so stack dot append the current node and then move our current pointer down to the left and we're going to keep doing this as long as it's possible once this loop exits that must mean current is pointing at null so what we should do now is pop from the stack so stack dot pop and our current pointer should now be pointing at this node that we just popped let's append this to our result just like we did in the drawing and remember whenever we pop a node we append it to the result and then we shift to the right so now our current pointer is going to be shifted to the right node and what do we do to the right node after we've shifted there well we just run our regular in order traversal so what should i write here for the code to simulate a regular in order traversal well didn't we just do that right now isn't this whole thing a in order traversal so what would happen if we didn't put anything here well we're going to go back up to the loop we're going to see that our current pointer is non-null or at least our pointer is non-null or at least our pointer is non-null or at least our stack should be non-empty and if that is stack should be non-empty and if that is stack should be non-empty and if that is the case then we're gonna get uh back into this loop right for that node that we just shifted down to the right we're gonna try going left as far as we can which makes sense because that's what we do with any node but if that node is null then this loop is not even going to execute so then we would end up just popping again from our stack and then appending that to the result and then doing it all over again so as you can see even though this code looks a lot different from this one they are doing the exact same thing with a stack maybe i made it look easy but this code is pretty tricky to come up with on your first time if you've never done an in-order uh iterative solution before in-order uh iterative solution before in-order uh iterative solution before but that is the entire code so now let's return the result and run the code to make sure that it works oops i was stupid again we're not appending the current node itself to the result we're appending the value so i always make that mistake but now let's run it to make sure that it works and as you can see on the left yes it does and it's very efficient so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
|
Binary Tree Inorder Traversal
|
binary-tree-inorder-traversal
|
Given the `root` of a binary tree, return _the inorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[1,3,2\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
**Follow up:** Recursive solution is trivial, could you do it iteratively?
| null |
Stack,Tree,Depth-First Search,Binary Tree
|
Easy
|
98,144,145,173,230,272,285,758,799
|
1,416 |
hello guys welcome to deep codes and in today's video we will discuss net good question 1416 that says restore the item so guys as you can see in the past few days we are getting very more and more questions on the string and deeper related in the lead code daily challenge so today's question is also very much similar to that so here the question says that you need to write a program uh but for that you are given one string as in the input and one integer game now what you have to do is you need to find them multiple ways to divide this given string into small substring where the number of each substring must be less than K so if you take a look at this example this will give you better understanding so here you are given the string as end an integerkin and you need to find in how many ways you can divide this string as such that each substring is less than equal to Q so if you take this current ah this string as a complete string then also it is less than K that is one way if you divide in 131 comma 7 this is another way if you divide like this 13 and 7 both the numbers are less than K so this is one possible way this is another so similarly you can see that these are the different other states so yeah at the end you can say there are eight possible ways to divide the given string into substrings such that each substring is less than equal to K this is what the question tells question asks us to do to find the number of ways to divide the string into substring such that each number is less than equal to M and we need to find number of such ways we can form a substrings now if you take a look at the first example uh okay but before that each and means we have to keep in mind that none of the numbers should have starting uh zero means no leading zero in an array is allowed so right so any number if let's say this 0 this cannot be separated as a substring because the starting of the number is zero so leading zeros are not allowed okay Cleo now we uh here if you take a look so it is one zero that is thousand here and this is ten thousand K is ten thousand how many ways you can divide this string into a different set of strings so there is only one possible way thousand because after that there are only zeros so we can't do anything for that okay clear now here uh the input s is 1000 and the K is 10. now we are the only way we can divide this string is to take the complete string but since K is uh K is only 10 and the substring or that array we can form is thousand here as you can see this is the minimum but this is not less than K so we return 0 as our answer because the error that we have to print must have the integer less than equal to K correct in this example we already discussed right so let me take one more example for better understanding so guys if you have some uh like some in integer like this one three seven one three five seven okay and let's say k is equal equals to 200. now here what you can do is the one of the way to divide the given string is something like this one three five comma seven okay 135 is less than 270 is less than 200 another possible ways 13 and 57 right uh another possible way is U divide 1 comma 3 comma five comma seven okay another possible way is one you divide one thirty five and seven okay you can reversal like this one comma three comma 57. okay then you can is there any other way possible yes one way is 13 comma Phi comma seven so guys this is how you can find the different ways to divide the given string into substrings where each the number of each substring is less than K so this is how I and I try to understood the question right now since we are dividing the given string into this type of substrings and we have to find number of ways so for each letter or you can say character we have choices so what choices does the character have so the choices is First Choice is uh take the character in the current substring so include in current substring or you can say current number or second away is to start new substring from that character so for each letter or character we have these two choices either to include in the current substring or you can start a new substring from that character so for an example let's say we have this only one three five seven and K is 200 1 3 5 7 and k equals to 200. so here if you take a look at the first character then for that ah this is it is the first character we have only one choices two is to start a new substring right we have only one choices to start a new structuring we have to at least start here so here we started now for the second character three we have now from here we have two choices either to include in the last number or start a new number one comma three now for Phi again we have two choices at each node we have two choices like either to include one three five something like this and we have to check whether including a 135 is it is less than equal to K or not if it is this then only we can do and the second choice is start a new number similarly for this also we have two choices one comma 3 35 and 1 comma three comma 5. and for the last letter seven we have to check if one three five seven is less than k no it is not less than K so this we won't move forward from this state now here the seconds choices to make a new number from this seven okay now we will check 57 is less than k less than equal to K here then we can write something like 13 comma 57 as the second choice is 13 comma 5 comma 7. now we are also 1 comma 3 5 is 3 5 7 less than equal to K no it is not less than equal q k so we won't form this okay and the second state conditions will create this state 1 comma 35 comma seven and from here also two states at 1 3 57 1 3 5 7. okay got it clear so guys this is one two three four five six so guys as you can see that these are the six possible answers that we can get with this string input and case is 200 so if you can look here that there are also three possible states that we have here generated by using the decision trim so guys that's how we can conclude that for each character there are two choices and based on the two choices we can form this decision tray diagram and there we can conclude the states right the different states now in order to approach this question what thing you have to keep in mind see the only thing you have to keep in mind is the changing index that will point to the string that will point to string s okay because for each let's say we choose uh and index fi as a starting index then for each starting and this what we will do is we will run a for Loop follow from the starting index up till s dot size and we will check see one of the choices is what include the new index in the current substration so we will check if so if we will calculate that if the current num plus this new index I so Phi DX means if you create a num by taking create a number by taking the index from idx up to I then whether it is less than equal to K we will check and do something and if it is greater than equal to K if the number is greater than k then what we will do is simply break because taking that number or taking that character in the current number current string we create a number greater than k n that is not allowed in our system so we will break so this type of states where we will produce the number greater than K we will simply click and don't proceed forward so guys I hope you are you guys have understood this that how we will take the situation right and now let's move on to the coding part is very much simple here we have only one changing variable idx that is the index of pointing to the string as and this is the memorization approach I am showing here uh so uh here what I did is I created the DP or 1ddp because we have one changing variable right and it is of the size of the string because this index will range nothing but from 0 up till as dot size okay because if the index is greater than s dot size then we have written condition so our DP won't have the index who with the value greater than equal to s dot size correct now if any starting index is uh the numbers is the character Zero then we won't be able to form the number so in that case return 0. here I have taken two variables into ways and long current number so this current I am calculating the current number that can be formed okay so uh how I am calculating this current number so for the same example one three five seven and K is 200 so let's say the our index equals to 0 1 2 3 so our current num would be 1 because so initially current number zero so zero into ten is zero plus this index that is 1 is the current time greater than k no so that's why we can move forward with this that uh and here we will count the ways right base equal to base plus solve s k i plus 1 NDP now what is this is nothing but uh start a new number start new number I plus 1 okay this is one condition or one choice we are doing and the another choice is by taking this for Loop C uh from each I plus when we can start a new number or we can include the number right include the number so after this for Loop and for the one time it will again start now the next index is what index is one uh so that number is three so what we will do is we will change current num to 1 into 10 plus 3 so that would be equal to 13 now is 30 less than K yeah 13 is less than Kim so we can again uh so again we have 13 in the first substring and here we can begin new number right begin new number so to begin a new number we are calling this ways right so yeah in the first state what we did we took one in the current uh substring you can say and then we begin a new number new now then this is the first thing we did now is because we can take 13 at the current num so we took 13 and then we begin a new number then in the next step we can take 1 3 5 and begin a new number so as you guys can see that this is the choice one that to include the current uh character inside the current num and this is our second choice to begin a new number right so yeah this is how we are handling both the choices choice number one and choice number two inside this follow got it so yeah guys that's how we are solving and approaching this question uh I'm not talking about the time space complexity so the time complexity here is bigger fan see as you can see the size of the DP item is this bigger fan so that many times we are this all function would be called but multiplied by log of okay see y log of K so as you guys can see for this example only one three five seven and case 200 so one possible state is this take one in the current and then begin you know then 13 to current beginning 135 into current number so begin you know so for uh so let's say this K is of length three so for the three different xmax three different possible state would be there right because see after that it our current number would be one three five seven so for that we would break because it is greater than K so yeah how many maximum different state possible with a K it is log of K different state possible so here this has to be multiplied in our time complexity got this if the K is 200 so it is of line three so it makes uh three digits the length can be possible in the current state so yeah this is how this we are calculating the time complexity here in the space complexity here is nothing but a bigger fan uh plus recursive stack you can take but overall you can say the space complexities we go as the size of the DP that we are using is a size of a stream so here we can say it is a bigger fan so yeah guys that's all for this video if you guys have any doubts then do let me know in the comment section apart from this guys I have started one new video series where I will be uploading videos on solution of the coding round challenges of the different uh companies so yeah make sure you check that out also like this video And subscribe to our Channel thank you
|
Restore The Array
|
check-if-an-array-is-consecutive
|
A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits `s` and all we know is that all integers in the array were in the range `[1, k]` and there are no leading zeros in the array.
Given the string `s` and the integer `k`, return _the number of the possible arrays that can be printed as_ `s` _using the mentioned program_. Since the answer may be very large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** s = "1000 ", k = 10000
**Output:** 1
**Explanation:** The only possible array is \[1000\]
**Example 2:**
**Input:** s = "1000 ", k = 10
**Output:** 0
**Explanation:** There cannot be an array that was printed this way and has all integer >= 1 and <= 10.
**Example 3:**
**Input:** s = "1317 ", k = 2000
**Output:** 8
**Explanation:** Possible arrays are \[1317\],\[131,7\],\[13,17\],\[1,317\],\[13,1,7\],\[1,31,7\],\[1,3,17\],\[1,3,1,7\]
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of only digits and does not contain leading zeros.
* `1 <= k <= 109`
|
Try sorting nums. If nums is consecutive and sorted in ascending order, then nums[i] + 1 = nums[i + 1] for every i in the range 0 ≤ i < nums.length - 1.
|
Array
|
Easy
|
298,549,1542
|
935 |
everyone and good afternoon to all of you today we have problem which name is night derer D code 935 problem so before going forward in this video please make sure that you have liked and subscribed to this Channel and also it's my advice to all of you that please read the problem and try to build up the inducer in your mind and also try to do the code if you will simply see this video and then do the code and it will not be beneficial for you so firstly do by yourself then see this video so let's read the problem statement the problem is saying that we have given a chest Knight has a unique movement it may move two square vertically and one square horizontally or two square horizontally or one square vertically means both with both forming the shape of L it's like a horse in chair the possible movements of chest Knight are shown in the diagram the it can move like L shape in any direction so we have a chest Knight and a phone PA as shown in the below so this one the Knight can only stand on a numeric cell life it given an integer and written how many distinct for numbers of length and weend dial means you are allowed to place the KN of a numeric integer and this and finally we have to return with modul so what it simply saying that if I have at the digit of eight I can go at one and three I can't go at six because it is not forming the L shape because we can only go up to three digits means three indexes it's like if I have and if I am at the five fifth index means in font pair I am at the fifth index I can't go anywhere because if I go upper Direction it will be two and uh now my uh pad is empty so I can't go anywhere so let's uh see the problem approach part for this yeah so what I will do is first I will create a map because I have to find the index next digit because I am at the digit if like I am at the digit of zero uh so I have to find the next digit where I can go so I will create a map and in that map I will create a key value means 0 to 9 and the corresponding values for that so it's like if I at the zero I can go four and six like if I'm at the zero I can go four and I can go six I can't go anywhere because it's like a L shape I can go in three Direction means three J 1 2 and three like this so firstly I will create like uh all digits for this then I will see if uh my n equals to 5 like my n equals to 5 then I will see the first index and I will Define from 0 to 9 because it can be zero it can be one it can be two like if it can be zero so our next digit can be four or six so if my next digit is four so now I have to find the N minus 2 digits and if my next digit is six now I have to find the nus two digit now see if my first digit is one so now next dig can be six or eight if my next digit is six so it's matching it's see 0 comma 6 and 1 comma 6 because I will do the function call I will take the function call from six so it's like a DP because the function call is same for uh further statement so it's a DP statement so we can use GP here so it's like that uh so further we will do like this let's see the code then so that we can understand proper so I have written this before this I started this video because it will be time con consuming so let's do the code for this yeah so firstly what I will do is I will create a vector because DP sorry because as you can see here are some function calls thata repeating so it's a DP statement so we have to create a DP and DP do the size of n + one size of n + one size of n + one comma vector int of 10 and initialize with minus one why 10 because we have 0 to 9 N index in keypad so now what I will do is I will create a function this name is let's define this long so long solve and in solve function I will pass int remaining part comma int current digit remaining part is like if I at the zero index if my first number is zero so my remaining part will be n minus one so it's like that now I have to write the base case for this base case our base case will be if remainder equals to Z I will dialect L minus one so as you can see I have created a DP so if DP of remainder of current not equals to minus1 then I directly return DP of remaining of current this is done I have to create this here because it's for Universal function now what I will do I will create a long answer equals to zero and four Auto next digit will be jump off that particular digit current digit and I will add this answer equals to answer plus now what I will do I have to add that answer so answer plus solve function solve of remaining minus one comma remaining means and minus one because I have my first index so remaining minus one comma Cent next this is done so finally I have to module also mod finally I will return DP of remaining of current equals to answer that I have to modul this now in that function what I'll do I'll create long along answer equals to0 and four in digit we can say current digit equals to 0 to current digit less than 10 and current digit Plus+ and I'll do 10 and current digit Plus+ and I'll do 10 and current digit Plus+ and I'll do the same answer plus answer equals to answer plus solve function in that Sol function I'll pass a remaining will be add minus one comma current and finally I will do the modul and let's return this return answer now let's send this code and see if this will work or not it is working perfect let's submit this code it's a memorization approach because we are using the DP so let's discuss about the time and space complexity for this so as you can see we are using the time complexity big of n into 10 approx big of N and also space complexity will be big of n into 10 which is a big of n approximately because we are using DP 2D DP so first is going n times so let's see n + one times and another is going 10 + one times and another is going 10 + one times and another is going 10 times so it is Big of n plus one ISO appro equal to Big of n so here can man approaches we can use tabular approach for big of one space that approach you will see and uh if you find this helpful then please like share and subscribe and if you know other approaches for this so please comment
|
Knight Dialer
|
orderly-queue
|
The chess knight has a **unique movement**, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an **L**). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight **can only stand on a numeric cell** (i.e. blue cell).
Given an integer `n`, return how many distinct phone numbers of length `n` we can dial.
You are allowed to place the knight **on any numeric cell** initially and then you should perform `n - 1` jumps to dial a number of length `n`. All jumps should be **valid** knight jumps.
As the answer may be very large, **return the answer modulo** `109 + 7`.
**Example 1:**
**Input:** n = 1
**Output:** 10
**Explanation:** We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
**Example 2:**
**Input:** n = 2
**Output:** 20
**Explanation:** All the valid number we can dial are \[04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94\]
**Example 3:**
**Input:** n = 3131
**Output:** 136006598
**Explanation:** Please take care of the mod.
**Constraints:**
* `1 <= n <= 5000`
| null |
Math,String,Sorting
|
Hard
| null |
452 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem minimum number of arrows to burst balloons don't worry it's not as hard as the original burst balloons problem and they give us a pretty long story here so I'll try to condense it for you so the idea is we're given a bunch of balloons but the balloons are really intervals in this problem so I'm not even going to draw them as balloons I'm going to draw them as intervals just drawing out this first example that they've given us here one interval would look like this starting at one that's like a big deal another one would go from 2 to 8 so from here to there and 7 to 12 and 10 to 16 so just quickly drawing those something like this the idea is that we can shoot arrows pretty much anywhere that we want to the goal as you can imagine is to pop each of these balloons in the worst case like at the bare minimum we can accomplish that with n arrows if we're given four balloons of course four arrows is going to be enough to pop those balloons but can we do even better I mean they tell us here that an arrow can actually go infinite like if we shoot it over here it'll actually pop both of these balloons and then we only need one balloon for here and one balloon for here that's a lot smarter than shooting the first Arrow over here where it's actually only going to hit a single balloon so that's the whole idea behind this problem as you can kind of tell this is very much an interval problem if you've never solved an interval problem before this one's going to be pretty challenging so I did want to quickly take a second to mention that I've created something called n code iio you might have already heard of it if you scroll down to the interval section over here this actually gives you all the background you need to solve this problem more specifically I think it's these two problems merge intervals and nonoverlapping intervals actually I think uh not this one probably the first two will probably be enough to understand this problem the rule of thumb with interval problems is you almost always want to do some kind of sorting which is some pre-processing sorting which is some pre-processing sorting which is some pre-processing that we're going to do on these intervals and typically it's fine to just sort them based on the start time and that's what we're going to do in this case so we're going to take these points that are given to us in a random order and we're going to sort them CU obviously you want to be able to identify in this case when we're talking about popping multiple Balloons with a single Arrow you want to be able to identify overlapping intervals if you want to find overlapping intervals it makes sense to order them in such a way that they're going to be overlapping right that's why we do the Sorting so we're guaranteed that the intervals that we're going to go through in order are going to be sorted based on the start time we know we're going to need to detect overlapping intervals in some case but how can we go about solving this problem let's think about the high level first I want to kind of remind you of something else so let's ignore this example for a second let's suppose we had an interval that looked like this and then we had a second interval that looks like this and then maybe a third one fourth one it doesn't really matter about the next ones let's look at these first two intervals for a second all these are sorted based on start time so that's what we're going to be focusing on we first are going to look at the first two intervals they are not overlapping first of all how do we know they're not overlapping well we can compare the beginning of the second interval with the ending of the first interval right we know that for them to be overlapping like these ones for example the start time of the second interval has to be smaller than or equal to the end time of the first interval in this case they are but clearly in this case they are not so these two intervals are not overlapping and my claim to you now is we can extrapolate this and say not only are these two intervals not overlapping but this interval does not overlap with any other interval in the entire array I guarantee you that because we sorted them based on start time remember if this isn't even less than or equal to this how is it possible that any of these are going to be so that's good but what exactly does this tell us so far like suppose we're iterating over this array what have we found out at this point in the context of this problem well basically we need an arrow for this interval like we have to have an arrow for this interval and that arrow is only going to be able to pop this interval okay that's good to know now let's go back to the original problem for a second let's look at these two they clearly are overlapping we have a method to detect that now so they're overlapping now what at this point we know for sure I mean we definitely need an arrow to pop these two and so far we only need a single Arrow to pop both of these intervals that's great to know so what are we going to do now we're going to move to the next position and now we're going to look at these two pairs of adjacent intervals and what we'll find is that these guys are overlapping too we only need one Arrow to pop both of these but that's not the most important question actually the more important question is does one Arrow pop all three of these or maybe we need one Arrow here and we need one Arrow here how can we determine that how do we know if that's the case by the way just so you know there's like a space in between here so like this interval does not overlap with this one in case like you couldn't tell uh visually so how do we figure that out you tell me think about it for a second well these two intervals are overlapping right we care about the section that's overlapping even though this one extends a bit further we know that the section between these two that's over overlapping is this from here to here by the time that we have this overlapping section of the interval at that point we don't even care about what this is and this is like we're just ignoring those at this point so now in reality when we go to the next iteration we already compared these two now when we compare these two we're not comparing the original intervals we already know it only takes a single Arrow to pop both of them now we want to know does that same Arrow also pop this one or do we need a separate arrow for this one that's the question we're trying to answer and clearly in this case these two intervals are not overlapping we definitely need a separate arrow for this one whether it goes here doesn't matter because one Arrow popped these two intervals anyway so that's the entire problem believe it or not and you can tell that there's two things that are important to this problem one is being able to detect overlapping intervals and two is being able to merge intervals but clearly in this case we're not merging the entire intervals we're only merging the overlapping section so I'll call that like an overlapping merge this is the entire problem and that's why I suggested those interval problems from the N code 150 there's one last thing when we're counting the number of arrows what you'll find is that it's actually annoying to count starting from zero because if we're counting from zero we get to the first pair of intervals we find that they are overlapping okay we'll take that to one now okay so then we will increment this to two and then if we find like these next two are overlapping well we keep this the same but you kind of notice that we have to handle it differently right like in this case these intervals are overlapping so two stayed the same in this case they were overlapping and it went from 0 to one I think you might be able to get around this by initializing a count to one but the way I solved the problem is just by first assuming that we need an arrow for every single interval so let's say initially the count is n every time we detect overlapping intervals we decrement the count so overlapping interval decrement the count cuz one Arrow will pop both balloons two birds one stone something like that and next these two are not overlapping therefore this will need its own Arrow these two are overlapping therefore we can just decrement this by one again that said the more I'm thinking about it maybe it is just more intuitive uh just to initialize the count to one so you can pick whatever you prefer now let's code this up but before we do what is the time complexity of this going to be even though we just go through it in order in oent time remember we are sorting before we do that so the actual time complexity is going to be n login depending on the memory usage of the Sorting algorithm there might be some additional memory needed for that okay so now let's code it up these are the notes in case you are interested but I'm going to get rid of them uh you can probably pause the video if you wanted to see them so first things first let's go ahead and run points. sort then like I said I'm going to initialize the result equal to the length and just decrement it every time but you can initialize it to one if you'd rather do that we're going to go through the intervals and we want to compare adjacent intervals but we also want to be able to merge intervals so if we were to initially try to solve the problem like this I in range from one to the length of points and the reason I'm doing one is because I want to be able to do something like this where we get the interval at I and we also get the interval at I minus one I want to be able to do that but you'll find that okay if we're comparing with the previous interval in some cases we're augmenting the previous interval with the merge remember we're augmenting it we're merging it technically we could do that in place we could modify the array if we wanted to I guess we kind of already did when we sorted it but I'd prefer not to do that so what I'm going to do is actually just keep track of the previous interval in a separate variable like this so points of zero is initially going to be the previous interval because we are starting at one over here and I guess I might as well get the current interval and put it in a variable so that we don't have to keep indexing like this now we're going to do the comparison we're going to check are these guys overlapping is the start of the second interval aka the current interval so that's going to be current at index zero is it less than or equal to the ending of the previous interval if that's the case then both of these can be killed with one Arrow so we say result minus1 we also now merge them and then store it in previous so just like this how do we merge it though I guess I didn't really talk about that visually though if you think about it since these are in sorted order the start time is always going to be from the current interval it's going to be the Lesser because this is always going to be greater than or equal to the start of the previous interval so we can say the start of this is going to be current of zero okay but what about the ending time technically we could have intervals that are sorted like this like let's say I have a 1 and a five and then I have a 2 and a six so in this case the second interval has an end time that's greater in another case we you can imagine we'd have something like this 1 15 and maybe 2 to 4 so this time the ending is smaller than this one so if we just want the overlapping section of these two it's going to be from 2 to 5 if we want the overlapping section of this it's going to be from 2 to 4 so we already concluded that this is always going to be from the second interval but the ending could be different and how do we know which one to pick well basically we're going to take the minimum of this and this it happens to be five this time we're going to take the minimum of this and this it happens to be four this time so that's what we're doing here we're going to take minimum of current of one and minimum of previous of one okay so this is the case where they are overlapping what about the case where they're not overlapping well we don't really do anything cuz we already assumed we need an arrow for every single interval over here I guess what we do is update previous still we will now set previous equal to the current interval so this is the entire code let's run it to make sure that it works and as you can see it's pretty efficient if you found this helpful please like And subscribe check out n code. if you're preparing for coding interviews thanks for watching and I'll see you soon
|
Minimum Number of Arrows to Burst Balloons
|
minimum-number-of-arrows-to-burst-balloons
|
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array `points` where `points[i] = [xstart, xend]` denotes a balloon whose **horizontal diameter** stretches between `xstart` and `xend`. You do not know the exact y-coordinates of the balloons.
Arrows can be shot up **directly vertically** (in the positive y-direction) from different points along the x-axis. A balloon with `xstart` and `xend` is **burst** by an arrow shot at `x` if `xstart <= x <= xend`. There is **no limit** to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.
Given the array `points`, return _the **minimum** number of arrows that must be shot to burst all balloons_.
**Example 1:**
**Input:** points = \[\[10,16\],\[2,8\],\[1,6\],\[7,12\]\]
**Output:** 2
**Explanation:** The balloons can be burst by 2 arrows:
- Shoot an arrow at x = 6, bursting the balloons \[2,8\] and \[1,6\].
- Shoot an arrow at x = 11, bursting the balloons \[10,16\] and \[7,12\].
**Example 2:**
**Input:** points = \[\[1,2\],\[3,4\],\[5,6\],\[7,8\]\]
**Output:** 4
**Explanation:** One arrow needs to be shot for each balloon for a total of 4 arrows.
**Example 3:**
**Input:** points = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\]\]
**Output:** 2
**Explanation:** The balloons can be burst by 2 arrows:
- Shoot an arrow at x = 2, bursting the balloons \[1,2\] and \[2,3\].
- Shoot an arrow at x = 4, bursting the balloons \[3,4\] and \[4,5\].
**Constraints:**
* `1 <= points.length <= 105`
* `points[i].length == 2`
* `-231 <= xstart < xend <= 231 - 1`
| null |
Array,Greedy,Sorting
|
Medium
|
253,435
|
354 |
hello guys welcome to algorithms made easy today we will be discussing the question russian doll envelopes in this question we are given a 2d array of integers envelopes where envelope i represent the width and the height of an envelope one envelope can fit into another if and only if both the width and the height of one envelope is greater than the width and height of the other envelope we need to return the maximum number of envelopes we can russian doll that is we can put inside each other note that we cannot rotate the envelopes in the first example we can see that we can rush into all three envelopes by putting 2 comma 3 into 5 comma 4 and then putting 5 comma 4 into 6 comma 7. and in the second example we can see that all the envelopes are of the same width and height so we return 1 as we cannot rush into all any of these so let's first see what the problem is all about and how we can solve this so suppose this is the example that is given to us and we need to find how many envelopes can we russian doll so as we know that we can rush into all three of the envelopes and how we can do that is we have these three envelopes two comma three five comma four and six comma seven we will put two comma three into five comma four as the height in the width is smaller and similarly putting this envelope into six comma seven so let's bring our attention only to the width of these envelope first and we see that they are in an increasing fashion we can easily make this array in an increasing fashion by sorting this array based on the width so what we can do is we can directly sort the array on the basis of width and then we will get this array so now all we need to take care of is the height of these envelopes they must be in the increasing fashion and no to envelop should have the same width now let's bring our attention to the second value which is the height of these envelopes we will discuss a brute force approach as to how we can find an increasing subsequence made from these second digits that is in this case becomes three four seven we know that we can put two comma three into five comma four but we cannot put 5 comma 4 into 6 comma 4 as the two heights are equal so we need a strictly increasing subsequence so we cannot include 6 comma 4 into our result in order to better understand this problem let us change the six comma four to six comma five and also add one more envelope with the width as seven and height as six so now the result should be 4 envelopes because as you can see in the diagram we can put in 4 envelope in russian doll fashion now with this new array the increasing subsequent result should be 3 comma 4 comma 5 comma 6 which we can see in the diagram also now let's see how we can find this subsequence using a brute force approach we will be using an array instead of the index we have returned the width and the height so that it is much more clear the value at the zeroth index of this array will always be one because the result will be at least one now what we need to do is for every value starting from five comma four till the end we need to compare the height with all the previous heights in the array so we will be comparing 4 with 3 in this case finding out what is the maximum value that we can get in this case we can get to 1 so we will put 1 plus 1 which is 2 at this particular index now we will move to the next value that is 6 comma 5 and we'll compare this 5 with all the previous value that is 3 and 4 as it is still a greater value we'll find the maximum of these values which is 2 we'll add 1 and put 3 over here and now we come across this 7 and we compare the values with three four and five the answer should be four over here but we have written three because we need to also take into consideration the width of the envelope should not be the same only when the width is not same and the height is greater then only we will be considering the value present at that index in this case the last value that was considered was 5 comma 4 so we take the 2 add 1 to it and put that at the index of 6 comma 7 and similarly we'll move till the end wherein we have 7 comma 6 we compared the 6 with all the values the last value that it consider is 6 comma 5 both the height and the width are greater so we put 3 plus 1 that is 4 at this index at the end we can find the maximum value stored in this array and then we can return it now it's time to code this approach so as discussed we need to first sort the envelopes array based on the width of the envelope so we'll use the arrays.sort over here now that the array is sorted based on the width we saw that we need a array in order to store the intermediate results so we'll have this array which we'll call dp and now we will have a max length variable which we talked about also we discussed that at the 0th index the value should be 1 because there will be at least one envelope now i'll start our loop from the first index till the end of this envelope array we know that minimum one envelope will be returned so at each place the minimum value will be one now for all the envelopes before this envelope that is from zero till i we will loop and we'll update the dp of i based on the condition that the width of the two is not equal and the height is greater than the envelope present at jth index so we'll write those two conditions so this is the first condition where the two envelope width should not be equal and now this is the second condition wherein the height of the envelope at ith index should be greater than the envelope at jth index and now we find the maximum so the value of dp of i will be either dp of i or dp of j plus 1 once we have found the value at dp of i will update this maxlen variable with the maximum value of either the max length or the value at present at dp of i so this max length will contain the maximum value in dp array at the end we just need to simply return this max length variable so the coding part is done when we run this code for all the test cases it is successful let's submit this so it got submitted successfully the time complexity is of n square while the space complexity is often this solution is good but how can we reduce the time complexity further we can only apply an optimization approach in this for loop or more precisely by removing this for loop which is going in the worst case up to n we can devise a method wherein we can bring it down to login now the concept that we will be using over here is called binary search it can be a tricky at first but once you get to know the idea behind it will be much more useful in further questions as well so do take your time to understand this properly so let's see what the approach says with the help of an example so this was the example that we discussed earlier and we had sorted the array based on the width only as we're doing the brute force on the height values so now let's consider we have an array like we had before and instead of storing the count of the envelope that we can fit in till that envelope we will be storing the value in this array so we'll first store three now we move to four and as four is greater than three we store that and similarly five and then also seven but here the flow is wrong as we cannot put in envelope six comma five into six comma seven as the width are equal so where we went wrong as we were putting in values into this array we were trying to find the smallest value greater than the current value that we are trying to put in and as we got no values we were putting the values at the end of the array but since we are not taking into consideration the width factor in this array we have no idea that we cannot put in 7 after this 5. now just for a thought if we sort the height in descending order when the width is same we get 7 before this 5 and the 5 won't be considered when 7 is already there so in that case we'll first put in 7 and now when we'll try to find a position for 5 it will point us to the same index which was of 7 and when we put this value we still have a count of 3 only and then we put in 6 which can very well be placed as it is higher than 5 and when we count the length of this array we have four values in this array and the result is also four now when we're trying to find the smallest value that is higher than the current value that we're trying to put in we can use binary search for that as the data in this array will be sorted and when we are using a binary search the complexity goes down to log n and hence the complexity of overall program goes down to n log n we'll see two ways to apply binary search first by applying our own manage search and then by using the inbuilt function given by java so there is a slight difference in the two so it's time to code that there are two major differences that we saw that firstly we need to sort the array based on the height also and we are sorting that on the base of descending order only when the width of the two envelopes are equal so if the width of the two envelopes are equal then we will sort the array based on the width in descending order otherwise it is based on the width now the next difference that we will see is over here so we'll remove this and we don't need this dp1 as well we'll have this max length which will be initially 0 now and we will loop from 0th index we will try to find a position for every value of the envelope or more precisely for its height so find the index of height of envelope at its position is what we need to do over here so we'll have an index and we'll have a binary search in binary search we need these many parameters we need the array we need the start we need the end and then we need the value which we need to find and that value in this case will be envelope of i at 1. now once we have this index we'll put the value that is envelope at i in 1 at this index and if the index and the max length are equal that means we have added one more value into this array so we need to increment this max length and at the end we will be retaining the max length now let's implement this method which is binary search it will return an index variable it will take a dp array will take array there will be a start value will be an end value and there will be a target that we need to find now we know that a basic binary searches a start is less than end will find the mid value if the value at this mid is equals to target then we have already find the index and we directly return the mid else if the mid is greater than the target we make end as mid and in the else part we make the start as mid plus 1 at the end we return start this completes the coding when we run this code it runs successfully let's submit this it got submitted successfully the time complexity in this case becomes o of n log n while the space complexity is still of n now we do not need to implement our own binary search we can use the inbuilt binary search function so we'll implement over here so the index over here will now become arrays dot binary search which take the same number of arguments now this returns a negative value when the value is not present so if the index is negative then we'll change that into positive by adding plus one and at the end we need to return the index so by using this inbuilt function also we can solve this problem now this question is an extension to one of the lead code problems wherein we need to find the longest increasing subsequence and what we did by finding the increasing sequence of the heights is what primarily the longest in subsequence problem is so we can have this much of code into a method and put this code into the longest increasing subsequence and still get this right result so do try to apply the logic and the approach that we have learned in this question into longest increasing subsequence this is the problem that i was talking about which is longest increasing subsequence do let us know your thoughts in the comments below thanks for watching the video see in the next one
|
Russian Doll Envelopes
|
russian-doll-envelopes
|
You are given a 2D array of integers `envelopes` where `envelopes[i] = [wi, hi]` represents the width and the height of an envelope.
One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.
Return _the maximum number of envelopes you can Russian doll (i.e., put one inside the other)_.
**Note:** You cannot rotate an envelope.
**Example 1:**
**Input:** envelopes = \[\[5,4\],\[6,4\],\[6,7\],\[2,3\]\]
**Output:** 3
**Explanation:** The maximum number of envelopes you can Russian doll is `3` (\[2,3\] => \[5,4\] => \[6,7\]).
**Example 2:**
**Input:** envelopes = \[\[1,1\],\[1,1\],\[1,1\]\]
**Output:** 1
**Constraints:**
* `1 <= envelopes.length <= 105`
* `envelopes[i].length == 2`
* `1 <= wi, hi <= 105`
| null |
Array,Binary Search,Dynamic Programming,Sorting
|
Hard
|
300,2123
|
108 |
hey there so today we'll solve one of the problem on lead code uh the problem which says convert sorted array to binary search tree uh to solve that um we will be given input in the array in the binary tree we know that anything which is less than node a root node will go to the left anything which is higher than the root will go to the right so first do the sanity check if num is equal to zero then we will return just null else we know have i'll use recursion to solve this problem so i'll use add to three method and this method will take input as a num array then the start index and then the index length minus one and at the end i'll return this head okay now the main logic will be written inside this add to three um we have an array then start index and end index okay now uh if start is greater than in then return null will start to not be greater than end okay otherwise first of all we need to find the middle so that we can arrange the value between from root middle will be the root and we can arrange values to the left hand side of tree and right hand side the end may be 22 star plus n divided by two okay now uh we need to add value to the left as well as to the right okay so uh this and this will uh we can slide it with the value so num mid will be assigned to the root now node dot left equal to it will have nums to 3 here the start index will be make plus one and in index will be end okay and i think we need to return in this root okay so i hope this will uh solve this problem if nums everywhere i have used num node yes it will be root yeah so this is also problem so in the sorted area we have created a uh binary search tree from there this is the main logic that we need to focus on so thank you so much for watching today's video and if you think the videos are helpful do like the video and subscribe to the channel
|
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
|
100 |
question 100 delete code same tree so given the root of two binary trees p and q write a function to check if they are the same or not two binary trees are considered the same if they are structurally identical and the nodes have the same values so with this question it's going to be a recursive solution so what we need to look at is we need to create some base cases so with any recursive solution we have a base case and we have the recurrence relation so what the base case is going to do is it's going to pop us out of this recursive call stack otherwise we'll enter in an infinite loop okay and the recurrence relation is what's going to get us closer and closer to the base case after each kind of recursive call so we need to define some base cases and we need to define the recurrence relation right we're checking to see whether these trees are the same we need to check whether these nodes are the same and then we need to split it in two afterwards and check whether these are the same and also whether these are the same and then we'd split these in two so it's more of a divide and conquer approach okay let's consider these base cases so in the most basic tree you can think of we have p is equal to null and q is equal to null these are the two trees both equal to null so if they're both equal to null we can simply define this and say return true however what if one is not equal to null and the other one is so say one is equal to null or q is equal to null in this case we can return false so that's another base case sorted now let's work out what would happen if the values were the same we can return true right and if they're not equal to each other we can return false so these are the three base cases we've got so we've got this one where p is equal to norm q is equal to n we can return true if p is equal to null or q is equal to n we can return false and if p dot val is equal to q dot val we can return true and then with the recurrence relation what we need to do is we need to check both the left trees and also both of the right trees so we need to do two recursive calls and then what we need to do is we need to create that recurrence relation and in order to do that we need to do two separate recursions one that checks the left subtree of both the trees and then one that checks the right subtree of both the trees and with these base cases in place it will carry out the check within both trees with respect to time complexity we're going in the worst case scenario say all the values are equal to each other like in this case we have to iterate through each individual node of both p and q so it's going to be op plus q and then space is just one because we aren't allocating any extra space okay so let's write out the solution so we need the base cases written up so in this case it's going to be p is equal to null and q is equal to null we can return true if p equals null or q is equal to null then we can return false then we check the values of both p and q so if p dot vowel is equal to q dot vowel then we can carry out the recurrence relation so we can carry out these recursive chords both down the left subtree and the right subtree so we need to return this because we want to return a value whether it's true or false so is same trade p dot left q dot left is same tree p dot right q dot right and this will create that recursive leap of faith else what we're going to do is return false because if p.val does not equal false because if p.val does not equal false because if p.val does not equal q.val q.val q.val then return false let's give this a try submit it and there you have it
|
Same Tree
|
same-tree
|
Given the roots of two binary trees `p` and `q`, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
**Example 1:**
**Input:** p = \[1,2,3\], q = \[1,2,3\]
**Output:** true
**Example 2:**
**Input:** p = \[1,2\], q = \[1,null,2\]
**Output:** false
**Example 3:**
**Input:** p = \[1,2,1\], q = \[1,1,2\]
**Output:** false
**Constraints:**
* The number of nodes in both trees is in the range `[0, 100]`.
* `-104 <= Node.val <= 104`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
3 |
hi it's Tom today we are going to solve another very popular problem which is being used during the coding interview it's called longest Sam string without repeating characters so it's pretty easy to understand what's the problem but let's read the dead description given a string find the length of the longest substring without repeating characters and there are a couple examples here in leet code as always we are using cleat code so how can an input in the form of a string ABC be B the output is free of course because the longest substring is ABC or C a B it doesn't really matter we are being asked to provide the length not the exact string so maybe let's switch to the whiteboard so I can show you two solutions for this problem one will be the brute force as usually and the second one will be more optimized using so-called sliding window methods okay so-called sliding window methods okay so-called sliding window methods okay so we are already on the whiteboard I put the string as a reference and the first way to solve this problem is to use the brute force method so for each character from the string will be creating a set and checking all the following characters as long as there is no same character in the following set so maybe start with an example so start with the first character and the first set will be a then we are checking the next character is B it's not in the set and then we are checking see it's not in the set and then is a which is already in the set so it's the end of checking in this case and the longest substring in this case is free so now we have to check all the characters for the second character so starting with B there's a B then there's C then there's a then there's B so it's already in the set is complete it's free so and we have to do that for all following characters C a b c BB it's this pattern is pretty easy to understand this method works it's the easiest and the first one which will probably come to your mind and for a coding interview you can definitely use it then if this will work then you can try to optimize it and but yeah it's working and there's a second so solution which is so called a sliding window method and the sliding window method is definitely more efficient much more efficient and it's pretty simple to understand so we can start treating this string as an array of characters it's just easy to imagine this drink as an array of characters to understand the sliding window method and in this case we are starting with the array which contains just one element so maybe let's write it in these types because it's not a long string honestly and we create an asset which contains only one element and it's a it's okay and then we can expand the window make it longer as long as the set count contains only characters which are different so in the second step this set is a and B the sliding window is bigger in the third step the sliding window is a B and C it has three elements in the fourth step window has a B C and a and as you see it's no longer substring without repeating characters so after this step we have to change the datee window so we move the left part of this we remove the most left element so the we remove the we don't move this the window to the right we just make it a little bit small splitting the first element so now the window contains B C a and yeah it's still a set of its a substring without repeating characters in the next step we have B C a and B and it works in the same way as above so we have to remove the first element so we have C a B in the next step we have see it just you see the pattern see a b c we have to change it so it's a b c and okay maybe let's we split it in the seven step we have a b c and there's a B so as you see we have to remove two elements to make the sliding window an array of non repeating characters so it's only C B and last step we have C B and as a result the last set contains only one letter one character and yeah that's a result as you see there are four cases in which there is a there's longest sub tree frogs ribbiting characters and it's length is free so these are two methods to solve this problem and let's switch back to the xcode vs code sorry to see this solution written in javascript okay we are back in the base code so maybe let's start with implementing the first way the brute-force method so first way the brute-force method so first way the brute-force method so maybe let's start with counter and now we have to create a loop for all characters in the string okay maybe let's get crack their hat and create a set to start okay and then starting from this point we have to create another loop to check all the following characters as long as the set contains non repeating characters so Jeff maybe let's use the for loop it's so inefficient that it doesn't really matter if it's wider or 4G so if set has this character then we break gloop in other case we just add it okay and the count should be updated only if its speaker so count and set size okay yeah it should work let's try yeah it's working so this is the brute force solution it's very inefficient but if you will be able to write it quickly during your interview then it should work at least you will be given more time to optimize it so okay maybe now let's implement the sliding window method which is much more efficient we won't need that okay this is what we need so now we have to get the index of start of the window and index of the end of the window and the length okay great and you're set it might be empty so now I can use while of the roll is I has to be smaller than length of the string and J has to be smaller than length of the string can hit the character J yeah because we need the new character on which is the most right character hope it's you understand what I'm talking about okay so if set doesn't have this element this character we have to add it and we can move J to the right so we can move the right side of the window we can just expand it two to the right and we can update the count and the current count is the difference between J and I because that's the difference between the position of the end of the window and the beginning of the window it's zero and in the first case but after the first step as you see the J is incremented so this sliding window has one element and the difference J - I has one element and the difference J - I has one element and the difference J - I will be one so it should work okay and in other case we just have to delete the first element okay an increment I which will move the left part of the sliding window it will just make it shorter okay let me see it should work I believe yeah screw the output yeah it's totally fine and it's working so mmm I hope you enjoyed the video I presented two ways to solve the longest substring without repeating characters problem the first one was the brute force and the second one is the sliding window which is much more efficient method and if you enjoy these kind of videos please let me know in the comments thank you for watching bye
|
Longest Substring Without Repeating Characters
|
longest-substring-without-repeating-characters
|
Given a string `s`, find the length of the **longest** **substring** without repeating characters.
**Example 1:**
**Input:** s = "abcabcbb "
**Output:** 3
**Explanation:** The answer is "abc ", with the length of 3.
**Example 2:**
**Input:** s = "bbbbb "
**Output:** 1
**Explanation:** The answer is "b ", with the length of 1.
**Example 3:**
**Input:** s = "pwwkew "
**Output:** 3
**Explanation:** The answer is "wke ", with the length of 3.
Notice that the answer must be a substring, "pwke " is a subsequence and not a substring.
**Constraints:**
* `0 <= s.length <= 5 * 104`
* `s` consists of English letters, digits, symbols and spaces.
| null |
Hash Table,String,Sliding Window
|
Medium
|
159,340,1034,1813,2209
|
885 |
i Bakir read called questioner 885 square matrix 3 this is the mid intestine ok that's guaranteed on the two-dimensional grid two-dimensional grid two-dimensional grid did Allah and seek help and we started where i'll 0 and C 0 okay now we walk in the clockwise with the special shapes period shape is like this okay whenever we will put us out of boundary to create even that is outside we still continue to work outside of grid eventually we'll each or item what is all animal blood is countable rider is yes I modify see ya return arrest coordinate different age clip indicating the position of the great in the order they were visited okay let's get into example to can we provide a grid and creat allow is five zero one two three four six three oh five and then start position is out is one so at least one LC is four useful so we start here okay first we moved our only one right so when you move the one at that time we need to change the direction here to here right and how about the movement is still one right after mobile one we are we needed to change the direction and okay now you are here at that time how about movement number one it is 201 is increase okay let's see legs next easily next movement is one two all X's to happen next is one two and three oh yeah now is three and next three must be three one two three and next most before one two three four text must before 1:30 so we found four text must before 1:30 so we found four text must before 1:30 so we found some occasion first if first time is start okay let first is one direction changes to pi and then when they stop and we eat it all item is I'll notify see star okay then let's start with this condition all right okay let's say let make variable forest first we need to alpha to get coordination and the finally we will return and then you'll need love for storing color and initial use we will use one from so see not our actual teacher okay next one and then maybe we also need so it me now is the hydrogen see turn right and karate softer each mean is it able to up one time to book when you arrive the movement it will change direction and each to time we also increase okay let it ready okay I will use vibrating when you do stop all chattering planks is famous but I see it needed to be stopped so continue did you make a sense and then when calorie yeah inside of boundary between two feet it meet with like me to see and then I care coughs we needed to gap coordination right oh okay let me make be discreet max after that okay we will move to next item is we have state space we will move it depend on direction oh there is no direction has three taro must be okay right we will check this instant so time to time in is okay first is the law all right this increase no say how about in your life down here this is checkpoint if down is to increase yes this one is one this all one to increase one so increase okay next is how about left when you're like to hear want to want sake right 1 2 1 6 so this one does not decrease their oh when you're like all 1 2 3 so when we going down and we need to increase right so maybe we can write like this what is down is one but if you want more fancy maybe we also wanted is the sameness essential right so maybe this is and if you want to show to interview I know two-bit operation at the time we I know two-bit operation at the time we I know two-bit operation at the time we can able to change masks okay limit is free okay one is the mask is one it is tied if the attraction is one and one is through our course it is to write and then our three one two three with one actually it compared one and one so it is true so it come from one class and then I release it oh I think we finished yeah okay five six are tiny Mira okay all five six up this Jeremy I need to start from our zero black and I'm connections that Rho 0 by movement is possible and then while of these links is a let's see who noticed before movement yes this also quiet and interchange and knees in this time this columnist 104 and this is love this is column so increase column right yeah this is really okay now that the okay let see time and space complexity in this case is when if we assume the all item of eternal matrix is a maybe time complexities or and because we just it raised to one idea one by one space complexity there are no exchanging space except alpha also I think we can say oh one space complexity thank you
|
Spiral Matrix III
|
exam-room
|
You start at the cell `(rStart, cStart)` of an `rows x cols` grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.
You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all `rows * cols` spaces of the grid.
Return _an array of coordinates representing the positions of the grid in the order you visited them_.
**Example 1:**
**Input:** rows = 1, cols = 4, rStart = 0, cStart = 0
**Output:** \[\[0,0\],\[0,1\],\[0,2\],\[0,3\]\]
**Example 2:**
**Input:** rows = 5, cols = 6, rStart = 1, cStart = 4
**Output:** \[\[1,4\],\[1,5\],\[2,5\],\[2,4\],\[2,3\],\[1,3\],\[0,3\],\[0,4\],\[0,5\],\[3,5\],\[3,4\],\[3,3\],\[3,2\],\[2,2\],\[1,2\],\[0,2\],\[4,5\],\[4,4\],\[4,3\],\[4,2\],\[4,1\],\[3,1\],\[2,1\],\[1,1\],\[0,1\],\[4,0\],\[3,0\],\[2,0\],\[1,0\],\[0,0\]\]
**Constraints:**
* `1 <= rows, cols <= 100`
* `0 <= rStart < rows`
* `0 <= cStart < cols`
| null |
Design,Ordered Set
|
Medium
|
879
|
374 |
so hello everyone i am straight i am a software development engineer so we are starting with this lead code premium top interview problem series we will be discussing each and every problem which are mentioned on the lead code top interviews and also this will help you to crack your next coding interview in the top notch product based company so let's start with the problem so hi everyone today we look at this problem uh that is a guess number higher or lower okay so it's a very basic binary search implementation problem so let's read the problem statement okay so it says that we are playing a guess game the game is as follows i pick a number from the range given okay one to n and you need to guess that number we have a predefined api guess which returns three possible results that is minus one if the number guess is higher than picked one is for the lower one and zero is for the equals to the number if we get the correct okay so uh let's take an example and right then try to go through how we will apply binary search on this problem okay so let's say that the range given to us is 1 to n and let's say n is 10 and the pick number is 6 as given in the test case okay so it will be 1 2 3 4 5 6 7 8 9 and 10 okay and we pick number six we need to whenever we see this kind of sorted range obviously we can apply binary search on this okay so for applying binary search we need the sorted thing that is given to us okay then we need to find the lowest number okay lowest number that is following the guess let's say whatever is the number guess let's say our number will be m and which is less than equals to zero okay so the lowest number following this condition will be our answer according to binary search okay so let's try to implement it then it will be more clear to you what i'm trying to say okay so the range given to us is 1 to n so this is done now what is this we'll calculate the mid okay so this is the mid now what we'll see that what guess given to us if it's less than zero that is the case of minus one and zero okay so what we need to do we need to make our r point towards this okay now else l will be m plus one and what we'll do we'll return simple so let's run this and it will be good too less than equals to um okay i think oh there's a small thing this range is defined this is them okay let me just write it within brackets might be possible right now just click once okay and now it's fine oh it should be less than equals to zero okay that condition is all so now it will run fine yeah see it got accepted okay so we need to take care of this condition only and this will return the lowest number following the above condition okay so let's just submit this okay so one more thing that you need to remember in case of binary search is that it should be minus l and now if we submit it got accepted okay so the overflow condition occurs when we directly take the average of both the terms okay so uh make sure that this these things won't happen when you submit this and okay thank you do like share and subscribe and we'll meet you in the next okay thank you 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,800 |
all right let's do the code um okay easy okay have i done this no given an array of positive numbers it turned the maximum possible sum of an ascending sub array in nums summary is to find looking to use this on numbers in an array is sending of an ascending so it's not necessarily ascending size one is ascending okay so i'm gonna look what is ascending this is ascending so we have a 40 uh we have 50 60 there that's the answer oh actually oh 5 10 50 is the answer so i'm guessing just a linear loop through and as long as it's ascending keep adding to the array otherwise if it's if the current element is less than the previous element then just set the value to whatever the current element is so there's at least one element in the area i think oh it's only a hundred and that should work let me try on some examples um 12 17 that's ascending that's not the answer 15 nope that's by itself 13 nope 10 11 12 is probably 33 i think that will work here it's a hundred okay so i'll start from four into i is equal to one i less than nums dot size plus i so if the current element so if nums at i is less than the previous nums i minus one and answer is equal to nums i else answer um oops else answer plus equals to nums i right that makes sense and each stage also want to record the highest one so i'll say actually make this current and the answer is one i want to record so answer is equal to maximum of answer and current so initial initially we have a answer and a current and they should both be equal to num0 and at the end just return answer okay that's 65. okay i think we gotta find an easy one today come on oh my goodness what happened oh has to be i can't believe i didn't think of that less not equal to um so it's where l is less than or equal to i which is less listen ah and numbs eyes yeah so it's not ascending if um they're equal so oops damn it i thought i had that one all right
|
Maximum Ascending Subarray Sum
|
concatenation-of-consecutive-binary-numbers
|
Given an array of positive integers `nums`, return the _maximum possible sum of an **ascending** subarray in_ `nums`.
A subarray is defined as a contiguous sequence of numbers in an array.
A subarray `[numsl, numsl+1, ..., numsr-1, numsr]` is **ascending** if for all `i` where `l <= i < r`, `numsi < numsi+1`. Note that a subarray of size `1` is **ascending**.
**Example 1:**
**Input:** nums = \[10,20,30,5,10,50\]
**Output:** 65
**Explanation:** \[5,10,50\] is the ascending subarray with the maximum sum of 65.
**Example 2:**
**Input:** nums = \[10,20,30,40,50\]
**Output:** 150
**Explanation:** \[10,20,30,40,50\] is the ascending subarray with the maximum sum of 150.
**Example 3:**
**Input:** nums = \[12,17,15,13,10,11,12\]
**Output:** 33
**Explanation:** \[10,11,12\] is the ascending subarray with the maximum sum of 33.
**Constraints:**
* `1 <= nums.length <= 100`
* `1 <= nums[i] <= 100`
|
Express the nth number value in a recursion formula and think about how we can do a fast evaluation.
|
Math,Bit Manipulation,Simulation
|
Medium
| null |
611 |
Thank you hi everyone welcome to my channel it's all the problem first triangle number sudhir 1000 from are subscribe me to for triangle properties basically subscribe and share and subscribe video please language video internet subscribe a solution vic and dros bengaluru power free for life sexual more 2513 This hole from plus one upon in subscribe The Channel Please subscribe Security Sudhir and five plus Ujjain a great will do this channel subscribe our to condition president over and subscribe our number 90 meeting attend total number of the solution appointment not only and Just And Saw Her And Know The Little Improvement Thursday Like Subscribe Video then subscribe to The Amazing Two Examples Which Give Nomination Values vs. Them Were Taken From This Way Nomination Values vs. Them Were Taken From This Way Nomination Values vs. Them Were Taken From This Way Foundation Subscribe to Me on Twitter Subscribe to RSS Definitely The Meaning of This Country Will be improved with solution in terms of time complexity of you can do subscribe like in this not to that slide we can apply some sort of two point approved we can you solve these pointers and like the final point from 1000 likes I will run away for loop oil from - 121 running this is the name loop oil from - 121 running this is the name loop oil from - 121 running this is the name of the first and second clip from it - - of the first and second clip from it - - of the first and second clip from it - - 1929 subscribe plus names of this occasion z plus norms for add the numbers of i so in that case all the pair swiping diet k imu Positive From Left To Right Soldiers Were Taken From Every Move Away From Toward Always Be Values Of Your Form Total Be Values Of Your Form Total Be Values Of Your Form Total Number Of Channels Like This Condition Will Be For Boy K - 9 News In Hindi Boy K - 9 News In Hindi Boy K - 9 News In Hindi Subscribe For Latest Videos Subscribe To Channel Like Subscribe to this channel Ichchadhari from and minus one and abroad request to and I - - Sun President's is from it request to and I - - Sun President's is from it request to and I - - Sun President's is from it - 151 jewelers' check - 151 jewelers' check - 151 jewelers' check condition 9:00 plus fennel's is great according to condition 9:00 plus fennel's is great according to condition 9:00 plus fennel's is great according to fire in the case of number from tattoos for main strip le Take MBA degree ke no veer wa subscribe my channel is vansh hai android time threads in this can see fear for getting password note 210 isko viman battery saver is after some thing happening something standing time JK - - Jain and accept standing time JK - - Jain and accept standing time JK - - Jain and accept for Adult That Time Withdrawal Subscribe House Will Reduce And Subscribe Like And Minus One Time To Time So I Will Run From President Subscribe Time Complexity Of Square And Plus Login Which Can We Subscribe The Channel And Subscribe The But WiFi Setting Algorithm Subjective Cardamom Solution Hit the like button and subscribe my channel and also please share Priest to create more share Priest to create more share Priest to create more videos thanks for watching
|
Valid Triangle Number
|
valid-triangle-number
|
Given an integer array `nums`, return _the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle_.
**Example 1:**
**Input:** nums = \[2,2,3,4\]
**Output:** 3
**Explanation:** Valid combinations are:
2,3,4 (using the first 2)
2,3,4 (using the second 2)
2,2,3
**Example 2:**
**Input:** nums = \[4,2,3,4\]
**Output:** 4
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] <= 1000`
| null |
Array,Two Pointers,Binary Search,Greedy,Sorting
|
Medium
|
259
|
1,335 |
hello guys welcome to my channel and today i'm gonna share um legal question number one three five the minimum difficulty of a job schedule and the description is we have to schedule lists of jobs in d-days schedule lists of jobs in d-days schedule lists of jobs in d-days and the jobs are dependent which means you have to finish the first job and then do the second job and you have to finish the current job to do the next job and you have to finish on the next job then do the next job right so and we have to finish at least one task every day and the difficulty of a job schedule with the sum of difficulties of each day of the d days and the difficulty of a day is a maximum difficulty of a job done in that day so how can we solve this problem and so the question asks us to uh just return the minimum value instead of finding the specific job schedule so it is kind of a typical dynamic programming and the key to a dynamic programming is the first to find the uh state transition equation and then the second to uh determine the initial values so at first let's just find out the so-called state let's just find out the so-called state let's just find out the so-called state transition equation and when we solve algorithm questions we generally start with the intuition uh for example uh brutal force is kind of um intuition and in this dynamic programming we are asked to uh plan our job so uh so let's try to see from our intuition that if we uh can make a schedule so the problem requires us to do at least one job a day so each time we arrive at a new day we can choose to do one job or two job or three jobs and so on and then by the next day we can still choose to do a one job two jobs or three jobs and so on so how can we choose and the question asks us to choose the least difficulty combination of tasks each day that is we have to uh choose the least difficult combination among all the combinations well this is our intuition and each day has multiple choices and all the days make company many combinations so we have to choose the best one from all the combinations okay so let's use a table to show the process okay here's a table and we can see there are five rows and three columns that means we have to do five jobs in uh three days all right so okay here's a question what does each cell mean okay it means the minimum difficulty to complete j job j jobs in light days okay the first cell here is that means we just do one job in one day all right because that's just the first job and the first day so we have to do one job in one day and let's look down the next one that means we have to do two jobs in one day and this means we do three jobs in one day and this we do four jobs in one day and this means we do five jobs in one day so what's the value of these five cells okay so quite simple right uh in this first cell we the value will be the difficulty of job 1 and the second cell will be the max value amount between job 1 job 2 and the third cell here is the maximum value among job one two three and here is a max value in job one from one to job four and here is a maxwell from drop one to top five so it's quite easy to understand right and i just use a different color to make it clear to see and this uh yellow one i mean the first day we do the first job and the right one i mean the first day we do two jobs and the red a green one the purple the black so let's see uh the second calling in that's called what does this cell mean that means impossible that means we have to do one job in two days that's impossible because we are asked to uh do at least one job in one day so just one job in two days so that's impossible and we just set it to uh infinite and what does this mean this cell means we have to do two jobs in two days right so how many choices do we have or we have just only one choice just do the first job in day one and do the second job in day two so the first job in day one i use this yellow color that means is same as this one so this part is this part all right and plus the value just we do drop two in job in day two all right so let's look down the next cell how about this one this means we do three jobs in two days and how many choices do we have okay we may have two choices right the first is to do job one day one and then do job two and three in d2 and the second choice is we do job one and two in day one and plus do chop three in d2 all right so this is this cell right i'm sorry this uh is this cell right and just a plus to do the rest jobs and how about this one it's just a do two job in day one and kind of uh this cell right do two job in day one and plus do the rest job the third job in day two and let's look down the next cell how about this one it means we do four jobs in two days so how many choices do we have okay this is kind of um spend some time i just uh explain the details of this process to uh show you guys how the process is yeah right so this means do four jobs in two days so how many choices do we have we just do job one in day one which is this cell and plus the rest job do the rest job in day two and do one two job in day one which is this cell and plus the rest job in day two and do one two three job in day one which is this uh green that means we do three job in day one right and then plus we do the rest job in day two okay and this means we do full uh five jobs in two days and how many choices do we have four just do job one in day one and then do rest jobs to drop one two in day one do the rest jobs and drop one two three into one and do the rest jobs and do jump one two three four five one two three four in day one and then do the last job in day two and this cell the well this cell is the minimum value of all these values from all these values the minimum value in this four values okay so now is kind of a getting clear right now we can see how it works and let's just see uh this column it's quite easy right uh this impossible isn't possible because we cannot do one job in three days or two job in three days at least we have to uh do at least three jobs in three days so we start from here just do three jobs in three days that means uh we have uh no other choices but to just uh do two jobs in two days in two jobs in two days and plus do three job in the third day so this is kind of the black one is this one due to job in two days and then do the next and this cell is about to uh do four jobs in three days and how many choices do we have so we can have we can do two jobs in two days and then do the rest jobs on the last day and then okay this black one is this cell did to drop in two days and how about this one as a dark blue one i do three job in two days kind of this so right so and then do the last job in the last day which is a the fourth job in the third day how about this last cell let's look and this cell means we do the five jobs in three days all right and how many choices do we have we just do one job in two days two john two days three job two days and four job two day and then do the rest jobs right and the final value will be the minimum value of all these value values right and so this is a basic idea of how the process is so let's uh let's see the code all right uh let's just see the code and the code is quite short okay here's a job array and here's the left of the job array and here is a dp array and we just initialize it to the dp array with the uh just like the first column right it's quite easy to understand and then we do the loops there are a three level loop three loops here and the first is a day and then the job and then the what choices can you have how many choices can you have on each day for each job and here's a the max and we got the max value from the rest of jobs right and but this time complicity is a little bit slow because inside this three level loop we need to get the maximum value among the rest jobs on the last day here and we got the max value that uh it will take a lot of time it will take a lot of extra time but it seems we have no other choice because we just start drop one and then drop two and then drop three and if we do them just one by one and we don't know which job is the most difficult in the future because the jobs is jobs are in the future so we have to traverse all the rest jobs and so in this case how can we know which of the future jobs is the most difficult so we can consider another way that is let's just imagine that we have a time machine and we travel to the last job in the future and then we look backwards so here is a bad one and also three loops but we just keep the maximum value from the last one to the first one right so we just look backwards just keep the only maximum value each time and keep iterating backwards so that we can get the maximum value without iterating through all the rest of jobs each time so this is a better solution than this one so okay here's the explanation and solution for question 1 335 and this is my first time to do video and thank you for watching
|
Minimum Difficulty of a Job Schedule
|
maximum-candies-allocated-to-k-children
|
You want to schedule a list of jobs in `d` days. Jobs are dependent (i.e To work on the `ith` job, you have to finish all the jobs `j` where `0 <= j < i`).
You have to finish **at least** one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the `d` days. The difficulty of a day is the maximum difficulty of a job done on that day.
You are given an integer array `jobDifficulty` and an integer `d`. The difficulty of the `ith` job is `jobDifficulty[i]`.
Return _the minimum difficulty of a job schedule_. If you cannot find a schedule for the jobs return `-1`.
**Example 1:**
**Input:** jobDifficulty = \[6,5,4,3,2,1\], d = 2
**Output:** 7
**Explanation:** First day you can finish the first 5 jobs, total difficulty = 6.
Second day you can finish the last job, total difficulty = 1.
The difficulty of the schedule = 6 + 1 = 7
**Example 2:**
**Input:** jobDifficulty = \[9,9,9\], d = 4
**Output:** -1
**Explanation:** If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs.
**Example 3:**
**Input:** jobDifficulty = \[1,1,1\], d = 3
**Output:** 3
**Explanation:** The schedule is one job per day. total difficulty will be 3.
**Constraints:**
* `1 <= jobDifficulty.length <= 300`
* `0 <= jobDifficulty[i] <= 1000`
* `1 <= d <= 10`
|
For a fixed number of candies c, how can you check if each child can get c candies? Use binary search to find the maximum c as the answer.
|
Array,Binary Search
|
Medium
|
907,1886,2000,2027,2188,2294
|
18 |
welcome to good haircut is co-teacher welcome to good haircut is co-teacher welcome to good haircut is co-teacher here we're going to solve for some coding problem so given rate noms of integers and integer target are their enemies ABC and Dean are alums such that a plus B plus C plus D you go to target find all unique code to place in the array which gives a sum of target so not here the solution set must not contain duplicate called triplets for example here qumar a announced as a 1 0 negative 2 and target value is a 0 so our solution set is like this array of integers so we see here there are 3 quadruplets in this artery so that each culture place has a 4 numbers so 4 numbers they add up together or you could through the target so fossa is a follow-up question for so fossa is a follow-up question for so fossa is a follow-up question for popular Korean equivalent you may sing before that's a Tucson so Tulsa is about in rate we need to find two numbers and up together to the target and Tucson is a very popular Kooning public and Tucson has a many follow-up question thanks has a many follow-up question thanks has a many follow-up question thanks Teresa to first reason we need to find three numbers in re and up together to the target and then start fossa it requires even more to find the four numbers in the array to end up together to the target so it sounds more difficult so like a forza like a force answers more difficult than the Tucson tretinoin father but actually underline the hood the foursome has a similar pattern with a tu sonrisa so once we figure out the similar underlying pattern between the force and Tucson streets on Cohutta we were either figured the very straightforward approach to solve this for some code public so here let's take a look at some example here so suppose we have they seem to array that's 1 0 negative 2 and our goal is to find 2 output array of our array of integers so inside the speaker we have a lot of culture please so each culture will have the four numbers and all together should be equal to the target so when we see this re the first step we should do is to sort a sorry because this is a unsorted array so we can sort this array to have a more clear vision about the patterns behind this array so we saw this artery into ascending order so it would be like this so negative 2 negative 1 0 1 2 so this six numbers becomes a sorted array so this sorted array so our goal is to find the four numbers equal to the adult killer equal to the target so this for some coding problem for some so we can introduce our index variable called a pie at meaning you just start at the beginning of this already so for the fourth up our goal is to find noms I value plus find another three numbers add with this eye index number value should equal to the target so for here the target is just 0 and the beginning and lumps I precision and beginning has a negative 2 so that means we need to find three numbers three other numbers there some should be the two so that they can add up with this eye index value you go to the devil so then so easy about converting this for some public to the 3-sum problem so for the public to the 3-sum problem so for the public to the 3-sum problem so for the three some public so we can introduce another index where about for the G so G just started right behind the right position so G start here and the gene needs to find out so here is a cereza so here is one number so we define another two numbers so there are some pluses J index value should equal to the target but here the target change the target we see here in a fossa for the fear these are just need to find that's you go to the tool for the gene when you here is a negative one so for other two numbers the urrh-sa' so for other two numbers the urrh-sa' so for other two numbers the urrh-sa' should be the three so three some a game becomes a to some problem to Santa Paula so to some if you have seen my previous on with you future before that's about Atossa so for a sorted array we can use a two pointers techniques to solve the to some power so like we have a one left the index and the right index so letting that start at unit just as the beginning of the search range part of the index and right as I at the end of this search part of the array so here the left as a beginning of search fan of debris so left and right they should move toward the same direction so net so and write this to index they are lumber we come here with the target and we come here with the target you thought there some add up together is a greater than of hockey we should make the right one left forward so decrease a bigger number so that we can compare our King with a target value so if that's just still like a smaller than the target so that means our smaller number should be bigger so smaller number big bigger that means the left should meet move to the right and a compare again until we find out whether there's two numbers they can echo through the target so for the true son is announce left and plus knowns right they should equal to the target so for their target here is a stress free as we see in the reason is so there should be the street so for this example we see here that 1+2 1+2 one left add one this here that 1+2 1+2 one left add one this here that 1+2 1+2 one left add one this precision and right under that isn't true procedure so they should adult cater to the street so now we find one called shoe police that's up when I add a negative to G and a negative one and the left add one right here to there's one car to bleep negative two negative one two as one culture bleah yes you go to the target to find out next culture beliefs we can move like a left - all right and right water name on God - all right and right water name on God - all right and right water name on God for the two Center for youth waste do not find we can go back to the three sound level and I can make the chain right forward to check whether it's fun or not what we can find yes we can find I got one the negative 2 and J 1 is a zero and there's a another culture place and again if that's finish that you know streets under what iteration we can go back to the 4th underworld iteration so move the I to the next sub of a position to move the I start from the negative one where to find the four numbers added together to the target yes we can have negative one they were all they wrote one there's another culture please add up together to the target so we have this foursome we see here like a using the three somebody introduces resound Tucson approach we can also help to solve this for some public so we can use this approach to build other codes to solve this problem again the real Kody we should also pay attention to remove the duplicates so that we won't have a do break culture place so like here when the left naga 0 so two zeros here so one left move to the second 0 we can compare whether the second liberal just equal to the first opposition named well if they're still the same that means we can just skip to the next iteration so that we won't put it out same contributed into the final result ok so here we can come back to the public to coding to solve this public so as we see here the output type the return type would be these of a list of integers so that's a result let's call us read out and that's our final output as we just mentioned we should sort this out right we can solve this our read first so arrays dot sort will make this embroidery into a Sunday order so now we can do our awesome iteration so continue I just start from the first beginning of the index and his world finds out four numbers so I can terminate at a eins Nam's minus three position as we mentioned which need to pay attention to the duplicates and we need to handle the duplicates in area so that alpha I is not the first one and this I position value is equal to the lumps I'm minus one so we should continue to the next just keep this one to the next iteration and then we can go through the three Sonowal three Thunder whoa that's a I J we introduced a J variable so J just start right behind the I and J terminates at the non terminals -2 position so here J terminals -2 position so here J terminals -2 position so here J increased and also in to Billings handle the duplicates Jezza check if the jail is not in the first one for clear the jail for not first one is I plus one so even there is not the first one and lumps J is equal to the lungs previous a precision weather so we can steep and continue to the next iteration then we can do becomes on we need to find for this chair position we need to find another two values another two value equal to some target so that's a for the Tucson table for the Tucson problem we can introduce to where the index where you possess the left and right so never shoulda just right behind on G and right Jassa and then noms balance minus one and the for the two pointer since we already saw today sorry we can use our two pointers technique so one if the mine is a smaller and the right so we can have a into your elbow to check of these four numbers at ocular houses some compared to the target so the right now the lumps I plus J plus lumps left plus lumps right and we compare this son with our target so if the son is a smaller than the target if the son is smaller than the target that means our smaller number should become bigger so we can increase the dick else if some is greater than the target the prettier than the target that means the bigger value should become smaller should become the smaller we make the right index left forward else here means such as a sum is equal to the target for that case we need to store this up for four numbers stop lists store these four numbers so we can introduce one as I injure its quarry as a cold shoe please so this is a couplet you are really nice so we can edit it and add these phone numbers to the culture breeze culture please don't add so announced I pour to play add nums J or to play and mom's name or through Lane add nums right and we have one culture please and we should address culture bridge to the result so we add this code to plate to the result and make it right since this finish and we can go to the next place so make the left right forward make it right left forward and also waiting to handle the duplicates so when we increase up left and when we decrease the right we should compare whether the next left either just the same as a currently precision so while there is a smaller and right and if noms left is equal to the previous noms net - left is equal to the previous noms net - left is equal to the previous noms net - previous net so that we can continue to increase the left so similarly while right and lungs right just equal to the previous right we can decrease the right and here we have other iteration so we can come back to return the final result okay before some meet we can quickly check if there are some typos so at the beginning we introduce a nice operand is of an integer class or a final result with one for return and we sorted this inquiry in ascending order and then we do the iteration introduce our variable and handles our duplicate handle the duplicates so if there are two became we skip to the next iteration and then go to the three Thunder whoa so for a current-i precision we need to find current-i precision we need to find current-i precision we need to find another three numbers and of crater to the negative value of this negative that is the target of an ad with ASIC I precision you go to that hardly so for this reason we also handle the duplicate hello - okay hello - okay hello - okay and then introduce a two pointers technique to pointers technique and we use this two pointer technique and inside the while loop which here we have this some of the poll numbers and compare with it's full numbers and some with a target if they're smaller than target we increase of smaller number and if the greater than the target weight the quiz or bigger number and also you know I told you for the sum is just equal to the toggling we see where you have a culture plates available and adding these four numbers and the address culture plates to the result as to the result and increase in FD quizzes right and also doing remove the duplicates wire left uh smaller than right and the next names just equal to the current net we continue to increase the length similarly if the next variety at your charge just equal to the current right with Acree so we can continue to move the right to live for and the finally week Jassa returns as a final output so looks correct so we can colliculus up me okay accepting so very beautifully we have less a very Street approach to solve this for sound culpable so as you can see we use a for sound use of pure set to some sweet some approach to help solve this for some current public and for this corner pub the time constant positive now for this approach would be the thank you so time complexity would be and for the space complexity it's also o and Q for this approach so thank you see here this fossa his son looks more difficult than the two sons on coding father so I guess in the real coding intervals and maybe it's very few occasional you were encountered this for some holy mother in that case means that the interviewer is using a very difficult problem to test your skill but we can still make rackets again and just like things we see like and work having in soccer few like a Cristiano Dorado he may do in training I got for practice if he's a freaking cooking and maybe in a real game he will only have a one or two times opportunity to make a free-kick in a real game but since we free-kick in a real game but since we free-kick in a real game but since we practice more and you know so that he can build skill and to make a go in a real game so it is similarly for us like when we do look for something like this problem in our practice so we can I can be more confident when we do the real coding in to then we more make more practice and we become more practice confident and more professional tools so no matter what problems were freezing we can find it like a similar pattern and solve those problems okay so here is a about these for some coding puppet so thanks for watching it's a subscription to go take our channel so see you next time
|
4Sum
|
4sum
|
Given an array `nums` of `n` integers, return _an array of all the **unique** quadruplets_ `[nums[a], nums[b], nums[c], nums[d]]` such that:
* `0 <= a, b, c, d < n`
* `a`, `b`, `c`, and `d` are **distinct**.
* `nums[a] + nums[b] + nums[c] + nums[d] == target`
You may return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,0,-1,0,-2,2\], target = 0
**Output:** \[\[-2,-1,1,2\],\[-2,0,0,2\],\[-1,0,0,1\]\]
**Example 2:**
**Input:** nums = \[2,2,2,2,2\], target = 8
**Output:** \[\[2,2,2,2\]\]
**Constraints:**
* `1 <= nums.length <= 200`
* `-109 <= nums[i] <= 109`
* `-109 <= target <= 109`
| null |
Array,Two Pointers,Sorting
|
Medium
|
1,15,454,2122
|
1,649 |
so lead code 1649 create sorted array through instructions so in this problem you're giving an integer array of instructions which are just numbers and you need to insert them into a nums container and you need to keep this nums container sorted and at every step you have a cost which is the minimum between the number of numbers that are strictly less than your current number and the number of numbers that are strictly greater than your current number okay so for example here we need to insert one into an empty container what is the number of numbers that are strictly less than one is zero what is the number of numbers that are strictly greater than one it's a zero so the cost is zero and so on and at a certain point you are like this so your nums container is like this and you now need to insert a two because it's the last number that you need to insert how many numbers strictly less than two it's there's only one so the cost there is one how many numbers strictly greater than two there are these two so the cost is two and so the minimum is one and so the cost is one and so at the end your total cost of all of the operations is one okay so if you try solving this with a trivial like not trivial but naive solution which maybe uses binary search to find the amount of numbers that are less than or greater than it's not going to work it's going to give you a time limit exceeded i implemented that here it's using a binary search and splice to insert into the nums array and it doesn't work it doesn't even reach the last test case so if you really want to get accepted on this keep in mind it's a hard problem you're going to have to use a less known data structure so there are two data structures that can give you accepted on this problem and one of them is easily understandable and the other one is really going to confuse you but it's the optimal one so the one that is easy to understand is the square root of the composition technique so that's a much easier technique than the fenwick tree which is the second way you can solve this problem and it's optimal it has a better asymptotic time complexity but it's like dark magic you cannot understand it without spending a lot of time into it so in this implementation in this solution of this problem we're going to use the fan week tree but we're not going to explain exactly how it works so we're going to treat it as a black box and if you really want to understand how it works you're going to have to watch other videos on the topic okay so here we're just going to use this function we're just basically going to paste in an implementation of the family tree and just use it for the sake of this problem okay so we're going to start with an m3 result which is going to be our return value and at the end obviously we're going to return it and we're going to have our array that represents the fenwick tree okay and keep in mind that the family tree is always one based so you need to add one to the upper bound of the length which is ten to the power of five so here we have ten to the power of five plus one okay so this is going to be our auxiliary array that basically doesn't do anything other than storing the fenwick tree information okay and now sorry about that so now you have your loop that goes through all of the elements in your instructions array and you take the element and you add to your total cost the minimum between the number of numbers that are less or equal to your current value minus one and that equates to the number of numbers that are strictly less than your current number okay so again let's say it one more time so get is going to be a function of our fenwick tree that returns it takes a parameter let's call that parameter x right and get of x returns the amount of numbers that are less or equal to x so if you want to instead get the amount of numbers that are strictly equal to strictly less than x then you're gonna have to call get of x minus one okay that's what we do here and the other cost is i minus get of the current element and what this does is i is also keeping track other than the index of a array is also keeping track of the length of nums because at every step you're adding one number into your numbers array and so i at the beginning is zero because the length of nums is zero at the beginning it's an empty container and then at every step you add one more number so i also gets incremented so by coincidence i is also the length of nums and so you're doing basically you can substitute this with nums.length nums.length nums.length so you're doing nums.length minus so you're doing nums.length minus so you're doing nums.length minus get the number of numbers that are less or eq less or equal to a of i and so that gives you the amount of numbers that are strictly greater to a of i okay because you take all of the elements and you remove the number of elements that are less than or equal to a of i so you're only left with the amount of elements that are strictly greater than a of i okay right so this is adding the cost of the current element then you don't forget to do the modulo by 10 to the forgot what it is uh 10 to the nine plus seven okay and then don't forget to actually insert the num the current instruction into the numbers array and so to do that we're going to have a dedicated function which is update afi okay so this would actually work if you had already implemented the get and update function maybe from an external module or something like that from a library but actually we have to implement them ourselves so i'm basically going to paste in the code and very briefly talk about it but again if you want to understand how this function works you're going to have to watch a in-depth video about the fanbig tree in-depth video about the fanbig tree in-depth video about the fanbig tree okay so here are the get and update functions so the update function is showcasing the direct relationship so given an index in your auxiliary array the way you can travel to your parents to your ancestors is by adding your least significant one digit your binary representation so here for example let's say that x in binary is something like 1 0 something like that right then this is going to give the last one going towards the right that is in this binary representation and it's going to add that same one to itself and so by doing that you're basically shifting all of the ones to the left up until there is only one digit in your number in your binary representation and then you are starting to double yourself okay so that's exactly the definition of the relationship between node and ancestor node in our array so that's how exactly an array can represent a tree right and then the get function is doing kind of the same thing but instead of adding it's subtracting right so it's reversing the tree in the opposite direction basically and you also have a cumulative result which at the end you always update it for every iteration and at the end you just return it and always keep in mind that the fan week tree is one indexed so you do not start with zero you start with the index one okay so now is the time to go ahead and watch a in-depth video on how the fan work a in-depth video on how the fan work a in-depth video on how the fan work tree works if you truly want to understand this or if you're fine by just using it as a black box this is fine already and just one more thing basically all of the tutorials on fenwick trees use a prefix sum or range sum to showcase the fanwyk tree and here we're not doing the prefix sum or range sum we're actually doing the count of the numbers that are less or equal to our current number but that basically is equal this problem is kind of equal to the prefix sum if you pretend that all of the values in the array are ones right because the prefix sum of all of the numbers from index 0 to 1 000 is equal to the count of numbers that are in the array that are less than a thousand right at least that's my understanding of why you can use a family tree even though the fan victory is usually used for range sum okay so that's it for me today hopefully this has been helpful to you and thanks for watching bye
|
Create Sorted Array through Instructions
|
maximum-number-of-non-overlapping-subarrays-with-sum-equals-target
|
Given an integer array `instructions`, you are asked to create a sorted array from the elements in `instructions`. You start with an empty container `nums`. For each element from **left to right** in `instructions`, insert it into `nums`. The **cost** of each insertion is the **minimum** of the following:
* The number of elements currently in `nums` that are **strictly less than** `instructions[i]`.
* The number of elements currently in `nums` that are **strictly greater than** `instructions[i]`.
For example, if inserting element `3` into `nums = [1,2,3,5]`, the **cost** of insertion is `min(2, 1)` (elements `1` and `2` are less than `3`, element `5` is greater than `3`) and `nums` will become `[1,2,3,3,5]`.
Return _the **total cost** to insert all elements from_ `instructions` _into_ `nums`. Since the answer may be large, return it **modulo** `109 + 7`
**Example 1:**
**Input:** instructions = \[1,5,6,2\]
**Output:** 1
**Explanation:** Begin with nums = \[\].
Insert 1 with cost min(0, 0) = 0, now nums = \[1\].
Insert 5 with cost min(1, 0) = 0, now nums = \[1,5\].
Insert 6 with cost min(2, 0) = 0, now nums = \[1,5,6\].
Insert 2 with cost min(1, 2) = 1, now nums = \[1,2,5,6\].
The total cost is 0 + 0 + 0 + 1 = 1.
**Example 2:**
**Input:** instructions = \[1,2,3,6,5,4\]
**Output:** 3
**Explanation:** Begin with nums = \[\].
Insert 1 with cost min(0, 0) = 0, now nums = \[1\].
Insert 2 with cost min(1, 0) = 0, now nums = \[1,2\].
Insert 3 with cost min(2, 0) = 0, now nums = \[1,2,3\].
Insert 6 with cost min(3, 0) = 0, now nums = \[1,2,3,6\].
Insert 5 with cost min(3, 1) = 1, now nums = \[1,2,3,5,6\].
Insert 4 with cost min(3, 2) = 2, now nums = \[1,2,3,4,5,6\].
The total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3.
**Example 3:**
**Input:** instructions = \[1,3,3,3,2,4,2,1,2\]
**Output:** 4
**Explanation:** Begin with nums = \[\].
Insert 1 with cost min(0, 0) = 0, now nums = \[1\].
Insert 3 with cost min(1, 0) = 0, now nums = \[1,3\].
Insert 3 with cost min(1, 0) = 0, now nums = \[1,3,3\].
Insert 3 with cost min(1, 0) = 0, now nums = \[1,3,3,3\].
Insert 2 with cost min(1, 3) = 1, now nums = \[1,2,3,3,3\].
Insert 4 with cost min(5, 0) = 0, now nums = \[1,2,3,3,3,4\].
Insert 2 with cost min(1, 4) = 1, now nums = \[1,2,2,3,3,3,4\].
Insert 1 with cost min(0, 6) = 0, now nums = \[1,1,2,2,3,3,3,4\].
Insert 2 with cost min(2, 4) = 2, now nums = \[1,1,2,2,2,3,3,3,4\].
The total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4.
**Constraints:**
* `1 <= instructions.length <= 105`
* `1 <= instructions[i] <= 105`
|
Keep track of prefix sums to quickly look up what subarray that sums "target" can be formed at each step of scanning the input array. It can be proved that greedily forming valid subarrays as soon as one is found is optimal.
|
Array,Hash Table,Greedy,Prefix Sum
|
Medium
| null |
1,417 |
Ajay Ko Hello Viewers Welcome Back To My Channel I Hope You Enjoying All Videos The Time Uploading Rihai Manch subscribe To My Channel Airtel Is Gold And Subscribe And Also Share With Your Friends Through This Problem Reformer Distic Give One Alpha Numeric Jayenge Iss Channel Ko Subscribe Station superintendent subscribe for it's written in this possible subscribe basically letter for arduino id porn taurus 6816 golden look at this example 80 straight hai ya don't do anything for district magistrate and get rs par month will find words in the three formats payenge itne bittu list ko Dry sleep in the question only if you liked The Video then subscribe to subscribe our 205 characters and five fluid electronic digital possible to give the Neeraj Yogendra Exam Council's also one to three 500 600 800 beaten so let's get anything to be possible by Giving information for health benefits to a drop subscribe egg subscribe for kids in english subscribe and subscribe the that deserts and there protests are which gives up the phone quantity chakran sub give that aaj vet practice chakradhar letter so if in english language problem subscribe like and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to the है है है थो यह विल बी स्वर्ग दौर पर है इस यह विल बी स्वर्ग दौर पर है इस यह विल बी स्वर्ग दौर पर है इस दहेज एक्सट है है एस एक्स एक्टन है 241 गौटम टक्स वॉर्न फिल्स 1620 एक्स टो है है है वेस्ट 2FA 241 गौटम टक्स वॉर्न फिल्स 1620 एक्स टो है है है वेस्ट 2FA 241 गौटम टक्स वॉर्न फिल्स 1620 एक्स टो है है है वेस्ट 2FA IN RECENT TIMES E APPEARED In the half hour do subscribe Video then subscribe to the Page My device for example woman is this character's 120 and did not more than one so and ask them which contains more than one without 2008 Discuss Sudhir Withdrawal subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the Page Construction Period Motivation Lights and Electronic Cigarette Stringbuilder Write and Creative Thursday Other Accounts subscribe Video Subscribe for Latest Videos Phone Number Visit Site Will Start with Characters Year of Birth * 16 Sexual President Vice President Birth * 16 Sexual President Vice President Birth * 16 Sexual President Vice President Rule in Difficult Times subscribe Video subscribe Angry Birds Smile and Your Wall and Speculative liked The Video then subscribe to subscribe Station subscribe and subscribe the Channel and subscribe the Subscribe to Reminder All Dhoop Se Requirements for Different morning time complexity doctor futus competition maximum hotspot cleared in question every thing problem solution please comment section thank you for watching my video subscribe my channel friends please don't like you will get notifications for all my video thanks for watching problem hai hua Was
|
Reformat The String
|
reformat-the-string
|
You are given an alphanumeric string `s`. (**Alphanumeric string** is a string consisting of lowercase English letters and digits).
You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type.
Return _the reformatted string_ or return **an empty string** if it is impossible to reformat the string.
**Example 1:**
**Input:** s = "a0b1c2 "
**Output:** "0a1b2c "
**Explanation:** No two adjacent characters have the same type in "0a1b2c ". "a0b1c2 ", "0a1b2c ", "0c2a1b " are also valid permutations.
**Example 2:**
**Input:** s = "leetcode "
**Output:** " "
**Explanation:** "leetcode " has only characters so we cannot separate them by digits.
**Example 3:**
**Input:** s = "1229857369 "
**Output:** " "
**Explanation:** "1229857369 " has only digits so we cannot separate them by characters.
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of only lowercase English letters and/or digits.
| null | null |
Easy
| null |
116 |
hey yo what's up guys babybear4812 coming at you one more time this time today we're doing problem number 116 populating next right pointers in each node uh old problem been around for a while but past six months amazon facebook bloomberg microsoft and google have all asked it so that means it's relevant if it's relevant i teach it to you and hopefully you learn you get a job everyone's happy as always um like i always tell you if you haven't tried the video yet if you enjoyed the video if you haven't tried the problem pause the video give it a shot then come on right back otherwise let's jump into it um and there is a second part of this problem which i will be releasing i'm still kind of going through the solution myself and trying to figure out how to best explain it so we will do that one in the future as well okay but this is the first one and it says that we're given a perfect binary tree uh meaning that all the leaves are on the same level and every parent has two children uh the binary tree has the following definition so it's got sure some vowel but strictly speaking what we're interested in is each node has a value has a left and right pointer as usual but it also has a next pointer so it's slightly different than the usual structure and what we need to do is we're told to populate each next pointer to its next right node uh if there is no next right now the next pointer should be set to null initially all pointers are set to null okay um the follow-ups are there are two points the follow-ups are there are two points the follow-ups are there are two points it says we can only use constant extra space and the second is that recursive approach is fine we may assume implicit stack space does not count as extra space for this problem we're not going to be doing it recursively um so we don't have to worry about that but we will do it in constant space and we'll talk about how and really let me actually let's look at this example briefly and i think the problem is pretty self-explanatory the solution is not the self-explanatory the solution is not the self-explanatory the solution is not the problem is where each node needs to point to the node to its right so this uh one will point to the right there's nothing there so it could be given a null or none value the two points to three points to nothing four points to five points to six points to seven points to nothing i think you guys get the gist and i think that's the only example um sure we're given some constraints but nothing to worry about here i will say that using linear space is an approach that i still think is somewhat reasonable and to do that one i won't be covering it today but what you would do is just do a standard breadth first search and so even before i say that like this problem is just screaming bffs because we're really going at it level by level so level order traversal is i think uh the intuitive way to do it there could be a dfs solution as well i haven't thought about that uh let me know in the comments down below if you have a good one but either way so this is i'd argue this is screaming out for a bfs solution and what we're you know what we can do typically is we'll do bfs with a cube and we'll kind of add items in and pop them out in and in this case there's a way to do with the queue on my first attempt i did it with the q um it's not too much of a deviation from the standard bfs search so i'll leave that ball in your court if you're interested with that solution but constant extra space let's think about this so i've gotten my pen over here and i've drawn this out already so let's think about this if we were to walk through this mentally and again this is what i'd always encourage you guys to do in an interview is to say what would this look like step by step at least first off on an intuitive basis so intuitively i kind of look at this one and say okay let me step to the right and if i see nothing there i'll point to none all right um i'll then take a step down and look at two and then i say to myself okay well two needs to point to the right we get the three and then i notice i say okay well where's the three with respect to that two and it looks like you know the two and the three share the same they show the same parents so if i'm here i can just only take my parents right no then but then you know you kind of get caught and you realize okay well i can't do that because there's no parent pointer right this problem has the most tree problems becomes trivial if we had a pointer to the parent we don't okay we don't so i can't jump to this level and say you know let me jump over here so that's one difficulty another one is you know let's say from four to five we have the same issue and then let's say i try to go five to six so i ask myself it's an awful arrow i asked myself how do i get from the five to six well this one's even weirder because well i mean this five is the child of this two and the six is the child of this three so i have to like check the parent go across come down and do some weird motion it's like so that's a second problem that we gotta deal with so maybe that's something worth writing down so we can say we have um you know uh one situation we got to deal with this is same parent and the second one we need to deal with is different parent right different parent so two separate scenarios we got to deal with and even so we haven't even answered the first one yes like how are we going to do that and so if you want to try to if you can really wrap your head around this one issue that'll be as obviously that'll be the crux of the problem and if you can get it then the rest of it becomes a lot easier so if you think of a way of thinking but you can pause the video now try for a minute or two kind of play around with and then come on right back um so if you just joined us again welcome the way you want to think about it is i almost use this analogy so think about you know if you have children of your own and maybe some of you do uh as a parent more often than not i like to think i don't know i'm not a parent um but you know when you're when your kids are young you're taking care of children you take care of your children first before you take care of yourself okay so you tend to your children first then you take care of yourself i think that analogy actually oddly works in this problem as well and let's think about how so if i actually i want to read i don't even know if i have an eraser here i kind of wanted to erase this let me jump out the black really quickly um scratch yourself pretend it didn't happen all right just briefly and so i want to look at this from scratch and so if i'm taking a look at my children first if i'm this parent node i want to say okay let me look down to my children and we'll put some sort of condition to make sure that we always have children okay that we're going down only so far as we're up until the second last row i want to say take my left child okay take my left child and then make it point to my right child after i've done that let me then point myself over to the next direction take care of your children first set their pointers first before you set your own and before you start moving your way down that's the big picture general idea of what we want to do so if you've got the same parent all that you need to say is something like i'll call it cur maybe oh i'm really gonna shorthand it here i'll say something like uh you know current dot left dot next is equal to current dot right something like that okay so and that just takes care of itself that'll be one scenario now let's say we're and then after that of course like i said you know this you're gonna apply the same logic upwards now or not even actually and then you'll see why because when we jump down and we jump down a level guess what happened already parent already took care of itself right so it's literally it's almost like a generational thing i don't know why i'm running with this analogy but it's like your parent takes care of you and then they take care of themselves then we jump down a level and we say okay well now i'm going to take care of my children and then i'm going to take care of myself oh i don't even need to my parents already took care of me that was already in existence so all you really need to do is kind of keep taking care of the child first and then jumping down all right so that'll be the general logic with the different parent situation now let's uh let's look at what we do so we get this one's straightforward enough so i set my current thought lap dot next will go here fine what about this one now i want to go from five to six and remember before at this point already this exists okay because somebody took care of it for us the grandparent took care of it for us so what i need to say is if there is a next note if we do have something to jump over to i want to take my right child so that's gonna be current.right gonna be current.right gonna be current.right and set its next property so current.right current.right current.right dot next we want to set that equal to my current.next my current.next so i my current.next my current.next so i my current.next my current.next so i said that like definitively as if i'm done i want to set it to current dot next dot left okay current on next thought left if i want to set my left child from my left child to my right child straight forward if i want to set my right child to the next left child i say take my right child and take its next property set it equal to my next node it's left node bam once we do that i take care of this stuff i've taken care of both my children okay i've taken care of both my children they're both connected they're ready to move on and spread their wings and pull out the fly out the nest i've done my job let me not pass it over to the next right this is done this exists now let me go over to three is gonna have to do the same thing three is gonna have to go to six and establish this connection three is gonna have to go here and say okay if there is a next node which there isn't we're gonna point this way otherwise we'll set it to none and that's what we're that's we're going to take care of your left child take care of your life that right child append those connections then jump on down you're already now taken care of you've got to take care of your kids your children and keep on going downwards so we're essentially just going to be going down after us and saying you know something like current equals current.next and um current.next and um current.next and um this is obviously extremely rough pseudo code but believe it or not it's actually not too far from what we're going to be typing and so that was so we're just about at the 10 minute mark usually that's what it takes to get a decent explanation i hope that made sense if it didn't let me know in the comments down below and we'll and i'll address any issues you have but i think we're in a good spot to go take a look at the code and try to hammer that out now i've left this definition of a note up here just kind of for completion but quite frankly i think it looks cleaner without it so i'm just going to strap it the order we want to do things in men as well is we're going to say this um we want to do some error checking like usual uh and then we're going to say well we're going to need to jump into some sort of loop okay so you know we'll uh loop through trees somehow or we'll look through the tree levels three look through the tree levels and we know that within that loop we're gonna have to do something like you know uh connect the left to right child and then we're gonna have to connect to right to next left child something along those lines and then eventually we're going to want to return the route so we're doing everything in place we're gonna change the tree as it is and we are we're just going to be redefining those next pointers all right so this is the just a high level um breakdown of what we want to do and so to start with the error tracking we again check if no route is given we'll return none so if not we're going to return none oops otherwise we want to loop through the tree levels okay so remember what we said we want to keep jumping down until we actually have or while we have children so if i'm sitting up here oops i'm sitting up here starting right there i need to make sure that i actually have children for this logic to work if i do i'm going to jump down i stay here now i'm going to get check here okay i have children if i'm sitting up here i've already taken care of my children so if i go to the final child or the leaf node there's nothing for me to do so there's no point in really there's nothing for us to do there so we're only going to want to jump down until this point the second last level so maybe what i'll do is i'll define a variable that's called um let's say a leftmost node and we're going to set that equal to root and what we're essentially going to do is we're going to say uh while left node while uh most no dot left exists then do some awesome stuff and so uh we're going to need to i'm going to leave that leftmost node as it is for the simple reason that i need a reference minus to where i am so i can always keep jumping down like basically when this loop is kind of over um you know after we go through all these conditions i'm gonna have to say leftmost node is equal to most no dot left so we can keep going down the tree um in the meantime though at every single level i'm going to have to be jumping from one node to the other when i say from one to the other onto its next node so what i'll do is i'll just set up some variable call it curve for current and set it equal to begin with throughout the leftmost node oops uh i'm sorry so i'm realizing here that i was inconsistent in my name here so i'm sorry um okay so curse that and now we need to connect left to right child okay and we're going to be doing this repeatedly as we jump through the rows so what i'll have to do is i'll have to say while kerr exists essentially um do all this wicked stuff uh afterwards oops okay so we're going to go all this weekend stuff then i'll jump to the afterwards i'm getting ahead of myself so the first thing we want to do is we want to connect the left child to the right child and we're going to want to do that every single time we always know that we're guaranteed to have children the reason we're guaranteed to have children is because we're given a perfect binary tree in the second version of this problem the i think it's 117 uh those aren't guaranteed so then we'd have to do a bit extra to check but in this case it's always guaranteed because again we know that we're never going to jump down the leaf note to the final leaf though because of this and um and also because of the perfect binary tree so what i'll do is i'll simply say that cur dot left dot next is equal to curry. cool easy enough one liner next we said that we want to connect the right to the next left oops we want to connect the right to the next level bam i got it so i drew this one out from scratch so one of my better ideas um and so maybe we can follow along with the code as we're doing it so i've set curd.left i started here all right curd.left i started here all right curd.left i started here all right it's by the way this next pointer is already set to none so that's why i don't need to change it okay we can just start with taking care of the children i set cur.left of the children i set cur.left of the children i set cur.left dot next to equal credit right bam this is what we have okay now i need to ask myself if you know if we have a uh if we have occurred on next so if i hypothetically had a note here and it had children then what we'd have to do is set this one over as well but i would only do that if i had a next in order to jump both uh wow if i had a next node to jump over to so basically i'm just asking myself if i have a if curr.next exists then i want to do if curr.next exists then i want to do if curr.next exists then i want to do the following then what i want to do is i want to take this logic that i was talking about up here let's just go back to it i want to take my current node or sorry i'll start my current go to the right child and set its next property okay so take my current go to the right child set its next property equal to my next node's left child my next nodes left child this is one connection this is the other connection from one note it's kind of a sibling note i don't know if they're called sibling knows i'm going to call them sibling ones all right they're two children same parent siblings so this is connection to the there are actually cousin nodes cousins i'm sorry so from one to the next this is connecting our children nodes this is connecting our cousin nodes and finally we need to move our current pointer over so we're going to say occur is equal to occur dot next so move her pointer the reason we're doing that is as follows i'll jump back my clean version here we didn't have to do anything in this diagram right this one was done it was already none now we set we went from here this was kind of our left most node we jump down here now because what we said is we jump out of this loop ker is no longer valid there's no current next we try it while occur that's not true we jump back out leftmost no dot left even more so i'm sorry we try to set kur.next kur.next kur.next meaning i try to go from here to here there's nothing there it's none so we check this fail we jump out of that loop we set our left most node equal to leftmost node.left node.left node.left we went from this being our leftmost node to this being our leftmost node now all right so we're at the two while leftmost no dot left is that true yes it is true this exists it's a four while leftmost node uh dot left okay that's true we're setting curry equal to leftmost node oops is equal to leftmost note which is this all right walker okay curve.lab.next equals cur.right cur curve.lab.next equals cur.right cur curve.lab.next equals cur.right cur dot left dot next equals right good now if cur.next good now if cur.next good now if cur.next yes qr.next it's right here we yes qr.next it's right here we yes qr.next it's right here we already took care of it so it does exist so what we're going to do is we're going to say cur.right.next equals cur.next.left cur.right.next equals cur.next.left cur.right.next equals cur.next.left cur dot right dot next equals cur dot next dot left curve dot next dot left points here we jump the current point over curry square dot next this is now occur okay i'll do it with the c can we do the same thing walker yes curve dot left dot next is kurt right okay curve dot left dot next square dot right if ker.next nope if ker.next nope if ker.next nope no right no kurd.next no right no kurd.next no right no kurd.next if that's the case we don't we're sorry it's not the case so we're not jumping into that now we say kurzker.next into that now we say kurzker.next into that now we say kurzker.next which is none meaning that we check this we jump now that's not working we set our leftmost node down one this is now leftmost node does it have a child a left child no it doesn't have a left child we jump out we're done we return root i press to run code am i too confident no i'm not because it looks like this will work there we go you got the job we got it right nothing right now though all right so that was that i hope that one made sense again i don't know if the analogy was weird like let me know down below what you guys thought about it for some weird reason it just clicked in my head and it got me to stop thinking about exclusively doing this problem with the queue that's about it that's it for this one i don't think it was too hard i think it's a decently challenging problem and i hope that you guys learned from it let me know what you'd like to see next like comment share tell your friends scream it off the rooftops the whole nine i'll see you guys next time peace
|
Populating Next Right Pointers in Each Node
|
populating-next-right-pointers-in-each-node
|
You are given a **perfect binary tree** where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node {
int val;
Node \*left;
Node \*right;
Node \*next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`.
Initially, all next pointers are set to `NULL`.
**Example 1:**
**Input:** root = \[1,2,3,4,5,6,7\]
**Output:** \[1,#,2,3,#,4,5,6,7,#\]
**Explanation:** Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 212 - 1]`.
* `-1000 <= Node.val <= 1000`
**Follow-up:**
* You may only use constant extra space.
* The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
| null |
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
117,199
|
1,913 |
he everyone today we are going to solve theal equation maximum product difference between two pairs okay so constraint said so all numbers are positive so simply um maximum product difference should be first biggest multiply second biggest minus first smallest multiply second smallest so if we use Sal and then take the first two numbers and the last two numbers so we can solve this question but that solution should be order of n log n because we use salt so it's boring us right so let's think about the O solution and uh so we need four numbers so that's why we uh we should think about the four cases and basically we iterate through all numbers one by one in my solution code first of all I compare first smallest and the next second smallest and the s is first bigest and U at last we compare um like a second and biggest so let's think about the small first smallest so let's say uh current first smallest is five and the current number what if current number is three so in that case so we compare these two numbers and it turns out three is a smaller than five right so in that case um so current first smallest should be like a second smallest right so this five will be the like a second smallest and the current number will be the first smallest right no wonder so that's how we calculate like a smallest first smallest and uh let's talk about the second smallest so um if current number is smaller than um current second smallest number so in that case um we can just update a current smallest number with current number because we already compareed the current number with the first smallest number so we are sure that so current number is so first smallest is less than current number less than like a second smallest right so that's why uh U current number is definitely uh second smallest so that's why we don't have to uh compare anything just update um like a second smallest with current number directly so in this case um so now first number so first smallest is three and the second smallest is five and the current what if current number is four so in that case so first of all um we compare the first smallest with current number but the current first smallest is smaller than current number so we don't update first smallest and then next We compare the current number with second smallest so current second smallest is five and the current number is four so that means so four is greater than three but less than five right so that means this four will be like a second smallest so just update second smallest um with four right so that is a um second smallest okay so let's talk about the biggest part but actually uh we apply the same idea so um thir comparison is first biggest so let's say uh first biggest is now like 10 okay so and the current number is let's say 15 so in that case um so current first biggest will be a second biggest right and the current number will be a first biggest so in the case um second biggest is 10 and the current so first biggest is current number 15 right and then um let's talk about the second biggest so now first biggest is 15 and second biggest is 10 and uh current num so let's say 12 so in that case uh so first of all we compare first biggest but uh 15 is greater than 12 so we don't update first biggest and uh next let's compare current number with second biggest so 10 is less than 12 so in that case so 12 is like a current second biggest right so just update Uh current uh biggest second biggest with 12 uh so that we can get the correct like a second biggest so that is the basic idea to solve this question so without being said let's get into the code okay so let's write the code first of all ins first b equal second big initialize be zero and uh first small equal second oops second small and initialize with infinity number so float and the infinity number so that's because uh these variables manage like a smaller part so what if we initialize with zero so constraint set all numbers are positive so these two number uh will not be updated right because zero is always less than a positive number so that's why we need like a big number and then so let's uh iterates through one by one so for n in nums and then as I told you first of all check first smallest so if n current number is less than first smallest so in that case um so update second smallest and the first smallest equal and the second smallest will be like a number of current first smallest right and then first smallest will be a current number so n and else if n is less than so let me copy this second smallest so in that case um just update second smallest is current number and then let's write a like a biggest part so if n is greater than first biggest so in the case second big and the first big equal so second B will be number of current first week and the first Bak should be current number so n so else if n is greater than so second B so in that case update second B with kind number and then at last return so first big multiply second Pi minus uh first small um multiply second small yeah that's it so let me submit it yeah looks good and the time complexity of this solution should be order of n because weate through all numbers one by one here and the space complexity is I think o1 we don't use extra data structure just simple variables right this is a step-by-step algorithm of my this is a step-by-step algorithm of my this is a step-by-step algorithm of my solution code yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
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 |
914 |
hey folks welcome back to another video today we're looking at question 914 x of a kind in a deck of cards the way we'll be approaching this problem is by getting the occurrences of all of the like the numbers in the deck and then we will be using those occurrences to get uh the greatest common um divisor if the uh greatest common divisor is greater than one we know that it can be divided into groups um of size two or more so uh that's the solution once you understand uh why that works it's a pretty simple problem so let's jump right in the first thing that we need to do is actually um check for the base case so let's do that if uh the length of the deck if it is less than or equal to one you would just rip down a fault if not you want to initialize the hashmap will keep a track of the occurrences so let's do that right once we have the hashmap set up what you want to do is go throughout the go through the entire deck and map.put um and map.put um and map.put um i'm not dot get or default um i zero plus one perfect this will give us all of uh the occurrences and the next thing that we need to do is just get the greatest common divisor for all of these um occurrence occurrences so what you do is you would want to iterate through all of the values in the map not the keys um but before that let's initialize the result and set that to zero um so the result would be the greatest common divisor of the current and the next value um and then in the end you would just want to check if the result is actually greater than one awesome uh but you'd also want to write uh a method for greatest common divisor and this is a pretty simple um and commonly used method in java um so i won't really go into the depth of explaining this but it's pretty simple if you look it up um zero great common divisor of the um a model is b b perfect um so let's all right where did i go wrong let's quickly undo this deck oh wait hold on sorry let's try it again okay awesome the first test case is okay everything else is okay as well awesome um so let's talk about the space and the time complexity uh of the solution the space complex complexity of the entire solution is of n since we are using the hash map to store the number of times we see a particular number the time complexities of log square n um the reason why we have log square n is because of uh the computation that's required to get uh the greatest common divisor awesome so if you have any questions please let me know in the comments below uh please don't forget to subscribe i really appreciate that and see you all in the next video peace
|
X of a Kind in a Deck of Cards
|
random-point-in-non-overlapping-rectangles
|
You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card.
Partition the cards into **one or more groups** such that:
* Each group has **exactly** `x` cards where `x > 1`, and
* All the cards in one group have the same integer written on them.
Return `true` _if such partition is possible, or_ `false` _otherwise_.
**Example 1:**
**Input:** deck = \[1,2,3,4,4,3,2,1\]
**Output:** true
**Explanation**: Possible partition \[1,1\],\[2,2\],\[3,3\],\[4,4\].
**Example 2:**
**Input:** deck = \[1,1,1,2,2,2,3,3\]
**Output:** false
**Explanation**: No possible partition.
**Constraints:**
* `1 <= deck.length <= 104`
* `0 <= deck[i] < 104`
| null |
Math,Binary Search,Reservoir Sampling,Prefix Sum,Ordered Set,Randomized
|
Medium
|
912,915
|
29 |
welcome to february's leeco challenge today's problem is divide two integers given two integers dividend and divisor or divisor divide two integers without using multiplication division and mod operators return the quotient after dividing dividend by divisor the integer division blah basically the quotient is going to be the floor integer of our answer now one note assume that our integers are within the 32-bit signed integer range 32-bit signed integer range 32-bit signed integer range and for this problem assume that your function returns 2 to the 31 power minus 1 when the division result overflows basically if our answer falls outside the range of both either side positive or negative then we want to return the floor or the ceiling of 231 minus one okay so if we had this problem here dividend of 10 and divisor of three how can we solve this without using divide function well if we did it straightforwardly what we do is subtract three as many times as we can until the dividend is less than three right once that happens we could count the number of times we were able to subtract and just return that so that would be an o of n solution assuming that n is going to be the number of times we can divide here so let's go with that solution at first what we'll do is first make these absolute values so that we can account for the positive and negative and later on we can check to see if one of these is negative and if it is then we could flip our answer to be negative instead so what we'll do is get the absolute value of dividend here same with the divisor called dv and later on we'll check to see if only one of them is negative and then we can flip our answer so output will start off with zero so if we did this straightforwardly we would say while d is less than or equal to divisor we would subtract from d the divisor and we would add to our output one each time and once we do that we can just return our output but we also need to make sure that um one we need to check to see if one of these are negative so to do that we can just say if dividend is let's say less than zero and the divisor was greater or equal to zero then we want to flip it uh if it's the other way where divisor is less than zero and dividend is greater or equal to zero then we'll get our output and we'll make it equal to the negative output this so this would work but it's not very efficient right i'm sorry not less than or equal to greater or equal to yeah so here we go this would work but it's very inefficient like what's some ways that we can make this more efficient well one way we could make it a little faster say that we had some large number like ten thousand instead of subtracting three every time what we could do is exponentially increase it by itself so we can multiply this by 2 and count up the multiplier by 2 as well and subtract that and that would make the number of loops we have to take logarithmic we can't use multiply though so instead of multiplying by 2 we can just add it to itself so that's what we'll do we'll have we'll do it in two loops then what we'll do is say okay while d is greater equal to dv we'll have some sort of temp variable that's gonna increase each time we run a loop and we'll also have a multiplier that starts at one we'll say while d is greater or equal to temp what we'll do is subtract temp from d first to our output we will add the multiplier and then what the multiplier will add multiplier to itself as well as the temp this way we'll avoid having to run too many loops and once we once our 10 variable is too great we'll start over and we'll start over like from the bottom and increase it each time like that so that would also work that would be actually uh log n instead of n so let's make sure this works here that looks like it's working now one thing to note is i do need to take care of some edge cases uh say that we were given some value like i don't know like this and negative ones like that uh this would actually flow out of bounds oh no not this one we did this would probably fly bouncing right hm no oh maybe i got this wrong okay maybe this work is gonna work let's make sure nope okay yeah so here's an example where would it flow out of bounds we get our output and we get something that's going to be out of bounds here so just to take care of that what i'm going to do is return the minimum between this number and this but i also need to get the maximum of i believe it's negative this one here to make sure we take care of our edge cases and we don't flow out of bounds so make sure to make sure that works i believe that's working let's go and submit it and there we go accepted so this is a log n solution and it uses constant space now there are some more clever beautiful solutions using bitwise operations where you can shift and stuff but technically i think it's debatable but you could argue that bitwise is actually multiplication so i don't know if that would count and plus i don't really like bitwise solutions so i'm not really going to go into there i think this is the most straightforward and typical solution so that's it thanks for watching my channel and remember do not trust me i know nothing
|
Divide Two Integers
|
divide-two-integers
|
Given two integers `dividend` and `divisor`, divide two integers **without** using multiplication, division, and mod operator.
The integer division should truncate toward zero, which means losing its fractional part. For example, `8.345` would be truncated to `8`, and `-2.7335` would be truncated to `-2`.
Return _the **quotient** after dividing_ `dividend` _by_ `divisor`.
**Note:** Assume we are dealing with an environment that could only store integers within the **32-bit** signed integer range: `[-231, 231 - 1]`. For this problem, if the quotient is **strictly greater than** `231 - 1`, then return `231 - 1`, and if the quotient is **strictly less than** `-231`, then return `-231`.
**Example 1:**
**Input:** dividend = 10, divisor = 3
**Output:** 3
**Explanation:** 10/3 = 3.33333.. which is truncated to 3.
**Example 2:**
**Input:** dividend = 7, divisor = -3
**Output:** -2
**Explanation:** 7/-3 = -2.33333.. which is truncated to -2.
**Constraints:**
* `-231 <= dividend, divisor <= 231 - 1`
* `divisor != 0`
| null |
Math,Bit Manipulation
|
Medium
| null |
189 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem rotate array we are given an array and we want to rotate the array by k steps where k is always going to be a non-negative integer so going to be a non-negative integer so going to be a non-negative integer so what exactly does rotate mean well take a look at this first example we are given an array one two three four five six seven and we wanna rotate it by three so what does that mean well basically means we're going to take every single element in the array shift it to the right by one or in other words shift it to the right by k times we're going to shift it by 1k times but what happens to the rightmost element such as this one we can't really shift it to the right because there's no space so if we do that we're basically looping it all the way around back to the beginning now if we ended up doing that three times you can see that this seven would actually wind up in the third position and the four here which started at this position is going to be shifted to the right three times so it's going to end up in this position and that's what you can see is true in the output so there are many ways to solve this problem one of the simple ways is going to be an o of n time and space solution but the way they want us to do this problem is to modify the array in place we can still do that with an o of n time and space solution but there happens to be an even more optimal way linear time but we can actually do this without using extra space with o of one memory so i'm going to be showing you both of the solutions i'll admit that this solution the constant memory solution is definitely kind of tricky to come up with so the simple way is yes to use an extra output array and then we can take this new array and then copy it back into the input array because we want to update this array in place but so yes the simple ways let's just go through every single element such as the first one shift it by case k spaces right k is 2 in this case so we're going to take this one it would be here but we're going to shift it by two so we're going to end up putting the one over here so we've done that next do the same thing with the two put it two places so it's going to be over here same thing with the three shifted by two spaces it's gonna be over here now we get to the interesting case four right now when we were doing these previous ones it was simple right for example let's say the index was over here at this first position the target position that's going to be at is just going to be i plus 2. that's really simple but where 2 obviously comes from k but from here it's a little bit more difficult if we say i plus 2 we're going to end up over here in this position right when in reality what we want to do is put it in the first position right and similarly for this five if we shift it by two we're going to end up over here like in the second position out of bounds but in reality we want to put it over here a good way a clean and easy way to get around this math is basically take i plus 2. since this value could be out of bounds it could be greater than you know the length of this array we want to take this mod it by the length of the input nums right so if we take i plus 2 i plus k mod it by the length of nums it's always going to work so if we did 4 right this index which is 3 plus 2 is going to give us index 5 over here modded by the length which is also 5 then we're going to get 5 modded by 5 which is going to be equal to 0 which is going to put us in this position the zeroth index which is exactly what we wanted to do right so the math works out in this case so when we want to know where to put four we can put the four over here similarly with five we can put five plus the index of this is four plus two modded by five is going to be index one which is over here so the five is going to go over here that was really easy so then we can just take this uh output array copy it into this one and then that will be the entire result now i'll admit that this next solution i'm going to show you which is the of one memory solution is a little bit tricky but i'll give you a quick hint and honestly with the hint i bet you could probably figure it out so notice how when we rotate this array we really have two portions we have this portion which is going to be shifted to the end of the array and then we have the last k elements right this size of 2 which is equal to k which is going to be shifted all the way around into a loop so that's going to be at the beginning of the array right let me just show you something what would happen if we took this entire input array and reversed it let me just do that and then once you look at that you'll probably be able to figure out what to do but if not i'll explain it anyway let's reverse this array okay so i took this entire array and reversed it over here do you notice anything about this array first of all is this the array that we're looking for is this the rotated array it's definitely not right it's not the rotated array because we would want this 4 and 5 to be in the correct order right in the same order but it's not in the same order and see these values one two three we would want them to be in the same order over here but they're not in the same order but what can we do to this array which is just the reversal of the input array what can we do to this array to get it in the rotated format that we want well we just took the entire array reversed it so how about we take the first k elements of the array this portion reverse that and we take the remaining portion of the array and reverse that as well what's gonna happen if we do that reverse this we get four five reverse this we get one two three is this the rotated array that we were looking for yes it's exactly what we were looking for is that obvious to come up with not in my opinion but once you reverse the input array you can kind of see the remaining stuff that we have to do is kind of a little bit obvious at least when you kind of draw it out so basically what we did is reverse the input array then reverse the first k elements then reverse the remaining portion so we did a few reversals three different reversals but then we get into the format that we wanted and we didn't use any extra memory to do this even though i drew an extra array we could have done all of this in place reversing is something that can be done in place with no extra memory so with that being said we can jump into the code now so now let's get into the code and i'll be honest it's going to be pretty simple once you kind of know the whole reversal explanation one thing i want to mention though is we're going to take k and mod it by the length of the entire input why are we doing that because technically k could be greater than the entire length of the array so if the if k was the exact length of the input array then we're basically rotating the entire array as zero times right if we have an input array of length four and we're doing four rotations we're not really changing the array at all so uh nfk is greater than the length of the array we want to mod it by the length first we're going to reverse the entire array so i'm going to initialize our left and right pointers to the beginning and the end of the input array nums and then to do the reversal it's pretty straightforward while the pointers have not met each other or past each other we're going to basically swap the elements in python you can do it pretty easily like this we're just swapping the left and right elements in place we don't really need a temporary variable in python and then we're going to increment the pointer so left is going to be incremented by one and right is going to be decremented by one and so that's pretty straightforward and remember the next thing we want to do is reverse the first k elements and then reverse the remaining portion of the array now you're going to notice i'm literally just going to copy and paste to do this but since we're noticing we're copy and pasting you could put this in a helper function if you wanted and then just call the helper function three times uh updating the boundaries that we're trying to reverse from if you want to shorten the code and i think they'll be pretty easy for you to figure out on your own so the first thing we want to do now is reverse the first k element so from index 0 all the way to k minus 1 we want to re we want to reverse these elements we do that with the exact same while loop and then once again we're going to do another reversal this time we're going to do the remaining portion so we just did from 0 to k minus 1. let's do the remaining portion from k until the end of the array and you know that's all we really are updating so you can kind of guess how this helper function is going to be structured just passing in two different values for left and right so that is the entire code as you can see it works and it's pretty efficient 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 thanks for watching
|
Rotate Array
|
rotate-array
|
Given an integer array `nums`, rotate the array to the right by `k` steps, where `k` is non-negative.
**Example 1:**
**Input:** nums = \[1,2,3,4,5,6,7\], k = 3
**Output:** \[5,6,7,1,2,3,4\]
**Explanation:**
rotate 1 steps to the right: \[7,1,2,3,4,5,6\]
rotate 2 steps to the right: \[6,7,1,2,3,4,5\]
rotate 3 steps to the right: \[5,6,7,1,2,3,4\]
**Example 2:**
**Input:** nums = \[-1,-100,3,99\], k = 2
**Output:** \[3,99,-1,-100\]
**Explanation:**
rotate 1 steps to the right: \[99,-1,-100,3\]
rotate 2 steps to the right: \[3,99,-1,-100\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-231 <= nums[i] <= 231 - 1`
* `0 <= k <= 105`
**Follow up:**
* Try to come up with as many solutions as you can. There are at least **three** different ways to solve this problem.
* Could you do it in-place with `O(1)` extra space?
|
The easiest solution would use additional memory and that is perfectly fine. The actual trick comes when trying to solve this problem without using any additional memory. This means you need to use the original array somehow to move the elements around. Now, we can place each element in its original location and shift all the elements around it to adjust as that would be too costly and most likely will time out on larger input arrays. One line of thought is based on reversing the array (or parts of it) to obtain the desired result. Think about how reversal might potentially help us out by using an example. The other line of thought is a tad bit complicated but essentially it builds on the idea of placing each element in its original position while keeping track of the element originally in that position. Basically, at every step, we place an element in its rightful position and keep track of the element already there or the one being overwritten in an additional variable. We can't do this in one linear pass and the idea here is based on cyclic-dependencies between elements.
|
Array,Math,Two Pointers
|
Medium
|
61,186
|
1,796 |
uh okay welcome guys welcome to my league also in section one seven nine eight oh sorry i'm sorry one seven nine six subscribe to my channel before i start so second largest theory in the stream right someone give your alphabet string and return second largest and numerical digits that appear in s if minus one that doesn't exist and alphabet string is a string comes in lowercase english so basically you only have you have a string which connects or english letters and digitals and you need to first find that so you need to find the largest uh second largest numerical digit okay and now return minus one if it doesn't exist let me see example so dfa one two so the number we have is one two three two one right so second largest is two right so the digitally appears in one two three the second largest two uh are all one right and therefore this case is only one so no largest okay so the idea first is that we need to take uh we need to find the set right the sets of all the numeric right and after that we can sort it and uh pick the second if left second exists then we pick it if not then we return false so let l to be integer i for ins basically and if i is dj so this l will collect all the number we have all the digits so for example if you i use this l will be one two three two one it's a list and we take a set and why i take a set because i need to delete the same number and i sorted this so and then i so i will get one two three okay so there are two cases the first case is that the length of l is less or equal to one so that means there's no digits although or there's only one digits then i should return minus one otherwise that i return the second largest right so it's minus two indexes that's it all right very easy subscribe to my channel yeah i will see you guys in the next videos
|
Second Largest Digit in a String
|
correct-a-binary-tree
|
Given an alphanumeric string `s`, return _the **second largest** numerical digit that appears in_ `s`_, or_ `-1` _if it does not exist_.
An **alphanumeric** string is a string consisting of lowercase English letters and digits.
**Example 1:**
**Input:** s = "dfa12321afd "
**Output:** 2
**Explanation:** The digits that appear in s are \[1, 2, 3\]. The second largest digit is 2.
**Example 2:**
**Input:** s = "abc1111 "
**Output:** -1
**Explanation:** The digits that appear in s are \[1\]. There is no second largest digit.
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of only lowercase English letters and/or digits.
|
If you traverse the tree from right to left, the invalid node will point to a node that has already been visited.
|
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
114,766
|
433 |
welcome to lead to JavaScript Channel where we solve every single little question using JavaScript today we have 433 minimum genetic mutation this is a medium question so a gene string can be represented by an a character long string with choices are a c g and T we suppose we need to investigate a mutation for Gen string start to end where one mutation is defined as a single character being changed in the gene string for example we have to do three strings where only the last character was changed from T to an A and that's considered one mutation for a gene mutation to be valid has to be in the bank and the bank just records all the validity mutations given two strings start and end and the gene back return the minimum number of mutations needed to mute a different story to end if there is no such mutation we have to return negative one and we also start is valid so it must not necessarily be in the initial bank so to say this a bit more clearly or more simply you have two strings there you can only have a c g or t as valid characters and we want to know whether by changing a single character at a time we can reach end with a caveat that every single change or intermediate steps that we have to be present in the gene Bank and that also includes the result itself both the intermediate steps and the result of the cell has to be in the bank and we just returned the number of steps it takes and of course if we don't find it with return negative one so we're going to use breadth first search as an approach and for breakfast search we must use a q so I'm going to initialize a q variable let's add an empty array um actual is initialized it as both start in zero remember you can use an array as a q in JavaScript and the first element that we're going to have is an array itself that contains inserts index the current mutation that we're looking at and the number of steps we start at zero because there haven't been no changes initially then we're also going to need a set I'm going to call that set mutations and it's going to be a new set let's create it for the bank this essentially creates a set for all the elements that maybe contained in the bank now if you ever done breath research this might look like a familiar syntax so we're going to do while cue that length greater than zero now we want to check the current mutation and the step number how do we get that well it's relatively simple we can use the distraction operator in JavaScript it's called C is the current and as a step and that's going to be equal to Q that's shift and q.shift removes the first shift and q.shift removes the first shift and q.shift removes the first element and returns it so here we have two variables that have been assigned the first one to the current mutation and the second one to step number respectively and then we check whether C is equal to n that means the current mutation is equal to the goal if that's the case we turn S which is a set number now we're going to use a for Loop to find every single mutation that's valid and what you do that is we're going to have a simple for Loop see that leg plus we're going to iterate through the current mutation and of course we start with the initial value and then we want to change every single character to either a c g or t and then check whether the imitation is valid and mutation is valid if it is contained in this set there will occur over here so we're gonna have a note in a loop um we call it CH for character of we get a cgrt now to actually change my character at a time we need to use the following Syntax for a substring in JavaScript and it's going to be see the substring the target zero ends at zero oh sorry instant I plus the current character CH but see the substring that starts at I plus one all right so now we have M and we want to check whether this n is valid the way to do that is check the imitation and if it is contained in the set then we're going to do two things first we're going to do mutations that delete M because we're only concerned with the first time we find it so we can make the other current one and yes ignore it for the rest of the problem and then we cue that push M as a chrome mutation and S plus one as a step number now this is going to repeat for every single first single permutation that we find and whenever we find a value mutation is going to be added to the cube now if all of this fails and we do not find it and Q remains empty you're gonna return negative one let's find this code and it is accepted for submitting let's go through what we're actually doing once again we create this skew that has both the current mutation and step number and we create a set from the bank that we were given then using breadth first search we want to check every single mutation that's valid and how many steps it took us to reach to that mutation and whenever we find limitation the first time that we found imitation that's equal to the end we simply going to return s and we have two primitive every single possible combination or Everything Will Change that can be done to a small character and check whether that the change is valid and then we eventually returned it or return negative one it would never found it so we're going to submit this and there you go the right time was 100 milliseconds this is an average speed solution because that's essentially the only way to solve it well the standard weight solid rather thank you very much for watching don't forget to like And subscribe
|
Minimum Genetic Mutation
|
minimum-genetic-mutation
|
A gene string can be represented by an 8-character long string, with choices from `'A'`, `'C'`, `'G'`, and `'T'`.
Suppose we need to investigate a mutation from a gene string `startGene` to a gene string `endGene` where one mutation is defined as one single character changed in the gene string.
* For example, `"AACCGGTT " --> "AACCGGTA "` is one mutation.
There is also a gene bank `bank` that records all the valid gene mutations. A gene must be in `bank` to make it a valid gene string.
Given the two gene strings `startGene` and `endGene` and the gene bank `bank`, return _the minimum number of mutations needed to mutate from_ `startGene` _to_ `endGene`. If there is no such a mutation, return `-1`.
Note that the starting point is assumed to be valid, so it might not be included in the bank.
**Example 1:**
**Input:** startGene = "AACCGGTT ", endGene = "AACCGGTA ", bank = \[ "AACCGGTA "\]
**Output:** 1
**Example 2:**
**Input:** startGene = "AACCGGTT ", endGene = "AAACGGTA ", bank = \[ "AACCGGTA ", "AACCGCTA ", "AAACGGTA "\]
**Output:** 2
**Constraints:**
* `0 <= bank.length <= 10`
* `startGene.length == endGene.length == bank[i].length == 8`
* `startGene`, `endGene`, and `bank[i]` consist of only the characters `['A', 'C', 'G', 'T']`.
| null |
Hash Table,String,Breadth-First Search
|
Medium
|
127
|
1,051 |
Hello friends, today we are going to do problem number 1051 of lead code, its name is Height Checker, it is going to be an easy category problem, let us understand this problem first what does this problem want, in this we have been given an array of heights, we want that Let us create an expected array which should be in sorted fashion. Sorted means that its elements are arranged in increasing order. Okay, so first we will have to sort the elements and put them inside a new array. We will create an array with the name expected. In which we will put the sorted elements and then in this we have to compare which elements i.e. how many number which elements i.e. how many number which elements i.e. how many number of elements do not match the height on its indices like here one is on row ok one is one, both have two heights. There is four in the expected array and there is one in the expected array. At its second index, it becomes one. How many such elements are missing, if 4 and 5 are not matching, then total three elements are not matching. Our output will be OK, so we are going to write its function whose name will be height checker. It will be an int return type, meaning its return type will be int or it will be returning an integer. We will take an array of heights as argument in it, so we will first Let's create a variable with the name of a count, int count and set it to zero and then we will run a for loop for int a e 0 i lesson heights dot length i plus now we are ok first we will create an array expected Array int expected equal to new int What size will this array be? Heights dot length or Heights array? What will be the size of height dot length? Okay, now we will store all the elements of our heights in the expected array, then expected. We have to store the elements of heights at the eighth index in the expected array. We have stored all the elements of the heights array in the expected array. Now we will sort the heights array. How to sort, we have the inbuilt function of sort. Why use arrays dot sort s dot sort heights in build function? Because the time complexity of these build functions is less. Compare to our bubble sort and insert sort functions. Now our heights array has been sorted. Now we can do the comparison. Again we will run a for loop int a i 0 i lesson heights dot length i plus now we will compare if heights is index i equal to i is not equal to we are not equal to the condition is to be compared with expected i then we will do We will make the count plus and then at the end we will return our count. Okay, so first we created a count variable, initialized it with zero, then we created an added array, we first placed all the elements of heights inside the expected array. After getting the heights array sorted, we compared the heights and the expected array with the help of for loop and did a count plus on those which were not equal and then Got your count variable returned, run it once and see if it has been run, now let's submit it. It has been submitted. It took 2 ms. Its time complexity is B go off and on because we have not used nested loops in this. In this we ran a fall loop, then again we ran another fall loop and all the tasks inside it are of constant type.
|
Height Checker
|
shortest-way-to-form-string
|
A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in **non-decreasing order** by height. Let this ordering be represented by the integer array `expected` where `expected[i]` is the expected height of the `ith` student in line.
You are given an integer array `heights` representing the **current order** that the students are standing in. Each `heights[i]` is the height of the `ith` student in line (**0-indexed**).
Return _the **number of indices** where_ `heights[i] != expected[i]`.
**Example 1:**
**Input:** heights = \[1,1,4,2,1,3\]
**Output:** 3
**Explanation:**
heights: \[1,1,4,2,1,3\]
expected: \[1,1,1,2,3,4\]
Indices 2, 4, and 5 do not match.
**Example 2:**
**Input:** heights = \[5,1,2,3,4\]
**Output:** 5
**Explanation:**
heights: \[5,1,2,3,4\]
expected: \[1,2,3,4,5\]
All indices do not match.
**Example 3:**
**Input:** heights = \[1,2,3,4,5\]
**Output:** 0
**Explanation:**
heights: \[1,2,3,4,5\]
expected: \[1,2,3,4,5\]
All indices match.
**Constraints:**
* `1 <= heights.length <= 100`
* `1 <= heights[i] <= 100`
|
Which conditions have to been met in order to be impossible to form the target string? If there exists a character in the target string which doesn't exist in the source string then it will be impossible to form the target string. Assuming we are in the case which is possible to form the target string, how can we assure the minimum number of used subsequences of source? For each used subsequence try to match the leftmost character of the current subsequence with the leftmost character of the target string, if they match then erase both character otherwise erase just the subsequence character whenever the current subsequence gets empty, reset it to a new copy of subsequence and increment the count, do this until the target sequence gets empty. Finally return the count.
|
String,Dynamic Programming,Greedy
|
Medium
|
392,808
|
712 |
hey everybody this is Larry this is day 31st of July the last day of the July legal date and so if you've been here with me uh congratulations and thank you I suppose uh we'll be doing August as well I mean you know me now uh we have a 12 16 and then that's a 1216 Day Street going so I don't know it'll fight and at some point but not quite yet so let's do it together let's do more anyway Tony's Farm is 712 minimum Mass key delete some for two strings okay what are we doing here we turn the lowest ASCII sum of deleted characters to make two strings equal okay so we're deleting characters um where the cost is I mean this is um you know very standard e edit distance uh problem uh which is you know just dynamic programming of course uh or what are the people's names there's also like the summary something distance which is named after people which I always forget but of course it's not um you know there is a variation where add and change is infinity and delete is this ASCII cost right and you can kind of just you know write it that way do you want to just copy and paste and change some uh some minor things otherwise uh yeah it's gonna be well actually let me double check okay yeah n is n and M or whatever it's a thousand so it should be good um now I don't really have notes on this one so let's get started uh the idea here is just reboot voice what happens when we delete a character um so okay so for this particular one we have to match uh we have to match the entire string right so then we have so let's so the idea here is just so okay well in that case let's match the first two characters or first one character of each string because we have to start from somewhere right so um and of course if you just start by the character by character um you can kind of it actually do the way that canonical way of doing it is you're trying to match the suffix right meaning the suffix of string one and the suffix of string two um knowing that the prefix is already calculated um and then you kind of do math on that and of course the length of the suffix or some or the length of the prefix that you already calculated can be used um as um the determinant uh because they only end distinct inputs for each one so maybe I'm going too fast if not if I am let me know in the comments maybe I'm going too slow uh well that part you can solve easily you can skip forward but uh but yeah that's why when you see some people do something like uh index one index two that's what it really means right you can it can mean a couple of things depending on how you like to phrase it but like for example you mean the index one is equal to uh the number of characters we already processed uh or like you know that's one way one interpretation you can also say uh um the first index of the suffix with where um calculating the mean for uh or something like this right so there are a couple of ways to interpret it um and these things are fine they're interchangeable but having uh having a consistent understanding of these ways to think about it will allow you to kind of you know like um you know like uh this is an easy-ish you know like uh this is an easy-ish you know like uh this is an easy-ish problem or it's a medium but it's one that's very well studied so it's a more easy but as you get harder and more difficult problems that require using two or three or four of these random uh observations and techniques uh that's when having a very solid base and a very solid understanding will come into play uh which uh maybe sometimes Jim and I don't right so yeah so if index uh let's just say you know N1 uh it's one and two is equal to invest two and then you have uh every index one is equal to N1 that means that we're done then one so we have to delete the rest of index two um I was going to just actually write something like N2 minus index two but that's actually wrong right that's not the base cost um because um yeah that's not the base cost because you have to delete each ask you one at a time so it's actually something like return uh get min index one the index two plus one plus ASCII order something or you just do a sum but I think maybe it's some uh I think if you just if you do a naive sum technically maybe there's a degenerate case so that's maybe why I didn't do it that way but then here if you do it this way you have to think you have to be careful about the memorization so that's uh the thing right so yeah so then um and then now maybe the next one is equal to N1 and index two is equal to N2 then movie times zero because that you have no characters left and by default that means that they both are done right uh same idea here right it right and then now um we just have to now you have this uh suffix one and suffix two both on the strings and then the question is well now uh you only have if they do quote then you're good right so because well I'm trying to I mean so sometimes you can make some optimizations but with these optimizations you have to prove it right and the optimizations that I'm faking in my mind I think it should be true but I don't now prove it off my head and if I'm on a contest I don't want to spend time proving it um and it's not that necessary of an optimization necessarily um what I was going to say is that like I was going to do something like maybe if S1 index 1 is equal to S2 index two then we just return get min index one plus one index two plus two uh plus one right and that's it um so in theory so this is the you know just go to the next index but um I think this is something that I talked about a little bit on the last Q3 where people make um like a how do you say it like a very um like very unnoticeable observation um that they maybe can convince themselves but it's not proven right and yeah it worked out in that case for the um come out acute do we walk down in that case because um well it really works sometimes right that's why sometimes you'll agree um but I don't always you know it is you know maybe sometimes it's just me getting burned in the past by it by solutions that I thought is would work so now I'm like Ray like I don't need a hard proof like a mathematician but at least for me like I need like some indication of um you know but that's why people were able to get away quickly and I kind of wrote it in a way that was more conservative but end up taking way more time and also just a lot of silly mistakes but that's another story and what I mean by that if you want to kind of follow along why I was talking about it is that here this is not always the ideal right so the promise that we have for this function is that this gives I mean this may be obvious but it just gives the optimal answer for the suffix index one and index 2 right for each of the string I'm too lazy right now but right but it's not always clear to me that this is actually the best answer right and what I mean by that is that um the other way to write it is that you can write best as you go to Infinity right with some big number and then in this case you would just write best is you're gonna Min of best this and this is just that means that now instead of always returning this skip thing um now you're just like okay well we can't skip if we want to so let's consider it if we still get the best answer then do it otherwise we don't do it right um and then of course in the other cases now you have um you know just delete one of them one from the left and one from the right um technically you can also delete from both but because if you delete one from the left one from the right and you do it excessively um deleting them from both including the courses are kind of you know the uh a state that you will get to anyway so that's why you don't need to do that explicitly but yeah uh but and then same but for the left one hopefully I'm not going too fast I mean I think we've been doing the harder DPS uh recently so I don't know right and that's basically the idea minus maybe typos I've been really bad in typos lately uh yeah and of course the next thing that you know I was going to do is uh memorization right it's about to kind of be careful and so let's do it uh what am I doing uh so we know that index one goes from uh zero to N1 index two go for two zero from zero to N2 and well that's really all you need to know uh we only do three operations ish uh I mean all of One operations right we don't have any for Loops uh I mean it's not the only real thing but you know let's actually do it this way uh and then oh I gotta messed them up has cash and yeah and I know you can write this definitely into it I write this is just for mostly teaching purposes so that's you know yeah um yeah and you do want to memorize this so that doesn't get in the loop every time otherwise you kind of get uh well maybe that's okay in the sense that it would degenerate into n square but I guess overall it would be unscreen anyway and it only happens for N1 because for every one of those uh for every N1 answers you uh right so maybe it's not that bad but you know I don't have any contests like in a kind of uh take my time to do it right otherwise yeah you could just do something like this is very awkward actually this is why you use a decorator and uh in uh um and in C plus you use that like memory address which is pretty cool actually but anyway yeah oops still looked okay let's give it a quick submit hopefully I don't have any silly mistakes and yeah uh have I not done this before huh I mean it I maybe I haven't submitted a neat code before but you know obviously I've done either this one or similar before so yeah um yeah so okay so I don't remember my exact YouTube video but haven't you I mean look it up real quick uh but yeah but what I was going to say with respect to that is that um you know so what's the complexity right I mean we kind of went over it as N1 times N2 um is the number of inputs so the total time is gonna be N1 times N2 or quadratic-ish quadratic-ish quadratic-ish um and space as well right but uh why I kind of bring that up is that if I could find my fingers um is that I actually do because this is one of my uh Favorite Things uh I always forget that I'm in Hong Kong when I have this thing um well hopefully yeah there's a I basically have a uh La uh a DB progression uh so that the idea is that from here you can convert this to the top down or this is the top down you convert it to the bottoms up um it's worth practicing because it does help in a lot of different ways um especially just being more familiar with how to do these uh Bottoms Up and because once you do more and more practice you're able to do it without expressing converting it you're able to kind of see the Matrix if you will actually I guess that's a pun because it's a DP Matrix but in any case you're able to see how the kind of like how to see transitions more creative before writing the code and then you're able to kind of just jump straight to the bottoms up and I think that some people do get taught that way um but yeah but after you do that the key thing for this one is that you can kind of see the space optimization part and here you're able to reduce it to all of N1 plus N2 the linear uh of one of those things so which is kind of a nice trick to have uh and for an interview definitely something that you know I don't know if it's necessary but it's nice uh yeah that's what I have for this one let me know what you think uh have a great rest of the weekend it's still on the weekend uh have a great rest of the week and have a great rest of the August so yeah stay good stay healthy take your mental health I'll see how they then take care bye
|
Minimum ASCII Delete Sum for Two Strings
|
minimum-ascii-delete-sum-for-two-strings
|
Given two strings `s1` and `s2`, return _the lowest **ASCII** sum of deleted characters to make two strings equal_.
**Example 1:**
**Input:** s1 = "sea ", s2 = "eat "
**Output:** 231
**Explanation:** Deleting "s " from "sea " adds the ASCII value of "s " (115) to the sum.
Deleting "t " from "eat " adds 116 to the sum.
At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.
**Example 2:**
**Input:** s1 = "delete ", s2 = "leet "
**Output:** 403
**Explanation:** Deleting "dee " from "delete " to turn the string into "let ",
adds 100\[d\] + 101\[e\] + 101\[e\] to the sum.
Deleting "e " from "leet " adds 101\[e\] to the sum.
At the end, both strings are equal to "let ", and the answer is 100+101+101+101 = 403.
If instead we turned both strings into "lee " or "eet ", we would get answers of 433 or 417, which are higher.
**Constraints:**
* `1 <= s1.length, s2.length <= 1000`
* `s1` and `s2` consist of lowercase English letters.
|
Let dp(i, j) be the answer for inputs s1[i:] and s2[j:].
|
String,Dynamic Programming
|
Medium
|
72,300,583
|
487 |
See, in this video we are going to ask the question ' See, in this video we are going to ask the question ' See, in this video we are going to ask the question ' Maximum Consecutive Once Tu Premium Hai Bhai'. If this is not a lover then this Hai Bhai'. If this is not a lover then this Hai Bhai'. If this is not a lover then this question will not be visible. It is telling you 'Given and binary arrears are telling you 'Given and binary arrears are telling you 'Given and binary arrears are binary' and it is telling you in the question 'You have to binary' and it is telling you in the question 'You have to binary' and it is telling you in the question 'You have to retain', what is your retain', what is your retain', what is your maximum? Consecutive once in direct if you can flip at most one zero one more time we can flip these one then zero can be converted Atmos so one zero at most one zero you can convert these van this done Now tell me the maximum number of vans which is consecutive like I saw here brother 10011 see here which is zero here if I convert this van then four vans will come consecutively ok right like this see the next example 10 1101 ok in this You get the maximum number of WANs which are continuously coming out. If you want, you can convert maximum one zero into WAN, so like I take this one, I have taken all the errors, okay this zero I If I convert the van then it will be the maximum, similarly I can take this one also. Now see the last video. If you have not seen the last video then you should watch it because in it I had told that whenever the question of all errors comes, all are there. What is this in the morning? Whenever Sabri gets a question here, we do the sliding window technique. Now let's see what is here, so the most 10 have to be flipped. The definition of this question is something like this, but I can also solve this question like this. I can say that brother, such a long sub, oh carefully suniyega, such a long patience, in which at most one zero, you are understanding, such a long patience, in which there is at most only one zero, even if there is not even one, it will work, now you are understanding that it is like this condition A. There is one more zero, we know why we are looking for this, so that we know so that we can convert this zero into one, there is no need to do anything, we just have to remove all those erasers with sliding window techniques. In which there is at most one zero, I have opened the video of the last lecture, in which I had told how the photo of sliding window is, every question is the same, so we will put the photo from this also, the logic of sliding window is the code. Let's start writing, what do we do, take one left mental, the left pointer of the window of all errors, and one take the right pointer, take one, write the answer, what do we do with zero, add the right one by one. Let's go to our sliding window, it's okay if the condition is unsatisfied. Okay, the condition of the question is that the maximum should be 100. If it is not satisfied, then keep destroying it from the left. You will not understand if you have not seen the last video. I take the window is equal to zero, I will keep adding to the window, add plus is equal to what is right, number of right, and here we will check the answer will appear, something is ok, very good, bad condition is unsatisfied, if It happens to us, so what to do here, left has to come out of the window -= left and left plus left, come out of the window -= left and left plus left, come out of the window -= left and left plus left, what is left now, very good condition on 0, what is the meaning of unsatisfied, which condition brother, if there is zero, then more come. You are understanding from one, okay, now you will see what is the condition actually, what is the condition that brother, whether it is one zero or one zero, write 10 or zero, it is okay, there is no problem, now how to write it in the court, now see the window. What is window? Basically it is even. Now tell me one thing. It is written that if my friend is 10 11 then what will be the value of window. What is this window? Basically even is 1, 2, 3. Good and what is lance, its four is good now. Look carefully, if the length is four and the sum is three, what does it mean, if there is more than one zero, then there will be one more example. If the length is also four, sum is four, what does it mean? There is not even a single zero, why because it is binary, one. And it can also be zero. Well, what does it mean? What condition will it become? What will one zero be one condition? One zero condition will become one. Look brother, how will the current be equal length? Is it right from right-left plus van? What is length? Is it right from right-left plus van? What is length? Is it right from right-left plus van? What is written if 0 Sam, which is exactly equal to the length, what does it mean that the condition is being satisfied, or else, or is one of these, that is, Sam, which is exactly equal to the length, minus one, that is, remove one, that is, the condition or this. Yes, if both these conditions are not being satisfied, it means cut it by using Control Like 10 man take this time this was mine okay so the loop came out okay then put it in the loop window plus name sequel tu right me a gaya i.e. it is done now sequel tu right me a gaya i.e. it is done now sequel tu right me a gaya i.e. it is done now see he checked again brother what is this Sam, what else is the length, okay, I just took it as the condition is being unsatisfied because two zeros have come, what does it mean, it will start coming out from the left now, okay now it will be done, will check again, okay so again the left one. It will come out, now this will be done, okay, the condition is happening like this, okay, after watching the last video, people will come, okay, this is over, this is a very good answer, what will be the answer, nothing will happen, math dot max answer, earn old answer or new answer, how? The new answer will come out, if our length was then basically the length, we have to get the maximum number of consecutive vans, it is okay and we have to get out by doing one flip, like man, this is the length at this time, if the length is okay, then we will make it as if brother, which is zero, we have done that by flipping. If given is ok then long is our answer for the current loop ok just this and finally we will return the answer return aansor ok let's run let's submit ok it has been submitted too very good time complexity is big of n Because the sliding window is big and the reason was told in the last video, it is ok and if you have not seen the last video then it will be found in the description and here you will get it on the I button. Ok brother, you will get the link of the next video on this card.
|
Max Consecutive Ones II
|
max-consecutive-ones-ii
|
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most one_ `0`.
**Example 1:**
**Input:** nums = \[1,0,1,1,0\]
**Output:** 4
**Explanation:**
- If we flip the first zero, nums becomes \[1,1,1,1,0\] and we have 4 consecutive ones.
- If we flip the second zero, nums becomes \[1,0,1,1,1\] and we have 3 consecutive ones.
The max number of consecutive ones is 4.
**Example 2:**
**Input:** nums = \[1,0,1,1,0,1\]
**Output:** 4
**Explanation:**
- If we flip the first zero, nums becomes \[1,1,1,1,0,1\] and we have 4 consecutive ones.
- If we flip the second zero, nums becomes \[1,0,1,1,1,1\] and we have 4 consecutive ones.
The max number of consecutive ones is 4.
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`.
**Follow up:** What if the input numbers come in one by one as an infinite stream? In other words, you can't store all numbers coming from the stream as it's too large to hold in memory. Could you solve it efficiently?
| null |
Array,Dynamic Programming,Sliding Window
|
Medium
|
485,1046,2261
|
367 |
welcome to Mays LICO challenge today's problem is valid perfect square I actually made a video for this a couple days ago but unfortunately forgot to plug in my microphone so be doing again so here's the problem given a positive integer num write a function which returns true if num is a perfect square and all that means for it to be a perfect square is if the square root of that number is an integer so say that we've been given the number 16 square root of that is 4 that's an integer so we'll return true it's a perfect square otherwise if we were given a number like 14 there might be a square root number but that's not going to be an integer so we'll return false so straightforward approach to that is basically iterate down a list from range of 1 to the number that we're given so a list of integers incremented by 1 and we'll just square that number and check to see if it equals the number given to us our input and if it does we can return it true otherwise if we were able to go through the entire list we can return to false but we could click in the process a little bit by doing a while loop so every time we check an integer we can just square that check to see if it's greater than the number given to us number we're checking for and as soon as that number the squared value is greater than the number given to us we could break the loop and return to false so all I did was start with an index number of 1 and a squared value that we're gonna check for so we'll start with 1 and start with something like squared equals 0 so while the squared value is less than a number we're checking for we're gonna first calculate our squared value so that's just I times itself that's exponent of 2 and check if squared equals num return true otherwise we'll increment our index number by 1 and continue to loop for able to break this loop then we'll go ahead and return false so let me just make sure that it's accepted so that doesn't get accepted and that surprised me because it's so straightforward I thought that they would probably look for a better solution because technically this is a biga love ends solution they'll never that's a very worst-case they'll never that's a very worst-case they'll never that's a very worst-case scenario but even so it was too straightforward for me what I thought initially probably was my approach you could do some sort of binary search instead because we already know we're gonna be checking a list of integers from 1 to whatever input value we've been given and if so we can at least do this in log n squirt our log in Big O of log n time by doing a binary search so what you could do is start with left and right values l and num would just be our right value and we don't need to actually create a list of anything we're just assuming that they're kind of like visualizing one and just doing a typical binary search so while left is less or equal to R will just calculate a mid value so that's what L plus R right / - value so that's what L plus R right / - value so that's what L plus R right / - and all we need to do here is first find our squared value which would be mid times itself and check ok if num equals squared whoops return true else if num is or squared I should say whether it's less than them then we want to search our the right side outside of this list this imaginary list so left will equal mid and we can say minus 1 here and otherwise we know that squared is going to be greater than num so if that's the case we want to search our left side so R equals mid plus or I'm sorry minus 1 messed up here plus one like that and if we have to break this loop that means this number doesn't exist so we can go ahead and return the false if that also works okay great so this is a big ol of log n solution and there are other ways to solve this you can use like bitwise you can use some obscure mathematical formulas I saw one about Newton's method but I don't think those are really necessary for like an interview this would probably suffice in fact the first one itself is probably enough for like a phone screen but that's how I solved so thank you
|
Valid Perfect Square
|
valid-perfect-square
|
Given a positive integer num, return `true` _if_ `num` _is a perfect square or_ `false` _otherwise_.
A **perfect square** is an integer that is the square of an integer. In other words, it is the product of some integer with itself.
You must not use any built-in library function, such as `sqrt`.
**Example 1:**
**Input:** num = 16
**Output:** true
**Explanation:** We return true because 4 \* 4 = 16 and 4 is an integer.
**Example 2:**
**Input:** num = 14
**Output:** false
**Explanation:** We return false because 3.742 \* 3.742 = 14 and 3.742 is not an integer.
**Constraints:**
* `1 <= num <= 231 - 1`
| null |
Math,Binary Search
|
Easy
|
69,633
|
257 |
okay so now we are going to solve a problem which has been very frequently Asked in interviews okay so uh we will be given uh binary tree okay before we move ahead let me ask you a very quick McQ kind of question so we have a binary tree okay we have a binary tree with n nodes what can be the maximum value of its height yeah maximum value of the height will be n and when will that happen that will happen if all the N nodes are lying along the same line which is the case of a skewed tree okay my next question is what will be the minimum value of height of a binary tree if there are n nodes okay let's take example only let's say n is equals to 7 if n is equals to 7 you have got 1 2 3 4 five six seven nodes along the same line here the height is seven and if there are seven nodes what will be the minimum height will happen when you have got a perfect tree this case here the height is three does it make sense yes or no correct yeah and I had told you that when you have got a perfect tree like that comprising of n nodes then the height of this is log of n base 2 correct so I can say that if there are n nodes then the minimum value of height will be log n base 2 and the maximum value of height will be order n and it all depends upon what is the structure of the tree if it is skewed it will be uh tree having huge height and if it is perfectly balanced then it will be log of nas2 let's look at that question now we have been given a binary tree and what we want to do is we want to print all the root to leaf paths so let's say your binary tree is like that how many root to leaf paths are there in this tree there are three root to leaf paths can I say that number of root to Leaf parts will simply be equal to number of leaves isn't it like uh see there is only one root but there are multiple leaves so this is one path so this is three comma 4A 5 and this is another path this is 3A 4 comma 7 and that is the final path which is 3 comma 2 comma 9 so similarly there can be multiple root to leave paths I want you to write a code which prints this data which you can see right now on the board this is uh a problem which you can easily solve using uh recursion again so uh let's look at the board now everyone this is quite important let's say there is a big tree okay there is a very big tree I'm just drawing a small portion of it so let's say uh it has an edge coming from some node and here you have got a four and here you have got a left sub tree of four and here you have got a right sub tree of four it's a big tree by the way okay and there is root somewhere let's say root is present over here something like that now answer me one thing there will be some root to leaf paths which are present in this left sub tree when I say present in left subt tree uh I mean to say that there will be some root to leaf paths whose leaves are present in this left sub tree and there will be some root to leaf paths whose leaves are present in this right subtree can I say all such paths that cross this four and land here or here will have four in them just think any path that goes like that or that will definitely have four in them so it means that if I am there at a node let's say I am doing a recursion on this tree I'm visiting the nodes one after the other okay and I'm doing that using recursion so if let's say I am at four then it means that all the paths that cross four will have four in them so how many paths are there which Cross Four this is one path this is another path and both the paths have four in them so what I'll do is whenever I am at a node I'll put that node in an array or in a list or in a vector whatsoever you want okay and after putting that in a particular list or vector I'll make a call to the left subtree and I'll make a call to the right subtree and while making those calls I'll pass that vector or I'll pass that list okay this is the idea that I'm trying to convey so let's just take a quick example I'll draw so look at this particular tree what I'm going to do is I'm going to make a call at this particular node when I make a call at this particular node uh let me draw it let's say this node is three and I'll pass over here an empty list an empty array whatsoever you say okay and now because I am at this node three I know for sure that all the paths that passes through three will be having three in them so the first thing I'll do is I'll push this three in this vector or array whatsoever you say and then I'll make a call to the left child and the right child so when you push this three inside this you will have three over here and then you will make a call to the left child which is four okay and then you will also make a call to the right child so three has been pushed and the right Child is This to now I'll keep doing this thing in a repeat mode so when I at this node four I know that all the paths that cross this four will have four in them so I'll push this four in that vector and that way I'll have three four with me and I'll make a call to the left and right child of four so you make a call to the left child you make a call to five and now you have 3A 4 with you similarly you make a call to the right child uh you go to this seven and you have 3A 4 with you know this is how I'll keep going down now again when I am at Five I'll push this five inside it okay and after pushing five inside it I'll make a call to the left and right so I'll push this five I'll have 3 four five here and the left side over here is null where maybe I can dominate so this is the idea that we'll be trying to use we'll have a vector with us in that Vector we will push the current node and then we will pass that Vector to the next recursive call which is to the left subtree and also to the right subtree this is what we'll keep doing what is the basic idea of backtracking is that if you are doing something you also have to undo that thing okay so it means that see when you are at this node you are pushing this node inside this list when you have pushed this node inside this list you make a call to left you make a call to right that's totally okay now you are at four you push this four inside this list and then you make a call to left you have three four at this five and you make a call to right you have three four at this particular thing now when this particular recursive call is over should you not remove this four from the list because when this call is over you will come back over here and when you come back over here you will start considering these paths that go in this direction now the paths going in this direction will not have four in them so it's your responsibility to remove four so whenever you are at a node the first thing you do is you push that node and after pushing that node you visit the left subtree you visit the right subtree so far everything is okay but once you have visited all the paths that emanate from that node now it's responsibility to pop that node because if you do not pop that node that will be reflected in the other paths as well so this is exactly what backtracking is you do something so pushing is like doing something and then you make your recursive calls and then you undo that thing undoing means in this instance you just pop that particular node as simple as that so this is what we'll be doing now if you take a look at the code it goes something like this so let's say I have got a method called as print paths it is void because it does not return anything it simply prints all the paths out there okay so here your you are passing the root of the tree and you are passing a vector so let's call that Vector as temp mind it you are passing it by reference okay because whatever change you have done to this Vector if you have push this three you want that push to be reflected here as well as there that is the reason you can't pass it by value you have to pass it by reference okay so let's say I want to write this code let's first talk about this idea this is what you do whenever you are at any particular node so whenever I am at a particular node the first thing that I do is I push that node in my Vector root data this is what you do and after this what is the next step is to make a recursive call in the left subtree making a recursive call in the left subtree means calling print paths for root left and passing your temporary vector and then you will make a call to the right sub tree also which is rooted at root right and you will pass your temporary Vector do you see that I have pushed this thing and then I have made a call to my left and right why because I know for sure that all the paths in my left sub tree in the and in the right sub tree will contain this node that is the reason after pushing it I have made those two calls but when these two calls are over that means I have visited the left as well as right subtree emanating from this node now this node is no more useful for me because now in the other paths this will not be reflected so now it is my responsibility to do temp dot pop back so this logic is your backtracking logic this is what I had written over here in this code there is something which is missing and what is that termination condition so what will be my termination condition okay how about having a termination like that I can say okay like look at this scenario five left means you reach null keep looking you reach null and by the time you reach null you have the data of this path in your uh in your vector so you can maybe print it so I can say that hey if my root is null then I'll have a logic over here which will print the contents of this temp and after that we will return we will exhib so can I have this simple termination condition with me yes or no so this is quite interesting a lot of people who even I have interviewed I have seen they write such kind of code and this code has a major flaw you know what will this code print so for that you can just focus your attention over here see this is already uh the recursion tree diagram of this code already so you were at this three this node you pushed this three and you made a call to the left child and then you made a call to the right child now again over here you push this four and that way you made a call to the left child and then the right child five and seven now again at this five you will push this five inside it and you'll make a call to the left child and also to the right child okay also to the right Child 3 4 five now what will happen here is this is the case where the past node is null so you will print 345 and this is also the case where past no node is null so again you will print 345 so what has happened is you have printed this path 34 five not just one time you have printed it two times so that's a big problem over here and you know this problem will only amplify think of it by the time you are here at this node when you are at this node what will you do you will push this two inside this vector and you will have three2 and you will make a call to the left child of two is null right now again here because this is null you will print 3 comma 2 now tell me one thing do you want to print 3 comma 2 do you want to say that 3 comma 2 is a root to Leaf path the answer is no why is the problem happening because the way your code is written the way your termination condition is written you are trying to print root to null paths you are not printing root to leaf paths you are printing root to null paths so if you if I attach the null this is one null this is another null this is one null so in reality this code will print 345 at this null 347 at this null 34 7 at this null 32 at this null 329 at that null so in questions like these whenever you see that you have been asked to print all the root to leaf paths or you have to do something at Leaf if the question is a function of leaf then instead of terminating at this particular thing it's better to terminate at Leaf so this is a really important point to understand uh so how do I fix this code so what I'll do is I'll just make a few changes over here so let us erase it for now okay so what I'll do is um let's say I was at five at this five I pushed this five inside it when I pushed five inside it I got three comma four comma 5 but once I got three comma four comma 5 then I do not need to make further calls why because this five is a leaf so over here I'll have some condition okay just look at that so I'm going to write something uh in this part I don't have space so I'm writing it here so I would say if root left is null and root right is also null if that is the case that means the current node is a leaf and if the current node is leaf then I'll print the contents of my Temp and then I'll return that's it and if that is not the case then only I'll make a call to the left I'll make a call to the right and then I'll do a uh temp dot pop back this is how it'll happen Okay so you can put this thing in an else condition from here to here so this thing will make sure that when you are there at a leaf node when you are there at the leaf node you are pushing that leaf node but after making that push you are checking whether your R is leaf or not if your R is leaf then you are printing the contents of your temp and then you are just returning okay in fact this return would not be needed over here because you eventually have to pop back as well you just print the contents of your temp otherwise you are doing these two things so if you are at a normal node you push it and then you make a call to left and right that is what you are doing over here and then you are popping back okay now some of you have a very good question that hey uh in that case is what to do if certain times the root is null and that can very well happen see if you are at this node you might make a call in fact you will make a call to your left as well as right correct now when you make a call to your left if that is null then because of this check you will get null pointer exception so what to do you will add one more check over here if the root is null just return don't do anything so it means that if you have ever reached at null at that point you will have three comma two in your array so at that stage you don't have to do anything you simply return correct you know similar sort of thing we had done yesterday also when we had written a program to calculate number of leaves do you remember that we wrote a program to calculate number of leaves and there as well we had two termination conditions first termination condition was at the Le itself and the second termination condition was whenever our root got null so we are doing exactly that over here if we touch a path if we ever stumble upon a null we are not going to do anything otherwise the first thing that we are going to do is we are going to push the node now if the node is a leaf we are going to print the contents of array otherwise we are going to make a call to the left and right and finally we are going to pop whatsoever we had pushed in the array any thoughts about the time complexity of this program it's an interesting question lot of people even good programmers make this mistake when I ask this question that what is the complexity of this program so if you're making this mistake no worries let's learn through it uh let's say you have a tree which looks like that okay uh how many roote to how many root to Leaf path will be printed for this tree only one and what is that path is one to 3 4 5 let me write it 1 2 3 4 five okay do you understand it here that each integer is printed only once one is printed once two is printed once three is printed once four is printed once five is printed once okay let's take some other example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 how many root to leaf paths will be printed here eight okay and what is the first path going to be 1 2 48 second path will be 1 2 49 1 2 5 10 1 2 51 and then you have 1 3 6 12 1 3 6 133 I hope I have not missed something 1 3 714 you can check that 1 3 7 15 okay here also can I say that each integer is printed only once the answer is no how many times this one got printed eight times 1 2 3 4 5 6 7 8 two got printed for four times three also got printed for four times you know there is a very strong reason why because how many paths cross this two 1 2 3 and four similarly there are four paths that cross this three so you can see that two has got printed four times three has got printed four times now how many times this four has got printed two times because there are two paths that cross this four so two * this four and cross this four so two * this four and cross this four so two * this four and this five also has got printed two times because the first path is this second path is that similarly the six also two times and the Seven also two times okay how many times each of these leaves have got printed only one time each so one time this one okay now let's be realistic what is the total number of prints at first level eight correct what is the total number of prints at second level 4 + 4 again eight four times this level 4 + 4 again eight four times this level 4 + 4 again eight four times this four times that total number of prints at this level 2 + 2 + 2 + 2 again at this level 2 + 2 + 2 + 2 again at this level 2 + 2 + 2 + 2 again 8 and total number of prints at this level 1+ 1 plus 1 again it so I level 1+ 1 plus 1 again it so I level 1+ 1 plus 1 again it so I can say that at each level the number of prints which is happening is eight only this is a point which is worth noting now what I can say is that if the tree is perfectly balanced and there are n nodes then how many levels will be there or what will be the height it will be log of nbase 2 okay it will be log of n base 2 and now think and say if there are n nodes then roughly how many nodes will be there at the last level roughly n nodes will be there at the last level and you know it is uh something which is very easy to understand you know last level has maximum number of nodes in case of a perfect Tre like that because you can see here the total number of nodes are roughly 15 nodes and out of 15 eight nodes are there at the last level okay you can cross check that it can be mathematically proven as well so I can say roughly n by two nodes which is half of the nodes will be there at the last level only okay half of the nodes will be there at last level so I can say that each of these nodes will get printed one time okay now each of these nodes will get printed one time each of sorry two times each of these nodes will get printed four times each of these nodes will get printed eight times so I can say that if there are log n levels right and if there are n by two root to leaf paths because there are those many leaves only then total complexity will be n by 2 into log n this two can be ignored so it'll roughly be n log n now what is this n by2 is simply equal to number of leaves which also symbolizes uh number of root2 leaf paths so it means that there will be n by two paths which will contain one in it similarly there will be n by4 paths which will contain this and N by4 paths which will contain this n by4 plus n by4 again n by2 n by 8 paths which will contain this n by 8 Parts which will contain this n by eight parts which will contain this again n by 8 plus n by 8 will be n by2 so I can say that there are almost login levels and at each level the number of prints that is happening that is almost n by2 which is n so total data which will be printed will be almost n login where n is the number of nodes so a lot of people who say that the time complexity is going to be order n that is not right because when the tree is balanced like that then a particular node will be printed again and again okay and this is quite contrary to the case of a skew Tree in case of skew tree only a node will be printed only once
|
Binary Tree Paths
|
binary-tree-paths
|
Given the `root` of a binary tree, return _all root-to-leaf paths in **any order**_.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3,null,5\]
**Output:** \[ "1->2->5 ", "1->3 "\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[ "1 "\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `-100 <= Node.val <= 100`
| null |
String,Backtracking,Tree,Depth-First Search,Binary Tree
|
Easy
|
113,1030,2217
|
1,060 |
hey everybody this is Larry this is us doing week five of the weekly premium problem 1060. missing element inserted away hit the like button hit the Subscribe button join me on Discord let me know what you think about today's Forum or these problems or well I don't know we this week's for this week's Farm all right so given an intro wait numbers were just stored in ascending order or its elements unique and all given also an integer K we tend to Cave missing number starting from the leftmost number of the way what does that mean oh is why is the first missing number five the missing numbers are five six okay I see it's a really awkward way of saying it because you don't start at one I think that's why I feel like it's a little awkward because you don't start at one but uh okay fine um yeah I mean I think there are a couple of ways you can think about doing this um I think you can I mean this is gonna be binary search um or at least the way that I'm thinking about doing it um okay Kate coming 10 today I was like if K is small you can actually maybe do something funky about it with respect like walking it up or something like this um there are a couple number of algorithms obviously uh and even with walking it's not that bad of an idea if you don't do it linearly right there's this thing called um repeat I call it repeated doubling I think some people call it Galloping or something what's it called repeated doubling Galloping I never call it this so I always have to uh something scallop or something uh God loving search but I just got repeated doubling so uh but the idea is that uh basically your search link is gonna be one two four eight sixteen dot two to the X and therefore it's kind of reverse of the n and over two dot so it's gonna be uh linear in that case right um in theory depends how you do it but uh um uh well linear in the size of the thing uh of the number of bits so yeah I'm saying this very awkwardly today because every repeating gives you one more bit of information which is another way of doing binary search but in any case uh yeah I what is the non-login solution but what is the non-login solution but what is the non-login solution but uh where n is the answer I suppose wait is it hmm oh I think maybe I cheat or maybe I lied in general um in that I think initially I was going to do a binary search and then kind of do it this way but it actually is again so it's even worse than and uh because then you could have an N solution where you basically just walk from left to right you count the number K's off and it should be okay right you just gotta do math and then you know you kind of okay so yeah so in that way it's walking it up right so let's repeat you can sort and then do a linear thing also you can binary search and do a linear thing and then um uh and then yeah um uh but that's going to end again and then the other thing is just walking it directly right meaning that um meaning that uh you know you try it's five it's a six this is seven is it eight uh or whatever right I think I skipped seven for some reason uh five six seven eight I don't know whatever but just one at a time so that's gonna be of n um because you can actually skip ahead right you go okay this two four that means that there's one number in between so we just take one number from here and then we keep going until at the end or between one of those numbers so that's gonna be linear so that's actually pretty good um hmm can we do it in LA again I mean I think the way to do it is going to be with can I do another gun I mean yes it's the short story but that function is so yeah I mean I think it's still binary search um I mean you could do the repeat doubling thing but I think binary stretch actually makes more intuitive sense because um basically the idea is just to use the index as the numbers of numbers before that are not missing right so almost like the inverse of what you have uh let's give it a try it's good uh I'm not gonna lie it's a little scary in that you know it's very easy to make uh silly mistakes but you know uh you know this is what we're for right basically we want to find uh let's kind of Define uh what we binary search for first right we want to find the index in which num um the cave number is between numbers of index and num sub index plus one or you know Infinity right or whatever it is um yeah uh yeah so that's basically that what we want to do at we want to make it clear because that's not the answer right getting the index is not the answer getting the index allow us to calculate the answer if we're you know um yeah just in general so yeah and I like writing D this like that because uh I think I get questions about is inclusive bounds um so that when left as you go to right then we have one element in the inclusive bow so yeah okay so yeah so if good as mint I don't know how to write this yet because I don't know what the good function is right so that's why the hesitation the good function is we want to uh is and it doesn't matter how you want to write it right um as long as you're consistent with if the question you're asking and using that as a guideline to solve the answer it's fine it's just that it's kind of right um is the cave number and you can say to the left or to the right but I'm trying to be really precise to the left of numbers maybe right um yeah let's say it's this way and every you know it doesn't really matter so if this is the case then obviously we want to shrink right and because if it is the cave numbers to the left then mid it cannot be the answer uh that answers this question because it means that it is not mid and mid minus one so that means that weight is equal to Mid minus one and then L is left is equal to Mid uh yeah and then you have to do a plus one to kind of cancel this out a little bit and yeah so that means that um now the answer is between uh num sub left and numbers of left plus one um because left is equal to right and that is basically the only answer left uh let's write the good function first maybe we're jumping around a little bit but I think that makes it a little bit clearer so let's say we have some uh index X let's discard index live okay fine let's say we have some index X right so how many numbers it's a login maybe this isn't login maybe I like because we want to do this in all of One oh no this should be fine uh I think this I thought about it but then I got we don't have to we literally so okay numbers of Index right what does this mean I think that's the product that I have some ideas in my head but I have to uh try to be very clear about um because it's very like this is why I said I have a healthy respect because it's very easy to do an off by one or something like this and of course you want to do this one time so you have to be which is not that bad as long as you because it's just a lot of constant operations even if you do a mess in a messy way but okay um so okay so if the num nums is four what does this mean um that means that how many spaces are there before this number right because the case missing number is going to be the number of gaps between this number okay so that means that if the this is the number here at the numbers of index that's the this is total numbers um index is the Numbers number of numbers that are taken uh and this is actually not quite right it is actually this minus uh num Sub Zero or something like this right um because basically this is saying that the three numbers between one and four is not quite right let me think about this one second right yeah so there are like I said there could be plus and minus ones but that's the general framework that we're working with um yeah total number total count numbers to be size so for example with this four and the first number is one that means that there are three numbers is that true um depends how you want to phrase it I mean I think one thing that we can do is re-index it but obviously that would re-index it but obviously that would re-index it but obviously that would take linear time and that'll already be longer than not again so we can do a impromptu re-indexing by subtracting impromptu re-indexing by subtracting impromptu re-indexing by subtracting everything in our calculation by numbers of zero um so that means that we can pretend this is a zero and this is a three and that means that um there are zero one two three we know that this number is always going to be taken literally by the definition of this number and zero is going to be taken so then you minus um so then you minus one for the number of uh I guess maybe just we can also take track of that here but we subtract one for the first number uh yeah and then the index is the number of numbers that we used so in this same case so 0 to 3 and let's just keep it this way right um so zero to three is this number of numbers inclusive um and then the third index is going to be index plus one in because that's the number of numbers that includes the current index is the number right so then the number so yeah so total is equal to this I'm writing it out uh just so that may be easier and then gaps is equal to taken right so then now oh sorry total minus taken right uh so that's number of missing numbers to the left of index right um so now is the cave number to the left of it well if the number of gaps is bigger than or equal to uh k then this is to level it and that's basically going to be a thing let's print it out real quick um just so we could go and make sure we're okay um so we print out 0 as the first index uh yeah that's right because the answers between here the answer is eight so it should be zero one right we print out one that's good uh it is what we expect and here the answer is six which is to the right of two which is also what we expect okay I mean it's not definitive obviously you know these cases are not going to be 100 percent excessive but it gives us at least some confidence to at least get the right so now the answer is between Def and that plus one um let me make this smaller um yeah again we can use this formula that we had in good so Toto is a good nums up left mine is numbers of zero taken is equal to uh index plus one and then gaps is equal to Total minus taken just for the sake of whatever and then now minus you go to uh gaps right because that's the number of missing numbers that we removed um and then it should be just return numbers of left plus uh K plus one because K could be the zeroth number we're doing zero index um I think by definition it should be good what the well this is the left we don't use index well that didn't work um maybe I just kind of you know let's write it out here but maybe I just missed one step okay so we start at the left that's good total is zero numbers oh yeah because it's from the left so that means the total numbers on left taken is one so total minus taken is oh did I miss the plus one yeah I missed a plus one in my copy and paste in my mental copy and paste okay so it's still one but uh maybe we don't need this plus one maybe I was wrong on this one but yeah uh gaps so we take up okay gaps so then K and gaps we use zero gaps to the left which makes sense because this is the first number so then one is so maybe I was wrong about the zero index maybe it is just one index so maybe that's why we don't need this um I thought it would be zero index but if there's one Gap and K is one then I guess it would be on the previous okay fine yeah maybe I buy that all right so that looks okay let's give it a submit hopefully we don't make a silly mistake and we haven't so we have a streak going on uh yeah um so yeah so I kind of talk a lot about um uh binary search and you know people always talk about templates on my Discord on everywhere in the interwebs really um and hopefully this is a very step-by-step kind of step-by-step kind of step-by-step kind of um engagement into binary search and how I solve it without really you know like you could kind of see how my DOT processes every step of the way and none of it depends on the template I don't ask myself if it's last true last Force last whatever I just ask myself what is it that I really want every step of the way and you're able to kind of get it um yeah like and if I like for example you have easily change this to um you know once the cave is the to the right and then that changes things and it may not even be what you think which is just flip these two because about how you handle the inclusiveness right and stuff like that so it's actually you know you just enter it differently like maybe this instead or something right it could very well be um so you have to be very careful but you don't have to worry about being careful uh you do but yeah you don't have to worry about how it fits into your real templates if you're just able to ask yourself questions uh every step of the way that are consistent and makes sense and this as long as you're able to kind of Define this good then you kind of implement this by itself and you don't even have to think about how it fits in because that's how a modular code works and yeah and here allow us to kind of because this part now we know that here the answers between left and left one then we can just calculate how many gaps gets used and that's just a very easy formula after that right um easier anyway I mean I still got enough I won because I kind of misunderstood a little bit uh but yeah that's all I have for this one uh maybe I should complex the other thing I forgot uh space we only use linear space right number of variables uh in terms of time uh you know this is going to be log n which just goes from zero to n and like rhythmically binary search and this is all one so this is like an algorithm uh that's what I have for this one let me know what you think and yeah stay good stay healthy to good mental health I'll see you later take care bye
|
Missing Element in Sorted Array
|
longest-repeating-substring
|
Given an integer array `nums` which is sorted in **ascending order** and all of its elements are **unique** and given also an integer `k`, return the `kth` missing number starting from the leftmost number of the array.
**Example 1:**
**Input:** nums = \[4,7,9,10\], k = 1
**Output:** 5
**Explanation:** The first missing number is 5.
**Example 2:**
**Input:** nums = \[4,7,9,10\], k = 3
**Output:** 8
**Explanation:** The missing numbers are \[5,6,8,...\], hence the third missing number is 8.
**Example 3:**
**Input:** nums = \[1,2,4\], k = 3
**Output:** 6
**Explanation:** The missing numbers are \[3,5,6,7,...\], hence the third missing number is 6.
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `1 <= nums[i] <= 107`
* `nums` is sorted in **ascending order,** and all the elements are **unique**.
* `1 <= k <= 108`
**Follow up:** Can you find a logarithmic time complexity (i.e., `O(log(n))`) solution?
|
Generate all substrings in O(N^2) time with hashing. Choose those hashing of strings with the largest length.
|
String,Binary Search,Dynamic Programming,Rolling Hash,Suffix Array,Hash Function
|
Medium
| null |
334 |
hey guys in today's video we'll cover the question increasing triplet subsequence this is a commonly asked question in interviews of google amazon and facebook it's a medium difficulty problem so let's jump right into it the question is given an integer of array nums return true if there exists a triple of indices i j k such that i less than j less than k and number at i less than number at j less than number at k if no such indices exist return false this basically means that if in your array there are three numbers in an increasing order you'll just return true otherwise just return false let's look at some examples and edge cases here we're given three arrays if you look at the first one i can tell that two three and five are in the increasing order so this is true in the second one i can find the increasing triple sub sequence i see that there is three and four but there isn't a third number there which will make it true so we'll mark this false third one is a little interesting i see that the increasing subsequence here is 1 5 and 6. notice that these numbers aren't continuous like number one but there is a valid solution your increasing numbers don't have to be continuous they just have to be in ascending order keep this in mind when you're working on the solution so let's look at how we'll solve this is a good stopping point if you want to practice solving this on your own okay to solve this we'll just traverse through our array or vector in this case now at every number we want to check if there has been two numbers before that one which were less than in value to keep track of this we'll need to define two integer variables and so while looping if we find any numbers less than these variables we'll just replace them this is an important step and our algorithm wouldn't function without it so we'll first check if our number is less than or equal to eight then we'll check if it's less than or equal to b we need to keep it in this order to maintain ascending increasing order for it to be less than or equal to a or b our number has to be the maximum integer possible when we actually defined it in the beginning so we'll define our variables to max and when they start if it's neither less than a nor b that means there is an increasing triple subsequence and we just return true in our loop if it never hits true we'll just return false at the end of it let's look at the complexity of this code we are looping through once so our runtime complexity is called n for our space complexity we're just using two variables to store data for our algorithms function which is a constant number and will remain constant at our algorithm scales so the space complexity for this would be just o of one you
|
Increasing Triplet Subsequence
|
increasing-triplet-subsequence
|
Given an integer array `nums`, return `true` _if there exists a triple of indices_ `(i, j, k)` _such that_ `i < j < k` _and_ `nums[i] < nums[j] < nums[k]`. If no such indices exists, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** true
**Explanation:** Any triplet where i < j < k is valid.
**Example 2:**
**Input:** nums = \[5,4,3,2,1\]
**Output:** false
**Explanation:** No triplet exists.
**Example 3:**
**Input:** nums = \[2,1,5,0,4,6\]
**Output:** true
**Explanation:** The triplet (3, 4, 5) is valid because nums\[3\] == 0 < nums\[4\] == 4 < nums\[5\] == 6.
**Constraints:**
* `1 <= nums.length <= 5 * 105`
* `-231 <= nums[i] <= 231 - 1`
**Follow up:** Could you implement a solution that runs in `O(n)` time complexity and `O(1)` space complexity?
| null |
Array,Greedy
|
Medium
|
300,2122,2280
|
389 |
hey guys welcome back to another video and today we're going to be solving the lead code question find the difference okay so in this question we're given two strings s and t which consist of only lowercase letters string t is generated by random shuffling string s and then added one more letter at some random position find the random letter that was added to string t all right so how do exactly do we solve this question so there's several different ways that we can solve this question uh one of the ways is to use a dictionary we could go through the string s then go through string t accordingly adding of letters to our dictionary and then uh using that in order to find out what the extra letter is so that's one way to do it a second way is to do it like how i did it so what i did is i took each of the letters of t and put them inside of a list and then after that i iterated through all the letters in s and then i removed whatever character we came across so whatever letter we're at in s i remove that and think about the remove function over here it only removes one instance of whatever it finds so if we say remove a it's only going to remove one instance of a and that's why i'm using remove and not replace since replace replaces all the instances of whatever you give it and at the very ending we're going to be left out with one letter and i'm just going to end up returning that so that is one more valid solution but both the solutions are not actually very fast so this is where we want to understand how can we use the xor operation to our advantage to get the fastest and most optimum solution all right so real quickly let's just go over what the xor operation is so over here i have two binary values so one of 0 1 and zero one so if i perform the xor operation on this and in python it's represented using that and uh so one and one is going to end up giving me a value of zero and zero is also going to end up giving me a value of zero when i perform the xor operation but in both the other cases so one and zero and one i get a value of one so what do you actually notice over here so when you have two values of the same thing so if you have one and zero we end up getting a value of zero so in other words you can kind of think that when we have two of the same values they're kind of negating each other so let's now apply this uh formula or idea to our question over here so over here using this xor function there's one property that we need to understand in order to be able to solve our question in the fastest way so this property is the fact that when we have two of the same numbers so let's say we have a wearable y and y x or y is going to give us a value of zero so no matter when you xor two of the same values we're going to end up getting zero so similarly like i showed you earlier so when we had one and one or zero and zero we ended up getting a value of zero when we xor those two values so this property is really important for us so now let's see how we can use this in our function right in our question sorry okay so let's say i have a variable a and b and similarly for our t variable right so for the other string i have a b and c so the extra variable is obviously c so how do we actually get hold of that so in order to do that we're going to xor all of these together so what's going to happen is we're going to do a x or b xor a x or b x or c so now in this case what's going to happen is so when you do a x or a so let's just rewrite this actually just to make it easier so this is same as doing a xor a and then xor b x or b and then x or c so what happens is a xor a ends up giving us a value of zero so that's equal to zero and then uh zero then b x or b also ends up giving us a value of zero so we have zero again and then c is actually going to end up staying where it is so we have zero x over zero x or c and in order to simplify this further more we have one more property so if we have x or zero that is going to end up giving us a value of x keeping that in mind this over here is the same as writing the value c so as you can see by xoring all of the values here the duplicates are going to end up canceling and giving us a value of zero so all the duplicates end up becoming zero and we're going to end up with one last and final value and that last value is going to correspond to whatever the extra letter is and using that we can end up finding out what that extra letter is so now there's one last thing that we want to talk about is how we can we convert a letter to a number so to do that we can use the ord function in python so you do ord and then you give it some sort of letter and it's going to give it the unicode representation in other words each of the characters has a integer represent a representation for it so that is what this is going to give us so that is exactly how we're going to solve this question hopefully it does make sense and now let's take a quick look at that so let's remove this over here and let's call a function or variable called diff and this is going to start off at a value of 0. and over here we're going to go inside of a for loop and we're going to iterate through everything instead of x so we can just do for character and s so now we have everything in each of the things inside of s we're going to perform the xor operation on the diff variable here but before we do that we want to convert this value of the characters into its unicode integer value so to that we can do ord care and we want to perform the xor operation so diff is going to be equal to diff x or care and that is writing uh this like this it means the same thing so by the ending of this we're going to have taken the xor of all of the characters inside of x but now we want to do the same thing for everything in t so let's just copy this over here and copy it and one more thing you could just directly over here do s plus t but actually doing s plus t is slower than calling for two for loops so over here we call a second for loop but in this case this is going to be for t and it's going to be and that's going to be it so at the very ending of this what's going to happen is the duplicates that we end up having are going to end up getting cancelled right so duplicates are going to get cancelled and we're going to be left out with 0 xor of whatever the extra character is and now we want to convert that integer value to an character so to do that we're just going to return it so we're going to do care c-h-a-r or sorry c-h-r and we're going c-h-a-r or sorry c-h-r and we're going c-h-a-r or sorry c-h-r and we're going to give it the value that we're on and that value is just going to be the diff and this is going to convert our integer value to its uh representative of the string or a character right so at the ending of this we end up getting the string so let's submit this and as you can see our submission did get accepted and finally thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe thank you
|
Find the Difference
|
find-the-difference
|
You are given two strings `s` and `t`.
String `t` is generated by random shuffling string `s` and then add one more letter at a random position.
Return the letter that was added to `t`.
**Example 1:**
**Input:** s = "abcd ", t = "abcde "
**Output:** "e "
**Explanation:** 'e' is the letter that was added.
**Example 2:**
**Input:** s = " ", t = "y "
**Output:** "y "
**Constraints:**
* `0 <= s.length <= 1000`
* `t.length == s.length + 1`
* `s` and `t` consist of lowercase English letters.
| null |
Hash Table,String,Bit Manipulation,Sorting
|
Easy
|
136
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.