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 |
---|---|---|---|---|---|---|---|---|
62 |
Do Hello Everyone Welcome to Ashlam Going to Explain This is Very Unique Five Them Into This Problem in This Question Located at the Top Left Corner of Amazed at Any Point in Time Subscribe by Clicking on Subscribe Button Row End Column 1 Column 105 Subscribe to the Urs of the World channel that example2 Voice Prem Sorry Arvind to Front of Units Point to Point Mintu 110 012 Used Cars Contact Implemented from Bulk Pack to Retail Pack Written Statement Meaning of Place Column - Na the Festival of Roman Renaissance * FACTORIAL OF PEOPLE - * FACTORIAL OF PEOPLE - * FACTORIAL OF PEOPLE - 1ST YEAR TO MEDIUM HALF 12345 137 90 NUMBER OF UNITS SUBSCRIBE STATEMENT A PLUS MINUS TO
|
Unique Paths
|
unique-paths
|
There is a robot on an `m x n` grid. The robot is initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time.
Given the two integers `m` and `n`, return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.
The test cases are generated so that the answer will be less than or equal to `2 * 109`.
**Example 1:**
**Input:** m = 3, n = 7
**Output:** 28
**Example 2:**
**Input:** m = 3, n = 2
**Output:** 3
**Explanation:** From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
**Constraints:**
* `1 <= m, n <= 100`
| null |
Math,Dynamic Programming,Combinatorics
|
Medium
|
63,64,174,2192
|
1,834 |
foreign Matrix basically uh each row contains for each process so uh we are given that in tasks array each task that is at index I has its NQ time it means at which time it arrives and its processed in time so what we are told to do is we need to uh create a order and will you have to tell that in which order the CPU will process these items so uh we are told to process all of those item and we need to return the order at which or order of processing so we are given with this following rules uh let me read it one by one first off uh first is that if CPU Z is harder and there are no available tasks to process the CPU will remain idle and the second one is the if the CPU is ideal and there are available tasks the CPU will choose the task which has shortest processing time if two tasks have same processing time then it will select the one which is smallest index third rule is once a task is started the CPU will complete the task it can't preempt to any other task fourth rule is the CPU can finish the task then start a new task instantly so there is no need to cool down the CPU so now let us try with this first test case so what test case is saying is that we have the array one two four three two and four One S process so uh yeah let's start let us just declare a output array initially it will be empty and let us say our cpu's time is this zero initially so we will scan through whole array and see if is there any process available at time T is equals to 0 so what we can see is there is no available process at this time so what we can do is uh yeah one more thing is that it is not by default from the question given that this particular item will be sorted it's just a coincidence that this test case shows that it's sorted so we'll sort this uh array itself first task will be that so we will directly jump to the first elements arriving arrival time because all other elements after that will arrive after that or at that time so we can safely say that we can skip the time we can see uh safely say that we can skip the time to the first process arrival time or the process arrival time so will change the time to 1 at inch now we will scan again through the array and find all the processes which start at uh time T is equals to 1 so we will find we can see that we have this first process itself so we'll add it uh so we will process it and it will take two units of time so now our time will be one plus two three and this process is done so we can mark it with minus one or something like that uh also we can keep a counter so this process is done we will move forward now we'll check from here only now our T is equals to 3 how many processes are there so we can see that we have these two processes so out of these two processes the process which we will select should follow this uh rule the second rule here so according to that rule we should select the process which has a shortest processing tag so it is two so we select this process we again mark it minus one and it has it had a processing times two so we process it now time variable is 3. and one more thing is we need to keep track of the element like in which order we are taking it so 0 to yeah now T is equals to 5 how many process we have at that time the this process we already have and this plus we also will have so out of two we will again select the smallest the shortest processing time process so we'll select this time will be 6 now we process third index process so we uh in we track it in output array now uh at T is equal to six we have one process so we will process it marking it as minus one pushing it into our output and time will which uh change to 7 now uh we what we can see is the size of our output array is equal to size of input array that is tasked so we can safely terminate this uh this program so now let's see code for this program code for this problem so this is the Brute Force solution which we just discussed right now so here we can see that first of all we will declare a variable uh time variable uh output array and we will run a loop until the output size and the task which we were given with has same size so all processes are done in short so for each and every single iteration we need to decide that these process is the one which will execute so we need to decide it by scheming uh by scanning through the whole array so the best candidate we will uh store it here so we will iterate to the array and we will check uh that the candidate which we are selecting should have a less the least processing time among all of the those which are available at that time so here we can see we are doing that only and one more thing is once we select uh once you select any process we should Mark it with minus one we will do it later in this code only uh but this is the thing to be remember we have needed to remember otherwise we will call we will do one process multiple times uh after that if suppose that uh we are at time where there is no process so what should we do in that case uh what we can do is we can directly jump to the time at which uh the process is the earliest process is available so uh we will also keep track for that and just in case we don't have any candidate for current time we will jump to uh the next possible time at which the process will is guaranteed to be there we can also increase it by say one unit every single time but no need to increase that time complexity uh at last we will push it in output array and then we will Mark that particular process minus 1 which means that we won't process it again and it's already processed we will increase the time after that we will return the output array now the issue with this approach is that we are scanning through this array again and again so it can increase the time complexity so if we see we have a one Loop inside of that we have another loop and each so we are traveling say n iterations in this Loop and this bigger Loop also and iterations so we are say doing n cross n that is n Square complexity we go of n Square plus some polynomial say constants of this code will run n Square time so what we can do is we can optimize it now how can we optimize it as a question so uh we need to see the we need to find some observations in this from the rule itself it is clear however let's just go back yeah so in rule we are given that specific Matrix how to choose any process from bunch of processes available at that time so we can consider this Factor this Matrix as a priority priority and as we have this Matrix as priority this is the hint to use the priority queue or a heat so let's uh implement the that Heap based solution so here you can see we have the heat based solution so this in this solution we did some uh the tweets as well I will just show you it in a moment so first of all we will do uh we will actually create a comparator class what does comparator class is doing is basically it is uh giving a Boolean false or true it will help to solve uh sort the elements inside the Heap so uh first priority will be obviously to see the processing time and second one will be the ID if the processing time is same then we will see the ID we Define this macro so that we do not re and we don't need to write this array of size 3 again and again now let's just move to the important part yeah so we declared a Time variable again this time as well uh we declared array now this time we declared a priority queue and how the elements will be cured will be queued in it this will be defined in this comparator class so we will store element as three uh three so each element will have three integers in it what first integer will be is it uh it will be processing time so uh it's not a processing name sorry uh first one will be arrival time second we will be processing name third will be its index now it is uh in question not mandatory that the input will be always sorted so we need to sort it but we also need to store its original index with that element itself that's why we can't use the uh provided uh array itself so we make a new array after that we push back all elements into the new array with its index as you can see here as third element after that we can safely sort the already now we need to sort it by First Column so what we can do is we can use a we can use com custom comparator here I use the Lambda function so uh here I compared their arrival types to sort the tasks array now you can skip this part is it was for debugging yeah so again the same Loop tell the output is not equals to the task foreign what will run in the iteration is if the CPU at the current time does not have any process so our queue is empty and our time is less than the earliest available process arrival time so we can directly jump to that time after that in the same iteration what we can do is you can select every process from that array which is available at that time which means that process we already uh didn't execute it and that process is available to us at current time or time before it uh current time so we just use this condition and push each and every element available elements also to start from the next area the next element only we keep track of the index this will help us we do not need to actually change any process to -1 or pop off so change any process to -1 or pop off so change any process to -1 or pop off so we can maintain an index separately for that now uh to process to execute any process what we will do is we will pop off the top element from Priority queue we will see what is it what's it all right its arrival time is however it won't be needed uh as we already at the T the current time uh how much time it will take to process and its index so uh we will execute it so the next so at next time the CPUs CPU will be at this time so current time plus how much time it will take to process after that we will push it to our output then it's index to our output and we can safely pop it off we will run it we will run this iteration until we process all our processes and when we will be done with the process will be with execution of all processes our output array size will be equal to input or S size so this is the most optimal solution and what we can say is its complexity will be uh n log n where n is the size of input and space for space complexity you can see that we have declared these variables uh this was for output so you can you don't need to count it this it can take Big O of n I declared this which also can take B off and uh we used sorting so uh yeah it will also take some time complexity just in case if it is not in place merge sort uh or let's just consider it is a in place much sort so these are two spaces which we declared so yeah code codes link will be in description thank you for watching
|
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 |
29 |
in this video we're going to solve a coding interview question divide two integers without using division multiplication and mode operator you're given two integers dividend and divisor divide two integers without using multiplication division and mode operator return the quotient after dividing dividend by divisor we have to return only the integer part of our quotient we don't have to care about fractional part if quotient contains fractional part then we can simply ignore that the integer division should truncate toward zero which means loading it fractional part for example if we truncate this number eight point three four five then we get eight if we truncate this number minus two point seven three five we get this number minus two here we're just ignoring the fractional part if you're given dividend equals to 10 and divisor equals to 3 now if we divide this number 10 by 3 then we get this number 3.333 number 3.333 number 3.333 we see on the problem statement we have to ignore the fractional part we have to consider just the integer part and this is integer three so we have to return three if you are given divided equals to seven and divisor equals to minus three if we divide seven by minus three then we get minus two point three we have to return just the integer portion and minus two is the integer for this number minus two point three okay so we have to return -2 okay so we have to return -2 okay so we have to return -2 for this input we know that division is a special types of multiplication to solve this type of problems we have to use the technique called bit manipulation for that we have to use bitwise operator to solve this problem we're going to use three b2 is operator b2 is left shift operator beto is right shift operator and bitwise one's complement operator let's suppose that we're dealing with an environment where we have eight bits for an integer we're assuming here for integer we have eight bits for better understanding and the concept exactly the same for 32 bits okay now let's talk about for left shift between operator b2 is left shift operator what i can do using btw left shift operator we can shift numbers bit to the left okay shifting all of a numbers bits to the left by one bit is equivalent to multiplying the number by two in general mathematics if we have four times two that equals to eight times two equals to sixteen without using this multiplication operator we can use bitwise left shift operator if we left shift the bit of this number 4 then we get this number 8 if we left shift the bit of this number 8 by 1 bit then we get this number 16. if we left shift open numbers bit to the left by 1 bit that means we multiply that number by two okay here we clearly see that for four and eight we get eight and sixteen all right now let's see how this actually works if we have two number four and nine let's see how this actually works this number four represented in binary like this for better understanding we're assuming we're dealing with an environment where we have eight bits for an integer so this four represented in binary like this if we left shift all the bits by one bit then we get this binary number and this is equivalent to eight if we convert the binary representation of the number nine is this now if we left shift all the bits for this number nine then we get this binary representation and that's equivalent to 18. we see that we can multiply a number by 2 without using multiplication operator we can just lift shift that number by one bit then we get the multiplication of that number by two okay now let's talk about bittoy's right shift operator shifting all of the numbers bit to the right by one bit is equivalent to dividing the number by two and the dividing result always return an integer it doesn't return the fractional part here we see that if we divide this number by 2 we get 2 if we divide this number 8 by 2 we get 4. if we divide this number 9 by 2 we get 4 because if we divide two integer the result is an integer now we can do this operation without using division operator let's see how we can use videos right shift operator to do this if we right shift this number four by one bit then we get this number two that means we divided this number four by two then for eight if we right shift this number eight we get four and this is equivalence to dividing this number by two for nine if we write shift by one bit we get this number four and this is equivalent to dividing this number nine by two now let's see how this actually works let's suppose that we have this number four and nine for represented in binary like this if we right shift four by one bit we get this binary representation and this is equivalent to 2 this number 9 represented in binary like this if we right shift this number 9 by 1 bit we get this binary representation and this is equivalent to 4 so we can divide a number by 2 using right shift operator and we can multiply a number by 2 using left shift operator here what we have seen that we can multiply a number by 2 without using multiplication operator and we can divide the number by two without using division operator now let's talk about one's complement now we're going to talk about bitwise one's complement suppose we have 7 divided by -2 in this case our result is by -2 in this case our result is by -2 in this case our result is -3 but computer doesn't know -3 but computer doesn't know -3 but computer doesn't know negative numbers right it uses the concept called two's complement to calculate choose complement we have to use bitwise once complement operator okay if we convert this number 3 into binary then this is the representation of this number 3 and here the leftmost bit represent sign bit here we have 0 this means that this is a positive integer but we have to store in computer memory or we have to tell the computer somehow that this number is a negative number so how we can do that for that we're going to use one's complement first let's calculate one's complement of this number three using bitwise once complement operator then we get this binary representation what we did here we just reversed the bit if we have one then we replaced it with zero if we have zero we replace that with one okay now this is one's complement now if we add one to this binary number then we will get the two's complement let's add one to this number then we get two's complement and this is the two's complement of this number three and this means that this is the negative integers this binary representations computer stored in computer memory system okay how computer detect this is a negative integer here we have one right this means that this is a negative integers the leftmost bit indicates the sign of a number here we have one so this is a negative integer negative now in order to calculate the value of this binary number we have to calculate two's complement of it if we calculate two's complement of this number then we will get this number okay and the value for this binary representation is three so we have this value minus -3 this value minus -3 this value minus -3 now if we store this number in computer memory then computer know that we store in computer memory a negative integer so if we have result equals to minus 3 we have to written one's complement plus 1 this means two's complement hope you have understood the concept of one's complement and two's complement we're using here eight bits for integer and the concept exactly the same for 32-bit integer we're using eight for 32-bit integer we're using eight for 32-bit integer we're using eight bits for better understanding now let's see how we can divide two integers without using multiplication division and modulus operator for sake of understanding let's assume we are given this two integer four and two here four is divided and two is divisor we have to apply this algorithm to solve this problem now let's see how we can solve this problem using this algorithm first we're going to divide this number four by two okay now our goal is to find the quotient how can find the quotient value to find a quotient value we have to follow this formula divisor times quotient greater than dividend and quotient must be multiples of two now we have to find a quotient that is minimum and that follows this rule the minimum quotient that multiples of 2 we can choose here that follows this condition that is 4 let's choose here 4 so if we choose 4 here then 4 times 2 is 8. now what is c this is greater than our dividend when we see divisor times quotient is greater than dividend we will right shift quotient and the value we get by multiplying divisor and quotient so if we write shift 4 we get 2 if we right shift 8 we get 4 now if we subtract this 4 from this 4 we get 0 here what we have found quotient so let's add this quotient to this result so 0 plus quotient is 2 at this point result equals to 2 and then we have to calculate remainder divided equals to reminder now from this algorithm we see that now our reminder is our dividend okay now we have to divide the dividend by the divisor is two right and we see that our condition for this while loop dividend must be greater than or equal to divisor but for this while loop stop running here because this condition falls so we have the result equals to 2 we should return 2 and this is how we can solve this problem don't worry i don't think you understood this problem by washing this part of video now let's take another example let's suppose that we're given 24 and 7 24 is divided and 7 is divisor what is c here we're going to divide 24 by 7. now our goal is to find the minimum quotient that multiples of 2 and that follow this rule and the minimum quotient is 4. we will see how we can find the minimum quotient when we will go through our pseudo code now first look up understanding we're going to calculate the quotient using our human intuition now if we multiply this 4 with 7 we get 28 when we see divisor times quotient is greater than dividend then we'll right shift quotient and also the value we get by multiplying divisor and quotient so let's right shift if we write shift we get 2 and here we get 14 right now if we subtract this 14 from 24 we get 10 okay and in this case we're going to add this quotient total result then results become 2 now here we see divided equals to remainder so now 10 is our dividend and divisor 7 our goal is to find the minimum quotient that multiples up to that follow this rule and that is 2 if we choose 2 here then we see that this condition is true and 2 is multiples of 2 okay now if we multiply divisor and quotient we get 14. when we see quotient times divisor is greater than divided then we'll right shift the quotient as well as the value we get by multiplying divisor and quotient so these two became 1 and 14 became 7 all right in this case if we subtract 7 from 10 we get 3 and here we have 1 now let's add this quotient one to our result so two plus one is three so now we have result equals to three now this three is our dividend and seven is our divisor we see that this condition falls here so while it starts here at the end will return 3 and this is how we can solve this problem and this is the intuition now our goal is to find the quotient that follow this rule and that's multiples of 2 then we need to find the remainder how we can find perfect quotient and then how we can calculate remainder we'll see that when you go through the pseudo code now let's see what we'll do when we have result equals to negative value in this case we have three if we have any of them is negative dividend or divisor then we'll have minus three answer when we have negative value then what we're going to do is that we're going to take the absolute value here we have 24 and here we have minus 7 the absolute value of 24 is 24 and the absolute value of minus 7 is 7 then we're going to follow this rule to find the quotient we will detect if the result is a negative integer then we will return two's complement of three simply we'll use this formula return once complement plus one that we have seen in previous slide and this is the concept when we have negative output all right now let me show you how this actually works with the help of pseudocode first i'm going to declare a function divide the text dividend and divisor as input then we're going to check if the final quotient is negative here we're going to declare this variable is negative equals to false then we're going to check this condition if dividend is greater than 0 and divisor is less than 0 or if we have dividend less than 0 and device are greater than 0 then also we will have negative answer in that case we're going to update the value for is negative 2 true then we're going to get the absolute value for dividend and divisor the absolute value of 2 is 2 and the absolute value of 2 is 2 not minus 2 the value the absolute value of -2 is 2. of -2 is 2. of -2 is 2. then we're going to get answer equals to 0 and this will hold the answer or the value we get after dividing divided by divisor then we're going to run a loop for while avs dividend greater than or equals to avs divisor that means absolute divisor and absolute dividend then we're going to store the absolute divisor to attempt variable then we're going to declare a variable quotient equals to one okay then while temp is less than equals to absolute dividend this is our code to find the perfect quotient that followed the conditions what we have seen in intuition okay and that was the question must follow a rule where we have quotient time divisor greater than dividend and the quotient must be multiples of two then we're going to add the quotient to this variable answer by doing right shift that we have seen and we're going to get the reminder then we're going to check if the number is negative then we'll return the toast complement if not then we're going to check if answer is greater than max int the maximum value we can store in an integer variable then we will return the max well we can store in integer variable if we see these two quantitation faults then we'll just return answer whatever value we'll have at this variable and let's see how this actually works let's suppose that we're given 24 minus 7 okay first we're going to get the absolute value for 24 and minus 7 so 7 and 24 now our goal is to find a quotient that multiples up to and follow this rule and quotient must be the minimum value here the minimum value we can have four and that we can get using this while loop right over here okay and here we will have 28 after that here we're going to right shift 4 and right shift 28 if we right hip 28 this becomes 14 and if we write shift 4 it's become 2 and we're going to add this 2 to this answer so 0 plus 2 is 2 then 14 here and we have to calculate the remainder so remainder in the sketch 10 and here at the end for first iteration of this while loop will have abs dividend equals to 10 we're going to set this reminder as dividend so 10 and we have divisor here 7 for the next iteration we're going to find by this loop the minimum value of quotient that multiples up to and the minimum value in this case two so two times seven is fourteen at the end of this while loop we have fourteen and two and this is the for loop for finding or the perfect quotient value this is the loop that we use to find the perfect value for a quotient then we're going to right tip the quotient so in this case this 2 will become 1 and this 14 will become 7 okay now we're going to subtract 7 from 10 and that is 3 okay then we have to add this number 1 to this answer variable we have 2 plus 1 is 3 so answer equals to 3 now all right now we have reminder records to 3 so this is our new dividend so 3 is our new dividend and 7 is our divisor we see that this condition is false here so this loop stuff here then we have if is negative equals to true for this input 24 and minus 7 this condition true dividend is greater than 0 and divisor is less than zero so is negative equals to two this value turns to true so in this case it will return the two's complement of three first we're gonna find the ones complement then we're gonna add 1 to that then we'll have 2's complement and the 2's complement we're going to return that means we're returning the negative value and this is the solution to this problem and this is my solution to this problem so at the end this function will return minus 3 this will return 2's complement of 3 and that means we're returning -3 returning -3 returning -3 and this is my solution to this problem this solution will takes constant time complexity this solution also takes constant space complexity here this while loop will run at most 32 times because we have 32 bits for an integer here this while loop also will run for worst case scenario 32 times so we see that 32 and 32 is constant so this solution will takes constant time complexity and here we're just using some variable is negative absolute dividend absolute divisor answer temp and quotient okay so the solution will takes constant space complexity as well all right guys this is a long video hope you have found something helpful thanks for watching this video i will see you in the next video
|
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 |
160 |
hey what's up guys it's Nick white here I do tech and gaming stuff on twitch and YouTube check the description for all my information you can go over to my patreon I'll do the premium problem solutions there and if you want to reach out to me discord is a good place I try to get back to everyone this problem is called intersection of two length lists it's got a lot of likes it's a pretty good problem to getting good at length lists if you don't understand a basic list traversal I would definitely say check that out first or an easier problem the objective is write a program to find the node at which two singly linked lists intersect or where the intersection begins so in this example we can see clearly that they intersect it nodes c1 these are the two separate linked lists a 1 and a 2 B 1 B 2 B 3 they intersect here in this case 4 1 501 they intersect at note 8 in this note in this example here they intersect at node 2 pretty obvious they give you good pictures here so you understand and then there's no intersection here you can see these are just separate linked lists they never intersect so what are the ideas well the ideas if what is going on sorry I don't know I didn't know that it would direct me to a PNG or whatever if these were the same length if these lists were the same length that were given we're given two head nodes one of one list one of another so we have the head node of each list we're traversing each node as a value in the next node if these were the same length well we could just set a current node or a runner to the head of each node and then just traverse just do you know go to the next node and when they're equal to the same node we just returned that note because that's where they intersect these aren't the same length though so if we started traversing at the same time they wouldn't match up right so a 1 dot if we started going a 1 equals a 1 dot next so it's here this one equals this at the same time then this equals this so this shorter one's always going to be a note ahead because it has one less note to traverse so there's a two approaches you could do one is we do some pre-processing kind of where we some pre-processing kind of where we some pre-processing kind of where we traverse each list and we get the lengths of each list and then we calculate the difference and then we wait on the longer side until we wait on the shorter side for the longer side to catch up to the spawn the traversal it needs yet but there is a better way to do it that's a little bit shorter basically what you're gonna do is you're going to and it involves the length still basically you're gonna traverse the shorter one in the longer one at the same time so we'll set pointers to the heads of both of these we're just going to traverse step-by-step and when we get to traverse step-by-step and when we get to traverse step-by-step and when we get to the end of the shorter one we'll set it to the head of the longer one and when we get to the head at the end of the longer one we'll set it to the head of the shorter one so they the difference in lengths won't even matter they'll both be traversing each of the nodes that are our pointers will be traversing both lists in the exact same amount of nodes and they will eventually end up finding the intersecting node or they will both hit null and we will return null so that's the idea let me know if you have any questions about it I think I explained it as thoroughly as I could if head of a is equal to null a head of B is equal to null then our head notes are messed up so we can just return all there's no intersection right if there's one of the lists as null or at both of them we'll set up our pointers or runners you could call it a runner you can call it a pointer I'm gonna call it a pointer you call it a you could call whatever this is gonna be traversing the smaller list in this case first this one is going to be traversing the longer list and example one well a pointer is not equal to B pointer so while the nodes are not equal what we'll do is if a pointer if the node at this position if the a if this node is equal to null that means we've hit the end of the list so what we'll do is we'll say okay a pointer after the first and after the first time we get to the end of the list we're setting it to the head of the longer list so we're gonna say is equal to head B if it's not at the end of the list it's just a regular traversal so we'll say a pointer equals a pointer dot next and this is gonna be the same thing for B pointer I already explained this B pointer gets to the end of the list then we set B pointer equal to a and then B pointer equals B pointer dot next this way they traverse the same amount of nodes and in the second loop they catch up to each other and they'll be at the same node because this one goes one less node in the first traversal so in this one goes one longer note in the first traversal but when they go when this one gets put to the head of this one and this one gets put to that of this one then they grab the difference in length anyway so then they'll be at the same node and they'll reach the intersection at the same time and the while loop loops until they meet so once they meet then we're good and we can just return the node so you can return a pointer or B pointer or they you know both hit null at the end which they meet anyway so you know there you go that's the problem let me know if you have any questions I think I made it pretty clear you know what I mean one more time this we set pointers to the head of each linked list this one traverses to the end in the first iteration then it sets itself to the head of this one so it traverses a total of three plus one two three four until it gets the intersection so seven this one Traverse is one two three four five but then it goes here six seven so there you go thank you guys for watching I really appreciate it over on the watches videos and yeah I hope you enjoyed it let me know if you have any questions I'll try and answer them in this in the comments thanks see you next time
|
Intersection of Two Linked Lists
|
intersection-of-two-linked-lists
|
Given the heads of two singly linked-lists `headA` and `headB`, return _the node at which the two lists intersect_. If the two linked lists have no intersection at all, return `null`.
For example, the following two linked lists begin to intersect at node `c1`:
The test cases are generated such that there are no cycles anywhere in the entire linked structure.
**Note** that the linked lists must **retain their original structure** after the function returns.
**Custom Judge:**
The inputs to the **judge** are given as follows (your program is **not** given these inputs):
* `intersectVal` - The value of the node where the intersection occurs. This is `0` if there is no intersected node.
* `listA` - The first linked list.
* `listB` - The second linked list.
* `skipA` - The number of nodes to skip ahead in `listA` (starting from the head) to get to the intersected node.
* `skipB` - The number of nodes to skip ahead in `listB` (starting from the head) to get to the intersected node.
The judge will then create the linked structure based on these inputs and pass the two heads, `headA` and `headB` to your program. If you correctly return the intersected node, then your solution will be **accepted**.
**Example 1:**
**Input:** intersectVal = 8, listA = \[4,1,8,4,5\], listB = \[5,6,1,8,4,5\], skipA = 2, skipB = 3
**Output:** Intersected at '8'
**Explanation:** The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as \[4,1,8,4,5\]. From the head of B, it reads as \[5,6,1,8,4,5\]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory.
**Example 2:**
**Input:** intersectVal = 2, listA = \[1,9,1,2,4\], listB = \[3,2,4\], skipA = 3, skipB = 1
**Output:** Intersected at '2'
**Explanation:** The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as \[1,9,1,2,4\]. From the head of B, it reads as \[3,2,4\]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
**Example 3:**
**Input:** intersectVal = 0, listA = \[2,6,4\], listB = \[1,5\], skipA = 3, skipB = 2
**Output:** No intersection
**Explanation:** From the head of A, it reads as \[2,6,4\]. From the head of B, it reads as \[1,5\]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
Explanation: The two lists do not intersect, so return null.
**Constraints:**
* The number of nodes of `listA` is in the `m`.
* The number of nodes of `listB` is in the `n`.
* `1 <= m, n <= 3 * 104`
* `1 <= Node.val <= 105`
* `0 <= skipA < m`
* `0 <= skipB < n`
* `intersectVal` is `0` if `listA` and `listB` do not intersect.
* `intersectVal == listA[skipA] == listB[skipB]` if `listA` and `listB` intersect.
**Follow up:** Could you write a solution that runs in `O(m + n)` time and use only `O(1)` memory?
| null |
Hash Table,Linked List,Two Pointers
|
Easy
|
599
|
2 |
hi guys welcome to algorithms made easy today we will go through the question add two numbers you are given two non-empty linked list you are given two non-empty linked list you are given two non-empty linked list representing two non-negative integers representing two non-negative integers representing two non-negative integers the digits are stored in reverse order and each of the nodes contain a single digit add the two numbers and return the sum as a linked list you may assume that the two numbers do not contain any leading zero except the number zero itself this is a pretty straightforward question of adding two numbers in a linked list let's see this example graphically in more detail as mentioned in the question we are given two list l1 and l2 and these are the head of these both list we need to return the sum of these two lists as another list and the head of this list would be the first note if you would see carefully the addition would look like this we would need an additional integer variable that would be carry and we would need a result list so we take a dummy node and then add the result list nodes to the next of the dummy node initially the carry will be 0 and we add carry list 1 and list 2 value which gives us 7. since this is not greater than 9 the carry still remains 0. now again when we add all these 3 values we get 10 and now since the sum has become greater than 10 we would get a carry that is 1 and similarly we repeat the process till we have our numbers added up till the end finally there can be a situation where the carry is still greater than 0 and at that time we need to include the carry also into the result now that we know the simple addition rules let's go ahead and code this so firstly let's take all the variables that we would be needing first is the dummy head next is the head of l1 and l2 and the third thing that we need is carry now that we have all the variables that we need we will take a while loop and execute the while loop while one of either p or q has a value in it in this while loop let's take two variables in x and y that would store the number from l1 and l2 that is p and q so this would take care of the size mismatch in our l1 and l2 list our sum would be addition of x y and carry would become sum divided by 10. now we need to create a new node that would be attached to our current node the value for this new node would be somewhat 10. with this we'll shift the pointers of all the nodes that we are having now after this while loop is terminated we can have a condition where we have a value in carry so if carry is greater than zero we need to attach the value and carry to our current dot next after this is complete we just need to return dummy dot next let's run this code and it gives a perfect result let's try to submit this and it got submitted the time complexity for this algorithm would be maximum of the size of l1 and l2 and the space complexity also would be max of l1 and l2 plus 1 that is for the carry that's it for today guys see you in the next one you
|
Add Two Numbers
|
add-two-numbers
|
You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
**Example 1:**
**Input:** l1 = \[2,4,3\], l2 = \[5,6,4\]
**Output:** \[7,0,8\]
**Explanation:** 342 + 465 = 807.
**Example 2:**
**Input:** l1 = \[0\], l2 = \[0\]
**Output:** \[0\]
**Example 3:**
**Input:** l1 = \[9,9,9,9,9,9,9\], l2 = \[9,9,9,9\]
**Output:** \[8,9,9,9,0,0,0,1\]
**Constraints:**
* The number of nodes in each linked list is in the range `[1, 100]`.
* `0 <= Node.val <= 9`
* It is guaranteed that the list represents a number that does not have leading zeros.
| null |
Linked List,Math,Recursion
|
Medium
|
43,67,371,415,445,1031,1774
|
797 |
hi everyone so today we'll be solving lead code question 797 all paths from source to target so let's see what the question has to say so uh according to the question we are given an directed acyclic graph uh by a cyclic you mean that you cannot have cycles in the graph and uh there are total n nodes and they are labeled as labeled from 0 to n minus 1. so we have to find all the possible paths from the node 0 that is the source and to the node n minus 1 that will be our destination and we have to actually print the paths in which uh like we'll travel to reach the destination from the source and we can print them in any order as you can see that any order is acceptable so uh like if you see this example the source here is 0 and n minus 1 that is 3 here because total number of nodes are 4 so we have to print all paths from 0 to 3 in this case so we can print them in any order so now we'll see that how can we reach to reach and travel to every part from source to destination so i hope the question is clear now to see that how we are going to work on this question so the algorithm that we are going to use is called dfs if you are familiar with graph algorithms that is going to be a great headshot for you to solve this question so uh the approach that we're going to use here is as i mentioned dfs that is going to be a very simple dfs which you may have used in a like earlier simple questions also so here we go like you can see that um we have a start node so this is our source node and in this case we have five nodes right so n minus one that is the destination will be the fourth node so this is our destination now we know that we have to travel from zero to four and store all the paths and return it in the form of an answer so um my way of doing it will be that uh we'll start with the simple dfs so we start with zero because it's the source node and the source node is never going to change right so we have always to start from 0 that is what we have been given in the question so i'll start my dfs from the source node 0 and let's see that where all the paths that i can travel from 0 and then like if i come to one then from one how many nodes can i travel from one so in this way we'll do the normal dfs so before uh going into the depth of how the algorithm is going to work so first of all i would like to tell you that the important uh storage that we are going to use over here uh the vector that you can see over here is going to be a storage and this is going to be a kind of a temporary storage to store the current path on which we are traveling right so this is uh basically our path vector and it will suppose if we are traveling from 0 to 4 so we'll store the path that is 0 and 4 in the vector so that we can push it to our answer vector once we reach our destination so this is a temporary path vector so uh now let's start how the dfs will actually work as you can see that we have been given an input in the form of a graph uh vector so basically um if you see it carefully it's kind of an adjacency list that you have been given already in the input form right so um like you can see that this is the zero uh like uh if like it's like the zero with node over here and you can see uh all the neighbors that you can travel from zero like you can reach four three and one so that's what it is given over here similarly this is for zero this is for one this is for two and this is for three and this is for four so the fourth one is empty because four is a destination node right so this is the adjacency list that we have been given so now we have to look how can we traverse it just so that we get our all our paths according to what is being asked in the question so let's start from zero uh so now when we start from zero we look upon the adjacency list that we have so we see that uh like the first neighbor to 0 is given 4 over here right so we look the adjacency list and see that first we can go to 4 from 0. so we will do a call to the neighbor of 0 that is to the 4. so before you know making any calls our first step should be uh so since i started my dfs from zero so now when i am on zero so my first step should be to push the node i am currently standing on into my path vector so that i can track the current path i am going to follow so when i was on source node i started from the source node so my initial work is to push it into the path vector now i am going to call my first neighbor from the adjacency list that we have so we call upon four so we go to the fourth note fourth node right so our first work at the said is to push the node that we currently are on so now we are on 4 so we are going to push it into the vector so our temporary path vector has 0 and 4 right now in its state now after pushing it you need to check that the node that you're currently standing on is it your destination node or not so in this case we see that yes 4 is a destination node so that means that we have reached the destination and now we have two like we have to store the path from which we have come to this destination right so the path that i'm talking about is here right so we just stored it once the way uh when we were traveling to four so we now have the path so once you reach the destination node you're gonna push the contents of this temporary path uh vector into the answer vector that you are going to make so that uh you get all the paths so now the answer vector will basically uh be a vector of vector as you can see the format of the output so now in the answer vector you have 0 comma 4 right so your first path is done but since there is it is not necessary that you only have one path right so we need to go back and find that are there any other paths possible to reach 4 or not so um now if you see there just now since like it was the destination so its adjacency list is empty so now we need to go one step backwards and see that are there any more paths that exist to reach 4 or not so now when you go one step backward so you must be familiar with how recursion works right so when you go one step backwards so like since i have not passed the path matrix uh so the path vector by reference so uh it's its contents are going to be uh like changed as uh like change back the state how it was before the call was made so since you are backtracked to uh the previous state that in which we are standing on node zero so your path matrix will have the contents that were uh originally there when we were standing on zero so when we were standing on zero we didn't have 4 there in there right so currently we have 0 now from 0 you see the adjacency list we have traveled to 4 now our way is to go to node 3 to find out all of the paths so now we are going to make call to three now we are on three so our first work is to push three in there and from three we are again going to see that is it our destination no it's not so we are going to look to our uh adjacency list of three so the list of three only has four as its neighbor so we can only go to four so we are going to make called four now first work is to push forward because we are now on note 4 and then we check that is this the destination yes it is my destination so uh the work we did previously was to like push all the contents that you have in the path matrix to your answer path vector to your answer vector so now you have 0 3 and 4 over here okay so your second path has also been traveled successfully now your work is to go one step back and see that are there any other paths that can make us reach for so you go back from here and then you three and you then you uh come to three and see that in three is adjacency list we only had one neighbor that is four and we have already traveled to that node right so we don't have any other node to travel so we are going to backtrack from here also so as i'm backtracking uh you we also need to change the state of the path vector right so we are back again on zero so now from zero we see that we have traveled four and we have traveled to three now we have to travel to one right so now we are going to make a call to one once we make a call to one we are going to write into our path vector that we have over here now we are on one so one is not a final uh destination right so we have to see one's adjacency list and you see one has three neighbors so we'll call upon the first neighbor that is three over here right so we'll go to three now one will make a call to three now once you're on three you again first of all push it into the path vector that we have and then you see that it is not a destination that we had in the question right so we'll again look to the three's adjacency list and then you see you have four here so you again make a call to four now you are on 4 so you push 4 again and then you see it's a destination so your work is to put like push this path again so you will have 0 then 1 then three and then four now in the answer vector so you have explored three paths now you'll do the same step again you are on four so you'll go one step back and see if any other paths can be made to reach four so from three we cannot go to any other neighbors so we again backtrack the one step now uh backtrack here to one right so now we are on one so we see the adjacency list of one we have traveled to three now we have two more neighbors to go so we'll go to the first one over here that is node two so now we make a call to node two it's okay so first of all we need to make our path vector correct since we are on one so we will have contents till we were on till the state when we were on one so from one we have made a call to two right so we come to two now so you push 2 over here so we push 2 over here and then you see that from 2 you have only one note to visit so you make a call to 3 then so from two you can go to three so you will make a call to three and then you push three in here right but since now uh three is also not a destination node so we'll again look three and then you can see that we can reach four from three so when you reach four so you'll again push four here and then you see four is a destination so uh you have another path to reach four so and that will be 0 1 2 3 and 4 right so we have four parts till now we have explore four paths so now we'll go one step back we come to three and then you see you cannot go anywhere else so you back backtrack one more step and then you come to two from two also you only have one note to visit so we have already visited that so let's go back one more step and then you come back again to one so let's first make our paths vector correct since we are on one we have to make it look right so now we have one now we are on one so on one we have only uh one more neighbor left two traverse we have two hours three and two right so we can also go to four from 1 directly so now we'll make a call to 4 and then use once we are on 4 we need to push it over here and then you see 4 is the destination so you are going to push the contents of this path again into your answer so we have zero one and four over here right so uh we this is a destination so we'll backtrack one step and see if other path exists now we are on one and we have successfully traversed all uh the neighbors of one that we could so you have no nowhere else to go from one so you'll backtrack one more step and then you reach back to zero so let's make our path matrix right now you are back to zero so from zero we'll see that in zero also we have traverse all our nodes that we could right so now you have no place to go so that is where your dfs comes to an end and uh this simple backtracking technique using the simple backtracking technique we were able to actually find out all the paths that we could uh you know travel to go from zero to four so in this case there are total five parts you can see in the answer we can return them in any order um so we have zero four zero three four zero one two three four and zero one four so this is what your answer is going to look like i hope the algorithm uh walkthrough is clear so let's go ahead and write the code so initially as i mentioned that the return type of this function is vector of vector that is going to be your answer so let's create a vector of vector to store our answer and i also mentioned that we will be needing a temporary path vector so we'll name it as path right we'll pass it into the function uh that will cause over here so the next work is to uh actually call our dfs right so we'll uh like we'll create a function name dfs so we'll see what all do we have to pass so first of all the graph uh vector of vector that is basically our adjacency list that we have been given here so we'll pass it and afterwards we need to pass the path vector the answer vector and then we need to pass our source so our source is zero right so every time it is going to be zero so we will send zero and a destination every time is going to be uh here right three n minus one so um we will do graph dot size minus one so yeah so that's the n minus one so now we put a semicolon and now you have to write the dfs function that we mentioned so let's write the dfs function so first of all the function has to take certain parameters you have graph and then you need to take this path so uh please note carefully that i am not passing path by reference because i needed state to change according to the recursion state that we are in if you want to pass it by reference then you need to use uh that you need to pop the elements also at the end of the recursion so i don't want to get into those complexities so it's easier to do it without bypassing it by reference so let's also pass our answer right so this answer has to be passed by reference because every uh the change that is being reflected in it at every recursion needs to be reflected in their final answer so we are passing it by reference and then we have source and then we have destination right we have got them all now let's start the call as i said that our first step when we come to any node is to put like push it back into a path vector so we push the source so the current node that you are on is basically going to be the source right so not every time it is going to be the source so we are going to change the source every time you will see how it works so initially you push 0 right so you come over here and then a next step was to check that is the current node that you are on is our destination or not so you see if source equals to destination so we have two things to do over here that is to push back the contents of our path vector into an answer vector and second thing is to return right okay uh we didn't mention the return type it is going to be a point over here so what if this was like what we if we have not reached the destination so our work is to traverse through um let's say i traverse through the adjacency list of that node that you're currently in and then when you traverse you have to make a dfs call again so we have to pass graph then path then answer then uh yeah so now at the place of source so source is basically um you know you can say every time you come on a node so the node on which you are currently on is representing the source we could also name it as node if you want you can do that just understand the logic behind it so we so the like we are going to travel to its neighbor right so the source will have to change so um it will be i so i will be uh like the neighbor of the node that we are on so we have to pass it instead of source and then we pass destination because destination is not going to change and then uh that's it yeah so the dfs function is complete and in the end you need to return the answer so that yeah you're done with it so now let's try running the code you can see this past so now let's try submitting it right so we have successfully solved this question i hope the concepts were clear and if you guys have any doubts or any improvements that you want as a suggestion to be suggested you guys are free to welcome in the comments uh thank you for seeing the video bye
|
All Paths From Source to Target
|
rabbits-in-forest
|
Given a directed acyclic graph (**DAG**) of `n` nodes labeled from `0` to `n - 1`, find all possible paths from node `0` to node `n - 1` and return them in **any order**.
The graph is given as follows: `graph[i]` is a list of all nodes you can visit from node `i` (i.e., there is a directed edge from node `i` to node `graph[i][j]`).
**Example 1:**
**Input:** graph = \[\[1,2\],\[3\],\[3\],\[\]\]
**Output:** \[\[0,1,3\],\[0,2,3\]\]
**Explanation:** There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
**Example 2:**
**Input:** graph = \[\[4,3,1\],\[3,2,4\],\[3\],\[4\],\[\]\]
**Output:** \[\[0,4\],\[0,3,4\],\[0,1,3,4\],\[0,1,2,3,4\],\[0,1,4\]\]
**Constraints:**
* `n == graph.length`
* `2 <= n <= 15`
* `0 <= graph[i][j] < n`
* `graph[i][j] != i` (i.e., there will be no self-loops).
* All the elements of `graph[i]` are **unique**.
* The input graph is **guaranteed** to be a **DAG**.
| null |
Array,Hash Table,Math,Greedy
|
Medium
| null |
434 |
all right let's talk about numbers of sequence in the string so you are given a string s return a number of sequence in the string and a sequence is defined to be a continuous sequence of known space character so you're given example one right hello my name is john so this is five characters five words and one word and four words because love lie music forever you ignore the punctuation and this is zero and that would be it so what you actually need to do is you have to traverse the string and just kill your bacteria is fine and you need to make sure when you find a new character and then the period before is a space you need to add another uh add another count for the return value so i'm going to say equal to x equal to zero and then i will have to return the answer and now we can go in i to the u i less than star length i plus and i will have to try first so traverse i will have to keep track if the sub chart and i which means uh if i'm here yeah i will have to check if i'm here i will have to check but if i'm right here right uh so if i'm here i have to check the one before right so i will say and start shot at n minus one is base so i would just definitely need to add uh add answer so let's just think about it so hollow and then comma and then space and then mining my eye is at this position right so this is not a space but like i minus one is a space right so i know there's a word at this position but what happens if you have only one character one word right you also need to make sure if i took a zero this also works this also will so uh another furnishing yes so let's just run it and see what happens yeah that will be a solution and yeah pretty easy so let's talk about how you actually need to spend on the time and space complexity for the time is all the learn right traverse every single one of the industry space is constant the answer is not a big space in the ram so that will be constant for the space all the fun for the time and that will be the solution and if you feel is helpful then leave a like subscribe if you want it and then comment if you have any questions alright peace out bye
|
Number of Segments in a String
|
number-of-segments-in-a-string
|
Given a string `s`, return _the number of segments in the string_.
A **segment** is defined to be a contiguous sequence of **non-space characters**.
**Example 1:**
**Input:** s = "Hello, my name is John "
**Output:** 5
**Explanation:** The five segments are \[ "Hello, ", "my ", "name ", "is ", "John "\]
**Example 2:**
**Input:** s = "Hello "
**Output:** 1
**Constraints:**
* `0 <= s.length <= 300`
* `s` consists of lowercase and uppercase English letters, digits, or one of the following characters `"!@#$%^&*()_+-=',.: "`.
* The only space character in `s` is `' '`.
| null |
String
|
Easy
| null |
446 |
16 Love You Today Will Be Solving All Dual Report Problem Details Who Like And Comment It Slice 250 So In This Problem Be Happy And Given Clearance And When Vitamin A Number Of All Your Activities Subsidy Now Directly Which Novartis Benefit In Subsequent Which Is zakhm sequence of events 220 pulsar 135 reel and real wealth and its difference between delhi two consecutive elements in samsung m20 like it means set clarification show latest updates of us should stop this 1371 to 0.5 inches and difficulties in life is later 0.5 inches and difficulties in life is later 0.5 inches and difficulties in life is later what center test totally free The culture element of offering and different is similarly 307 round me difficult for railways and the difference between a collective limited European difficult effect I have this period Indian Tennis Association teacher is her emphasis workshop temperatures and account statement of energy in this academy for varicose veins time limits of you Are So Like It That Slowly Interview Reporting From President Of The Great Saint In This Can Be Called For The Solar System Definition No Like And Other Problems As Voting Test Cases For Kids To Dance Of Its Significance 200 So Toyota Gyan Singh Anil Dancer Me fit in distilleries so let's take a look at our concern for that so this your lake placid over 100 Indian body and this development officer body just a little in this we can see that if I tried to add to like velvet shopping in our body like it Packet Merit and Proof Fennel Ice Practice to Use Long S Much S Ko Superintendent Increases Final Answer Pimple Previous Song Matka Nigam Pal Ready Laga English Example of the Reason and Continuity Element 680 786 Shyam and Example in Which Year is American Information Resource Person has been sent to give 60 subjects of this results in subsequent se alive to happy lens and on the other hand more will pc in the subsequent revolt and different s always you should delete and meet again here then three number of with sequence left difficulty hanging 3 Plus E4 Plus Size Different To Daayan Ka Star Plus Latest Subscribe To That Sonalika Two Me Chatting Also Like Calculating The Arithmetic Sequences Full Length At Least Three Good Talk Preventive Worth One Like They Can Find The Number Of Birth Sequences Of Length Greater Than Equal To 2nd subject to like that at all the subsequent is absorbed in the city are sun for dinner and sequence software straight forward agency to which element in the to so like finding side meeting sequence as well as you can but you will discover with multi Services shv itki how can videos and so they can speak any to element and form sequence of to like and medical certificate softwares and wikinews sikayat difference between list elements a prayer for extending effective one tujhe signal fooling admit solid difference between 30 and this To and I Singh Differences Are Descendants Are 100 Ko Kiss Problem Black [ __ ] Lips And Something Vacant Like This Problem Black [ __ ] Lips And Something Vacant Like This Problem Black [ __ ] Lips And Something Vacant Like This Problem Yagya 12345 Telegraph Asked So Let's Consider Oneself Say Zinc I Comedy Subscribe This Who Is This Thank Represents A Number Of Modifications Ask Lo This Search Glass Element Kaise Naam Side And Acquits God Shift Difference Difficult To Win This Number Office Dpi Comedy After Var Yes Bhai Swami Lodhi Take Over S Plus Waqt Were Tagged With Details Ka Naam Sahib Ki Maine Su Ko Achhiye Hum Saari Ras Hum Sirf Weekend This Name Sahi To Abhi Subscribe Miding Adams 52-Shaktipith And This One Is Like 52-Shaktipith And This One Is Like 52-Shaktipith And This One Is Like Regarding This Vansha Begins For Another Subsequent Of Artificial Systems Is Why Hindus The Situation Different Views On This Subject And 284 Every Year This Website But Why And Will Have Opted To Vardi Arijit Torch light bill you ok operation black values of all chief is formed and death and all the values of all chief is formed and death and all the values of all chief is formed and death and all the respects to get a total number of subsequent s medical shop distinction to end when they can rise upright and one minus 1.2 tutegi bhagalpur show latest tried to minus 1.2 tutegi bhagalpur show latest tried to minus 1.2 tutegi bhagalpur show latest tried to implement this Ki Kripa Timing Scoring This Side Of Freedom With A Minute And I Will Need For Speed 93422464 Because Matriculation Like Friends Office Number Appeared In The Morning And Differences Of All Operators That Video When TT Are For Calculating This Thank Sorry Yaar Post Susan On Map That end of and pari presenting this state a defining and have a absolutely fish that to be different to 2053 pressed music twelfth class is ranges from 12150's twenty-20 pitch of 108 that and they can cause notice to be easy was subscribed And Navami can start this point Ludhiana am starting from big guide for 120 extra sp college life in the world does not from asr sequence win the match ended up aur phir ko aap bhog the pain and gain worry na bandhe who is the president for every It is day but now induction has come no like this that Vijendra updated on that Choudhary Stadium size - 96 Choudhary Stadium size - 96 Choudhary Stadium size - 96 A collection Shyam se yaari third wicket got toss world wide web tracking dam 122 sump immigration officer 2015 birthday Mitthu Long and 10th music competition on and On the day of Navami like this was the former's notification for health benefits on this picture of help audit's current sit ki woman herself had taken two 120 business pension ki pir wa ki prayog remind ki and yu hai ab kaise hai jhala a novel tutu this Thank Winters Straight Forward That Hindu Subscribe To Main Tere Current Loot Person 's Comedy 's Comedy 's Comedy That Videos A Plus Seat 220 Rally This After Doing This Looks Like Or Dislike Will Have All Data For All The States And Save Them All The Total Time Set Up Loot Ko Start from this undertaking 11.22 Uttarkand hai jhala kar do ki vikalp hai that reddy ne a part of this state scientific achievement hindi and they can do sub traction a aaj din bhar officer the first number sequence consisting of positive a that Arvind ko the patient was given equal To return them Sharif difficulties in constitution you slept the complexity of this the whole program is like water and 0 guests people is a and friends this system android operating on flash light off do in this can be the most difficult episode 900 cigarette status as it is Remains that this show the evening nr club cutting amazed to latest events aspecific loot is a young man for 220 this tube second day were walking some whether all's submitted on were recent improved it attending a software
|
Arithmetic Slices II - Subsequence
|
arithmetic-slices-ii-subsequence
|
Given an integer array `nums`, return _the number of all the **arithmetic subsequences** of_ `nums`.
A sequence of numbers is called arithmetic if it consists of **at least three elements** and if the difference between any two consecutive elements is the same.
* For example, `[1, 3, 5, 7, 9]`, `[7, 7, 7, 7]`, and `[3, -1, -5, -9]` are arithmetic sequences.
* For example, `[1, 1, 2, 5, 7]` is not an arithmetic sequence.
A **subsequence** of an array is a sequence that can be formed by removing some elements (possibly none) of the array.
* For example, `[2,5,10]` is a subsequence of `[1,2,1,**2**,4,1,**5**,**10**]`.
The test cases are generated so that the answer fits in **32-bit** integer.
**Example 1:**
**Input:** nums = \[2,4,6,8,10\]
**Output:** 7
**Explanation:** All arithmetic subsequence slices are:
\[2,4,6\]
\[4,6,8\]
\[6,8,10\]
\[2,4,6,8\]
\[4,6,8,10\]
\[2,4,6,8,10\]
\[2,6,10\]
**Example 2:**
**Input:** nums = \[7,7,7,7,7\]
**Output:** 16
**Explanation:** Any subsequence of this array is arithmetic.
**Constraints:**
* `1 <= nums.length <= 1000`
* `-231 <= nums[i] <= 231 - 1`
| null |
Array,Dynamic Programming
|
Hard
|
413
|
1,650 |
hey guys so today we will be solving the code 1650 which is lowest common ancestor of a binary t3 so in this question we are given two nodes of a binary p and q and we need to return their lowest common ancestor each node will be level difference to its parent node the definition for node is flow we are given the value we are given the left pointer in the right corner and the parent so think about it why are we given the current formation here because that's why this question is unique right you have to find the lca using the parent that's the crux of this question if you see the functional definition you can see that you are not given the root of the tree right generally in lc is the simplest situation you will be given the root of the tree right so basically that's the truth right that you have to find the lca using the parent formation of the two nodes how can we do this so if you have solved intersection of two linked list this problem is very similar to that let me show you by right and how can we use that logic to solve this question so basically we won't be solving one question but we will be solving two questions okay so now yeah i will use the same logic that i am showing you to solve that question as well so let me resize my window so that it becomes much clearer to you okay so let's say we have two linkages let me draw through the image up here so uh this linked list has let's say four nodes and then one node where this the both of the links intersect and then this english style and it's just two and then they intersect and two additional notes here so how can we find the intersection of the storyline list right there are a couple of ways to do that one way is to just find the length of both in english subtract find l1 minus l2 right and then uh increase this much right this much amount in the large link list and then start traversing the notes one by one so if we follow that logic right uh the length of this linguist is pi the length of this list is uh four and three seven right then uh the difference is true we will be starting the bigger uh node here bigger linguist here and the smaller linguist here and then traverse basically one by one will be drivers one by one you see we have to try with three nodes here so ultimately we will find this uh intersection right but right we can even there's no need to find the length we can basically have a smaller simpler logic over here which is let me show you how can you do this so this is this will be possible through the two pointer technique if you're not a two pointer technique don't worry it's very simple right so let's say we have one pointer over here we will be incrementing both the pointers one by one right so when this pointer will reach the end by incrementing one by one we will let's say this is p1 right and p1 which is signed will be incremented uh we will assign p1 to be head of the other language so this is h1 let's call it h1 and this is h2 so when p1 reaches end we will say p1 will stretch two else if fp1 is not at the end obviously p1 would be p once next or what happened even be the three p1 is next right in other cases this would be and similar for let's say this is p2 which is pointing to s2 initially right you will increment it one by one and then when p2 reaches uh and we will say p2 equal to h1 else what as p2 equal to you know it right p2 is next this is the whole crux right and we will be doing this both operations at the same time and ultimately what will happen is uh in the next iteration what i mean by that when both of the nodes have uh okay not in the next iteration let me just try to show you how this works uh let me clear all this explanation yeah so here we have uh p1 p2 h2 h1 right let's increment p1 one by one so in the first iteration of p1 and p2 let's see will be here p1 will be in the next iteration p2 will be here p1 will be here then p2 will be here now what we need to do p1 is uh at the end we will say p1 equal to s2 so p1 will reach here where you see here right even let me just draw it over here so p1 will now reach here and p2 for that what will happen to p2 in the next iteration p2 will be just incrementing one by one okay now in the next iteration p1 will be here p2 will be here in the next iteration p2 pertains to 2 to p2 t2 equal to h1 right so here we will become with the p2 here now right so basically the head of the other linked list okay so now we have p1 in the next iteration people will be reaching here and then we will be having p2 here again increment one by one p2 here p1 here what we see p1 and p2 are now pointing to the same one right even if you are pointing to the same so we know that this is intersection it will just return this node then so basically the code will look something i think you got the idea what happens is that we are just uh traversing the long let's say we're traversing the longer node then yes then we assign the head of the long then we assign that pointer to the head of the shorter node so what happens is uh we are just basically trying to balance out uh the lands of both the linguist so basically that's the crux and the same logic we can use uh even with the trees even in the trees we can use the same logic because tree is basically kind of in english as well if we have trees right let's say i will just take a simple example because it will work right uh let's say we will have to find the lca of this two nodes what will happen okay so they are the same distance from the lca then in the on the first iteration itself you can return so in the first iteration we will go to let's call it p1 let's call it p2 right we will go to p1's parent and we will go to p2 right uh in the first segment so both are equal we will just return this let's say we were here let's say another use case would be this case would be that we have to find the parent of this node and find the parent of this right then in the first iteration uh p1 would be let's say initially p1 is here v2 in the first iteration p1 will uh reach here right and p2 will reach here and then what we have to do we will say p1 equal to h2 because initially when where we started is the hand right so it would be asteroid it would be h5 yeah so p1 will reach here in the next iteration and p2 will be reaching here the next iteration right uh right and then p1 will be here and then p2 will be say h uh h1 right so yeah so p2 will be here again in the next iteration both will be pointing to the root node so basically it won't take more than order of n plus m time to just find the lca right because in this case in both it is several let me just uh code it out right so we have two pointers let's say a node for tan b1 which will be assigned to p or let's just call it time p which will be assigned to p and then another point here which is tan q which will be assigned to q right so till then we have to do this by p not equal to q what we have to do is if p naught equal to null what we have to do in that is equal to p squared right as what we have to do else if uh that does not mean pointers so 10p over here as well let me just cut up them uh if it's not visible let me just maximize my screen right yeah so okay let me just erase this and start from beginning let's say we have two pointers which is tam p equal to p and tan q equal to q so by tan p not equal to and q what we have to do is and f not equal to null uh we will say what we will say we will assign 10 p to 10 piece parent exactly right else's and p equals equal to null what will happen in that case we will say time p is to what cube that's what we discussed other nodes parent in that case would be q i mean not the parent but the initial point in the case of a tree and had in case of a linear and similar logic will go for the other time u right so if tan q is not equal to another we will say then q equals to 10 q squared and if than q becomes so yeah i think this is it right and this should work if there's no bug over here let me just try to run my code uh i'm just trying to adjust now but yeah let me just try to run my phone uh so i think there is one error i'm not sure why it is okay let me just do it okay then let me just again there is an error okay so typo man so there is a typo uh cool tmpdf right now this looks good let me try to submit this and let's see what happens okay got accepted so yeah guys this was it if you had any questions please comment uh below i can take those right thank you like share subscribe if you found it useful thank you
|
Lowest Common Ancestor of a Binary Tree III
|
find-root-of-n-ary-tree
|
Given two nodes of a binary tree `p` and `q`, return _their lowest common ancestor (LCA)_.
Each node will have a reference to its parent node. The definition for `Node` is below:
class Node {
public int val;
public Node left;
public Node right;
public Node parent;
}
According to the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor)**: "The lowest common ancestor of two nodes p and q in a tree T is the lowest node that has both p and q as descendants (where we allow **a node to be a descendant of itself**). "
**Example 1:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 1
**Output:** 3
**Explanation:** The LCA of nodes 5 and 1 is 3.
**Example 2:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4
**Output:** 5
**Explanation:** The LCA of nodes 5 and 4 is 5 since a node can be a descendant of itself according to the LCA definition.
**Example 3:**
**Input:** root = \[1,2\], p = 1, q = 2
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[2, 105]`.
* `-109 <= Node.val <= 109`
* All `Node.val` are **unique**.
* `p != q`
* `p` and `q` exist in the tree.
|
Node with indegree 0 is the root
|
Hash Table,Bit Manipulation,Tree,Depth-First Search
|
Medium
|
1655
|
349 |
today we're going to be working on record question number 349 uh intersection of two arrays uh given two integer arrays nums one and nums to return an array of their intersection each element in the result must be unique okay and you may return the result in any order so just by the definition of it we know we're gonna be returning unique values and the intersection meaning like both of them needs to happen so it's a perfect candidate for using a set so that's what we're gonna be doing okay so for that one we're gonna have our set of integer called that ah new action so this is gonna have basically this is gonna uh remove all the duplicates there but then we're gonna have another set for integer and which is gonna keep record off the intersections enter sect so that would be new hashtag okay uh third thing is like we're gonna fill move everything from the nums one to our set okay for that we can just put it in so once our we have the unique uh values of this uh of the arrays inside the set we want to make we want to check if the other ones like we're gonna go through the other one and see if we have seen it or not and if we have seen it's going to go into the intersect one okay so for that we're going to say int i is equal to zero i is less than nums two dot length i plus now if uh basically we're gonna say that uh we're gonna say that okay if the set contains that all right f set uh dot contains this number of two of i and then you're gonna put it into the intersection that would be enter sec dot add uh again the same number num of two of i so once you are done putting it into the intersection all we need to do is to put it into the result because we want to return an integer array so for that we'll use we have the result whose size is going to be equal to like whatever is the size of that enter set dot size okay and then we're gonna go through and i equals to zero for integer num inside the intersect okay we're gonna say that the result of i plus is equal to that num and then we're gonna be returning the result looking good and it works
|
Intersection of Two Arrays
|
intersection-of-two-arrays
|
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must be **unique** and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[9,4\]
**Explanation:** \[4,9\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000`
| null |
Array,Hash Table,Two Pointers,Binary Search,Sorting
|
Easy
|
350,1149,1392,2190,2282
|
1,605 |
well there is problem number 1600 5 liters which is called fine the matrix with robbins with sounds this is a very interesting test because if there is really a problem that can be done in an interview in fact that is the typical problem that they answer through an interview It's pretty good because you can make good backtracks in many ways, but use the bases in the way that I consider the easiest, because our social network is a bit geeky. Here I arrived is a solution that I'm going to give to someone else. This thread explains it, not what this is about is that they are going to give us something like this they are going to give us it is called russian and colson and this is basically this good two arrays and what we have to return is an array for example in this case we have to return this array that meets these conditions then the result already rawson means that it is the sum of the rows no then row 0 the sum of the numbers 5 row 17 57 and row 2 is 82 10 is yours is the sum of the columns no 86 22 38 56 and 88 entities with know there are many possible solutions to this there are not many matrices that can give us these solutions like a sudoku good as a shock for him it is something like this so there are many ways to do it I am going to explain it with flowers and in the code but basically this is what we need as you are going to need it we have to initialize our array because we are going to do this not if we were to return it so well I wouldn't have to do it no but since it is not like that I have to declare the array initialize it so let's go to do first a links and france for the credit or something like mine in rawson point legends because I do it like that because if I put it here the colson like we had it in java if being heavy is wrong this one was not going to initialize ours without k is equal to zero collins and is equal to zero while y is less than grid after and more and well simply write y is equal to new and colson lens and that's it then we already have to initialize the array that we are going to return the matrix sorry and then We are going to make two variables that will be called row, which will be equal to row, they are point lenses and ah, and it would be colon, which is equal to coulson, point lentz and that advance the variables beats error and colon and while this when you put it with a wild and as long as r is in fact this I did it wrong I'm going to do it and these two in relief made to zero and well this one well yes it would be yes no so what we are going to do is we are going to compare these two in the first possible case seville and road are bruce is less than mattress if so we are going to do one thing and if not so we are going to do the thing then this in this case this is the cause of coming back before now row and colom are both here as roe is less than columbus to five is less than eight what we are going to do is we are going to put the 5 here and the 5 itself if we are going to be the 8 and we are going to have a 3 here no then creed is equal to rawson r and then c - equal rawson ere and then ere more and well I'm going to get here the count d because they increase being these to the next we're going to have to see what we're going to compare how the now is worth 12 we're going to compare if 7 is and if 20 comes out 7 is greater than 3 We are going to fall here guys half to 3 we are going to do this we are going to see it but this time with a mattress and make it then because of being now Robson they are doing exactly what well and we are going to increase so here what it is doing is that good 3 is less that 7 then r 10 is going to go here we are going to put this 3 here and the 7 we are going to remove 3 no and we are going to have this 4 and we are going to think about holding 1 then now we are going to buy these 24 is less than 6 and then is going to fall in this part and what we are going to do here is that we are going to put 4 here and the 6 we are going to subtract 4 we will be 2 and we are going to advance this one then we have these 2 10 is greater than 1 when it falls here and if is greater than 1 so sorry 10 is greater than 2 so what we are going to do is we are going to put this 21 and it is here I know I was wrong to see ah of course 10 is greater than 2 so therefore we are going to put the 2 here which is this 2 we are going to put it here we are going to advance the column and from this 10 we are going to subtract 2 it will become 8 the wave then 8 is equal to 8 again in this in our second case and we are going to put here the 8 to 8 we are going to be 8 and 3rd etcetera and you see this result that if you realize I am going to put the problems values of am going to put the problems values of am going to put the problems values of rose or thread Colom that were these here then it is worth 54 37 82 days 5 38 42 6 and 8 is equal to 8 and this result is correct so it is not a solution that I no longer reach and it says something more elaborate that I am obviously less efficient but well I do not know if it works and if it works it is then the best possible solution I insist no solution arrived but I thought it was the most interesting and what I asked them for in an interview, this is obviously a typical interview problem and I am sure they could come up with something like this if it is worth studying this problem
|
Find Valid Matrix Given Row and Column Sums
|
minimum-number-of-days-to-make-m-bouquets
|
You are given two arrays `rowSum` and `colSum` of non-negative integers where `rowSum[i]` is the sum of the elements in the `ith` row and `colSum[j]` is the sum of the elements of the `jth` column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column.
Find any matrix of **non-negative** integers of size `rowSum.length x colSum.length` that satisfies the `rowSum` and `colSum` requirements.
Return _a 2D array representing **any** matrix that fulfills the requirements_. It's guaranteed that **at least one** matrix that fulfills the requirements exists.
**Example 1:**
**Input:** rowSum = \[3,8\], colSum = \[4,7\]
**Output:** \[\[3,0\],
\[1,7\]\]
**Explanation:**
0th row: 3 + 0 = 3 == rowSum\[0\]
1st row: 1 + 7 = 8 == rowSum\[1\]
0th column: 3 + 1 = 4 == colSum\[0\]
1st column: 0 + 7 = 7 == colSum\[1\]
The row and column sums match, and all matrix elements are non-negative.
Another possible matrix is: \[\[1,2\],
\[3,5\]\]
**Example 2:**
**Input:** rowSum = \[5,7,10\], colSum = \[8,6,8\]
**Output:** \[\[0,5,0\],
\[6,1,0\],
\[2,0,8\]\]
**Constraints:**
* `1 <= rowSum.length, colSum.length <= 500`
* `0 <= rowSum[i], colSum[i] <= 108`
* `sum(rowSum) == sum(colSum)`
|
If we can make m or more bouquets at day x, then we can still make m or more bouquets at any day y > x. We can check easily if we can make enough bouquets at day x if we can get group adjacent flowers at day x.
|
Array,Binary Search
|
Medium
|
2134,2257
|
54 |
Merry Christmas let's take a look at number 54 spiral matrix we're given a matrix of M n elements M rows and n columns which are all elements of the matrix inspire order which is a one two three six nine eight seven four five this is actually this is not about algorithms about this is about how we Travis special data set actually let's just analyze the behavior first we start with the first row and go just to go straight forward until we met the last element there's no moral umbers we will move downward and move just to go straight forward if there is no element we turn right and then again there's no element turn right but until four we find that the previous element is already Travis we need to just avoid that and then turn right yeah actually so that left core problem is very simple it's like the first we need to turn right when there is no number or the element is already traversed right yeah so this is basic rule when we will stop or stop is that when we will stop at this number right number five or here number seven which means even we turn right there the rest the next number is already Travis so yeah that's where we should stop if there is only two rows what happens we go to one two three six four five and then we turn right for return right it is already Travis so yeah so how can we turn right the head is actually two right yeah right here the direction actually could be expressed in a you know it's alright we actually could define a vector the direction is just how we calculate the next up coordinate right for the first number first two real numbers in a soup a row of zero one zero two there are three so the direction should be the right should be zero one right if it is downward it means one zero if it's left it means zero minus one right to up go up it should be minus one zero so this is the directions because we are doing it in the only one direction which is turn right so actually we could put them all directions into the array and just loop it loop through it over and over this is the direction okay Karen let's say that current Direction equals index equals zero kind of turn right we should just this right update this 2 plus 1/4 direction then after to write the index will be changed yeah cool so now let's start the traversal let's say the result equals empty that's equal zero net J equals zero we start at two zero then we go to next one yeah so yeah we can so the while loop while it would be so we put or put we check the first number because it exists we should turn we go to next one mmm yeah well actually well rest salt 9th guess more data matrix then tricks okay constitute total because totally is this right so it's if it's smaller than total we should just continue we should continue she continued moving forward the wider boot is that when there's not enough numbers we will check the current number and I put push them in so it should be ending at the last one okay so let's say it should push right result push matrix I J and then check if we need to turn right because possible let's say if let's say next possible equals I plus directions current Direction zero J plus yeah this is the possible next direct possible now let's say if it is out of town boundary okay if it is over float or it is Travis turn right so the condition should be if next possible this is the row is smaller than zero or bigger than matrix that net or so zero or if this is outer boundary matrix 0 total net or matrix if it is already Travis it should be next pass is 0 next price or one the elements so yeah let's say if it is no because we're already connected we update here - no we should connected we update here - no we should connected we update here - no we should if that's the case we should turn right okay i this is we change the direction so I actually should be this is the direction cut a new direction J okay we're done let's try result try round the code there's nothing mmm wait yeah who me we didn't get anything near the result the first Direction is 0-1 so ah else there's no there is no if this we should turn right but yeah the else doesn't if not we should do the same right update the coordinates yeah okay we get something like one two three six nine eight seven four zero what is zero hmm this is weird the direction should be go to here right okay zero one zero okay zero minus 1 I minus one zero there's no zero how we push matrix there's no zero anyway we log console.log by N and J check what we console.log by N and J check what we console.log by N and J check what we have done zero one zero two we should be 1 to 2 1 to 0 it's 7 to 0 then 1 0 & 1 0 but we already said then 1 0 & 1 0 but we already said then 1 0 & 1 0 but we already said it to know if next one it's you know we sure turn right this is not true but this is true right let's check console.log because you let's check console.log because you let's check console.log because you wrote until we get to zero and then it says to zero is 1 0 1 2 to 0 it should be next possible should be yeah it's of course it's undefined so we turn left to right I should be 1 0 yeah 1 0 then we lock wait a minute 0 ah God I made a typo here it should be something like this let's run it again hmm I think we can oh it's em when it's empty the educators the regular cases we should always consider if matrix named equals zero or matrix 0.9 equals zero or matrix 0.9 equals zero or matrix 0.9 equals zero return yes yay we passed and I think this is does not need to be more addressed it's just a playing implements implementation problem that I think the only way only thing we can learn is that the way of how we can have the directions yeah the devotions could be expressed as this vector which adds up to the current coordinate and then we're just doing it over and over game and find the final result yes zero one is to the right one zero top down zero minus one to the left minus one zero bottom up yeah hope this video helps see next time bye
|
Spiral Matrix
|
spiral-matrix
|
Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,2,3,6,9,8,7,4,5\]
**Example 2:**
**Input:** matrix = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\]\]
**Output:** \[1,2,3,4,8,12,11,10,9,5,6,7\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 10`
* `-100 <= matrix[i][j] <= 100`
|
Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row.
Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not.
|
Array,Matrix,Simulation
|
Medium
|
59,921
|
1,489 |
Hello everyone, welcome to my channel, we are going to do video number 33 and today a very good application of the playlist with graph convolution questions that I have created is going to be released, okay, so I want to say that every time I see it in the players with graph convolution questions. It is quite good. You will get to know from the comments. You will also get to know from the very good feedback. Okay, today 's question is hard marked. Okay, but do 's question is hard marked. Okay, but do 's question is hard marked. Okay, but do n't leave it after seeing it hard. Okay, do n't agree right now. Now look at me, trust me. The thing that I will tell you, if you have seen it in my already playlist, then this question is going to be very easy, okay, I would not say no to this, liquid wale bada maa jaaye, let's take medium maa, I will definitely make it medium. I am okay with this, the number is find critical edge in minimum three is okay, let's see what the question has to say is six, Meta and Amazon have asked this okay brother, but this question is a very time taking question, if seen from the interview point of view, then the interview. I can solve it so quickly, it will take time, only those who have solved it before will be able to solve this question, it is okay, otherwise it will take a lot of time, so what is my request to you brother, look, I have given minimum three in the question, so you have to get minimum spinning tree. So, if you want to come, then in my graph concept hum questions playlist, what is the minimum entry, I have told you that it is only a 9 minute video, see what it is and two ways to find the minimum entry are love and remove it from love, algorithm and Krish. Tomorrow, today is a little straight forward, so how will I do it tomorrow, so remove this also, that is, all you need to know is what is a minimum tree, it is a 9 minute video and what is the Kiskal algorithm, it is a 24 minute video, okay and In Kiskal, DSO also happens to him, hence you should also come to DSO and there is also a video of DSO, very good video, very good feedback has been received from it, graph concession question paper is fine in English, so you should come to that also, but I am the one. Let me tell you a good news, even if you don't know either of these, you will definitely understand the structure of the question. Whatever you have to do, I will definitely explain it to you. You just stick the code of Crush Color DSC, Dog and the rest. I have told you to do that after understanding this question, do that then the question will be solved. You may not be understanding many things right now, but let us understand the question for now, then we will move ahead and you will be released and IF YOU DON'T KNOW THE CODE OF CRASHKALAN DSO. If you just know what both of these are, then this question will also be solved. Okay, I'm going to make this very easy. Trust me, so look, let's start by giving you a weighted undirected connect graph. It means that it is weighted and undirected. Next, it will be okay on both sides and connected, that is okay, N vertices should be connected, zero, one minus, what is A, I, B, connected, it is connected to most of the graph edges, which is that all the vertices should be connected, but from those edges. Should be connected whose sum should be minimum of weight of minimum with d minimum possible total further weight, that is why I am saying what is minimum spinning tree, after seeing that which is fine from my playlist, before the graph concession questions, its video number 33 is minimum. Tree has been told in video no. 36, Kriskal has told it, okay, if you watch it will seem even simpler, this is not a lot, I will explain it here, so you may not get confused, fine, which is the critical and video critical edge. Okay, I have already said, find out the critical in the graph of minimum tree, that is, first find out the stage of the graph that has been given to you. Okay, in Mast, you have to find out which edges are critical and which edges are pseudo-critical, okay? pseudo-critical, okay? pseudo-critical, okay? So it is clear that brother, first we will take out the MSC. Yes, we will have to take it out first. Okay, that is, I will paste the MSC in the code and which code have I given? Chris, yesterday's one is fine and I remember it in the crystal as well as the DSO. If it were, then I am going to paste the DSO in the code too. If you watch the video, you will understand but I will paste the code so that this video does not become long, it is useless, okay, that thing is already read by me, Rakhi is okay and very delicious, so it is critical. Meaning is telling that Mast is ahead which increases on deletion. Brother, what is the meaning of MSG whose weight is minimum and if I remove someone and if the weight of MSC increases too much then he is critical and cannot be removed. You can, okay, now it will be very clear from the example and this is what is the critical understanding that on the other hand Assertive Critical further it is date witch can upper in some mystery but note which means such further which will be in MSC like a graph You should also know that a graph has a very messy head, right? And I have told you in these videos that a graph can have a very messy head, okay, you will become a minimal pen interior, a graph can become very messy, okay? In some MSC, he will be ahead, in some he will not be ahead, however, in this video, the critical further speaks, trust me, now everything will be clear from the exam, note date, you can return disease of the age and give other orders, see, you know. What has to be done is critical next and their index has to be returned, this much has to be returned, their index has to be returned, whatever their index is, you have to return whatever their index is, okay, till now it is clear, so understand from this example. Look, this is my example. Zero and one, which is the vertex, both are connected. Look, pay ahead of weight one. Okay, so if I represent this whole thing in the graph, then the graph looks something like this. You are seeing that all these are this. I have drawn it here, okay, now let's come down, okay, so first of all, let me do one less thing, what I said in the question, what is called critical and surgical, I will draw it and explain it to you here only. First he said, brother, take out Mast, so what was the meaning of Mast? It is a subgraph whose weight is minimum. Okay, now see how much is its weight. Now its weight will be very poor. All the connections are there in it. Isn't it two, one, three, two, six, three, no, three, 15, six, 21, its weight is fine, minimum, first entry has to be taken out, let's try entry with Vinay, what should I say, all the vertexes should be there, so I drop all the vertexes. Okay, you should come here, see how much is there, Sir, how much is the vertex here, one, two, three, five, there is neither agency nor tax, they should be mines, okay, I will draw that too, zero, one, three, four, okay, its cool. If many MSGs are possible then this will be done, this is done, okay, I will write its weight 121, okay, so see MSC, I can make multiple but MSC weight will be from all, isn't it, look, cool weight, it has unique chemistry weight too. It will happen, but MSC can be too many sir, so let me make another MSC and show it to you. First, Sir, it should not be ahead. Sir, Vertex should be sorry. Sir, what is this drawn, now look at it sir and what is the number of address. V - 1 2 3 4 Okay and all the vertexes are V - 1 2 3 4 Okay and all the vertexes are V - 1 2 3 4 Okay and all the vertexes are connected, this is what chemistry used to be, and minimum agency is also an election. Look, one is one, you are this too, this was mine, this was also three, so look at its sun, how much weight was removed. This equal, you took out 7, so what did I say about this? Look, Messi's weight is unique, 7 will come, all MSG's butt can have many representations, it can be different, okay, I will write 01234, okay two more. That too can be made, I have made it here and shown it to you. See, two of these were possible. I have made them both below. If you look at their weight, it will be only 7. Look, its weight is 7. So I told you that its weight is 7. It will be unique but the tree that can be formed as MSD can be many, you must have seen that here, okay, I have made all the MSGs, now I will try to find the critical further, so see here I said that it is not one such chemistry. Which is to be deleted from the graph, how did you increase the MST weight, which means if the weight of MSG weight is not increased, then let's reduce one. First, I have seen this further. Look, then look at this further. If I delete this then do it. Okay, if I delete the one connecting 1 to 2, look, I have removed it from here, removed it, okay, your full attention should be here, now I have completely removed it, look, let's connect, okay, someone else is late. Take some other response, let's bring this one, okay, its weight is two, now we get 2 4 5 3 8, brother, it is eight, is n't it cool, while there was the weight of minimum spanning tree, so it means it is very critical to remove it. You see, my weight is flooded, what does it mean that this zero, one, this one, you were there, this is my critical ahead, after removing it, look, my weight is flooded, I had given the same in some definition, so now I have seen. It is possible that it was just connected to this one, nor have I tried connecting it to another one. Okay, it means that when I removed it got disconnected, so it will have to be connected, so I have connected it further. Its weight is 3. Let's see. How much weight does it cost three six three no a gaya brother this is bigger so brother what does it mean that we cannot ignore it we have to keep it so that means this is critical ahead, this is my critical, okay so critical. In the list, I add here, he said, tell me the list of critical and sodo critical, okay, so look in the list of critical, which one is ahead of the one, you are the one, its weight is one, here is this one, so what is its index, see? So the index of this one is added that brother, the one with index one who is ahead is critical, very critical, after that let's see if there is anyone else who is ahead who is critical, so I redid this one again that he is critical. So let's make it from green which takes it to critical, isn't it okay, there is one more which is critical, let's see, let's take it, if it is ignored, if it is removed, then see if zero is disconnected, then zero has to be connected, so this one. I have removed it, neither is there anyone else, let's see whether it can connect or not. I have connected to it and seen that this is two. Let's see by doing two, five, three, eight, brother, eight weight, which is bigger than the minimum planetary, it means that this is I have taken out a new weight, brother of Minimum Silent Tree, it is big, which means it is definitely critical, I cannot ignore it, okay, let's see if there is anyone else who can help, no, look, this is also three, six, no. This will also be the new weight which is minimum, it is bigger than my original entry weight, it means that we will have to keep this weight, so I will make it green, this is my minimum spanning, sorry, this is my critical weight, okay so this is There are zero and one, let's see which one is ahead, here is this one, look, zero and one, its weight is one, what is its index, brother, its index is zero, so one and zero, which one of mine is ahead, critical is ahead. A Okay, let's do the rest of the inductions 0 1 2 3 4 5 6 Okay, this is my critical taken out, now let's see if there is more critical ahead. Do you see, you will not get more critical if you try. These are the two criticals that you will get. Okay, now let's see which one is the critical next in this video. So see which one is called Sodo Critical next. Witch can appear some masts but note that is okay so let's see. Pay attention to this next one. This one is on this one. Look, it is present in this also, but there is no style in both of them. Look at the weight of MSC, it is equal to the intake of intake. It means that even if you put it in or not, still see the weight which is 7. It is present in some of them. If no one has it, then this one who is ahead is not mine, what is mine? The one who is third from you, the one who is third from you, that is my PSE, it is udo critical, what should I call it, Pado Critical PC can speak, okay, so which index are you? And let's see which one is ahead from 0 to 3, let's look at this one, the one from zero to three, is ahead, it is not here, it is ahead, it is not only here, it is also here, so it means the one from zero to three, which is ahead. No, this is correct, let's look at the four with index number three, which one is next, yes, look, it is not here, it is here, but it is not here, it is here, so what does it mean that this fourth index one is also Sodocratic. Let's see, the one from 3 to 4, yes, which one is the one from 3 to 4, first let's remove them all, yes, the one from 3 to 4 is ahead, mine is here, it is not here, so the one from three to four is next. What is its index, what is five, that is also my video is critical, let's look at the last one, pay attention to this one is ahead of four, neither here nor here, so is this video critical? If it is on story, it is in some MSc, if it is not in chemistry, then one to four is not critical, okay, if it is clear till now, then this is a question that has been understood and this has also been understood, okay, this too very well. Got it, ok, now let's move ahead, let's see how we will approach it, you will remember once I do a quick recap, do you remember what used to happen in Crack Cizzle that if we had given the agent, we would have sorted it. Based on weight in ascending order but if you sort it then everyone's index will be last, right in index number zero, this is one, you are three, four is there, if you sort it then this index will become last, that's why what will we do? No, first we will put its and original index in all the inputs like here we put zero here we put one here we put tu, after that we will sort them according to the weight, then after sorting them in the sending order according to the weight. And we have also added the index, so look, it will look something like this, here I have written it, okay, so look, it is sorted based on weight, okay in the sending order, and they have added index also, they have added an index, it is the original index, isn't it? I have added it so that it does not become last, okay for now, here I am indexing zero one two three four five six but where is the original index of all, see here its original is inside, zero is inside this, one is this Three is its tu hai so on all, I have written the original index so that in the end when we have to find the answer, we can put it in the original index, it is ok till now it is clear, now let's move ahead, do you remember what I had to say, first of all sort it. You did it according to the weight sending order, after that I had to say that in the beginning all the vertexes of mother are standing alone like this, okay and we will process according to the weight in the ascending order, so first of all I am in this, I saw that its Wait one is ok and zero comma one is ok zero comma one then first let's see if zero is connected to zero and one is ok do n't see if zero one is not connected then let's connect ok it was waited for one was ok After that, next is One Aur Tu, is it connected or not? Right now One Aur Tu is not connected and how did you know whether you are connected or not? We used to know from DSO, that is why I am saying, check it tomorrow, okay, One Aur Tu. If it is not connected, then what did I do? I connected both of them and wrote the weight one. Okay, after that when you come here, look, you are zero and three. 03. If it is not connected, then I connected it using weight. You are after that, are you and three connected, look, are you and three already connected, so we come with 2 and 3, it is not necessary to put weight, okay 2 3 because it is connected, okay now it comes here. So let's connect, using weight is three, okay, after this three and four, three four is already connected, so this becomes our minimum three, its weight, I got MST weight, MSG weight, so it will be fixed, yes, chemistry weight. If you look at how much, it is 2 3 4 7 2 3 5 2 7. Okay, I have come to know that Chemistry is 7. Even the word 'Maast' is clear, word 'Maast' is clear, word 'Maast' is clear, I have figured it out. Okay, so look, till now I have learned only that thing which is I have mentioned in the question what I did. I had said in the question that brother, first of all, take out the chemistry, then I have taken out the M.Sc weight, I have taken out the M.Sc weight, I have taken out the M.Sc weight, after that remember what I had said that I have taken out the chemistry weight, after that I will take one by one. I used to go to the next one and check that brother, are you critical or is this video critical, then every one is critical, I will go to the next one and find out, okay, so now we are going to do the same, so I am writing step by step. Here we will follow all the same, see what we did in the first step, push the original index, also okay, remember we did it, after that we sorted it based on weight, we also did it, why did we shorten it because we need to know about Krish. Had to plant a garden, okay, after that yesterday, what did we do after planting a garden, took out the weight of MSG, crushed it yesterday, applied algo, this is mine, we have done three steps, it is okay now, after 3:00 set, is okay now, after 3:00 set, is okay now, after 3:00 set, what did I tell you that I will do it every day? I will go to the next one and ask, brother, are you critical, this video is critical and how will it happen, I will tell you right now. Okay, so look here, we have reached this step, MSC weight has been calculated, we have the age tax list now. One by one we will go to everyone and ask, brother, are you critical, this video is critical, so first I came to this person, okay, I came to this person, see, what is his U, so this is his, what are they, this is this. Meaning, it is next between zero and one, okay and what is its weight, let me also write the weight, I am its one and look at its original index i.e. ID It look at its original index i.e. ID It is here, right? It is here, if it is critical, then I will put the original index. Okay, it is clear till now, it is good, so let's check whether it is the original index or not, then it means it is critical. Otherwise, first let's check the critical. So remember what I said? It was said in the question that 'Critical', what does it mean that 'Critical', what does it mean that 'Critical', what does it mean that if it is removed, if I make Masti without making it a thing, then the weight of Masti will be bigger than my original MSG? Meaning, it will not actually be MSG. Without it cannot become the minimum penalty. Okay, so what will I do. Okay, I will tell Bina that brother, Chris, if you go ahead without this, show me the weight, then what will I do. I will do the classical tomorrow. I will say sorry, please find out the weight and show me the weight, this one without rectangle is next, meaning you skip this one, I will tell you which one is next after skipping the one with rectangle, then find out the weight and show me the weight. It will come ok, I will name it, skip weight, ok weight, I have taken out my skip weight, okay if it is greater den, my MSG weight is taken out, MSD is the original weight, I had taken out but the bigger one has taken out the bigger one, my original was seven and let's take the mother. If I got 8 or 9 A then brother, that means you are very important ahead for me, I am saying that you are very important for me, which is fine, so it means you are critical, so what will I do, then there is a person named Critical. Hey, if we make it then what was the critical index, I will push the RDX, then I would like to check what it is, then how to check, I will also tell you, so see, I understand the critical index separately here, okay, I told you, see Sandeep. The meaning of detail was that whatever is on the story and even if it is not on the story, look here, even then the minimum weight is 7. It is here too, the minimum weight is 7, it is cool, look here, that is not further, we have done that. Still look at the weight of Mast, it is the same here also, he did not get this one ahead, still look at the weight of MSC, it is the same, isn't it where he is, it is the same, but still, what can I say, look, when he is ahead here. But if he is ahead here, he is still at 7th, there is no change, don't increase the weight of M.Sc., the weight of M.Sc. increase the weight of M.Sc., the weight of M.Sc. increase the weight of M.Sc., the weight of M.Sc. is exactly the same, okay, so what should I do, I will tell Crush tomorrow, not brother, you will tell this Ahead. Try including it once and see, if even after including, MSC's weight intake remains the same, that means it is absolutely critical. Okay, look, I repeat here again, we have to check the studio critical that when MSC contains a lot of stones, you are great. MSC 4, then it will be in some future, it will not be in some, it will not matter, the weight will always be the same as the intake of Mast, intake will come in every way, it is okay, then I will say, brother, why are you including this further and see if the weight comes the same. Which means it is pseudo critical, means it is critical if this if because if it was critical, then I would find out here in the scales, it would lie here only, if it were critical, it would lie here only. It goes but if it is not critical then I am checking whether the video is critical. See if it is not critical then only then I checked this video is critical. If it was critical then it is very important to have it, without it you will not be able to get MSC 7A. Okay, if it is not practical, I should check it is okay, I should check the video, so what happens in the video critical, that even if I put that or that, even if I put this, my minimum P entry's weight intake should still be met. I repeat again that if someone is critical in front, that means he must be in all the masts. Without him, I will not be able to get the chemistry, that means my weight will increase, so he is needed in all the MSCs, he is critical, he will be found here. Okay, so first of all we are checking whether he is critical or not. Okay, so for the mother who takes Chhotu, he is critical, for that also I must have gone to the condition here, I have checked that brother, if it is not included in the video. If removed or skipped means even if it is not included then my MSG weight, grid mast word, is equal to this, it is not bigger than this, okay then it must not have been critical, right, it must not have been critical. So remember, let's check by skipping here, otherwise in LCF, what will we check to see that if it is added, it means include date further, even if it is included, then also my The new weight that will come should be equal to my SP weight. It is okay because look, it must have been checked while skipping. We must have checked it after skipping. Even if he had not been in front, my messy weight would have come. Mast comes equal to the weight, so it comes equal, okay, so when I saw like mother takes this video of mine, which one was critical of mine first, the critical here was our two, right, this one is okay, this is my photo, it was critical, so first. I have checked whether it is critical or not because even after removing 2 3, I saw that 2 3 had been removed here, still remember my weight, don't look at it was only 7, here even after removing 2 3, If only seven came then it is not critical then what will we do in critical, once we add this further we will add it and say see brother, still 7 comes, are all these also seven only? If one is gone then Leave it is critical. Now I understand that this thing is very important. Understand it properly. If you have seen the weight intake after skipping, then it is not critical. It means that without it will be less. Okay, I saw it by skipping here. After adding it, you will see it, that is, you will tell Crashkaal that brother, Chris Jail, you have seen this ad by adding it, otherwise how will you call it the video? You will tell Crashkaal, brother, after editing it, see it and add it and even then the weight that should come should be equal. What is required is the actual MSG weight, then leave it will be critical, even if it is clear, then our fourth step is also clear to us, brother, what is there in the fourth step, it is okay further, what will we see first by skipping it, if we skip it and check it and brother. If after skipping my weight becomes more than the MSG weight, then brother, it is very important, I cannot skip it, okay, then it will be critical and if it is not critical, then let's see by adding it. So we will see after skipping and secondly we will see that if after skipping then its further weight which is the total sum weight would have been equal to that of MSCBT, then what will I do, I will see if it is Sudhu critical, then I will see the skip. If you have n't passed then we will add it and see if it is equal to MSCBT, it means whether it is there or not, we can still take it is the same certificate, so we will add it in this video critical, we will square the critical here, okay If it is clear till now, then this is the code of the tax step, it is fine and look at it, the code of Crystall is fine and the code of DSO because Crystal also has DSC, I will copy paste it in both the codes, it is fine from my original video as I have done earlier. I have read it, so if you look for the code in the playlist of graph concession questions, you will get it from there. For now, I will copy paste these two codes, but doing this step is very easy, right? We will do the fourth set, we will check each one, ok, we will skip the crash call once for each one, we will do it tomorrow, we will say brother, check it out and give me the weight, then add it once and make the connection again tomorrow, we will say brother, take out the weight and give it. Okay, so Krish Kar is being done very often yesterday, it is not there and the consent is less, so even if you do it again and again, there will be no time limit on one seat. Don't worry. Okay, so if I write the code according to the 4 sips, then let's see. Okay, so let's see, let's start its code and everything is good, this is a very big question, so I will break it down and solve it first. Okay, so first of all, what did I tell you that brother, first of all I will append the edge. I give it and it is the original index, which means sorry, I append the original index i < edge size i + + ok, whatever was adjusted, i < edge size i + + ok, whatever was adjusted, i < edge size i + + ok, whatever was adjusted, I have appended the original index in it, like aa i dot push underscore back original index, put it till clear. We had to do this thing because we would need the original index in the last place to send the result. After that what I said was that we will adjust the sort according to the weight in ascending order, then in which index is the weight in each next and this weight. Na zero one is in the third index, you are on the second index, okay, so I write the comparison here, I define the vector of internet i.e. whatever is the weight, whichever is smaller will i.e. whatever is the weight, whichever is smaller will i.e. whatever is the weight, whichever is smaller will come first, so I have shortened it. According to you weight in ascending order, this has also been my second step. The sorting one is less ok. After that what I said is that let's take out the best weight first. Okay, so what did I say. To whom will I do it tomorrow? I will do it tomorrow. I had said no, let's move ahead to the crash period. I will do the same to him tomorrow. I will say that brother, either skip this index or add the next one with this index. If you have to skip and add more, then in the crush tomorrow I will also send that which next index has to be skipped and what. If I want to add then this is the normal minimum MSC weight. I am taking out the normal minimum MSC weight here. If I want to add any further then I send normal Mins one and Mins one. Skip comes and gives it to me first. Two, this is my third step, okay, after this I am ready, brother, I will have a practical, Sudo Critical, okay, till now it is clear, after that, the last one, start processing it, Inta = 0 I < all the ones, one- I am processing one by one, all the ones, one- I am processing one by one, all the ones, one- I am processing one by one, okay, so remember what I said first of all that brother, if you want to know that it is critical then first show it by skipping ahead, now you are processing ahead, I came here, you are processing this. Don't skip it and ask Crashcall, then who will you ask in the agency? Don't skip this one, the first one is the skip, it is fine and if you want to add, the ad guy is keeping mine as one because I am the one who is skipping. I am checking, okay two things, I will tell you one, which one has to be skipped and which one has to be added, so this is only the one to be skipped, I am asking him, I will tell him, brother, without this eye, I took out the MSC and checked, if the weight comes, it is my original MSG. Wait se bada a gaya means you could not skip this is critical ahead, okay so critical dot British underscore back, okay, which index will be mine, what was the original index, remember zero one, you saw the original index in the third, we pushed If I have given the original index, you will get it from here and do you remember what I did, this is my skipping ahead, this next, without taking this ahead, extracting the MSC. I said to whom, if the weight that came is bigger than the original. This means that I cannot skip further, all the MSG messages have to be there, it is okay and if it is not so, then it is okay without it, the MSG weight for further progress is not equal to my estimate, so I know what to do. That's why brother, do n't you come and add it, then skip the one, then I will send you the mines. To add it means to add this one and if the MSC that comes from it, if it is equal to my original masti weight, then it is okay, what does it mean that this It may or may not remain in some MSG. Even then, look at my MSG weight, it will not change. Okay, by skipping, you will get to know here. Add it this time and tell me, I have crushed since yesterday, it is fine, meaning force add this and this. See what happens, the weight is still equal, meaning this is pseudo critical, if it was not critical, then this video is critical, dot push underscore bag, okay edge of which is this is the index, which is the original, which is the higher third. It is clear till now and in the last what we have to do is send both Critical and Pseudo Critical. Okay, so here we have sent Critical and we have sent PSuedo Critical. Okay, it is clear till now. Now look, we don't have to do anything, just send us the code of Crisal. I have to paste everything else, I have written the entire structure, so we are done, we just have to copy and paste the code of the crystal above, so now I press and take out the code and copy paste it, okay, so I went here, see my graph. I went to Rapun here, okay, so what do I do? I take out this code here, I just copied it here, okay and here I paste it, okay, pay attention to what I said here, now I will crash. I changed it a bit, I pressed it yesterday, what I am saying is that brother, you can also take the one with skip as to whom to skip and whom to add, take that too and remove it on the basis of that, you are fine, it is clear till now. Now look, I am also sending the index in science, not which education skip is to be added, so here I cannot directly traverse like this, in which I will travel like this Okay, if I = I will hit skip, okay whatever comes. Now remember, if the skip person had not done anything then I would have sent mine one, otherwise how would it not have hit him, so I am saying that if someone wants to skip me then I will send it here and I will check that if If it is equal to the one that has come in the middle, then do not include it, continue here, okay, and now let's look at the ad, meaning, what happens brother, if my ad is next, if I have sent it to someone else, add the ad next to it, note equal, you Mines one means I have to take it, so what will I do in the beginning itself, whatever is next, I will add it to this, whatever I am trying to make an entry from me, I will add it to this, remember how I used to put it in the front, I did the union yesterday, okay back off, which one is next brother, the index of the one with add is okay, whose vertex is in zero and who has to do it to whom, union of both will have to be done, otherwise neither will connect. And the weight that I am calculating will have to be taken to this front. Sampras is equal you add sorry add, the weight of the next index was done brother, the weight was on the second index, okay so here we have already taken that weight. After that I will say, after that you do it, try to make your entry with minimum, okay now if you are doing science here from I index then you will have to remove time here, okay do it here only in different components. This is the union of Crustical, that's why I want to say, people, after watching the video, you will find this code very simple. It 's okay, but pay attention to one thing, during the 's okay, but pay attention to one thing, during the 's okay, but pay attention to one thing, during the crash, we used to paste the code of DSO also. Find the union of DCO in Right Crustical, it is of DSO only. But see, every time I have to do DSO tomorrow, once here DSO will happen tomorrow, then for every future, I am doing it tomorrow, and every time Crustical will do DSO tomorrow, then we create a class for DSO because if only one Whenever you write desi, remember that in DSO there was a parent and rank, so it should be different every time, so I reduce one by one, I am late in the class, okay, I paste the complete code of DSC and DSO in the class. Okay, it is clear till now, so what do I do, I create a class, look here, I have created the complete class of DCO of Union Find, I have written the constructor in it, written the code of Find of Union Find and written the code of Union, brother. Pasted it and did not do anything new, okay, you will get this code, it is okay in mine, and you will get it in the Criscle code also, look at the code of the press, look above it is the code of Union Bank, it is completely fine, but science, crush me tomorrow. So, what did I do all this so that means for the first time when you do criscale tomorrow, the parent and rank will change, there should be different DSO every time, so that's why I created a class, okay, so once here, press tomorrow. It will happen right here when I have done it tightly yesterday for the first time then I will create a new urine fine for it okay union find this is my class how many vertexes we have n vertex right here I have stored and let's just hint n right Okay, so what I did, I created an object of union find and with this object, the parent and rank of this object will change. You have dot union find uf.union find and here also off dot fine uf.union find and here also off dot fine uf.union find and here also off dot fine off. Dot fine is fine, it will be clear here, it is important that you understand this object thing, why did we have to create a separate class, because we will press tomorrow every time and not multiple times for every different scenario. Okay, so every time the parents will change, that's why what I did was that I created a separate class, then for this object created, the value of parent and rank will be different for it, then next time if I cancel again tomorrow, then there will be different parent truck for it, okay If it is cleared till now, then this is the complete code of my DSO. Sir, everything has been done till now. Let's run it and see. Let's pass the example. Till now, I have done everything but one thing is missing. Neither is this a field example, nor will it be known from this, I too had missed it. Don't worry about this. Now I saw that I want to tell you whether we have missed it. So look at this example which we failed because see we So everything has been done, only why it is failing, we have to find out. I have written this example, so I pushed the index, correct index and also sorted it according to weight, whatever had to be done, I did it and this In M.S. too, I took it out in the and this In M.S. too, I took it out in the and this In M.S. too, I took it out in the beginning, brother, the ideal chemistry weight should be 10. Okay, great. Now we are checking it all one by one and seeing the quantity and which video is critical. I do one less, I have looked at this further, once this is critical or sodo critical, then what will I say to check critical, I will say to skip this one, this index is fine, this one will say to skip this one. I will give it if it's okay, keep in mind that yes brother, when this thing gets big, I will skip it. Okay, I am trying to make MSG and trying to get weight. Zero one is okay, great, next is one, after that, zero, you are great. Next is one, after that 1 2 1 you are great. Next is one, after that 1 2 is already connected, so what is necessary, there is no need to do anything, one, you are already connected, if you will not union it, then this is done, after that, three is five, three is comma, five is connected. I am not able to see, look, if we have to connect, then we will put the union which will reduce that, I have written two here, reduce that, which will reduce that, I have written two here, this is also done, after this look, 4 and 5 are connected, this is 4 and 5 connected, okay, that's why we have to make this. It's definitely not okay, after that look, this one is here, 2 3, so it was asked to fit, remember, I skipped it will kill, okay, it's a good skip, now the total weight will also be calculated the whole time 1 + 1 2 4 2 6 It is done, isn't it ok? Now the 1 + 1 2 4 2 6 It is done, isn't it ok? Now the 1 + 1 2 4 2 6 It is done, isn't it ok? Now the weight that has been calculated is six, it is small, 6 < 10, all of them are known or is small, 6 < 10, all of them are known or is small, 6 < 10, all of them are known or not, MSG one has also been found or not, MSG has not been made, friend, look at this, it is disconnected, it should be connected, the vertexes should be connected. Okay, so this is not made of MSG, so we did not check this, no, we did not check this, remember what I just wanted to say, I am just you are the one who came to me, skip this one, tell me the weight, okay, skip this one. Please tell me the weight, if it is taken out give a grater, my original 10 is a little, then give a grater, 10 is a little, no, okay, then after that I go here, whether I have to do this or not, otherwise brother, go to critical hell first. Look at this message is not being made at all, it is not being made into an MSG, so how can I expect that the correct result that is coming is correct, first of all I have made it well and shown it, then what is the code of the crystal? Neither will I have to enter another check there which is my code of Crystal nor will I have to enter one more thing in it whether it has actually been created or not, meaning are all the notes connected or not? Look where it was connected but here it is not connected at all. Ok, so remember what MSC used to do. What MSC used to do was to connect all the vertices, it used to connect all the vertexes, they were connected, it was not like it was disconnected, okay, and it used to come out of the disjoint set union. Isn't it, how the connector used to do unions then it used to connect, okay so now when all the people are connected in one component then remember what used to happen in disjoints and unions that there was only one owner of the entire component, you. Mother takes this master, this is it, then if I ask, brother, who is your parent? Mother takes this is zero, you are three, if I ask four, then brother, who is your parent, he will say, my parents are zero. If I ask anyone, your parent's no, he will say, my parent is zero, who is your penis, my parents' is zero, your who is your penis, my parents' is zero, your who is your penis, my parents' is zero, your friend's no, my friend is zero, remember this is what used to happen in this joint set of urine, we parents, if there is a component, then it has a component. There was only one leader, right, so do you know what I will do, I will look at the simple look, I will do it within the crystal code, this is equal to you zero I < What will I ask him, brother, who is your parent, okay and after this no one And let's fix the parent of the second note, let's take the parent of zero, we will check every time, find zero, it's ok, and if it is not equal, then what will I do, I will find out, what will I do, I will say that this is brother Criskal, this MSC has not been made. Okay, I will return a very large value. I will return infinity. Okay, I will return an infinite value. Why did I return a very large value? It means it is valid, it is not mine, it means it is not valid for me, I have to skip this further. Shouldn't even have to think, ok till now it is clear so now see find I note equal you find zero reduces it, let's see it will reduce it here also look here I from zero see it here became two components, those fortunately two components. So every component has a different Malik, let's take the Malik of this compound is 5, the Malik of this component is zero, so I will ask the Malik of all from i = 0 to i < n, will ask the Malik of all from i = 0 to i < n, will ask the Malik of all from i = 0 to i < n, first I find i means zero is not zero. After that he asked note is equal, do you remember find out from zero, every time we were checking from 0, so friend of both is zero, it is good, now i = 1, i = 1, i = 1, okay brother, who is your pen, then he will say, my friend is zero, okay. If then find zero is also zero then the parent of both of them will remain zero when i = 4 then see what will happen. The remain zero when i = 4 then see what will happen. The remain zero when i = 4 then see what will happen. The parent of four by four is five because it is of the second component and find zero means that it has definitely been flooded in two components. It means that if there is no one component, then I will return infinity there, okay, we will pass and submit, this was very important and it failed when my example was found, otherwise I would not have caught it, I am fine. So what will I do, we will have to check whether the crust which I made yesterday is making it good or not, otherwise before summing the return, I will check here only forint i = 0 i < object find it ok So, I am returning international because I am sending Infinity, it is okay, otherwise he will be critical in the future, I cannot become him without my brother, he has to put me in the future, okay, remember, what was our mistake, right here? But look, the critical M was not even being formed, so brother, it should be like this, isn't the check of even, okay, we will put the check of even, but it also has to be seen, brother, what to do without it, anyway, it could not be formed. Then brother, if you don't add dal then I will make it international that brother, if you look at it then just add it, then give this grater in the brick, MSG will be the weight, I will take it as critical, it is good, till now I have understood it, okay, now look, you will say brother. Why are you doing find from zero, so brother, choose anyone, I am late by finding n - 1, brother, choose anyone, I am late by finding n - 1, brother, choose anyone, I am late by finding n - 1, okay, what is the issue, I am just checking that everything should be from parent, okay then do more minus one. Or do zero, I just have to check that everyone is connected to their parents, what does it mean that everyone is connected to their parents, all the people are in the same component, what does mast mean, only one component has been created, not all of them are connected, okay now look. If you submit then all will pass and Time Compressor TV is very easy, here it will be I < N, let's TV is very easy, here it will be I < N, let's TV is very easy, here it will be I < N, let's submit it, now time complexity is very easy, now I will tell you one by one in big lines, NDTV solves this question ok. Look, I have to tell you, do n't look at the solution of lead code, it is very conjuring, okay, I did not like their solution at all, they have done a lot of extra things, our code is very simple because if our code is what it is, if the union spread crystal is left out then Look, there is only this much support, this much code is there, it's ok, it's very simple, it's good, you can check our time complexity, there is no problem here, why do you think people are shorting, it's just that the time is favorite here. Gya after that look, this is a time run, this is a loop inside it, we are doing chrysal tomorrow. Look inside chrysal, again a time is here, and here we are doing a fine urine tomorrow. Whose address is, time compressed O of alpha. It happens, you will know that in its bigger part, okay, α is time compressed, so see here what will happen to all this, A will become time α, okay and here there is already A, so A* okay and here there is already A, so A* okay and here there is already A, so A* A time will become alpha, time compressor is okay. You help you out, it is ok and please I am pretty sir, no one would have explained this example by coloring and correcting it like this, so I have to say patiently watch my video, you will get to learn a lot, any doubt there is a residential tree, you help you in the next video, thank you. You
|
Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree
|
pizza-with-3n-slices
|
Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.
Find _all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST)_. An MST edge whose deletion from the graph would cause the MST weight to increase is called a _critical edge_. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.
Note that you can return the indices of the edges in any order.
**Example 1:**
**Input:** n = 5, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,2\],\[0,3,2\],\[0,4,3\],\[3,4,3\],\[1,4,6\]\]
**Output:** \[\[0,1\],\[2,3,4,5\]\]
**Explanation:** The figure above describes the graph.
The following figure shows all the possible MSTs:
Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.
The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.
**Example 2:**
**Input:** n = 4, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,1\],\[0,3,1\]\]
**Output:** \[\[\],\[0,1,2,3\]\]
**Explanation:** We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.
**Constraints:**
* `2 <= n <= 100`
* `1 <= edges.length <= min(200, n * (n - 1) / 2)`
* `edges[i].length == 3`
* `0 <= ai < bi < n`
* `1 <= weighti <= 1000`
* All pairs `(ai, bi)` are **distinct**.
|
By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic Programming to solve it.
|
Array,Dynamic Programming,Greedy,Heap (Priority Queue)
|
Hard
| null |
5 |
hello friends my name is too sharp and today I am going to talk about how to find the longest palindromic substring in linear time using monikers algorithm so here you are given a string and you have to find the longest palindromic substring in this string so there are many palindromic substring in this string for example this or this with Center X so the question is to find the longest palindromic substring so the longest minute of substring here is this with Center is B and the length is nine so there are many algorithms to solve this in over n square time but today we are going to consider the many codes and guard them which solves it in off n time also for keeping the video simple I am only going to consider the order length palindromes but I will show later on how you without losing generality you can also solve it for even length palindrome so in the next section let's see how medicals algorithm works the first thing I do is take a check very array of the same size as my input array so then I start expanding around a so there is nothing to expand around a so the length of the longest palindrome with center a will be of 1 then we go to B again we are just dealing with the odd length palindromes so we don't have to look for the palindrome between a and B so we can directly jump to B and this is for simplicity purpose so we go to be the longest palindrome around central B will be of length 3 then we go to a the longest palindrome around a will be of length 1 then we go to X the longest palindrome around Center X will be 3 5 and then 7 so 7 at this point the question is what should be the next Center so we have already explored till this point so the question is what should be the next century can they say this X will be the next Center no if we do that we miss the palindrome around B which is the longest palindrome by the droving substring in this string so can we go to a and then go to B and then go to a and like Explorer on a and then Explorer on B and then explore around a we can do that but the problem is then it becomes a orphan for n square time algorithm and cannot be done in a linear time so how do we effectively pick the next Center so to pick the next entry the idea is that we should pick such a guys the next Center such that the palindrome around it expands till the right edge of the characters we have explored till not so palindrome around a expands just till a and doesn't go to the right edge which is 6 so this guy cannot be the next Center because about anybody room around a will be contained around this bigger palindrome so this will never give me a longest palindrome what about B the palindrome are on be at least expands till Lindemann on B is here so it at least expands to the right edge of the current Center which is this guy so B can be the next candidate and what about a again palindrome around a at least expands to the right edge of the current Center palindrome which is X so a also can be the next candidate but out of BN a V gives me the longest palindrome which is at least of length 3 while it gives me of length 1 so my next candidate will be B again why we work why this works is because if my palindrome around this Center expands at least to the right edge of the current palindrome the thing is there is a possibility that it can expand even more since it's not contained in the bigger palindrome which means that there is a possibility it can expand more if you look at B it here it expands to the right edge and then it can continue to expand more and probably might and can give me a bigger length palindrome which is why the next century will be B so now the question is how do we know that which Center has a palindrome which expands to the right edge and then we can go to a and see does the palindrome around a expand to the right of the palindrome water under X and then we go to B and then we go away but if you do that again this algorithm doesn't stay linear so what we do is we use information we have calculated till now so if you look at X we know that there is a palindrome from 0 to 6 so we know that this side should be the mirror of this side so we have already calculated what is the longest palindromes around on this sides 1 3 1 so what I can say is that the longest pendulum on the other side will at least be of these lengths so this a is a mirror of this edge so the longest palindrome here will at least be of length 1 the longest part number on B will at least be of length 3 the longest palindrome are on this a will at least be of length 1 now I have this information and so now I can make a call that which will be my next Center and that will be this guy because the palindrome are on this guy at least expands till the right edge of the current palindrome I have found so this is how B will be my next Center let's expand our own schedule B so we know that the palindrome under center B was at least of length 3 so there is no reason to look at these two guys that we start comparing directly from here and here so this is same then this is same and these guys are different so the palindrome around Center B will be of length 9 so at this point our question is what should be the next Center so let's see again so we go back here we copy this number here the saying that palliative or this will at least be of length 1 or more then we go here can you copy this 7 here and the answer is no why the palindrome around this X was of length the palindrome around this X was expanding from this point to this point and the palindrome around this B is expanding from this be - this be so the Pauline devor this be - this be so the Pauline devor this be - this be so the Pauline devor this X goes beyond the left edge of this car my current palindrome so I there is no guarantee that the pendulum on the other side will be of length seven so the island over on this other side will we know that will be till this edge and this point so the size will be five instead of seven also then we go to a and this will be of length one and then we go to be the same is for B the palindrome around this B was expanding from this to this and this is beyond the left edge of my current bedroom under B so I cannot say that the palindrome that this B will be of length three so this will be of length one so another question is who should I pick as my next century should I pick five as my next Center I'm in this X is my next Center and the answer is no there is no reason to pick this guy's the next central and let's understand why if they pick the reason I'm saying there is no reason to pick X as a neck center is because there is no way it will grow beyond the current set current length of Y why I mean you might say that the current length is five what if this cat true was a and what if there was another X and another B after this it's a valid point the point is if this cat arose in you would have already expanded under this center so only reason this gets talked here was because this character was not if we matched to this point and these two guys were different so we stopped here so only reason we stopped was because this guy was not a if this guy was a we would have continued explode under this central D and we were not stopped and the dynamics would be different the values would be different so since this is not a this is B then the reason we stopped and since this is B or any character which is not a there is no way Earth's parameter X will expand more this palindrome is totally contained under this so let's look at this guy here also has the same problem there is no way the only reason we stopped for this B was because this a was not this a and there is no way we can expand more in this direction because I mean there is no way this guy would be a and expand more here because if this was a we would have explored continue to explore and under this Center so since this is not a be stopped here to do so this is B so there is no way we'll have a palindrome bigger than this size so the next Center will be this guy which is B last B and the palindrome around in terms of length 1 so finally we just write rate through this input array and 9 will be our answer in the next section let's look at another bigger example and let's try to understand this concept again let's work through this example to clearly understand their manicures algorithm so we have four cases here case one is do not pick a character as a new center if the palindrome under it is totally contained under the current palindrome the case number two is a current palindrome expands all the way to the end of the input there is no reason to proceed and we should break out of the while loop case three is pick a character as a center if it expands all the way to the right edge and it's mirror palindrome expands all the way to the left edge basically it's a proper suffix of the current palindrome a proper prefix of the current palindrome and do not take a character as a new center if it expands all the way to the right edge but it's mirror padded room expands beyond the left edge basically it's not a proper prefix so let's apply all these four cases on this example so what it has I took a new array of the same size and again we are only going to deal with the odd length parent room for the purposes of centricity so we start with a the palindrome here is of length 1 we start with B the palindrome here is of length 3 then we go to a the palindrome here is of length 1 if we go to X so this is same and this is same so the palindrome here is of length 7 so at this point where we have to pick the new Center so we work backwards we go to this one and copy it here since the palindrome here is of length one for this a it will be totally contained under the current palindrome which is off which is going from this a to this a so this is a case number one so this guy will not be the new Center then you go to here and be Papa this guy here so palindrome this is now case three the palindrome with Center B expands all the way to the right edge and it's mirror expands all the way to the left edge it's a proper prefix of the current palindrome so B is our new center so we expand around B again we know that B at least has a palindrome of length 3 so we start comparing this X with this exit say it's safe and it's same and then they are different so the palindrome here is of length 9 so then we have to pick the next Center again we start working backwards from 9 so one copies here this is a case 1 there is no way this guy is totally contained under the current palindrome going from B to B this 7 so the palindrome at center X is from was from a to a so it was the pile in right-center X was going beyond the in right-center X was going beyond the in right-center X was going beyond the current palindrome so it's not a proper prefix so we hit a case 4 so X should not be the new Center so we will put the value 5 which is the maximum palindrome which is the maximum size pareto with the center X but this guy will not be the new Center as because it's a case number 4 so then we go here this is totally contained so it's a case number 1 then we go here again this B has a palindrome which is goes beyond the left center of the palindrome under center B so again this B should not be the new central but we'll just put the value here of 1 which is a total sense palindrome under central B so next center will be Y since none of the other guys match the criteria so we expand around why this is saying this is same so the length here is eleven three five seven nine eleven so again we work backwards so we copied this guy here this is case one so this is totally contained under this palindrome this is case one this guy five so palindrome with center X was here to here and our current palindrome is from here to here so parental minor sin 2x is a proper prefix of this guy so this guy here will go till all the way to the right edge and so this guy will be our new center because it's a case number three so this guy becomes over newscenter5 so when I go here I already know that there's a pattern tomb of length five so I start working I five factors are already taken care of sigh compare them they are same and they are same so seven and nine and now we hit the end of the input so we hit case number two so that's it we'll stop processing at this point because all the valid rules are after this will be a smaller size so at this point we just i traits which is very fine for the maximum number which is 11 so the palindrome under center y will be of length 11 and that'll be the longest palindromic substring for this string the run time complexity will be two of em so basically oh and in the next section let's see how do we deal with the even length palindromes so let's see how we will deal with the even length palindrome so here the maximum length palindrome will be of length four and the center is between this two is so I got this technique from the leet code which and it makes coding really easy so what we do is we take a new input array of size 2 n plus 1 so this is 11 and what we do is we put a special Sentinel characters between all the these characters so let's say dollar was that character so we say dollar a dollar B dollar a dollar the dollar B and then dollar so now all we have to do is apply our regular algorithm which we just discussed before on this input string and then that will give you the longest palindrome and then once you get the longest palindrome all if you have to do is divide it by two so in this case the longest palindrome will be from here to here and it's length will be three five seven nine once you get this value all you do is divide it by 2 and get 4 which is the length of the longest palindrome from V to V so again this doesn't affect the runtime complexity because we are still dealing in and so even with this there are time complexity will be O of n so this is all I have to talk about man occurs algorithm today I would ask my viewers to LIKE this video share this video comment on this video check out my github link and also like my Facebook page the code is in the description section of this video the link to the code is in the description section of this video alright thanks again for watching this video
|
Longest Palindromic Substring
|
longest-palindromic-substring
|
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`.
**Example 1:**
**Input:** s = "babad "
**Output:** "bab "
**Explanation:** "aba " is also a valid answer.
**Example 2:**
**Input:** s = "cbbd "
**Output:** "bb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consist of only digits and English letters.
|
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint:
If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
|
String,Dynamic Programming
|
Medium
|
214,266,336,516,647
|
65 |
all right hello everybody um this is another uh lit go hard even though it's hard it's just the multiple test cases that you need to go through that is just annoying right so if we all done mumbo jumbo here uh we can just decide how to track a couple of things uh we need to understand if the number uh or if what we're evaluating is a space signal a number a decimal an exponential um and if we create three or four flags for it we should be good uh for the space um it's fairly simple we just make sure that we trim down the spaces uh from the beginning at the end and we go from there uh with that being said let's try to do this in less than five minutes all right so as we said we're going to create a couple of uh um what we call flags um and one for the signal one for the number one for the decimal and one for the exponential right and um this is going to be as always in this particular case when you're evaluating something it's a lot easier if you do with the with pointers we're going to use two pointers left and right uh just because we want to make sure that we track our spaces that are uh in the beginning and the end so fairly simple we just move our spaces um uh i mean our pointer is until we don't see a space anymore so oops new keyboard uh right so now it becomes trivial uh we make sure that we traverse our middle part of the string um and we're going to check so we're going to create a chart here so it makes it easier for us and if um c equals to um a signal would basically do something so if you think about it we have a couple of checks that we need to do the next check is basically if it's a decimal and then what else we need uh we need um well the numbers itself there's a you know if you don't want to use the characteristic kind of thing you can just uh greater than zero and that's when we see a number and then um we also need to check if it's an exponential there's a special case for it and else anything else meaning it's not valid so even if it's a space uh we already took care of it we can have spaces at the beginning and at n now we return number which is basically our flag for the number right so let's start with the signal uh if we already saw a signal or we saw a number uh that's a bad thing we return false otherwise we just you know flag it uh the signal and now for the uh decimal uh if uh we have an exponential we cannot have a decimal or if we already saw a decimal we don't uh allow this uh we just return false uh and then we you know we decide that this is gonna be true this particular flag and uh the signal we cannot have a signal anymore so we're gonna just say uh signal equals true um and then um a number um very straightforward oops true and exponential if exponential or different than number will return false we need a number before we do it exponentially goes true signal equals false at this point we can have another signal and number equals false and that's about it
|
Valid Number
|
valid-number
|
A **valid number** can be split up into these components (in order):
1. A **decimal number** or an **integer**.
2. (Optional) An `'e'` or `'E'`, followed by an **integer**.
A **decimal number** can be split up into these components (in order):
1. (Optional) A sign character (either `'+'` or `'-'`).
2. One of the following formats:
1. One or more digits, followed by a dot `'.'`.
2. One or more digits, followed by a dot `'.'`, followed by one or more digits.
3. A dot `'.'`, followed by one or more digits.
An **integer** can be split up into these components (in order):
1. (Optional) A sign character (either `'+'` or `'-'`).
2. One or more digits.
For example, all the following are valid numbers: `[ "2 ", "0089 ", "-0.1 ", "+3.14 ", "4. ", "-.9 ", "2e10 ", "-90E3 ", "3e+7 ", "+6e-1 ", "53.5e93 ", "-123.456e789 "]`, while the following are not valid numbers: `[ "abc ", "1a ", "1e ", "e3 ", "99e2.5 ", "--6 ", "-+3 ", "95a54e53 "]`.
Given a string `s`, return `true` _if_ `s` _is a **valid number**_.
**Example 1:**
**Input:** s = "0 "
**Output:** true
**Example 2:**
**Input:** s = "e "
**Output:** false
**Example 3:**
**Input:** s = ". "
**Output:** false
**Constraints:**
* `1 <= s.length <= 20`
* `s` consists of only English letters (both uppercase and lowercase), digits (`0-9`), plus `'+'`, minus `'-'`, or dot `'.'`.
| null |
String
|
Hard
|
8
|
3 |
hey everybody this is abel in this video we are going to solve a problem called longest substring without repeating character this is third problem in the lead code so in this question what we have to do we have to return the length of the longest substring without repeating characters so here we have a string abc bb in this one as you can see a b c is the longest unique substring possible with unique characters and the length is three here we have b so in this case one is the output because that's the only unique substring right here in this case p w k e w in this case you can see w k e as the maximum length of the substring without repeating characters right so in this case we have to return three so yeah that's it this is our problem so okay so now let's see how we are going to solve this problem so this is our string a b c b this was our string so here we are going to use sliding window method in which we will set two pointer which is initially set to the head not head at the zeroth index character this is the right and this is left right is the right boundary of the window and left is the left boundary of the window and character between these two boundaries is going to be our sub array with the maximum length without repeating correct attack furniture and characters among these two boundaries left and right boundary is going to be our sub array with the maximum length and without repeating characters right so uh we are also going to use set in this one so here we have an empty set and what we do here is our pointer at a now is a exist in our set no it doesn't because it is empty so we will add this to our set now write is shifted now here is the right is b exist in our set no it doesn't so we will add v and now again r is shifted to c this is the position of r so let's remove these okay now uh it is at c exists in our set node then so we will add c now as we shift our point to the right side here we have got a so a already exist in our array so till here till c is our first window this is our first window as you can see the right extreme is this right and left extreme is left so this is our we got our first window and here in the set we will store the size of the set which is going to be probably our maximum length right so this is unique and the length our size is three so here we got our first set now what we do here is our pointer at r right now set already contains a so what we do we will remove a so we have b c and a here so we'll add a so this is our new set and at the same time what we do here is the position of the right one and this will be now the position of the left one so right and left is both incremented so now here this is our second formed window which is going for from b then c then a so this is and the size is 3 which is also could be our possibly longest substring without repeating character so this is how we check for all possible sub arrays and keeps track on the maximum length of the sub array formed so this was our algorithm this is a simple sliding window method now let's see the code implementation for this one okay so here is our problem now here we will create a two variable which is end left which is the left boundary and then end right which is the right boundary of the window now here we have a max which will keeps track on the maximum size of the set now we will create our hash set of character right we will call it set as new hash set okay now while right is less than length of our string which is s dot length now what we do we check that if the character already exist in our set or not if set doesn't contains that character as dot jar at right so what we do we ask.jar at so what we do we ask.jar at so what we do we ask.jar at right if it doesn't contains in the set then we will add it set dot add start jar at right okay now else that means it is already in our set so what we do we will remove that character set dot remove it doesn't actually remove that character we remove the character at index left so set dot remove as dot char at left okay one more thing here and we will shift the pointer to the right side that is right boundary to the right side and at the same time we will have the size we have we'll have the maximum size of the set so max is going to be the math dot max and uh here we have either size that is set dot size and the max itself this will give us the maximum length of the our set right here now as you can see else part we have we removed the character at the left index now we will shift the left index left will be incremented and we are done now let's return max okay now let's submit our code okay so as you can see our solution is accepted so that's it for this video if you enjoyed the video hit the like button and hit dislike if you didn't also subscribe to the channel for more coding tv problems see you in the next video
|
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
|
39 |
Hello Guys Today We Are Going To Discuss The Problem Combination 14 Problems Galvanized Were Given In Araria Distic In Teachers Someshwar Dasham Distic Share And Attempted To Get Some Water Sports Doing Security Combination Candidate Sach The Number Subscribe Like To Create Different Combinations And Numbers With A target and have written by which way they can make its elements and Thursday user name numbers multiple times due to be easy that our solution so let's check the other conditioner given to be given all elements and district of ke and listen to masturbate with No example for it's a given it's 8060 request to make sure also amazing time 233 loot competition and 1000 combination the amazing 2358 start 84121 time to time 3153 loot scan ho hello how can solve this problem solving can solve this problem by like f-18 Element which can check this way can f-18 Element which can check this way can f-18 Element which can check this way can include in power solution set and they can not include in her first topic and introducing the current element in two of that at and other Sukum Twilight we exploded element and let's input and the elements Arvind yes okay so in This way can proceed like it say it directly example2 Bengaluru two three four next video incident half hour to the open definition of 128 10900 its update show after intruding from a plate Into two times they go for three low okay so in this way they can find one to three animal solution so basically what were going to for each element there 20% so after which can include element there 20% so after which can include element there 20% so after which can include introvert and here diagonal exported from if set okay sleep indies tour Web vital to generate a solution set by distance including element and starting element and the where going to like with and not a solution and will lead the candidates who looks so let's implementation of has so let's status size upper as limit two the candidate Dots main length ki aankhen and tak agla reference a list 120 rates ke par equal to the mewar east aapke hai ajay ko the benefits of and tap app the candidate nickel ghanta tap and candy rates a lot and equal to zero phone Fight Date Secondary School Chauhal Net's Investment Simply Itanagar Answer Are Near Ghatak Dal Janta Candidate And Let's List That They Teacher Takes Care Of Current Candidate Elements In On Do Ajay Ko That Job Solid Using Back Track Number At Se Create A Function Shaniwar Track Shroff VS Start Including Element From Zero This Also Let Se Were Given And Candidates Were Trend Sure Index And Targeted Required And As A Result Almost To The God Will Return And Sir Are So Let's Implement This Function On Do That I Track Silent The kid snacks and preeta edison that intergate is that candidate within the test 98100 vinod eight me to 8 that candidates to our solution seth shuaib target nickel 2051 will simply bed rest for is a product of a new read must be the candidate and simply return if he This Year 2012 Light Bill Check If With The Current Number Included In The Due To Get Required Greater Than The Number Per Current Tax Act Will Tree To Get A K Gum Side Effects Andar That VHP Loss Against VHP The Way Kal Considered For All Elements Saha And steel and target is not 0 Vinod add is not going to be the answer to a difficult does not length simply turn off Baroda Vinod this is not going to be our answer that today is Navami that according to you this relation is exactly the birth of target Ghee Add country the candidate dot noida that namaskar defects and e capsule equal for solving are bhayo singh se mili vent on follow up decide a target - no side follow up decide a target - no side follow up decide a target - no side effects on that and the candidate after discovery what we can simply date element and back youtu.be mode date element and back youtu.be mode date element and back youtu.be mode Content Size - Slaughter Size - Slaughter Size - Slaughter That Choudhary Like Behave This Printed Particular Element Nau Have To Consider Tak Swara Also One Slot Element So Let's Go Into Works Like Prevent Tax Lotus Element 9 That Party President Plus One Ko Un Target And Candidates Are So In This Way They can proceed late message solution 136 giving life and not one candidate you were the candidates ki himesh world tamil se kat diya hai ke rate mein kar diya ok divine and sorry answer dot you relate candidate aap jhal can not find symbol solved ho to pocket this time Track hai flash lights ee hai or click on choti rani show let's meet on ki choti thappad show hope you enjoy this video they tracking and like inclusion and explosion should thank you for watching my video like that and remaining problems competition-2012 and subscribe my channel competition-2012 and subscribe my channel competition-2012 and subscribe my channel thank you
|
Combination Sum
|
combination-sum
|
Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**.
The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input.
**Example 1:**
**Input:** candidates = \[2,3,6,7\], target = 7
**Output:** \[\[2,2,3\],\[7\]\]
**Explanation:**
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
**Example 2:**
**Input:** candidates = \[2,3,5\], target = 8
**Output:** \[\[2,2,2,2\],\[2,3,3\],\[3,5\]\]
**Example 3:**
**Input:** candidates = \[2\], target = 1
**Output:** \[\]
**Constraints:**
* `1 <= candidates.length <= 30`
* `2 <= candidates[i] <= 40`
* All elements of `candidates` are **distinct**.
* `1 <= target <= 40`
| null |
Array,Backtracking
|
Medium
|
17,40,77,216,254,377
|
1,880 |
Hello guys suggestion or hour song this question of list to deepen this thing words equal submission of two but this big question that we will explain and in this we have to do that first second third which is first world in all of these that we convert in the interior If we use this for , convert in the interior If we use this for , convert in the interior If we use this for , then immediately and then after converting and after determining the first and second, we put the condition that the option of both of them is equal to its coast or the example of the first one which is 2012 then enter If we do, then I have already written a little bit about the logic questions to catch it. I have this life that the value of one is zero, it is okay that the value of your wife is also the first one is 110 and so on. Okay, set it till the elephant is done, now we will have to leave it aside that the daily question is not meant to be moved, it will have to be stored somewhere, okay son, you can use it as little as possible from WhatsApp on the left side. We will say that it is okay to use I, use Na, okay, I will be in this set of my character, wait for the side, his name is M, okay, Ne was a poor bat, intent 520, okay, so what to do now, we store. What has to be done is to make Venus planet character On the side, on the left side, there is the character, on the right side, on the left side, ABCD will go, its body will have to be changed here, subscribe to see what will happen, then this is that 2016, then once again this one will end, so we will have this Means Ghr ko ok Jatin we will take sleeves three big so posts 204 back part 06 posts in it ok we will take out a rally to convert first and second their target is to melt so let us convert to run separately To do we would do you mean that's okay and then we will talk about these total parking next word come okay that's done for the first one that it's done for the first similarly what will we do for three then this Start drinking, collect your clothes quickly, it will not take much effort, it is a paste, let's paste it on you, okay, so here we have to make changes, we have to make it a second, we will make it a second and if you want to click on it, then do it sometime. This also has to be clicked. Sir, target word has to be given, Tiger has to be made a little like him, it is ok, it is like that, this is ours, changes have been made, basic education has changed the system, it has been considered as something strange here, we have made a mistake in our liver also. If you keep it and removed it, then what to do now it has gone so far friends, so do this number, convert the salt, it means you have converted the trick which was in it is fine in your balance, now you have to telescope, a little plus. Here we will make a big attack fast chat and set a plus now also why plus b because we need only edition of first and second so what do we have to do now we have to check a condition this pimple like means target is that ok so I What will we do, return for that, okay, and what will we do, return for that, okay, this is done, in our cold play map, we left something out and took their value, meaning the character, its aa karrespondingly interior value, okay, and then we See what has been converted to this, convert our words have come to convert our string to, festival operation has been done, sp and check it is equal to this or not, is it ok, quick testing version status, first Alia Bhatt true is. Okay, copy photo, copy paste, homicide, torch light will start coming, copy again, we had copied the best of the last one, see the paste of CBD Couple Dear, set the paste, turn it on, okay and we will receive the evening on Zee Plus, the name of my program is Hello Dash. CP is compiled and okay, you will get this code in the description, okay, you can copy and paste it directly, okay, this will be the most patient, okay, and if we compile this, we have to run it, now write this and tap Okay and what is person two, my alarm needs you too, now let's make friends, we have to do it here and the post in the second one is the same but leave it there, let's do it in the target and post it in the target that the traders are just fine, try. You do this, you run the office, you have done wonders, I am yours, the complete code will be found in the description, okay, don't do it, you need a year 2004, okay, the code was here, it had this in it, you just had to think about the meaning. How to do this thing, we can use fly also but it will be a little difficult and if it is 131 then you can subscribe, so this is the answer to our question, if it is ok then do some work, please like and share the video also. Please do subscribe the channel. Thank you.
|
Check if Word Equals Summation of Two Words
|
largest-merge-of-two-strings
|
The **letter value** of a letter is its position in the alphabet **starting from 0** (i.e. `'a' -> 0`, `'b' -> 1`, `'c' -> 2`, etc.).
The **numerical value** of some string of lowercase English letters `s` is the **concatenation** of the **letter values** of each letter in `s`, which is then **converted** into an integer.
* For example, if `s = "acb "`, we concatenate each letter's letter value, resulting in `"021 "`. After converting it, we get `21`.
You are given three strings `firstWord`, `secondWord`, and `targetWord`, each consisting of lowercase English letters `'a'` through `'j'` **inclusive**.
Return `true` _if the **summation** of the **numerical values** of_ `firstWord` _and_ `secondWord` _equals the **numerical value** of_ `targetWord`_, or_ `false` _otherwise._
**Example 1:**
**Input:** firstWord = "acb ", secondWord = "cba ", targetWord = "cdb "
**Output:** true
**Explanation:**
The numerical value of firstWord is "acb " -> "021 " -> 21.
The numerical value of secondWord is "cba " -> "210 " -> 210.
The numerical value of targetWord is "cdb " -> "231 " -> 231.
We return true because 21 + 210 == 231.
**Example 2:**
**Input:** firstWord = "aaa ", secondWord = "a ", targetWord = "aab "
**Output:** false
**Explanation:**
The numerical value of firstWord is "aaa " -> "000 " -> 0.
The numerical value of secondWord is "a " -> "0 " -> 0.
The numerical value of targetWord is "aab " -> "001 " -> 1.
We return false because 0 + 0 != 1.
**Example 3:**
**Input:** firstWord = "aaa ", secondWord = "a ", targetWord = "aaaa "
**Output:** true
**Explanation:**
The numerical value of firstWord is "aaa " -> "000 " -> 0.
The numerical value of secondWord is "a " -> "0 " -> 0.
The numerical value of targetWord is "aaaa " -> "0000 " -> 0.
We return true because 0 + 0 == 0.
**Constraints:**
* `1 <= firstWord.length,` `secondWord.length,` `targetWord.length <= 8`
* `firstWord`, `secondWord`, and `targetWord` consist of lowercase English letters from `'a'` to `'j'` **inclusive**.
|
Build the result character by character. At each step, you choose a character from one of the two strings. If the next character of the first string is larger than that of the second string, or vice versa, it's optimal to use the larger one. If both are equal, think of a criteria that lets you decide which string to consume the next character from. You should choose the next character from the larger string.
|
Two Pointers,String,Greedy
|
Medium
| null |
1,011 |
Hello friends today I'm going to solve liquid problem number one or eleven capacity to ship packages with d-days so capacity to ship packages with d-days so capacity to ship packages with d-days so in this problem we are given an area of Weights where each Elementary presents the weight of package at that index and we are also given an integer value days where this represent the number of days in which we have to ship all the packages and also we are given few constraints the number one constraint is that yeah that I already say that we have to ship all the packages in these number of days and the second constraint is that we can only shape the package in the order it's given so we cannot ship the package to along with packaged eight or package one along with package 10. we can only ship package one two three together or four five six and so on so now we need to find the minimum capacity of the shape where we could ship all these packages in these many days so now let's see how we could solve this problem let's look at this example here so um so our intuition would be that we have these many packages with these widths right and what's the maximum width 10 is the maximum weight so since chain is the maximum weight of a package which means that the ship should be able to carry this package which is of size 10 right the ship should also be able to carry the package which is of size one but it should be able to carry the package which is of size 10 as well so um it should at least be able to carry the package of size 10 because if it is able to carry the size chain it would obviously be able to carry the size package of way to one okay so uh so this would be the least so far that we can assume now what could be the maximum weight well um the maximum weight if it were day one all of these packages must be shipped in one day right so that would be mean that all of these the sum of all of these packages should be the minimum capacity of the ship so what's the minimum what would be the sum would be okay we have 10 we have nine plus one that would be ten eight plus two seven plus three six plus four and the five will load one two three four five ten so the total rate would be equals to 55. so the capacity of the shape should be anywhere between 10 and 55 and we know that it won't be 55 because we have five days so um what could it actually be so basically what we are going to do is we are just going to take a middle value between these two uh capacity so um what is the middle value let's calculate it's 55 plus 10 would be 65 so 65 half of 65 is equals to we are just taking the rounded value so that would be 32 okay so we assume that 32 would be the minimum capacity um of the ship now what we do is we start from the first and we calculate until and unless we reach the um size weight total weight equals to 32 so we are going to add this value so 2 plus 1 is equals to three plus three would be 6 plus 4 would be ten then plus 5 would be 15 plus 6 would be 21 plus 728 and 28 plus 8 would be um 36 right so we stop right here so we need to ship all of these packages these many packages in one day now what are the remaining packages eight right so eight plus ten is still less than 32 that would be um 16 17 right and 17 plus 10 is equals to 27 so these uh can be shipped in one day so uh basically these weights with this minimum weight we can ship in only two days right but uh we are given five days so we need to utilize all these five days so now what are we going to do is uh we found a value 32 here and since the days are less than the days we are given the value that we found is less so we are going to shift our right pointer so now this becomes our um right end and this becomes our left hand so between these two we are going to um the maximum capacity can be 32 minimum can retained for the ship now we take the middle of these two values so what would be that 42 divided by 2 would be 21 so we take the value 21 and then we perform the same operation again with these weights so what we do we start from the first weight one we add then 1 plus 2 plus 3 that's 6 plus 4 is 10 plus 5 is 15 plus 6 is um 26 right so since 26 is greater than 21 so we now found our one um uh the total weights that we could ship in one day now next we can start calculation again and we do six plus seven is thirteen plus eight is twenty five so we stop right here and then we got the total amount we could ship in one day next is eight and then eight plus nine is equals to um 17 right and then 17 plus 1 is 27 so since 27 is greater we stop here record one more day and this would be zipped in one additional day so we got a total of four and four is still less than five which means that we could still ship our packages which would have the minimum weight least weight that would be between the range of 10 and 21. so what is the mid value of 10 and 21 we calculate the mid value so 10 and 21 would be um 31 by 2 that would be 15 right we take the rounded value so 15 and now we again perform the same evaluation okay so we start calculating one plus two three six ten and then 5 15 and 5 plus 1 6 would be greater than 15 so we found this value and then next 6 plus 7 is equals to um uh what is that six plus seven is equal to 13 right so we get the next day then eight plus nine is greater than fifteen so we just take this value for uh next day for and then 9 plus 10 is also greater than 15 right so this would be package with weight 9 will be shipped in one day and the remaining package of weight 10 would be shipped in the next day so how many days are there five days right so we got the five days and um the mid value is equals to 15 so this will be our final answer so now let's try to code our solution so we are going to perform a binary search so we will need left pointer and the right pointer and what's our left and right pointer left pointer is the maximum weight in this area and the right pointer was the total weight right we started from value 55 and then we moved on with its middle value right and then we finally got this value 15 so we are going to take the final we are going to get for the left and for right we are going to compute the values from our width Airway so left would be the max of the weight we have and the value of the left so the maximum weight and right would be the sum of all the weights now what we'll do is we'll compute we'll perform our binary operation left less than right and we will calculate our mid value that would be the floor value okay of left plus right divide by two and then we also need two more um variables okay all right so this current would represent the um the sum that we were calculating one plus two plus three and so on and the days needed would represent the days that would need to carry these mini weights with the minimum capacity of this much and in I have initialized it to one and now let's check so what are we doing we are looping over each of the values from the weights right after we have found our mid value so okay for Loop we are going to use the for Loop for light weight of weights so for each of the weight we calculate the current uh value that is we add the weight and if our weight is greater than our mid value that is when we know that we need an extra day so what are we going to do is we are going to increment our value for days needed by one and we are going to set the value of current to zero because um we are current means current in the code means these are the addition of these weights so we added all of these weights and these weights are the sum of these are the current value which would be uh which should be maximum of 15 and then next for next day we start from 0 right our weight should be six plus seven so the current should be set to zero so that we add the value 6 and 7 to 8 and it doesn't have any previous values stored in it so now we have these two values and then we check if the needed days is greater than days which means that we need to shift our we need uh more uh the ship must have a more capacity than what we have right now that is the meat so since we need more capacity we are going to shift towards the right and the lift would be meat plus one else uh else as we are just we are going to shift towards the left and that would be right equals to Mid and finally we are going to return the value of left uh that would be the minimum weight of the ship let's run our code and look at the results okay immediate days that's days needed okay something went wrong with my code let's check so left is Max of all the weights and right is the sum of all the bits all right so we perform a while loop we find our meat with cursor current value zero and days needed to okay so we actually set it to the weight w y w because um now we are evaluating okay because okay let me just give you an example here so far a capacity of 15 so what we do is we add one to two that's three plus three that's uh six plus four that is equals to ten plus five that would be 15 and then while we are at this index with 6 we add this value 6 and that 6 is greater that would be equals to 21 which is greater than 15 right so what we did is we added we already have initialized one so now initialized one for these days and day right so now what we did is we know that now to ship this weight we need at least one day so what we did is we added one to our needed days and then our current value now starts from this weight itself so that's why we are assigning the weight to our current value and then in the next iteration our weight becomes is the is pointing at this value and we add these to our current rate and then when it's Square then 15 we then know that we will need an extra day to compute uh to ship this weight so that is how we are actually performing eval making our code so now let's run our code okay let's submit it awesome so we have solved this problem using binary search so that would mean that the time complexity of this solution would be off and but based on but since we are using a for Loop and we are looping over each of the weight right so that would be off and so yeah our time complexity is n log of n and our space complexity is constant
|
Capacity To Ship Packages Within D Days
|
flip-binary-tree-to-match-preorder-traversal
|
A conveyor belt has packages that must be shipped from one port to another within `days` days.
The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capacity of the ship.
Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within `days` days.
**Example 1:**
**Input:** weights = \[1,2,3,4,5,6,7,8,9,10\], days = 5
**Output:** 15
**Explanation:** A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10
Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.
**Example 2:**
**Input:** weights = \[3,2,2,4,1,4\], days = 3
**Output:** 6
**Explanation:** A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
1st day: 3, 2
2nd day: 2, 4
3rd day: 1, 4
**Example 3:**
**Input:** weights = \[1,2,3,1,1\], days = 4
**Output:** 3
**Explanation:**
1st day: 1
2nd day: 2
3rd day: 3
4th day: 1, 1
**Constraints:**
* `1 <= days <= weights.length <= 5 * 104`
* `1 <= weights[i] <= 500`
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
| null |
1,769 |
hello everyone welcome to another video now in this video we are going to look at a very easy level question this is very easy level question but we will be looking at the optimized solution here and uh for the sake of uh the beginning right this is just the beginning we are starting with the medium level question so we'll we all will always we will also be looking at the easy approach that is the Brute Force approach and after that we will look into the optimize approach okay so let's get started with the question first and let's understand what the question is all about so basically um we are given a string let's say take let's take for example the first question uh the first problem that we are given that is 1 and 0. so this is the string that we have given we are given okay and uh one represents a ball and 0 represents empty space okay so what we have to do here is that we have to count for like how many steps it will take for each position such that all the poles uh all the balls available will be moved here okay so right now we have three conditions okay first condition we need to move all the balls to zeroth position next is all the balls to the first position and then the second position so how are you going to do that so this is the index let's say 0 1 and 2 okay so to move so right now at zeroth position we already have one ball okay and another ball we have is at first position to move the ball at first position to zeroth position we have to make a move of one position to the left okay so that's going to take like uh one position and all the balls are now uh so this will become like one like two zero okay all the balls are in the first position okay for the second one the same thing um we have already a ball at first like index one and we need to move the ball at index 0 to index one right so that is also going to take one okay and that's will this will look like zero to zero all the balls that are at middle index the next the last one is that we don't have any balls here okay so we'll have to move the remaining two balls at this position so the first index that's going to take one position okay and the ball at zeroth index that's going to take two position so first we'll draw from here and then from here to here okay so that's going to take like two so total will have to make three moves and this one three this is our final answer we need to return this okay now how are we going to follow with regards to the solution so the Brute Force approach that's going to be really simple so 1 0 okay we'll have like um it so we'll have like a nested Loop okay outer loop that will be I and then we'll have inner loop where it is J okay and we'll check like this is I this is J so first thing that we need to take care is that both the indexes should be different okay if I is equals to J that means it is already there uh the ball is already at that position so we don't we need to um you know do anything here so first thing first condition that we need to check is I not equals to J okay and the second condition that we need to check is that the ball uh the box boxes type J that should be equals to one okay that means it has that ball okay if that is the case that means we will move that position because if it is zero okay then we don't have to move anything from this box to here at the zero position only we have to move when we have one okay so this will be like um we'll add it to result our result array result I that is going to be will add not simply equals to because if you see here we are moving this also and this also okay so that is going to be 1 plus 2. okay what we'll add is that absolute value because we are not sure like whether I is going to be the ith index is going to be great or jth index is going to be great okay so absolute value of I minus J that means uh 1 0 okay this is 0 1 and 2 so absolute value of 2 minus 0 that is 2 and then we have to plus okay an absolute value of 2 minus 1 that is 1 so this will give us 3. so I almost the pseudo code is available here now if you want to start with the coding you can go ahead and continue with the coding try it yourself okay otherwise I'll code this okay and we'll look into it so let's get started with the code here so first thing that we require is our final result array okay let me yeah result is new and okay boxes Dot okay this is string that's why we need to write parenthesis as well now our nested Loop that will that is going to be first is our Outer Loop that will be boxes dot length okay and then we have our inner loop okay so that is going to be Chase Loop okay again Box start okay now we have to check the two conditions here if first was that I should not be equals to J and the second was that boxes at that particular index sorry at that particular index it should be one okay only in that case we'll have at index I plus equals what absolute value of I minus J okay let me move it here yeah bit better okay let me move it here only okay now it's better now the condition is done the loops are done we are completely ready with our result so let me return this and submit this okay so it's done but um as you can see this is a very bad algorithm because this is taking o n square of time okay because we are doing an estate Loop and like we are going through the loop in a nested manner okay so this is not very ideal one so let's jump into the Brute Force approach let me remove this okay we'll be needing this result so I'll keep that now The Brute Force approach I'm sorry the optimized approach so for this what we are going to do is that we are going to follow to pass two pass is nothing but we pass through the array twice as the name says but not in a nested manner okay so how this works um if you are aware of um if you have been preparing for interviews and everything you would have come across a problem called um product of array except self okay that is one of the classic examples of two pass okay so I would recommend that you look on that question after this so you try to solve that problem using this optimized solution that I am going to show you there will obviously be some minor tweaks on that solution but you can work around so how are we going to solve this so first since this is a string we are given okay since we have to travel from one box to another in case of um where there is one okay so we'll make sure to remember that how much we have traveled okay this is the first thing second thing that we require is that the number of ones that we have encountered okay so why I am saying that encounter because in the first pass we'll be remembering the number of ones that are left to that particular position so at this position we have zero once okay at this position we have one once okay at this position we have two nums uh two ones okay similarly uh this is the first pass okay at the second pass we will remember the number of ones that we have seen on the right side of that index okay so on the right side of this we have 0 on the right side of this we have again 0 and the right side of this we have one okay so this is how it's going to be but if you will see here um we have to not remember exactly the ones okay we have to take care of the position it has traveled okay because we need to move these positions okay we need to move this to this place this to this position okay so for that we will have to write an additional thing what it will be I will show you in the code okay so let's jump right away over there and uh let's get started with the code I hope this was easy for you to understand okay that's the main skeleton of the whole solution so first pass so yeah so first thing we need is that our two variables that is uh we are going to travel and we are going to remember the once okay so the first thing um we'll go through our boxes I okay so that's in the first pass we remember two things first is going to be our travel that is going to be plus equals to once okay how um let me show you here let me remove all this so 1 and 0. and let me first write the whole thing and then I will explain okay so now the next thing that we have is that we need to store this travel that we have done in our array like the result okay so what we'll do is result at I plus equals to travel and the last thing that we need to remember is that we need to check if our boxes dot character at I because that is equals to 1 then we need to increment our ones now how is this going to work so let's go through the first pass we have written the first pass okay so we'll go make a little walk through here so in the first pass what we are going to have this is going to be post once and the second position we are checking a result at ith index plus equals to travel and lastly we are checking um if one found in that case once plus so how is this going to work let's see here so let me write here travel and we have once okay and we have our result okay so right now this both of these are zero okay first condition travel plus equals one travel plus one that is zero okay second condition result at I plus equals to travel the resultant I this is 0 right now zero plus zero this is going to be 0. okay now did we find a one at this index yes so we'll increment this that's it our first uh loop is done okay like the first walk through in the loop in the first Loop is done okay and now let's go ahead again the first step uh travel plus equals once so travel zero plus one that is one so we have one here resulted index I plus equals to travel this is 0 right now zero plus equals to travel is one so this is going to be one similarly did we find one yes so we'll increment this once so this is going to be 2 now okay now again First Step travel plus equals one plus two that is going to be three result that I index I plus equals to travel this is 0 plus travel 3. okay if one is found did we find no this is going to be remain as it is okay so after this is this first pass we have this result okay so let me write it down over here somewhere um okay naughty let me write it down here first pass result that is going to be 0 1 and 3 okay now we are going to do the exact same thing in our second pass as well exactly same thing no difference even in the code you will see um only difference is going to be is that in the first pass we are going from left to right in the second pass we are going to go from right to left okay so this is going to be like I is equal to boxes that is a minus 1 I greater than equal to 0 I minus okay and I will simply copy this whole thing okay it's that simple and before this before submitting this if you will see here we have created this travel and once as outside the for Loop okay so the value that we have changed in these variables after the for Loop they are going to remain like that only okay the values that we have changed it is going to be changed value it will not be converted to zero so we need to change that to zero because again we are trying we are going for a fresh start okay we are looking for once to the right of that particular index okay so how is this going to work let's go walk through here let's do a walk through here um so this is going to be a result okay so again the same steps are going to repeat it but in the backward manner in the reverse order let me write it one and zero so travel and once both of them are zero right now travel plus equals once okay that's fine so this is going to be zero result at index I we are at the last index remember so this is going to be like this we are at the last index that is going to be plus equals to travel what is the last index in the first pass okay that is three plus zero that's going to be 3. okay did we find a one no it is zero so it's going to be remain 0. again travel plus ones um uh like once was zero plus zero that is going to be zero result at I this is going to be plus equals travel okay so this is going to be 0 plus 1 that is 1. okay now did we find a one yes so let's increment this travel is equals to plus equals once that is zero plus one that is one resulted index I that is going to be plus equals travel so result at index I is 0 plus equals travel is one zero plus one is one okay and now we have found a one so let's make it two it doesn't matter so our final answer is over here okay this is our final answer that's it uh it is really that simple it's you uh try it yourself you try to do a walk through on a different kind of examples by taking different um strings and all that okay and so you will understand it much better way okay um let me submit this foreign so as you can see from the extreme right side of our um extreme right side of our solution we have come to extreme left side of our solution so it's like if you'll see the solution that I submitted earlier we were here okay that was 466 Ms and now we are here like around 10 ms okay so yeah so this was the time complexity yeah so time complexity is going to be obigo of n for this optimized solution okay if we include constant that is going to be Big O of 2N because we are going through the loop twice okay big of n plus b go of n that is going to be big of 2N but since we ignore the constants we can say that it is Big O of n okay so I hope you understood This and like this video and learn something new okay and I would suggest that I would again suggest that you go and watch uh or you understand try to understand the question product except self okay that is really a good example to get started with this two pass uh problems or Solutions okay that is going to be helpful for a lot of things uh going forward okay so yeah I will see you in the next one till then keep coding
|
Minimum Number of Operations to Move All Balls to Each Box
|
get-maximum-in-generated-array
|
You have `n` boxes. You are given a binary string `boxes` of length `n`, where `boxes[i]` is `'0'` if the `ith` box is **empty**, and `'1'` if it contains **one** ball.
In one operation, you can move **one** ball from a box to an adjacent box. Box `i` is adjacent to box `j` if `abs(i - j) == 1`. Note that after doing so, there may be more than one ball in some boxes.
Return an array `answer` of size `n`, where `answer[i]` is the **minimum** number of operations needed to move all the balls to the `ith` box.
Each `answer[i]` is calculated considering the **initial** state of the boxes.
**Example 1:**
**Input:** boxes = "110 "
**Output:** \[1,1,3\]
**Explanation:** The answer for each box is as follows:
1) First box: you will have to move one ball from the second box to the first box in one operation.
2) Second box: you will have to move one ball from the first box to the second box in one operation.
3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation.
**Example 2:**
**Input:** boxes = "001011 "
**Output:** \[11,8,5,4,3,4\]
**Constraints:**
* `n == boxes.length`
* `1 <= n <= 2000`
* `boxes[i]` is either `'0'` or `'1'`.
|
Try generating the array. Make sure not to fall in the base case of 0.
|
Array,Dynamic Programming,Simulation
|
Easy
| null |
51 |
welcome everyone it's time to do another lead code problem today's problem is problem 51 in Queens so the problem says uh it's an n Queen puzzle so you are given a n into n uh chessboard where you have to play Queens in h row okay and if you're familiar with queens and if you're familiar with chess and how the queen moves in the chessboard you know that the Queens can move uh in the straight lines right or they can move diagonally in any direction so they can go this way and then they can go also this way right okay so uh the problem says that you are given an N into N Chess board and then you have to put the coins in each row one Queen at each row in such a way so that the Queens can't attack each another uh as you can see here so this is you here you can see a four into four Chase board you can see here and then if you look at this queen you can see that there is no Queen it can there is no other Queen it can attack if it goes in the straight line or if it goes diagonally there is no Queen to attack right okay so if you check the other queens here you also see the same thing so going in the direction or the diagonal Direction there is no queens to attack right okay so this is the solution to the problem where you are actually putting one Queen in each row where these Queens can not attack each other now the problem here is you are given this value n you have to create and this n into n chessboard and then you have to place the queens in a way so that they are can't attack each another and there might be multiple Solutions so for example both of these boards are like four into four boards and you can see there are like two solutions for that and we have to find out all kind of solution like all set of solution and this is how the output will look like so basically for the empty uh empty Spa cells we have to put dot and so this is like this will look like dot Q dot that's exactly what you see here that's the first row and the second row is going to be dot q and that's the second row here right so this is the solution for this board and this part is the solution for this board so we have to return all of this similarly in the second example you see the value of n is one that means we have just a board of one cell and if you place a queen that's the only solution right okay um now how do we solve this uh obviously we'll try to have a board and then we'll put to place the Queens here uh but I'm going to do is I'm not going to draw Queens so instead let's say I these are the Queens uh by the circles I mean the Queens so I would try to put Queen in each row and then so for the first row my target is my algorithm is I want to try a queen in uh any place in the first row a valid place and then depending on where I'm putting the queen I want to put a second Queen here so you can see I cannot put here these are either in straight lines or diagonals right I cannot put here but I can put here right so that's a valid place so I will keep on doing this row after row right after I put these two then I will find H another one for this third row now you can see I can I cannot put here right uh but I also cannot put here right but I can put here right so I will keep on doing this row by row but once I to find the valid Place uh for the next Queen to place I need to know if that is a valid place and for that validity we need to check if there is a if the new place is in the same column right so and or it's in the same diagonal or it's in the same negative anti-diagonal right uh so it's in the anti-diagonal right uh so it's in the anti-diagonal right uh so it's in the same diagonal and then if it's in the same anti- diagonal because diagonals same anti- diagonal because diagonals same anti- diagonal because diagonals can be this way or it can be this way right so we calling one of these as diagonals and the other one is anti- diagonals and the other one is anti- diagonals and the other one is anti- diagonal now if you carefully look at this getting the columns is easy right so we can have a hash map and we know that which column we are in if already we are in a column so we can keep a hash set for a column say we call this column set if we put a queen here we can just put uh one zero in the column set and next time if I try to put another queen in the same column set it will first check and then it will check already this column has been occupied so I cannot put a queen here but what about the diagonal ones what about the diagonal sets how do we keep track of that okay and what about the negative or anti- diagonal set so for that let's anti- diagonal set so for that let's anti- diagonal set so for that let's carefully notice uh let's try to find out how we can do that so if you see here we have these columns and the rows and the column values and the row values so if you have this like if you uh subtract the column from the row let's see what we find uh in the first case you will find zero here is zero there is zero right okay so this one 1 + 1 - 0 is 1 right okay so this one 1 + 1 - 0 is 1 right okay so this one 1 + 1 - 0 is 1 this one 2 -0 is 2 then 2 - 1 is 1 this one 2 -0 is 2 then 2 - 1 is 1 this one 2 -0 is 2 then 2 - 1 is 1 here 3 - 0 is 3 uh 3 - 1 is 2 3 - 2 is 1 here 3 - 0 is 3 uh 3 - 1 is 2 3 - 2 is 1 here 3 - 0 is 3 uh 3 - 1 is 2 3 - 2 is 1 so as you can see basically the diagonals will have the same value so if I do this basically the value that it will give me will identify the same diagonal right okay similarly if we look like this so let's get rid of this if I add this row values and column values let's see what we've get so if I add this row value and column value I get uh I get say 3 + 0 three here and then I get four say 3 + 0 three here and then I get four say 3 + 0 three here and then I get four here I get five here I get uh six here okay and then here I get five I get four I get three I get uh two here right here three also this one is three and this one is 3 + 1 4 so you can see that this one is 3 + 1 4 so you can see that this one is 3 + 1 4 so you can see that this one now matches the anti- diagonal one now matches the anti- diagonal one now matches the anti- diagonal pattern right so this one actually gives me the anti- diagonal right okay so how me the anti- diagonal right okay so how me the anti- diagonal right okay so how do we now do this uh so as we said our plan is to use an algorithm which places the Queens in each row and then uh immediately update all the information so that the next Queen uh next row knows what are the valid places for the Queens so put suppose something here immediately what we want to do is I want to put column one as occupied and then I will put like row minus column so this is row minus column row is zero column is uh minus column is one so diagonal set we'll put minus one that means minus one column is occupied and row plus column that is the anti diagonal so I say one is occupied okay next time in the second row if I try to put something here let's see what happens so this one says the column is two okay column two is not occupied yet that's fine column two is fine uh and then let's do this thing let's try to see like row minus column row is one column is 2 1 - 2 is minus one and the column is 2 1 - 2 is minus one and the column is 2 1 - 2 is minus one and the diagonal says Hey row minus column is 1 - 2 = -1 but you already see - 2 = -1 but you already see - 2 = -1 but you already see that minus one is occupied so this must be in the same diagonal so I cannot do this because this is already occupied okay so we keep track of the columns we keep track of the diagonal values we keep track of the anti- values we keep track of the anti- values we keep track of the anti- diagonal values and every time before I put a new Queen there I keep on checking so let's uh do this uh from the beginning okay so let's start from here uh so I start from here and then for every row I will try to place the queen in so this is 0 1 2 3 0 one 2 3 so this is the rows and this is the columns right okay so for each row first I will try to do row zero right for row zero I have four options so I can put the queen in uh zero position I can put it in one in two and in three right I can put these are the columns the column positions where I can put the queen okay so let's put it in position zero okay next so I have put in the position zero next I move to the next uh row and here also I have like four options okay so once I put it in zero immediately I have to uh update where which column and which diagonals have already been uh occupied right okay so let's do that uh so the column that is occupied is uh zeroth column diagonal set that is occupied is row minus column so it's row minus column right and this one is row plus column so row minus column row is zero and column is also zero so diagonal set is also zero anti- diagonal set is also zero anti- diagonal set is also zero anti- diagonal set is row plus column which is also zero okay next we again want to try from 1 2 3 4 first I will try zero so I will try this now you see that the column already actually collides with this with the column set so that means I cannot do this so this is now this option is gone right so I cannot do this uh next I try this one column one uh column one is fine one doesn't uh Collide here one doesn't Collide here that's fine but the thing is uh row is one and the column is also one so row minus column is zero right so 1 - 1 is zero and you can see right so 1 - 1 is zero and you can see right so 1 - 1 is zero and you can see here that this one is there is already zero here that means it collides right and you can see the Collision here right okay so I this is also ruled out that means I canot do this next I try this the second column is fine row minus column is 1 - 2 minus one fine row minus column is 1 - 2 minus one fine row minus column is 1 - 2 minus one is fine and row plus column is three so all of these are fine so that means column is two this is minus one this is three so all three are fine so that means this is a valid position I am fine with this right okay so next let's move to the next uh this one now goes to again zero one 2 three all options are here 0o obviously doesn't match you can it collides right uh so this is rolled out uh one as you can see the diagonal will match so if you subtract the column value from the uh row value or sorry if you add the column value and row value uh that's going to be three and you can see three is already here so this is also ruled out next this one column actually matches if you check here right if you check here these are the sets so it matches so I cannot do this one you can see the column doesn't match there is no column three here and then row minus column is minus one ah you see there is a mismatch here that means there's a mismatch right okay so I cannot do this so all these four options are exhausted I'm done so what do I do now next what I have to do is I have to backtrack so I was here in row three right I was in row three this was row two right so I backtrack to from here I backtrack to here so this is what backtracking is so I just backtrack here and after I backtrack here I actually as you can see we actually started from two right okay uh so that means this one didn't work so what I have to do is I have to delete this one didn't work we couldn't go forward so let's delete this so I have to delete all the information regarding this and then I try a new place that new place is you see that this one didn't work right so I deleted it all the information WR it let's try four yeah why don't you try four okay so from four again we try Okay so backtracking and then trying the next one say then we go to the next row we go again go to row to three and this one is now it's also starts trying from one zero uh let's see so zero doesn't work obviously you see this one works right zero doesn't work one works okay so uh the column is one uh okay so before this when we actually tried four worked so the column was three uh row minus column was min-2 and row plus row minus column was min-2 and row plus row minus column was min-2 and row plus column was uh four all of those are fine okay next if I try this one in row three this one uh the column is one row minus column is minus one it doesn't Collide and row plus column is three that also doesn't Collide that means this is valid obviously this is valid okay so I move to the next one uh so I move to the next one you see is one sorry zero 1 2 3 there are all four options we start from zero doesn't work one doesn't work uh column two doesn't work because the diagonal matches right row minus column is minus uh sorry one uh anti- column is minus uh sorry one uh anti- column is minus uh sorry one uh anti- diagonal actually okay so this one is row minus column is uh sorry previous one was one just one two this one 2 - 1 one was one just one two this one 2 - 1 one was one just one two this one 2 - 1 was 1 okay so this one is also 3 - 2 so was 1 okay so this one is also 3 - 2 so was 1 okay so this one is also 3 - 2 so 3 - 2 is also 3 - 2 is also 3 - 2 is also 1 it's one so it doesn't match so I cannot do this so you see I ruled out all three now the next one this one also doesn't match oh you see that this one also doesn't match this is also ruled out so what do I do well backtracking so I backtrack to this previous row so I backtrack to the previous row and now I know say okay this one didn't work okay so what do I do didn't work so what do I delete this I delete all the entries that came with it I delete all of this I try the next one two can I do that no I can canot right so this one is ruled out can I do this I cannot ruled out gone okay so next what do I backtrack again I back track again okay so this time you see that four I tell that look four didn't work Fork didn't work I went down for didn't work so I delete I had backt Tren here four didn't work and associated with all the values the diagonal anti- diagonals and column I diagonal anti- diagonals and column I diagonal anti- diagonals and column I everything delete everything okay then I backtrack to since this didn't I backtrack to the beginning now I tell this hey you see this one didn't work okay so everything failed from that Branch so I delete everything now I try again the next one I am trying is one right so I can actually keep on drawing again you know the same way 0 1 2 3 now let's see I'm not going to draw anymore it's going to be the same so I'm trying this 1 0 and 2 right okay and then next uh from this I move to the next row so this is the next row right okay this is nextow zero doesn't work one doesn't work this doesn't work but this does work okay so four three this one does work okay so for that I put column 3 uh minus 2 and four okay next I move here for this row I start from zero this works yes this works okay so this works fine I put column zero I put uh 2 - 1 and 2 + oh sorry 2 - 0 2 - 0 is 2 - 1 and 2 + oh sorry 2 - 0 2 - 0 is 2 - 1 and 2 + oh sorry 2 - 0 2 - 0 is 2 and 0 + 2 is 2 okay so I put this uh and 0 + 2 is 2 okay so I put this uh and 0 + 2 is 2 okay so I put this uh next I move this here um I can't put here I can put here you can see that you can put here now um so this one is going to be U two this is going to be uh 3 - 2 1 be U two this is going to be uh 3 - 2 1 be U two this is going to be uh 3 - 2 1 and 3 + 2 5 okay so next I move this and 3 + 2 5 okay so next I move this and 3 + 2 5 okay so next I move this here so now I have the in I am in the end row right so once I reach the end row that means I have completed putting Queens in everywhere that means I have got to a valid state right so I will save this uh State I will save this state and I will save this like saveing the answer right I'll save it in the answer okay so and now how do I get the other states similarly what I do is I just keep on backtracking so I backtracked here right so I delete this and I try this one doesn't work right okay so that means I have exhausted this so I will backtrack again and I will go here so I will delete this try this okay that one will eventually fail so okay so if I try this actually it doesn't work if I try this it doesn't work right I will also try this one also doesn't work so I backtrack again this one is exhausted you see that okay so I will backtrack again and then I will start from here and then keep on moving right then I will start coming down again okay so I will keep on doing this going forward and back so backtracking and then eventually I will get another solution because this is a four into four board and in the problem description you saw that we have like two solutions we already have found this one and then the next one we will get is here this one okay or did we get the other one okay yeah so next one is going to be this one this is going to lead us to another solution and that solution is also going to be saved so this is how we do the algorithm now how much what is the time complexity of this algorithm you'll get some idea a rough idea about the time complexity of this algorithm as you can see that for each row we have n of these rows right so for each point it actually expand this tree expands to N More so there if there are like n here in the second row for each of this like this n into n right okay then in the third row for each of these n squares there are n options so is n into n that comes from the previous one that okay and then there is an init for each of them there is also n more options right so I keep on doing this until the nth level right so it's n into n that comes from the previous one into for each of them there is n options okay so overall if there are like n levels n rows and you see that is in factorial obviously for each of them we don't explore everything right sometimes we just stop here you see we don't go further down here but overall in Big O perspective we can say this is order of n factorial this is the time complexity the space complexity well at a certain point we just keep this state that's the maximum right at any point I just keep memory of the current state and that's n into n that is n² so the space complexity is going to be order of n s okay uh so that is the algorithm I hope you understood it now let's go and check the code for this so here is the code as you can see our result is going to be uh list a big list of lists right so because there are multiple each list represents one solution and each list has uh n number of strings which because each string is going to represent one uh row so each string is going to represent one row the list of string is going to represent a solved board and we can have multiple solved board so we need another list of lists okay so there goes the result that we U result variable where we will uh save our all the states of different solved boards now this is the solve in Queen function they given only thing that is going to given is the dimension of the board and uh so what we're going to do is we need a hash set to keep track of which columns have been uh occupied so far which diagonals have been occupied so far and which anti- been occupied so far and which anti- been occupied so far and which anti- diagonals have been occupied so far and then we need to save the transitional state of the board initially we are going to fill up the board with all dots because initially everything is empty and then we'll keep on filling up different rows uh with valid queens and we'll also keep on saving the result uh in these result very uh list of lists and finally we'll return it okay so now let's see the main part how we keep on adding Queens to different rows right so this is uh the function the overr and solve Queen fun uh solvent Queen function so uh we have to know that like which row we are processing uh this is the set to keep track of which columns have so far been occupied this is the diagonal the same thing for the diagonals and uh this is a hash set to keep track of the anti- diagonals and keep track of the anti- diagonals and keep track of the anti- diagonals and this is the current state of the board so initially we are going to set send start with row zero and all these are like empty at the beginning and the current state is all with dots okay so next once we go inside uh first thing that we have to check is if the row has gone out of bound that means this is the board right so this is the size of the board the current board if my row reaches the length of the board that means the board index starts from Z up to length minus one so if it reaches this that means I have solved filled up the whole every Row in the board and I'm out of bound in that case I have solved the board in uh so what I have to do is I have to save the current state into a list right so the way we do it is we first declare a list and then we read uh if uh we read every Row from this current state right every Row from the current state we'll convert every row to one string and add that to the list okay so overall this solved this is going to be a list of n rows we where each row is solved okay and finally we add this solved board to a result to our result right so there might be multiple solved boards okay so to the results we keep on doing this uh if I my row count is goes beyond the size of the board that means the whole board has been solved otherwise what we do is we are actually in an intermediate phase trying to solve a row for that we start as I explained in the explanation we start from index zero and go all the way to the end of the board right to the last column for every column what we do is we first check if that column has already been occupied uh or if the current position that we are trying to do uh for that particular row and column current cell if that current cell is in a diagonal position with another cell that has already been occupied or if the current cell uh the row column cell is uh is somewhere which is already been occupied in an anti-diagonal set that is already in an anti-diagonal set that is already in an anti-diagonal set that is already been occupied if none of these are true that means that's a valid position this row column cell position is a valid position so first thing that we have to do is I have to set that cell to Q that's a valid position and then I have to add the information about that cell to all these three sets Okay I have to add the information and then I move on to the next row so I add increase the row by one and send all the current state right so I have changed the states here and pass everything in recursively to the for the next row once I'm done with this I have to backtrack right so the this is a backtrack portion for the backtrack portion I have to bring whatever I had changed back to the initial position right I explained uh in the drawing explanation so what I have to do is I have to set this again to do dot character and then remove all the U cell information that I had put from the column said diagonal set and enter diagonal set okay so I keep on doing this and so this way I try each column and for this particular row then this thing is solved uh and recursively I'm calling one after another so recursively I'm calling uh the next row until I reach the final row and go beyond and then I copy the result okay so if I keep on doing this ultimately this result variable is going to have the all the solved boards in it and finally I return the result that is the list of all solve boards so that's it thank you very much for watching we'll come back next time with another problem
|
N-Queens
|
n-queens
|
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.
Given an integer `n`, return _all distinct solutions to the **n-queens puzzle**_. You may return the answer in **any order**.
Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively.
**Example 1:**
**Input:** n = 4
**Output:** \[\[ ".Q.. ", "...Q ", "Q... ", "..Q. "\],\[ "..Q. ", "Q... ", "...Q ", ".Q.. "\]\]
**Explanation:** There exist two distinct solutions to the 4-queens puzzle as shown above
**Example 2:**
**Input:** n = 1
**Output:** \[\[ "Q "\]\]
**Constraints:**
* `1 <= n <= 9`
| null |
Array,Backtracking
|
Hard
|
52,1043
|
1,456 |
hey everyone welcome back today we are going to see problem number 1456 maximum number of vowels in a substring of given length first we will see the explanation of the problem statement then the logic and the code now let's dive into the solution so here I have the first example from the lake website so here we have an input string that is s and we need to find a substring which contains maximum number of vowels right we need to find the maximum number of vowels substring and that substring should be a length of K right so here we have 3 right as K so first I need to check the first three characters this is the length of 3 right that is K length so I need to check how many vowels it contains this is a substring a b c is a substring in a string so in this substring I have one vowel right so the vowels are a e i o u right these are my vowels So within this substring that is a right so I will increase my count as 1 right then I need to move the window I need to check in the substring I need to neglect a now I need to extend my window the reason why we are neglecting is we need to only have a length of K the substring we need to have only a length of K that is 3 in this case that is a constraint right so we need to find a situation or a substring where we have maximum number of vowels so now we will see how we are going to do this so initially I will be having two variables where I will keep track of the maximum vowel count in mb for keeping track of the current vowel count I will have CB so both will be initialized as 0 at this start so then I will write a for Loop where I will I trade through the input string right so initially I will be having I is equal to 0. see here I is represents the index value and C H will represents the current character so current characters a here so this is the index of a that is 0 and current character a right this is my first value that is the first character in my window then I need to check whether the current character that is a vowel or not so vowels are a e i o u so here a is a vowel so I will increase the current count as 1. then I will update my Max count by taking maximum between Max count itself that is MV and the current count so here's 0 and 1 so my Max count will be 1 now then I will pick the next character that is B and its index 1 right then it is not a vowel then I need to check whether it is a vowel or not so B is not a vowel right so I will just increase my window so now I will pick C and its index so then I need to check whether C is a vowel or not C is not a vowel right so then I can neglect I don't have to increase my current account so by the time I will be updating my Max count since we are not increasing our current count I'm just not showing that particular steps here right so here we will take maximum between the current Max count and current count which is nothing but one right both are one so maximum between them is one so my maximum count won't change here right so now I will increase my window size right so now I will pick the current character as I and its index 3. so now check the substring is more than the given length K there are four strings here right but we need to have only three so in this case I will write another condition where if my current index is greater than equal to K if it is greater than the substring length K and we need to neglect this character right that is a right we need to reduce the length here we need to make the window PC and I we need to throw the A out so now I will check if this character that is the character we are throwing out if it is a vowel we need to reduce the current count to access this character we need to take difference between I minus k right if we do I minus k we will get access to the character what we are throwing out of the window right so then we need to check if this character is a vowel or not a is a vowel right so since we are throwing out of the window we need to reduce our current to count by one so now our current count becomes zero right so we are still here only in the third index right so now I need to check the current character I is the vowel or not I is a vowel right so we need to increase the current account then we need to take maximum between current account and maximum count and we need to update the max count so in this case it's going to be 1 only right so then I need to increase my window size again we have four characters we need to throw B out right then I will pick the current character that is I right we are in the fourth index so our index will be 4 now since the length of the substring is greater than the given substring length that is 3 we need to throw B out of the window right so I need to check whether B is a vowel or not B is not a vowel so we don't have to decrease the current count of the vowel right we it will be one only then I need to check the current character that is this I it is a vowel right so we need to increase the current count by one so it's going to be 2 and we need to take maximum between Max count and current count so the maximum value is 2 so this 2 will be my Max count now right then again we need to begin this I that is the fifth index I that is the current character now right so now our pindo increases to 4 so we need to throw C out so since C is not a vowel we don't have to reduce our current count by one and we need to check the current character the fifth index I that is the vowel right so we need to increase current account by 3. so maximum between 2 and 3 is 3 so we need to update our Max count as 3. then I will pick the next character that is d then the index of D is 6. so now the window will be like this since the length of the window is more than the given length that is 3 right the given length is 3 but the current window size what we have is 4. so we need to throw I out so I is a vowel right so in this case we need to reduce the current count by one so it will become 2 now right then we need to check the current character whether it is a vowel or not so in this case D is not a vowel so we don't have to increase the current count value then we need to take maximum between 3 and 2 since Max count is maximum so we don't have to update our maximum count right then we pick the next character e and its index 7. so now the window becomes like this now we need to throw this eye out since that is also oval we need to decrease our current count by one then we need to check the current character whether it is a vowel or not yes it is a vowel right e is a bubble here so we need to increase our current count by 1. again we need to take maximum between these two since maximum count is more here we don't have to update then we need to pick the next character f and its index is 8 right so again we need to throw this eye out of the window since that particular eye is a verbal we need to reduce the current count by 1. then we need to check whether F was a vowel or not that is the current character it is not a vowel right so we don't have to do anything then we need to take maximum between 3 and 1 so the max count is 3 since the maximum count is more we don't have to update anything then finally we need to return maximum count that is 3 right that is the answer for this particular example so the time complexity will be order of N and space will be constant space right that's all the logic is now we will see the code so before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future now also check out my previous videos and keep supporting guys so initially I'm taking all the bubble characters in a set right then I need to initialize the maximum count and the current count as 0 right then I will be writing a for Loop where I will take the index and the current character using enumerate function from the current given input right then I need to check whether the index is greater than given k and then we need to check whether the character that we are throwing out of the window is in my bubble or not if it is a vowel we need to reduce the current account by 1. then I will check whether the current character is a bubble or not if it is a buffer I will increase my current account by 1 right then we need to keep on updating our maximum amount by taking maximum between maximum count itself then the current counter right then finally we will return the maximum comp that's all the code is now we will run the code as you can see it's pretty much efficient thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys
|
Maximum Number of Vowels in a Substring of Given Length
|
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
|
Given a string `s` and an integer `k`, return _the maximum number of vowel letters in any substring of_ `s` _with length_ `k`.
**Vowel letters** in English are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`.
**Example 1:**
**Input:** s = "abciiidef ", k = 3
**Output:** 3
**Explanation:** The substring "iii " contains 3 vowel letters.
**Example 2:**
**Input:** s = "aeiou ", k = 2
**Output:** 2
**Explanation:** Any substring of length 2 contains 2 vowels.
**Example 3:**
**Input:** s = "leetcode ", k = 3
**Output:** 2
**Explanation:** "lee ", "eet " and "ode " contain 2 vowels.
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of lowercase English letters.
* `1 <= k <= s.length`
|
Use Floyd-Warshall's algorithm to compute any-point to any-point distances. (Or can also do Dijkstra from every node due to the weights are non-negative). For each city calculate the number of reachable cities within the threshold, then search for the optimal city.
|
Dynamic Programming,Graph,Shortest Path
|
Medium
|
2171
|
96 |
new elliptical problem unique binary first trees so these companies have already asked this question in interviews also so basically in this question if you know the Catalan CDs then this question will very easy for you because if you know catalencies you will directly print the Catalan numbers and that will give you the directly answer in this question the question says you have given the n number you have to print the all binary search trees so what is the condition for binary first trees is a the last part laptop deal part should be less than the root node and write 50 part is less than greater than the root node so here's the intuition for this problem is we have to if I is the root node then um 1 to I minus 1 will consist the left part in I plus 1 to n will consists the right part that is a problem that is a big condition for binary search trees so here is the approach to solve this problem we will make a DP array you can see they say here's the I minus 1 to I minus 1 and I minus I plus 1 to n means this is a another approach I will use another approach is the code for this problem let's look at this photo if 8 is a root node so one two eight minus 1 will consist the left part means I will use 3 in left I can't use nine in right left because 9 is greater than the 8 I can use 9 in right part so 3 will go in left part and 10 will go in right part and is the acceptor problem so now we will solve this question you can see the code and intuition and approach all also approach I will solve this problem here okay by using DB so firstly we will break a DP array n plus size of n plus 1 com initialized with minus 1 and we will return solve of n comma DP I am passing a number and that DB array so now we will make a function in solve will pass n and vector into DP now we have to write the base case for this problem what should be the base case if only single node So my answer should be one for that if I have no role means to zero means I have no node then it also service the answer equals to 1. so n is less than equals to 1 then return one if DP of n is not equal to minus 1 and return DP of n now I will make a loop into equals to g 1 because it will start from 1 to n I less than equals to n then I plus I'll write a I will initialize int answer to keep track of that answer one by one so answer plus equals to now I will make a function call I will show function call solve of 1 to n minus 1. 4 this should be 1 to I minus 1 sorry so I minus 1 comma DP Plus sorry multiply with solve of that will be uh that is 1 to I minus 1 4 this will be n minus 1 and so i n minus I comma DP return DP of n p equals to answer we have to multiply these two because if a left part is left what answer is one right part answer is 2 so we have to multiply these two and again but multiply these two and add again and again okay so let's run this code running perfect that's amazing score now it is taking 0 millisecond and better than the 100 percent of C plus users also so let's discard about the time complexity and space complexity for this solution so the space complexity for this solution is O of n plus 1 means approx o of n this Vector is taking the space and the time complexity is O of n Square because there are two function calls and we are multiplying that function calls so o of n Square will be the time complexity so is the complete code and you can see the another approach this one you can see that this code also and you can see approach and induction for this problem this one is a Catalan formula you can if you want to display the kettle and then it will be easy for you to solve this problem so thank you and like this channel if you feel this is about this is a perfect solution and good solution then write this channel And subscribe also thank
|
Unique Binary Search Trees
|
unique-binary-search-trees
|
Given an integer `n`, return _the number of structurally unique **BST'**s (binary search trees) which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`.
**Example 1:**
**Input:** n = 3
**Output:** 5
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 19`
| null |
Math,Dynamic Programming,Tree,Binary Search Tree,Binary Tree
|
Medium
|
95
|
914 |
all right let's talk about x of a kind in a deck of curves so in a deck of cards each card has an integer written on it return true if only if you can choose x greater equivalent than 2 such that it is possible to split the entire deck into one or more groups of course and then there are the rules each school has exactly s car and all cars in each group has the same integer so for this question this is pretty uh tricky you can actually use the greatest common divisor and then later on um you store every single integer into a map and then you the key is the one two three four five right which is in the unique interview in the deck and then the value is the frequency of each unique uh key so um let me just write a comma a comment greatest comment divisor and i will tell you later what should you do so private and then it's going to be it for qcd right with this comma divisor and i would say in a into b so if you don't know this you can actually search on google why is the greatest common divisor method so if b is greater than equal to it's either you turn the gcd b and then a mod b and then else return a right so you need to keep mine the number until you can mod right if that's greater than zero right where this comma divider is actually mean right if qcd23 right what do you actually return you can right i mean there's no greatest common divider right so it's going to be zero so what happened to q2 that will return 2 right so you probably no idea i have f max and integer and then this will be a map and new cache map and i'm going to say result equal to zero and then i will just keep up updating my result value and then later on we just um return the result okay so uh i'm going to traverse the deck so forward into e in d right go in d right so i'm going to say uh p and mfk or v4 uh network gate right oh sorry meta kod for b is either d or zero so uh this is how you actually add a frequency numbering into the map so if the d is into this it's already adding to the map right i would get the method and then plus one if the map. if d is not in the map so the frequency will start from zero and then plus one this is pretty straightforward and then uh i'll have to say in which is the frequency number and i'm going to say result equal to gcd and then what the result i don't know so if any number there is uh gcd with the num uh so uh result with result and num and then this will give you the greatest common divisor so if the divisor is greater than 1 which is result right which is true so 2 you will have result equal to 2 so this is true how about this three two this is actually zero right okay two is two right but i'll get two three so it's three two so three right three and two is zero right so this will return result is not greater than one which is false and one i mean nothing zero and one is nothing one two right now one two four two and four right greatest common divisor is two and four which is two which is greater than one right so let's just run it and see if i have any arrow now and this will be it all right and let's talk about time and space complexity for the time traverse every single element in the map uh in the array so that will be all of them and you do need to store in the map drive so that will be all of them full of space so list all the solution and if you feel any helpful subscribe like if you want it and then leave a comment if you have and i'll see you next time bye
|
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
|
106 |
Ajay Ko Hello friends dynasty site from wedding and today we have to solve the question whose name is Construct Mind Tree from Postorder and Inaudible so first of all let us understand this problem and we will see on verification. Lover in positive function inside which you get two green one poster and one inverter see this is the work of an inverter is 164 and makes you better than this which is unit made work so inside this problem we have here before that I will make the video. In this video, I have brought out this point in a simple way with the help of pre and inverter, so if you watch the video then it will be very easy to understand this problem. Now both the problems are very simple. If you have understood then the poster. If you understand this then let's do fennel here, I was asking something like this, see, this is our right, the post order of this cream would be written like this, so what is it, its solution is 183 loan 90 506 120 phase 738 here one 90 1524 so I already have the inverter poster, now with the help of this we create it here, so now let's create the sound, first of all what we have to do inside it is to find out which is the left or right intent, then left. Where will I get Sabri and Right Safari if I look carefully at the inverter, where is the inverter, where I add zero, whatever is before zero, this is my tab screen and this is my right active, ok but how do I tell in the poster, it is the opposite way. Right is all verb in the voucher, so he does n't even know, the tree inside the potter is like here I don't even know where should I end the left first, how do I know where the electrician is ending, so we have described it in this How will we find out how many people are there when I have all my TV channels? Look, this is zero, it is not a postmortem, the route which comes last, we are going to take the benefit of this thing, so my route will come last. So what I do here is go to this route Note 3 hotel and search, then I am creating a side named S which I am placing on ISI that is not trust enough and I am doing some industries, I am using one I will use the starting index of the inverter on this road and I am using one. I will be using the end index of the inverter. If the poster asks, these are some variables. So the idea is that I have kept the starting index of these orders. After Jyoti, who will start a dialogue here, this post order will be a burden on the people of this hair's purpose, first of all, go inside the three orders that have been given to me and search for whom, till a moment, do not look at this post. Order of Chief Postmaster What will we keep doing till then Side Effects Subscribe Plus So where will it be first will be the idea, first here is the poster's MyJio, zero elements of elementary school or not, do n't call now, like this, let's go, one that If I come and stay here then what more did I find out that the last element of the shoulder would be that of the inverter which Media Limited both equal it means that whatever it is, here I have got angry with us, the earlier revision of this route is and will be life is this. There is a war on the matter of root, right sub cream, how many elements are there in it, how to find out, they can find out very much, keep me in the range, within a common man, how many people come to semen with money, so that I can get a point. Do n't do it at all, it will be easy too - there are so many people, n't do it at all, it will be easy too - there are so many people, n't do it at all, it will be easy too - there are so many people, that is, I have to put my phone total number of elements of a total number of elements of plans or ID Find out that I have a total from the post and from the beginning of the elements will subscribe for the sting of the post. Will lock the left upper lip. Check just see. I turn it a little to the side. Now see a little bit from the rotating hormone elements 12345. This is guaranteed to select my free let's tree. Let's see. 786 In the whole post, first the seventh plate, then there will be two three elements whether it is yoga or the five faces. Let's see this amazing again. Just look at the one when you are free and pipe sex. 7 that the elements of juice are off, according to me, the limits have been reached. Who is this? Who will be the starting 27 elements of my post order? I also knew the text of my love story. Whose Harish Sharma was known with the help of inverter, then I found out through the inverter that we were 1.25 Have you taken inverter that we were 1.25 Have you taken inverter that we were 1.25 Have you taken how many elements will be part of Africa? These people will talk about electricity in the seven elements of starting the lesson of Mail Africa. So let's make it normally. How will we know how many heights are there for free in a love story? In the same way, I will bring it here. Whatever is your range, first match, you tell me lightly, update yourself here, see, first of all, 100 earning level, Q. Mandal, what did I pass, first of all, by writing, setting of post poster and setting of N x N order of research poster next9 Africa and Events passed the reduction with the help that the posters are teenagers. Yes, the road to your city level, from the hotel towards the NGO to the level, the route note was made within it, who will become its fruit, your zero was made from zero, the route note was made as well as We will see one more here, inside this here, seeing the stand, the thing is, how will this tight made arm hole of Zeromile a10 be presented and now see because it is going to be fitted with two cords, so first I am running the girl here, zero. I have made a note of the name, now if we put the roots of left, then what science center will they belong to, which long and which elements will they belong to, what has to be done, first type from r and then something like this. In a way, if I talk about a left woman, what will be the left Africa post and let us find out the left's post or the right's post, the coward right's inch, then what will be the Africa poster? Africa posters here below at the level from zero to the first one. The total number of elements of the account has been taken out. The total number of elements has been found. IS MINE IS HISTORY. How much part is tied so that I can know the total. Which element's juice is used in laptop theft? So here, can I believe it? It is the beginning of the shoulder. Index comma Starting index of this poster Total number of elements in plus - 1the Look just Total number of elements in plus - 1the Look just Total number of elements in plus - 1the Look just plus 7 When you reach here I was to be selected here One was to stay behind Here was my own So zero plus 600 The seventh element is counting stars from zero From two zero to seven minus one, accounting has started from zero, so if we can send messages, how many people have sent me the lens, how many people have sent me, how many people are in the index itself, then we will have to remind for that. Good inverter shop. In this yoga is from I to ID Total Number of Units If people from here to here plan Africa then guaranteed people from here to here will belong to Africa then the last element is my route inside the poster then the last step is my route then just before that and where But my Africa region is over, after that all the people will plan this, will make a bright problem that you will see this at night, first of all one how to free show is decided by peacock's pipe, this is we went home, now this is 7 minutes. After like here this is this 12345 78791 10th 11th hour who is this is needed then it means when the elected ends, after that the element which is to provide free songs from the start is nutrition only, first print the alphabets then rights of If you make a difference and print it on it, then I will know how much all the potatoes of the referee were. Now the elements after this will be guaranteed rights. They will be curved, so it means from here to here, referee from here to here, rights also pass this flavor. Just look at where I will reach in PSI plus total number of elements. Seventh index has reached here and from here how far do I have to go till here. Basically Posted by Admin May - Above and Basically Posted by Admin May - Above and Basically Posted by Admin May - Above and what will this happen I brought from index x plus one that our Ghaghra is ready, once the flower pot is made then its cost is very much given, so the transport is African, we will see here, we will make two sets, first of all silver 1101 and now it is planted in Africa, so let's call inside job. First of all, after talking about inverter, I first searched 'C' in the notary and first searched 'C' in the notary and first searched 'C' in the notary and inside the poster, I have found 'Next' inside the poster, I have found 'Next' inside the poster, I have found 'Next' on them i.e. from Jio to six, what will be on them i.e. from Jio to six, what will be on them i.e. from Jio to six, what will be its left text, OK, from zero to se, part of select. It's done and what will happen in the poster? The first one to be posted will be zero, don't count seven, zero plus one minus one, that is, six, my laptop is also fine, now cover it and put fruit kiss, this root will make that dream flour, how much have we made? Pass the day if you look at the element carefully we have green subscribe 080221 here five zodiac signs 80 402 sub last element and supplement this is my route Africa became the route so this is what I passed the test this is a poster of lipstick look carefully First letter is Tika 14th edition, if you were seventh, stomach speed is 98100 and second is this, it is important for the meeting, we have our own trees, if we are Amethi, then we will run the logic there, now we were running, so I have spread my stomach, this is That I pass the correct index inside the left here, tell which limits belong inside the referee, its post and give these hotels, which elements belong in the ride free, its poster and these orders We provide toe, I tell both of them to go and state themselves tomorrow and bring them after commenting on themselves, then the fruit that I had planted on the left will become my lifestyle and its roots will become textile. And the root of the right sub-free which I have put will right sub-free which I have put will right sub-free which I have put will become my right side, this will make my free complete, so what you are seeing here, see what will become of an element here, what will become of false note, which education limit? Time is looted from zero to past days to six elements of education post order. Process is element of one. Here to one I made a route note coolly pass it. Do n't cry. Sex is romance only romance is one. It is not yet connected to this. I did not connect, it will not connect now, will connect in the return time. Hmm, okay, now this gang has more monthly dreams, who will set it, then see who will set zero monthly like this, first searched for one, found it in many nodal centers, but on the element, what it means, it has ignorance. If you have applied smart to zero, then take the oil like this from Rome to milk and on that side, how much will it cost in the post mortem also, don't give one to zero, on this side, do n't give mar20 to zero, and who is the element here, we have the element, we have it here. In zero work, this element of 'Tu' has become 'Note', I have this element of 'Tu' has become 'Note', I have this element of 'Tu' has become 'Note', I have made it a root note here, now this is the root note, profit is now needed and it will be applied to the ends, after the monasteries, now see who will put the commando next, then 'To' is the Sarun and now I have made the then 'To' is the Sarun and now I have made the then 'To' is the Sarun and now I have made the tube element. He will go and search inside the inverter, he found an inverter, an airplane, on the left, you will see how many he has, how many helmets, how many people are there in it, one - 01 is the only person for how many people are there in it, one - 01 is the only person for how many people are there in it, one - 01 is the only person for quality, the total number of elements is one account, if it is ok, then just re-pass it. Let's do it account, if it is ok, then just re-pass it. Let's do it account, if it is ok, then just re-pass it. Let's do it now rally will go in three wards 0.0 now rally will go in three wards 0.0 now rally will go in three wards 0.0 Back side I got one on one I got Typing and Accounting and Provides - Typing and Accounting and Provides - Typing and Accounting and Provides - 150 Idea 121 - Vansh 150 Idea 121 - Vansh 150 Idea 121 - Vansh that if we go like this then I will get the value here Siropav ma0 phone like this I reached I got the value beat zero how much did I get Shiromani Romance Hero element I got the element from the account here is the sample I came to know that the element was part now look equal element is done if they mark like I have seven lots If I fry the Amazon, then the seven elements are equal to zero. This IDS of Heroine So what can we do by crossing each other, this cannot happen, this is a wrong range, it means that whenever our element reaches the media, you can sell it here and make it here, if we make it in front of the country, if once on the second cross. If it comes, then they will organize it, its life will be returned, there will be a red button from the right, so it must have pressed the right key, then the signal came to the left, in which tap was also attached to the left or right and it returned itself, in which it itself Sibal returned the book, who will get it after going there and will get the element free, three left free call will be missed by going to the call on the left side of free, this is the target of three, it has become complete and this tax has been paid, now let's go right people, let's see. How will the call of Wright's flight go while staying, see light only call, caller ID plus Bhandari, go within this range in 2012, here, by mixing happiness in the weeds with free cream, on NX1, then IDX plus one's two and I Which is how much has become of two commando, how much will be the value of this rally, which is the settings of hands free mode, which is zero. Total number of elements of one pretending S in phone plus - Om, which is two one pretending S in phone plus - Om, which is two one pretending S in phone plus - Om, which is two minus one, grind the leg, mother of life. It turned out that what is the meaning of you coming to boil, that the range I have made here is Peepal wali 1kw year 2012, how will the call be made inside it, the element will be made here which becomes the mother of the forest, its back has been made in the form and when will you set up its factory. So you will get tap and finally what to do return yourself to whom used to write written test also got the right three elements of the element, this will become a channel and from here it is removed MP3 will return to Bollywood to whom re stop don't send element is made essay which atmosphere was created That Pushkin will fall on the left side, now who puts this element as its own, that element will separate itself, a little earlier, sleep sees zero, beat six, 0, mask six, and here also syrup Thomas Sudoff, okay, keep this bird, it is zero, two. I gave such a route note to the fish forest person here, the element was perfect here, if you apply the dry key, then from IDS plus one, i.e. from the side, six keys will i.e. from the side, six keys will i.e. from the side, six keys will work tomorrow, I am running it from phone to sixty calls and free mode. What will we pass in the sweater? Pores and inside this we will pass here 159 name pass so on this side let's just look at the post element 131 how much we have an account so I have a free leg i.e. porter so I have a free leg i.e. porter so I have a free leg i.e. porter starting index is zero flats thriller comma posted In next that is 6 - one so this ranger goes three for you is like 6 - one so this ranger goes three for you is like 6 - one so this ranger goes three for you is like heroine passed I free forgive one more don't six for how to mount here 3 idiots 940 and here kitna pass hai 90 a chuka This three comma pipe has been completely passed, now inside it is the for wala judgment, here we have passed the green pass, sometimes even after passing the recipe, free comma MP3 pom poms 6 inside this, do n't become our root and who will become the last element of the post order, nutrition blast element. And do one child and pass this thing 9 see 9029 the tempo is correct see the inverter just see its 90 this means it is a factory on its own if that woman's pound in OD is coming right then it will be made in our form there is a post glass element inside it then I made four here in the form and placed another one on my left and right. First just loot the other one and search where did you find these textiles. Four will be passed because of this order to induce appointed - recession will come again in the same appointed - recession will come again in the same appointed - recession will come again in the same manner. How much will the rally go inside the border, nutritious will it go inside, let's see also now let's check from postorder starting index for Asus Zenfone La had made in that cutting the portion president and is free post start trusting him and total number of element in express How much is one minus one to get up three ko mayor - Mathri is coming on 1353 up three ko mayor - Mathri is coming on 1353 up three ko mayor - Mathri is coming on 1353 means this side HTML elements you will have elements in here 3030 sorry problem of course that he is going to be my element like this who is he going to be one I have made it here, it is ok, don't think it is ok, it has not become normal, here is one mode, now because with equal inductive, I will get left and right, but you are not going to get it, so its left then right. Manner finally that both of them have been used then it will return itself and attach the mail on the floor from four to left but now as it searches the network of the phone then it will appear more on its right that now if the right key is pressed then look at it. Free to forgive, right within the off, which was the element for freedom within and hands free from fear for six products, the element within six and 305, the fourth one, I got it in the element above these exports, so which is our postorder Kailash element. Who is it then where did I get it from IDS Plus One to ICICI on the index face - so what to do here ID Will to ICICI on the index face - so what to do here ID Will pass this shoulder's starting index which was also in press account that elements for one hour in nodia starting next9news minus point note and index we have 5 - 1404 point note and index we have 5 - 1404 point note and index we have 5 - 1404 forgiven and passed it absolutely right believed Kapoor's tomb limit Who is the potato masher element is the time you have the range pass close to pass for the course Thomas element and no yes but bank it good attach but if you call the referee then you will not get anything will return to finally whom will return 4K right before here If there is a return, then this positive note of Naan has been iodined only by pausing the right of the other, now finally both of the four's can be played, it will return 420, now the 1 quiet has also been returned from the light of the one, now both of the one's are objects. So what will one return eventually to the left of zero that now it goes from zero to the right key then see how it will work with night fall in the camps From zero the index was found from 728 to eleventh became 39 From this tree to the level of these voters Will how much will be in the pot, it will be inside the shoulder, our post order will start in next because the portion of 304 A plus 7 - 9th is ODDS - 120, the portion of 304 A plus 7 - 9th is ODDS - 120, the portion of 304 A plus 7 - 9th is ODDS - 120, the tank will consume more tav, till the month, the correct time of mutton will be passed while not watching 20 And from here to here, it is Prince's take 1562, here 11.2 66 Now is Prince's take 1562, here 11.2 66 Now see which element will be formed here, if it is a little then the intake will be less 80 come 800 11.3 Here the then the intake will be less 80 come 800 11.3 Here the then the intake will be less 80 come 800 11.3 Here the element will be formed in our intestine i.e. element will be formed in our intestine i.e. element will be formed in our intestine i.e. 22% will be mine. To Z element is two, it will 22% will be mine. To Z element is two, it will 22% will be mine. To Z element is two, it will become note, now we have to run the pole on its left side, then look, make two notes, do worship, let's search in the note, search me email ID, how many people are there before tan on the stand, total number of elements, height 21 Okay, so the train will go from here to one, do n't write skin and accounting index to miles - 54, what will index to miles - 54, what will index to miles - 54, what will be that product in the poster, IT index because how much is the seventh plus Mitthu Kar 2 - 127 how much is the seventh plus Mitthu Kar 2 - 127 how much is the seventh plus Mitthu Kar 2 - 127 plus two 9 - there 827 from Math. plus two 9 - there 827 from Math. plus two 9 - there 827 from Math. These two elements are more profitable, so I am Benjamin here, then he was in his seventh month from 8th to 9th. Okay, now let's run this festival of our girl. Issue - Commenting on these this festival of our girl. Issue - Commenting on these this festival of our girl. Issue - Commenting on these will become the fruit note. The last element of the post i.e. will become the fruit note. The last element of the post i.e. will become the fruit note. The last element of the post i.e. 80 years element because here we have made 5 in the form of pipe and fiber from here, who will provide tea to whom, who will provide free service from their F-35 and let's install free service from their F-35 and let's install free service from their F-35 and let's install server, first five elements in the fifth element, search in five elements of inverter. Do search in these wards, I found Index North, so how many people juice before this, 898 is equal to one, if one element adjusts, then the rings will pass, here the back is Mahapeeth mix, the shop ingredient of inverter is brightness - how much will mine go? brightness - how much will mine go? brightness - how much will mine go? Gumla will be made for Ajay and post mortem, then these chroma is one plus one minus one plus one - chroma is one plus one minus one plus one - chroma is one plus one minus one plus one - nickel 2019 one has definitely arrived, pet means bringing husband has only one meaning that planet means it has become in my list and It has a thrust element, it has a label and it must have run the practical first, if nothing is found then it has returned, in this it has moved itself to the left of the pipe, now from here it has moved to the left of the pipe or to its right, then to the right. Let's see who will run the snake, see where did I get the element, then it was found in these coma cart element, induction is more fixed from the ground, side 1000 and index - 03 hotel's end minus 1000 and index - 03 hotel's end minus 1000 and index - 03 hotel's end minus one invited to minus one, then what will I get, see this element I have got the pipe in N order 90 rider class ninth and tenth and N order candidates had done mine in Odisha 9 - Stopping candidates had done mine in Odisha 9 - Stopping candidates had done mine in Odisha 9 - Stopping Now if it has not come here then no will do - Now if it has not come here then no will do - Now if it has not come here then no will do - No will do in this and - If you have to No will do in this and - If you have to No will do in this and - If you have to consume regularly So this is a world by crossing again, the Titanic of the inverter has become bigger, everything invented is wrong, it means the light signal will not be liter from here, finally when both of these will work then it will return to you fight on the top left and Now, who is running it in his diet, the trace index element was searched, we have found three orders inside the inverter, what will we do now on the cent index, now teen and we repass it, these ODIS plus one will become 11.61. In plus one will become 11.61. In plus one will become 11.61. In Odisha will go through the margin, after this inside the poster the posts tagged starting index is this much for the starting index of 70 in this the total number of elements of two is here so we have a poster that in English - Om which is time - 1929 is in English - Om which is time - 1929 is in English - Om which is time - 1929 is there Not perfect otherwise in passed our normal note to eleven to mile to come and finally after the way to come investment limited does this next9 element is our exit six so here we requested the six element left ventricle drunkenness You will get it finally, Bigg Boss has returned it, both of them have been switched on your light, six has been returned, both of them are broken, also will return from zero to right, both of them have been searched, finally they will ask main and it has become ours to discuss, right vs. Wrong became perfect, of course, now let's code like this, see how to code, add, I am sitting inside, what are we doing, first I am making a pan, which is mine, it is 9th dots, I am length and one like this. A function is called, inside which if I repass, then first of all we will pass a poster, then there is the post starting index, the end events of the poster and then the inverter is being passed. Here, the starting of the inverter in back. Protein ODI is the first thing to check as soon as it comes. If you have invested in these 10 audio recordings on these tracks then you have to return them. Tap the second task. Let's make a note. From which note will be made, I am here as a tree note. I want to make it, how will it be made? I am not a tree in the post order of the node, so the road is N The note that you will return from is, first of all make an ID, that coward in Odisha and expert advice, let's return this note, unless the ID matches with that which it does not match, that post border's end animals until it matches with this, you are here People will keep running and every time side effect will be plus then I will take out the total number of elements which will be the result of IDS - Inverter starting result of IDS - Inverter starting result of IDS - Inverter starting in black that now let's run the call Bill Repo Pimendra will run the call Now so this is the post order I have K nodal ko starting and decided to minus one, this is the range fee of the inverter and here goes my ID Ka setting of post in starting plus - setting of post in starting plus - setting of post in starting plus - Total number of elements for the starting index Paunikar Total number of elements in starting index plus minus one Till yesterday we have run less than one question in that run Okay, okay and this side the case will be made for the right You will need total number of elements in post workout and express for this will come after our posted - work pump a come after our posted - work pump a come after our posted - work pump a final noted return run support will return once whatever answer comes from there return will be in digital form fruit mod ko Will return the messages, not at all that postorder that these orders Croma End - 101 Miles - 54 these orders Croma End - 101 Miles - 54 these orders Croma End - 101 Miles - 54 and have supported, we send a message to the code, the voice was one, this post is R, this post is toilet, apart from this, the oil had arrived early. Loot, this record is ours, once you think carefully and see that we have it, then if you have got to learn something from this video, then please like this video, share it as much as you can and understand anything. If it did not come, do you have any doubt or want to tell something, then you can write in the comment box. Now we answer all the comments. So please give your reviews in the comment box. Tell us how you liked the video. Do you have any doubt? So you can tell that also, you will get the answer by commenting. Apart from this, if you have come to the channel for the first time, then how much fun would it be to subscribe to a channel in which such video support will also keep coming, with these features, anger will keep coming in it every time. So subscribe to the channel so that your learning is always going on. See you in the next video and Halwa Steve. The question I had asked earlier was that how to get appointment for using pre-order inorder traversal. Make using pre-order inorder traversal. Make using pre-order inorder traversal. Make sure to watch it in the video Bigg Boss. If you get free mode on order then you can do both the questions. If this note goes for free then you can order online, then that question. If you get angry, someone is doing this and that question and is catching you. Then spy yourself. If you want to do then it is good Pratap, now note down this question in the next chapter, after this we will hand it over to someone else, inside this we will use some more tuition and start the free mode. Okay, see you in the next video.
|
Construct Binary Tree from Inorder and Postorder Traversal
|
construct-binary-tree-from-inorder-and-postorder-traversal
|
Given two integer arrays `inorder` and `postorder` where `inorder` is the inorder traversal of a binary tree and `postorder` is the postorder traversal of the same tree, construct and return _the binary tree_.
**Example 1:**
**Input:** inorder = \[9,3,15,20,7\], postorder = \[9,15,7,20,3\]
**Output:** \[3,9,20,null,null,15,7\]
**Example 2:**
**Input:** inorder = \[-1\], postorder = \[-1\]
**Output:** \[-1\]
**Constraints:**
* `1 <= inorder.length <= 3000`
* `postorder.length == inorder.length`
* `-3000 <= inorder[i], postorder[i] <= 3000`
* `inorder` and `postorder` consist of **unique** values.
* Each value of `postorder` also appears in `inorder`.
* `inorder` is **guaranteed** to be the inorder traversal of the tree.
* `postorder` is **guaranteed** to be the postorder traversal of the tree.
| null |
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
|
Medium
|
105
|
516 |
um hello so today we are going to do this problem which is part of Fleet code daily challenge uh longest palindromic subsequence so basically we have a string s and we want to find the longest palindromic subsequence um in s so subsequence means we can skip letters and then we want palindromic which means basically it treats the same forward and backwards right so what's for example if we take a look at this one what's the longest palindromic subsequence well this one here because BBB you can read the same like this and like this if you reverse the string it would be equal to the string itself okay um so and that's the longest one so um is that the longest one no because actually we can do better we can take all three here skip a take this one and take it and that way it would be the same reverse it and string itself okay and so the length of that one is four soda term four um for this second one um it's only the these two that can be a pattern drum and so we return two so that's the idea now the length of the shrink can be up to 1000 so it's reasonable and we have on the lowercase letters okay so let's see how we can handle it um okay so how do we handle this well the first observation we should make is let's say for example if I have a substring like this maybe X maybe some characters here actually let's just not any characters and then maybe I have another a here okay this string for this citring to be palindrome we need this one and this one to be equal let's say if these were an X and Y just to represent some characters these two strings need to be these two characters need to be equal for this for any sub sequence that has that starts here and ends here these two needs to be equal for to be a Parry drum because what is a palindrome really a palindrome if you have one like this maybe like this one two three four five you need five to be equal to one four to be equal to two and since three in the middle it doesn't need to be equal to anything but it's it would be equal to itself if you sort of um zero one two three four if you sort of do that I and N minus so and here is 5 and minus I minus 1 need to be equal so 0 and 5 minus 0 minus 1 is 4. so every I needs to be equal to Its Reflection on the other side so n minus I minus 1. so that's that has to happen even if it's let's say we have you have substring here in your string and then you have a and then you have some strings here and then you have a substring here for any subsequence that let's say this one is index I and this one index J for any subsequence that includes I and J to be a palindrome you need s of I to be equal to S of J okay so that's the main Insight that we can go from and try to construct the solution okay so um now the other thing is that there is really no way to predict that a subsequence will be a pattern drop or not and there is no greedy way to sort of determine a longest one and so what that tells us is less you can we can't think of a greedy approach right and so let's think about then trying all possibilities that's trying all subsequence um and checking if they are putting drum and then if they are we just add the length now for a string like this once we determine that s of I is equal to S of J what do we know from that well we know that at least we have a subsequence of length 2 because we could just take these two because subsequence can skip letters so we know that we can do plus two to whatever this one is if this one is not a palindrome and maybe it's like BCD then the substring will add zero but if this one was is a putted drum like maybe b a b then we know it will add three so here it would be whatever is these the longest subsequence in uh in that let's call it what is this one this is I plus one and this is J minus one on I plus one in J minus 1 plus 2. right that's what the that's what we would have here so from this idea we can sort of do a recursion approach um and try to solve it okay so we know if s of I is equal to S of J we know we will do this now what if it's not equal well if it's not equal we don't have any information in so let's just try both of them what does that mean so let me show you here so let's go back to I and J so let's say they are not equal so we have B here so what should we do in that case well we should just try possibilities what are the possibilities well one possibility is that we start here and ending here so maybe there is an a here um maybe that's a Punisher the other possibility is Maybe it's from here to here right and then when we recurse maybe this is not the right one and it's just here and so we recurse again but for the first recursive step it's just one of the two either skipping I or skipping J you may say why not skip to I plus two but if we do it in a recursion way I plus 2 will be the next iteration for this red part this red portion okay so we only need to do it for I plus 1 J and um and the i j minus 1 okay so what this means is that this is going to be just the max of trying I minus I plus 1 J and the trying the other part which is which ends here which is J minus one so I J minus 1. um okay so let's code up what we saw in the overview and make sure it passes so we said we need um we just have a recursive function that we can use but for that recursive function we need um just the left and the right side let's call them I and J um and so we need our helper function here and we pass it I and j i is the left side J is the right side and so from where do we want to start well we want the longest parindromic subsequence in the entire string so it should start from Z do the entire string range because each time we will reduce J and advance I so we should do a zero to n minus 1 and be in the length of the string so let's just clear that up here 0 and N minus one okay and this would be the longest like this and this is what we return at the end we will calculate the max now what are our base cases well one base case if the two characters are reach each other so let's say for example here um if we advance let's say from 0 to n minus one so I starts out here J starts out here if we advance and they reach each other on one character let's say B then what's the B alone is panindrome substring and so um they're like this one and so we should return one now what if we advance like I minus one and then I minus two and then let's say it can happen in a even length so i j if we advance we can they can just skip each other and not meet at a point so in that case what should be return well that means there is no that's an empty string because there is nothing in between if they cross each other because we are looking for only a string from I to J and so in that case we want to return zero so return zero um okay what else now that we've done this we can just do the recursive two functions that we saw in the overview so what's the condition is if the left and the right side are equal then we know we at least have a length 2 but we need to check if it can be bigger by Trying by just moving so if these are equal right we shouldn't keep J here or a here we should move both so that we can check this portion here and so we move I like this and move j like this and so we check this portion and so that's why here we'll do I plus 1 and J minus one that's the inner portion okay and so we want to get the max for this substring and so let's just have call it best start out as zero and then here we'll take the max and we will do else here now the else will try both possibilities we'll try this here and then we'll try this substring here so that would be just taking the max um best Max of first side which is I plus one to J so just this one or the second option which is I to J minus 1 like this and so that would be longest of I and J minus 1 and that should be it and then at the end this function this helper function should return the best for that substring subsequence from I to J so we return best uh okay we just need the length so let me actually just do length of s here okay looks reasonable it will probably fail with time limit because we do 2 to the power of 3 here with these three function calls and so there will be repetitions and so for these repetitions so time limit exceeded we could try to do a memorization and see if that will help it may not help and so if it doesn't help we can convert this one to um to a dynamic programming solution and so here we want to just check if I and J are already in our memo hash map then we can just return them like this because we already calculated them so no need to recalculate um and then if they are not then here we can assign it and return it okay and hopefully with this the time would be better but let's see if we if it's it doesn't get accepted right so you can see it does get accepted with that now if you want to change this a little bit to a dynamic programming solution for it to be faster what should we do well let's just so dynamic programming we will need our base case our state and our base case so what is our state well we want the longest each time here from this longest we can just look at the state here we want the longest from I to J so longest pen in drum uh palindrome subsequence for subsequence I to J okay R for s from I to J and so we know that for if we for any single character it's one so for any I DP of II is going to be one now the most important thing for that programming is to come up with your recurrence relation right so what's the reconciliation here well we can actually just sort of use this function but convert it to a DP format and so what it's going to be is i j and just going to be the max of what we have so far but here since it's the first one we have nothing and so it's going to be if so of course this happens only if SI is equal to SJ so if that's the case then it's going to be just the DP of what is this one I plus 1 right J minus 1. plus 2 exact same like representation just instead of doing that recursive function we'll use the table now otherwise DP of IJ is going to need to be the max of these two and so what's that so it's going to be the max of DP of I plus 1 J and then DP of i j minus 1. okay so that's the exact same representation except instead of doing a recursive function we'll save it in a table so that exact so that would be equivalent to memorization because um because we won't calculate the same thing twice and so it will be something like this um now the second piece of this is how should we iterate here it was easy to know how to iterate because it's recursive now here what should be the for Loop for I and what should be the for Loop 4J that we can do that will work here now for the for that Loop to work we need um we need when we calculate when we are calculating DP of IJ we need to have the state for I plus 1 and J minus 1. and so what this tells us is for I when we are calculating I we need to know the state of I Plus 1. now what does that tell us that we need to go backwards from the right because let's say we are at I equal to 2 to have the state for I equal to 3 we need to have went from three to two so we need to have to go backwards and so this tells us that here this needs to be the range backwards so from n b the length minus one to minus one zero and of course since DP of I is equal to I a DP of I is equal to 1 we can do that here now what about J well J here tells you that when you are at J we need to know J minus one same here and here okay and so what this tells us is that for J we needed to go forward because when we are calculating for J equal to 4 we need to know for J equal to 3 when we are calculating for J equal to two we need to know four J equal to one right and so what this tells us is that we need this to be up to n going forward but what should be here well for remember we did I begin the J we return so we want I to always be smaller or equal to J because if it's bigger than that's another valid subsequence it's not a valid subsequence from a to J and so we need J to always be bigger than I and so for it to be a valid subsequence right because we already calculated for one letter so we need it to be bigger and so we do I plus 1 here okay um and so that should be pretty much it now what should we return at the end well at the end we should just three we want the longest paranormal subsequence from zero to n minus 1 for the entire string and so to do that we can just do DP of 0 at minus one and that's pretty much that's all we need for DP is the base case the reconciliation and then the order of iteration which means basically how we set up our for loops and so let's actually just use this then so what we need is this here and we can return that we also need to define the array itself but that should be easy that should be just a range of N and wanted for I and J so each of them go up to n so that would be like this we need to Define n which is just the length of the string and then at the end we said we want to return for the entire string so DP of 0 and N minus 1. for on this uh looks like which is missing this and close parenthesis and then this one is extra submit and that passes out this cases um yeah so that's pretty much it for this problem now in terms of time complexity here for this we are doing an open loop another open loop so of N squared here and then in terms of space we are using this DP array which is overt squared as well and so overall we have only one thousand and so this should be yeah pretty fast because it's just one thousand to the power of 2. um yeah so that's pretty much it for this problem please like And subscribe and see you on the next one bye
|
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
|
229 |
Jhaal Hello Hi Guys Welcome to Lotus Today's question is maturity element to in this question Bihar Government Year for 10 to find all elements of the pear more than in three times when is the price of the year ago as children in need time and oven space it Means date for example give darkness also 2.3 element which is more than give darkness also 2.3 element which is more than give darkness also 2.3 element which is more than digit times latest hair style for this that is 30 so finally element which appears more than three times on divider latest model 110 vacancy date three has more than one times will return All Answers 3 A Winner Here Because Elements 11100 222 India's Server To Return All The Elements Which Makes More Than Death Time Here And Decided To Be Are Visible 2833 Is To Snow View To Find All The Elements Such Frequency Are Great Dane To Hindi Are Subha Considered That Two Elements 123 Country Will Return Given Yes Betu Not Died When Bihar Government Where Two You Find Elements For Battery Time A Criminal Edit Software Can A Maximum Of Two Elements Which Can Come And Three Times In A Day Maximum Of Two Elements Maximum two elements which can come and can they often take element if mod in three times like in this case vacancy date two elements advance and buy mob in three times pure maximum volume to medium value increase face in which are that these ideas each one contains Content Only Unit Number Two That Case No Element Mixing More Than Any Three Times Swadesh Wapsi Whole Question 9 Luti Approach This Question On That Boat Discussion Can Be Done In Freezer Process Fast Is Boot Polish Approach Taken Digital Optimizer Product Forces Maurya Voting and Amazing Most Optimized For fixed deposit approach in life into its soil and every position which stores in number in variable and thread through recipe are which is the meaning of account from frequency of date of number in the like this Jai Hind is English example Chief Editor Ne Court Small Ko Dare This Possibility Are Faslon Blitz Hai Are Agri Position Will Take Sidhi Element In Various Actions And Will Count The Frequency Of Back Hindi Laptop Diy Sugyan The Best Old Ex In Waste Products Noida Updates Gel Loop Is Used To D Best Of The Year And Every Index E Agri Funds Will Check Wether It Is Equal Unbearable Value Adams Ecuador Opulence and Not Exact As It Is Equal 10th Increase The Increment Account And At The End Of This Blog Will Check Wether That Account Is Later No. 28 And Not No. 28 York Not Give It's Better Will Up and Dance Director Sudhir Possible But This Is Very Time Consuming Approach York University b.a. Consuming Approach York University b.a. Consuming Approach York University b.a. Main to approach is fashion approach a main approach but will do opium literature added to the frequency of beach element hindi house map and letter when they were store play store dixit country of beach element in years map with benefits and hash map and find Difficult only element which is better than in 3D to like in this court first follow this jus to the frequency of which element hindi house map and second undertaking loop is for finding the a flying jut element that frequency is better than and excise best gift diet element will up and answer in president will not up and saw what is the problem with his approach in this phase i have reduced time complexity to end withdraw support and complexity but in this case were reduced to reduce its 2nd but gives that a little extra video .in that a little extra video .in that a little extra video .in A+ B Consume A+ B Consume Subscribe to Story of Elements To This Element Is High Nice Light With Minor Vikas Hindi Meaning Which Do Not Have Any Casualty Elements And Construction Account By All Songs Play Store Zero Vikas Sequence Of The Majority Elements Hindi Fix Zero Know What Will Do Will Simply Traits Are Agree Position Will Go Through This Condition And Preserve And Women Even If This Condition Of Us Will Do Certain Operation No Accent Why So Let's Sexual Code Records Plane Yudhi That Apple Bored Them Using Driver Only Burning Minute Points 204 That Vinod This Account Is A 0.10 Access Manager That Vinod This Account Is A 0.10 Access Manager That Vinod This Account Is A 0.10 Access Manager And Miles - 58 Mins That They Are Still And Miles - 58 Mins That They Are Still And Miles - 58 Mins That They Are Still Not Finding Any Majority Element Is One Or Two Of What Will Happen Thursday That Indexes 020 Condition Is Condition Will Run At This App Contents 1120 Every Actor Will Welcome Equal To Current element is not contacts frequency will be updated with 139 viravar elements in the contacts are vikram equal to front and back current element and frequency of contacts with 151 999 9999 ki reddy stadium check weather thi element bedardi element current element is double is equal to r Majority elements in yes channel frequency update element will increase the effigy not the condition will follow like this according to current element is equal to how much water element slept a distic s in this case frequency of contact will increase this post in edition dated back 112 Number Six True Aadesh Condition Will Follow Every Action And Navdeep Arbitration Will Follow Bigg Boss Vs Sonth Particular Position Only One Condition Will Yield A And Sunav 9 Point Alamu Next Index De Naagin Festival Check Weather Current Elements 112 Every Majority Element And Not Effective Will Update The frequency of the majority element message cash withdrawal equal listen what will oo will go to intake normal check weather this element current element is equal to one and 991 the weather this element is equal to our second element 2980 Citizens Not Possible Because Switch Still Not For The Second Maturity Element Steel - 102nd Check Second Maturity Element Steel - 102nd Check Second Maturity Element Steel - 102nd Check Weather The Frequency Offer Hurt In Your Purse Elements Zero And Not So In This Case Dip Frequency Of Majority Element Is Note Forced Check Weather The Frequency Of Elements Or Not This Element is video will update the frequency of elements and they will update the elements with current element subscribe to the Page is updated are why it is divya security element is now see this current element and frequency of liberty elements increase is 212 is normal note so next index not possible check weather this value is equal to and force mlot element and note that this is not equal to and will check weather this current element is equal to arrested development to note that this condition is a condition sudesh condition full films tattoo pe security elements in this Case will increase in frequency of sacred water element hai na ho desh ke school field will move to another next index main naagin mirch one way earth weather deep current element same chord pass maturity element and not be painful contentment is equal to setting element note hindi script Budh is condition that falls below check weather the frequency of current maturity element 10 notes 90 check weather the frequency offers seconds peak elements zero notes in this case also did not give some will be used for condition will not be true to India and also Will Return And It Will To Decrease The Frequency Of Mercury In Majority Elements David Beckham 2.1 Why This Majority Elements David Beckham 2.1 Why This Majority Elements David Beckham 2.1 Why This Is The Big Boss Main Encounter Element Who Is The First President And The Sacred Water Element In This Case Will Increase The Frequency Of Buddhi In Juti Elements That No Will move to next index these days in this case also it's three and the rate official will not valid and wealth will run at each rate the current elements not equal to a faujn katthi element s well s notification returned limit should you can see vikram the one Less direct original frequency no are mill free viewing and induction furnace position in this case possible check weather this element is equal to air force which element and not interested not when will check weather this element is equal to our second opposite element and not indicated for When Will Check Weather The Frequency Of Contact With Air Force John Element Kiss Gang And Note 5000 Will Update The Value Of Jagdish Commission Increase Frequency of Second Maturity Elements Zero and Note 3 Citizen of Hadith Every Morning Will Do Only in 2008 But They Still Not Encounter Perfect Second Maturity Elements in This Is What Will U Will Update in Front Maturity Security Element with Corrupt Elements And They Will Update The Frequency Of Current That Bloody Puncture Second Element Gathered With 212 220 Increase Condition In This Question Oil A Valid Reversal Belcom Pure And Electronic Systems And Will Get Values Which Will Get In Action By Economic Will Get Values Which Will Get In Action By Economic Will Get Values Which Will Get In Action By Economic Contenders Aditya Contenders You Worry Ambiguity Elements By Repeat Message B12 And Note 3 Not A Majority Elements But These True Values Economic Contender To These True Values Economic Contender To These True Values Economic Contender To Vikram Slow Joe Elements One And Three Election Once Up Subh To Values Laxative Election Once Up Subh To Values Laxative Election Once Up Subh To Values Laxative Will Do Turn Off But Will Do Will Again Trend Golden Will Half Golden End Will count given that bill account frequency of equal to one and account se frequency of bike one to three layer after depression is over can become artist are traveling to work with frequent only fence maturity elements comes out with great joy where woman moan and dinner answer is The value of liberty element come out to be a great effort and 223 days on death will again up and answer in that case Subha K Vinod add Maxim to make roti element can represent those people share more than battery minimum of unemployment element can also give president O 90 Swadesh Wapasi Loop In Which Were Cheating With Frequent See Over Two Contenders Is Equal To One Wife 231 Se Zilla Account Express And Why Should They Control Plus B Town 10.50 Sudesh Bolti Ho Plus B Town 10.50 Sudesh Bolti Ho Plus B Town 10.50 Sudesh Bolti Ho Gap Rochak Murals Voting Algorithm With Nothing To Always Strive To Check weather this content does not exist in the Vedic Math the weather heart cant element easy to introspect and majority element notification by forms and where to check weather the frequency of current maturity elements of majority element A0 and not give this a sequence of zero will Update will update r One And Only Are Values In Action With A One And Only Are Values In Action With A One And Only Are Values In Action With A Contender To Be Completed With Majority Elements Tatlu Kunwarsi And Buddhi Elements With Radhe MP3 And Not Tu Shanti Whole Approach Aayog Ne Jo Like An Approach Not Look At Record Aap Jis Election Hindi Code Is Taken Before Wesners Thoughts My Electronic Format For Elements Maze Contaminated Water Element And Contacts And Controls To Refrain From This Maturity Element Novil Chand Lukha Hande Raphael Condition In This Life And Every Position Only One Main Holi Bankar Edition Absolutely Film Sunil Shetty And Tarf Bachaye Discuss Early Years After Due First Delhi to New Delhi to maturity elements which will be presented Will Have A Frequency Of Acts In Context And Country Wise In Account By Your Accounts This Contest Se 1000 Account So Battery Saver Contacted Account Dandruff Dancer Winner Victor And Then Account Wizo Also Great Dane Her Account Deficit Vice President In Three Languages And Answer Will Happen The also saw Three Languages And Answer Will Happen The also saw Three Languages And Answer Will Happen The also saw minimum possibility of majority element 0ld maximum possibility of majority element to Sudhir Chaudhary whole code and law will run on record that Sachin's setting accepted the commission's district's video thank you
|
Majority Element II
|
majority-element-ii
|
Given an integer array of size `n`, find all elements that appear more than `⌊ n/3 ⌋` times.
**Example 1:**
**Input:** nums = \[3,2,3\]
**Output:** \[3\]
**Example 2:**
**Input:** nums = \[1\]
**Output:** \[1\]
**Example 3:**
**Input:** nums = \[1,2\]
**Output:** \[1,2\]
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `-109 <= nums[i] <= 109`
**Follow up:** Could you solve the problem in linear time and in `O(1)` space?
|
How many majority elements could it possibly have?
Do you have a better hint? Suggest it!
|
Array,Hash Table,Sorting,Counting
|
Medium
|
169,1102
|
83 |
all right so the clicker question is called remove duplicates from sorted list it says given a sorted linked list delete all duplicates such that each element appears only once the first example is the linked list 1 2 and the output is 1 2 because it removes the duplicate one and then the second example is 1 2 3 and the result is 1 2 3 because it removes the duplicate one and the duplicate 3 so when we start out we already have a variable called head so I'll just name it H to save space what we need to do is we need to have another variable called current and current will be whichever linked list node we're on and I don't denote that by the letter C all right just to show you how linked list works each one of these is called a node and each node has a valve property that is associated with the number in the drawing and a next property which points to the next node in the linked list and when you get to the last node you know it's the last node because it has a value like everything else but its next node points to a null linked list node all right so now that we know how a linked list works let's begin so as we said before right now head and current are the same we're going to keep head in the same place but we're going to move current along the linked list and I'll show you what so right now what we have to do is we have to check whether current Val is the same thing as current dot next dot Val it is so what we have to do is we have to reassign current dot next which is pointing here to current dot next which would be this one so now what you'd see is you'd see current not pointing to - alright let me current not pointing to - alright let me current not pointing to - alright let me clean this up a bit okay what's the next step in order to do the same comparisons later on in the linked list we have to reassign current to whatever is now current dot next is now - so now we move current to here now we - so now we move current to here now we - so now we move current to here now we do the same thing we check of current Val equals current dot next up Val it doesn't so in this case we don't have to change its next reference so all we have to do is change current reference so now again we change current to be whatever current dot next is alright now we do the same comparison this current dot Val equals current next dot Val it does so now we have to skip over its next reference by pointing to its next reference so again it's next is three so we have to do next dot next which is null should be this again let me clean it up and now we're done why because current is not null but Kurt's next reference is null so now all we have to do is redraw the linked list to make it clearer so it is one its next reference is now pointing to who's next reference is still pointing to three who's next reference is now pointing to null so this would be the answer what the duplicates removed all right so let's start with what lead code has given us it's a function name to delete duplicates which accepts a head and the head is just the head of a linked list and it represents the entire linked list it's not just the head all right so if we look to the left let's look at the diagram with the arrows so the number one represents the head of the linked list then it points to another node that has a value of 3 which points to another node which is a value of 4 which points to another node which has yet another value of 4 which points to null and if we want to see it represents it another way let's look all the way up above the first node has a value of 1 and what does it point to its next property points to another node that has a value of 3 what does its next property point to another node that has a value of 4 which points to another node which has a value of 4 which points to null all right so let's start remember the first thing we have to do is we have to keep track of the current node so I'll just put that here let current equal head now we have to loop over the linked list so we'll say while current doesn't equal null and current dot next doesn't equal null and I'll show you why that's the case so it's pretty obvious that if current becomes this node that we're done right but we'll also be done if current ever becomes this node and why is that because we're at the last node with the value which means we can't remove any more nodes all right so let's get rid of that ok now let's do the comparisons first one if current dot Val so if current value equals current dot next dot Val meaning the node that it's pointing to does it have the same value as the current nodes value well would we do we would skip over the next node but in our case right now current value doesn't equal the next nodes value which is three so we'll go into this else statement we would say current equals current dot next so current wouldn't now be this then it would start the next loop and do the same comparison this current value equal the next nodes value current values three and the next nodes value is four so no so again it goes into the else statement and reassigns current so the node that current is pointing to then it goes to the next loop in the while loop and asks again does the value of the current node equal the value of the node that it's pointing to yes it does so in this case what do we have to do we would have to reassign currents next property not to the next node but to the node after that so it would look something like this instead of pointing to four it would now point - no and let's do that above so current - no and let's do that above so current - no and let's do that above so current dot next so current is for current dot next will no longer be this it will look at what it's the next property is and reassign it to the next property after that and in the code that would be current dot next equals current dot next but notice at this point we have an actually reassigned current that comes in the next loop so remember what the while loop checks it checks whether current doesn't equal null and current dot next doesn't equal no at this point current dot next actually does equal null so it breaks out of the loop and now that we've broken out of the loop let me just redraw what the linked list would look like now so 1 points 2 3 which points to 4 which points to null and then we return the head so return head and remember head isn't only the head of the linked list since it's connected to every other node in the linked list returning head returns the entire linked list alright so now let's see how we did looks good submit it alright so our solution was faster than 93% of JavaScript faster than 93% of JavaScript faster than 93% of JavaScript submissions so as usual the code and written description are linked down below see you next time
|
Remove Duplicates from Sorted List
|
remove-duplicates-from-sorted-list
|
Given the `head` of a sorted linked list, _delete all duplicates such that each element appears only once_. Return _the linked list **sorted** as well_.
**Example 1:**
**Input:** head = \[1,1,2\]
**Output:** \[1,2\]
**Example 2:**
**Input:** head = \[1,1,2,3,3\]
**Output:** \[1,2,3\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 300]`.
* `-100 <= Node.val <= 100`
* The list is guaranteed to be **sorted** in ascending order.
| null |
Linked List
|
Easy
|
82,1982
|
45 |
hey what's up guys uh this is sean here so this time uh today's daily challenge problem right number 45 jump game number two um so given like an array right and you're initially standing at first index and each element in this array represents the maximum jump length from this position and your goal is to reach the last index in the minimum jump and you can assume that you can always reach the last index okay pretty straightforward right basically you have a numbers here you have a list of numbers here and at the beginning you are standing at this one and your goal is to jump to the end to here right so from index 0 you can jump two which means that you know from here you can jump to here right that's the basically that's the maximum jump length right which means that the furries you can jump with this one but you can also jump to three right that's why you know for in example two here the answer is two basically from the optimal solution is from two we can jump from this first index we can either jump to three or one but in this case we jump to three and then from here you know we can jump all the way back to the end that's why the answer is two right yeah so that's it right i mean so for this one you know it's obviously we can i think we can use like a dfs approach i mean basically you know but probably we cannot uh just blindly you use like uh brutal force way because you know let's say for at each of the location base when i'm saying brutal force i mean from each of the location you know we simply just try to jump to each of the places right after of this like kind of array but probably we can also do that because even though this kind of numbers it's pretty big but the length is the length it's only one thousand right so which means that you know at each of the at each half the location you know oh the maximum iteration we need to do is only one 1000 right that's why you know even if it's a brutal force we can probably still solve this problem but if this one is like also 10 to the power of 5 right the length of that no probably we cannot we will not be able to use the brutal force way to solve this one basically when i say brutal force i mean at each of the location i try each of the possible jumps and then i also maintain like the steps we have taken right and in the end we just get the minimum amount out of those kind of uh possible ways okay so instead you know for this uh problem we can use like a greedy right because you know it's kind of obvious that you know we always want to jump as far as possible right and so for this one actually it's another very classic example of this kind of called lazy greedy you know for those who don't know what late lazy greedy is so lazy greedy is something like you know we simply just uh keep going you know and whenever we cannot uh moving forward we go back to see what was the what could have what we could have done optimally to make us uh go in further right so in this case is that you know let's say we uh you know at the beginning you know we're standing at here you know whenever we cannot moving forward you know we go back to see okay so when was the so what was the maximum place we can jump to uh from the indexes we have been uh we have been processed so far if right if that and then we pick the biggest number from one of them right and then it means that okay so from it means that okay so since we cannot move forward it means that we will basically going back to that index that can make us jump the furthest and then we'll jump from there so which means that you know we have two three one four right so you know our initial state you know since we are standing at index one zero here you know from here that we only we don't have any other options but we have we can only jump to here right which means that you know the furthest we can jump is zero one two okay right that's the furthest we can jump and then from here we go we come to here right so from here you know we see that okay so the current index is one is still within two which means that we don't have we don't need to jump right but we can maintain like the maximum uh maximum of places we can reach right so in this case what's going on what will that be basically it will be a three plot it'll be one plus three equals to four right if we ever want to jump from here and then from one here you know two is still not equal to not greater than two here which means that you know uh so here we don't need to jump either so here what's going to so what will be the maximum place we can jump to from here it's going to be two plus one right which will be three right three is uh smaller than four so that's why we still keeping this four but when we reach here you know the i is 3 right 3 is greater than 2. so which means that you know if we ever want to uh reach to this place okay we have to make one jump right but which jump of course we want to make jump from this one which is the which is this which is the biggest one of this one and whenever we make a jump from here you know then we know that okay uh the farthest we can go is four right so we which is this one you know that's why you know when we reach this four here and we know okay we still don't need to make another jump okay that's basically the idea of this kind of lazy uh greedy approach no so let me try to implement the first brutal force uh solution real quick you know just to show you guys what's the what did i mean okay so it means that you know we're gonna have like a dp function here you know so the only state we have is the index basically dp's dpi index means that you know from this current place right what's the minimum steps we need to make uh to raise to the last index right so that's going to be the dp solution for the first brutal first way you know and so it's pretty straightforward so at the beginning we have system.max the beginning we have system.max the beginning we have system.max right size you know and then for i you know basically we from the current index we try to jump to each of the possible uh places right as long as we can reach that right basically it's going to be a index plus one you know since we want to jump at least one right and then we stop at index plus the nums dot index and then plot plus what right now we have answer equals to the minimum of the num answer down one plus because we make one jump right the dp of i right and then we return the answer right so what's going to be the exit condition where the you know if the index basically is either equal greater than n minus one right then we simply return zero we do we als we also use this kind of greater means that you know since this range you know could be more a bit exceeding the length of this index at the length of the nums here you know if that's the case we also return zero because we know okay we can also jump to the last one right so yeah and then we simply return the dp 0 right that's it so if i run the code here oh okay i have i forgot to define this length here this is going to be the length of nums okay cool so if i submit right there you go right so it works now as you guys can see so this for this one you know the time complexity for this you know since here we have like we have n right and for each of the n here you know we also gonna do another for loop here so assuming this kind of uh have the same magnitude so it's gonna be a n square time complexity right that's why i said you know this one passed capacity because the length is pretty small if this one is 10 to the power of 5 this solution will go tle okay cool so and then for the greedy one right then which means we need a better solution for this one which is a greedy one in this case it's like a lazy grady right so for a lazy greedy uh we also need kind of the length of numbs here you know and so in the answer we also start we start from one right uh we start from one um actually there is a special case you know because here you know we're assuming we'll make at least one jump but this length you know could be equal to one right so if there's only one like numbers it means that we can simply uh return zero because we don't need to jump so basically if the n is equal to 1 right we return 0 right otherwise you know we're assuming we'll at least make one jump right and then the max the current the max we can jump is as a starting point is nums of zero right and then we have a current basically the current will also be the numbers of zero so this current means that you know the so this one is the current uh farthest place index we can be okay so that's why you know for i in the range of 1 to n right we compare if the i is greater than the current right so it means that you know if the current i has uh x has passed the farthest index we can be right and then it means that you know we have to go back to find basically we need to jump right but which one we need to jump to it means that we have we need we'll jump to the place where this like the maximum can uh tells us that's why first we know we're gonna increase the answer by one right and then we're gonna jump to that place if we jump to that place you know we're gonna update this one currently gonna be the maximum right and then the right thing is that we're gonna keep maintaining this max right and then we have this kind of i plus num psi right and then we return the answer in the end so i think that's it right yeah there you go right so as you guys can see so this is how this lazy uh greedy works basically the greedy means that you know we always maintain the uh the maximum place we can jump to you know for the index we have been seen so far and we not we never and we just keep going you know a lot until we cannot keep moving that's when we will go back to pick like a previously visited index position to make a jump right but which one we need to make we always pick the maximum one you know so for this kind of lazy one you know uh for other problems for uh to use lazy uh greedy you know we often use that priority queue right to maintain either the minimum or the greatest or the biggest you know element but for this because for that one because we might need to some uh the reason we used the priority queue was because we might need to use some seconds some other like uh elements other than uh once we have used the uh the biggest one but for this one we don't need to use a prodigy because you know um we always want to basically use the uh things this thing is always increasing right that's why you know we always need to maintain like one maximum uh locations we have we could have average jump to right that's why you know whenever we cannot jump anymore we increase our answer by one and then we'll update this current one which means that you know okay so now i'll make the jump right but i'll jump to the farthest the place possible right and then the next and then later on you know when we uh keep then we can keep moving right keep moving forward at least to this current place okay and yeah and as you guys can see this one is simply like a o of n time complexity right even if it's like 10 to the power of 5 we can still pass yeah i think that's it right for this problem and thank you for watching this video guys stay tuned see you guys soon bye
|
Jump Game II
|
jump-game-ii
|
You are given a **0-indexed** array of integers `nums` of length `n`. You are initially positioned at `nums[0]`.
Each element `nums[i]` represents the maximum length of a forward jump from index `i`. In other words, if you are at `nums[i]`, you can jump to any `nums[i + j]` where:
* `0 <= j <= nums[i]` and
* `i + j < n`
Return _the minimum number of jumps to reach_ `nums[n - 1]`. The test cases are generated such that you can reach `nums[n - 1]`.
**Example 1:**
**Input:** nums = \[2,3,1,1,4\]
**Output:** 2
**Explanation:** The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
**Example 2:**
**Input:** nums = \[2,3,0,1,4\]
**Output:** 2
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 1000`
* It's guaranteed that you can reach `nums[n - 1]`.
| null |
Array,Dynamic Programming,Greedy
|
Medium
|
55,1428,2001
|
1,603 |
Let's talk about a Brahmin who has problem vs. Joe's design fighting system. What problem statement do we have in this? Designer parking system for parking lord dufferin lottery cancer packing specific medium and small with this number has lots of size so implementing the calling system class we are one. Parking system class is to be implemented which is a class of ours in which we are given contractor first system and in it I have three variables back medium smart so it is saying problem statement's parking system inter big inter medium and in text mod in its objective the parking System class body more benefit of the first look in parking system basically that parking lot is given to us then big represent tomorrow in parking lot media and subscribe to the association so now till us it is said in the statement that check weather while this parking specific And Dakadash want to get into the parking lot subscribe example on our three lines bake medium and small Thursday so basically the appointment system and we add na to us fakr subscribe so now appointed here now we na subscribe is 12345 One two and three will be represented. If ka is type-1 then she will go to back type If ka is type-1 then she will go to back type If ka is type-1 then she will go to back type parking space. If ka is tattoo then she is medium type and stays in the but again space then she will go to small task parking space. So if I here Let's see, the passing system has been given to us, parking system, that is, one space in between, one space in the space and subscribe in here, if you have not subscribed here, then subscribe, like, subscribe for specific, one in then, if I first, see this here. So no, this will be a tap for the parking system and it will add it like if it is Vansh's telephone then contact phone I have found that the reason for parking space of bigg type will be happy then special for the tax type. Day given that means one obstacle then he has subscribe to subscribe niyudh subscribe on upper back side subscribe this subscribe if I design well then first of all I take a global variable then and boy comedy gum crow small that I Brother, why am I telling you, what should I do? This is the tube in the bag, this is my ghagra, this is in the back, I will be able to access it from anywhere, this is the global fortune and this is the local level, this is class math, this is the internal source of the contractor, these are the five tractors which If the country also brings patience, then this is how it is directly request to back 210 run medium request low medium this is the best small request Osman put on deputation that whoever subscribes in the war, here he does it for me, he does it from anywhere. Here I will select the parking space, I am copying the type of the required type, Loot is the English typescript, if the type is one or bigg, then what will we do in it, see that we have space in the parking space. That's okay, you click on the parking space button, we have space, so what we will do now is that this is subscribed, already subscribed in type, then appointed in that, second one, if you are okay, then we will check. Those apps which cartage request to two and lag increase are our crazy medium, so let us set whether there is some space in the medium parking space or not. Madam, if there is climbing in the polythene space i.e. battles and then if there is climbing in the polythene space i.e. battles and then if there is climbing in the polythene space i.e. battles and then that time enters the medium parking space. If this medium car enters the parking space in a working quality, then we will do it on - - quality, then we will do it on - - quality, then we will do it on - - now we have left that place, we will do it again that type question three and a asmall key were greater i.e. the reason for Abu Ismail type were greater i.e. the reason for Abu Ismail type were greater i.e. the reason for Abu Ismail type That is, on this occasion, if the car type depression paratha, then it enters the small parking space, then the enemy has entered the parking space, then at that time, if the car is sitting, then it returns through and then it becomes the first of the small parking space. - - it becomes the first of the small parking space. - - it becomes the first of the small parking space. - - Do it, we have fixed one place, that has been done, now finally what will we do, if I don't have any place left, we will return the oil and system, we will design our parking system, what happened to both of us? I am submitting, it's time for this festival, you can use it in sentences, thank you so much.
|
Design Parking System
|
running-sum-of-1d-array
|
Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.
Implement the `ParkingSystem` class:
* `ParkingSystem(int big, int medium, int small)` Initializes object of the `ParkingSystem` class. The number of slots for each parking space are given as part of the constructor.
* `bool addCar(int carType)` Checks whether there is a parking space of `carType` for the car that wants to get into the parking lot. `carType` can be of three kinds: big, medium, or small, which are represented by `1`, `2`, and `3` respectively. **A car can only park in a parking space of its** `carType`. If there is no space available, return `false`, else park the car in that size space and return `true`.
**Example 1:**
**Input**
\[ "ParkingSystem ", "addCar ", "addCar ", "addCar ", "addCar "\]
\[\[1, 1, 0\], \[1\], \[2\], \[3\], \[1\]\]
**Output**
\[null, true, true, false, false\]
**Explanation**
ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0);
parkingSystem.addCar(1); // return true because there is 1 available slot for a big car
parkingSystem.addCar(2); // return true because there is 1 available slot for a medium car
parkingSystem.addCar(3); // return false because there is no available slot for a small car
parkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied.
**Constraints:**
* `0 <= big, medium, small <= 1000`
* `carType` is `1`, `2`, or `3`
* At most `1000` calls will be made to `addCar`
|
Think about how we can calculate the i-th number in the running sum from the (i-1)-th number.
|
Array,Prefix Sum
|
Easy
| null |
102 |
them one zero two 102 10 2 1 Nail 2 102 probably 102 on Lee code binary tree level order traversal so this is a medium um it's a Friday I felt like today I was going to approach just maybe an easier problem to get me hyped up for the weekend last thing I want to do is get stuck on a hard and then spend the rest of the week contemplating my entire life um but with that said let's just get right into the problem uh so binary tree level order traversal okay so yeah this is a pretty approachable this seems to be approach party let me look how short it is given the root of a binary tree return to level order traversal of its nodes values from left to right level by level okay so we're given this example so let's just go ahead and go through it so we have three nine twenty 15 and 7. so the first level is here three the next level is here so the next thing is here 920 and then 15 7. Okay so we're going to be searching on this binary search tree we're going to start here at the root now what I think we want to basically do is BFS or breadth first search because breadth first search naturally will kind of align with this level idea right because when breath first search occurs it'll look at this or I guess yeah breadth first search occurs it's going to look at this node first and then these two nodes and then these two notes naturally right because how breadth first search essentially works for any kind of tree setup is it always looks at everything at one level before continuing to the next level so the way breadth first search would look for this note is it looks at this one first then it looks at its neighbors on the queue this and this so this one is finished so if I did one by one it would look at this one add its neighbor this one's finished look at this one Addis Neighbors now this one's finished for this one look at his neighbors now this one's finished this one look at its neighbors no neighbors this one look at his neighbors finished this one look at its neighbors now it's finished there's no more on this level this one look at its neighbors no more look at his neighbors no more so the way that breadth first search will basically work in this case is we'll create a cue which is the root and then there's while we have something in the queue well expand or add everything inside of the queue is at that layer or at that level so append levels with q and then we'll explore Q to update with neighbors of the levels thing here and then return levels so basically we look at whatever's in the queue here right in this example it'll start with just three in the queue these neighbors will get added to the queue so we start with three in the queue we add that to the levels then we go add the neighbors then we add that to levels this is so sloppy I'm sorry I'm trying to go through this video quick today then we add the neighbors and add that and so on and so forth so I think that's the gist of it so let's go ahead and try to implement an example of breath research okay so level order so Q is the root wait can the root can the Q be empty I can't okay so if not root return nothing okay and then we'll just go here so Q equals root while Q so while there's something in the queue we'll have levels here be empty levels append a copy of the Q as it is and then we'll say Q equals the neighbor or the I guess since it's a binary search to be a child for each node in the queue for each child in the nodes left and the nodes right so for the nodes left and the nodes right of the current item in the queue if that child exists and then we return levels okay so it's looking like I need to do the um The Q's valued not the tree itself just the value at the tree so Lambda node so for each node just the nodes vowel now that's going to be a map and not a oh I guess it doesn't matter if it's happy I'm happy oh looks like I've done this problem before a long time ago okay well that's how it goes all right thank you
|
Binary Tree Level Order Traversal
|
binary-tree-level-order-traversal
|
Given the `root` of a binary tree, return _the level order traversal of its nodes' values_. (i.e., from left to right, level by level).
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[3\],\[9,20\],\[15,7\]\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[\[1\]\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-1000 <= Node.val <= 1000`
| null |
Tree,Breadth-First Search,Binary Tree
|
Medium
|
103,107,111,314,637,764,1035
|
46 |
hello boys and girls and welcome to another episode of your favorite algorithm channel my name is Ryan powers and today I'm gonna be taking you through leak code 46 permutations so let's introduce the problem given a collection of distinct integers we return all possible permutations well that was a pretty short description but let's take a look at the examples here so the input is going to be a set of numbers of distinct integers so 1 2 & 3 numbers of distinct integers so 1 2 & 3 numbers of distinct integers so 1 2 & 3 and we need to return all the possible permutations in an array of the like possible arrangements of these numbers right so 1 2 & 3 right so 1 2 & 3 right so 1 2 & 3 well there's 6 possible Arrangements right there's 1 2 3 just 1 3 2 there's 2 1 3 there's 2 3 1 2 & 3 2 1 right 1 3 there's 2 3 1 2 & 3 2 1 right 1 3 there's 2 3 1 2 & 3 2 1 right this is uh this is probably the smallest example that we could give that actually kind of gives you an idea of like what's happening if we did four it would get exponentially larger which is just a hint at what the time complexity this problem is actually going to be but as always I encourage you to try the problem on your own first and if you get stuck or you just want to see how I solve the problem then come and check out the video otherwise if you're ready to get started come with me to the white board on the screen here I have our number set here so these are the numbers we need to make all of our permutations with so we have the number 1 2 & 3 so what I want to do here is 1 2 & 3 so what I want to do here is 1 2 & 3 so what I want to do here is we're going to use recursion to solve this problem so what I want to do is I want to draw the recursive tree and I want you to follow along with the execution of this function I'm going to talk through the execution of this function keeping track of our variables and I want you to see if while following along with this recursion tree if you can kind of construct how this tree is or how to construct the code that this tree is representing so let's go through how this recursion tree is building itself talking through the execution of the recursion tree in general and I want you to see if you can construct this function based off of this recursion tree and this is what I do every time I build a recursive function I draw the recursion tree I draw the Kuragin pattern of how this tree might be constructed and if I can get myself all the way to the to every single answer then and I can draw the tree then I know I can write the function right it's just a matter of getting the order of the calls in the right order so let's go through the recursion tree and I want you to see if you can create the function based off this recursion tree okay so what we're going to do is we're going to iterate over this array and at each iteration we're going to be taking a number and adding it to our set and then we're going to remove that number from our possible numbers to use this array represents the possible numbers that we can use right so we're going to take one and then we're going to remove it from our possibilities okay so at each iteration we're going to grab a number and then remove it from the Urich so let's start with the number one here we're going to iterate over this array where I is equal to zero and we're going to take one and we're going to remove one from our possible numbers we can use so we're just going to be left with two and three well so now we're going to be iterating over this array here two and three right so we'll start at the first position where I is equal to zero and we'll take two and we'll push it into our poplar or number set right and we need to remove it now from the numbers that we can use so now we just have three so now we're going to iterate over this array making a call to our permutation function where I is equal to zero and we're going to push three in and we need to remove it from our possible numbers we can use well here's our base case right all right now of notice we can use this empty so we cannot we have no more numbers we can use so we know we can return from this function call but before we do that we want to push this into our answers array so now we have an answer of one two and three and we're going to return from this call here where we have no more numbers left to use bringing us back into the execution context of this function call where we had an answer set of one and two and a number an array of numbers we can use of just three what we had already iterated over that array where I is equal to zero so we are not going to iterate anymore we're going to return from this function call back up to the execution context where we just have one in our number set and two and three are the numbers we have to use well we have just iterated over where AI is equal to zero so now we'll increment I now I is equal to one so we'll add three into our number set removing three from the numbers we can use and now we will iterate over this numbers array where we have two to use so well iterate over that array where I is equal to zero taking that first number and we'll push it into our number set well we need to remove it from the numbers we can use so now our the numbers we can use is empty so we can return from this function call but before we do that we want to push our answer of 1 3 & 2 into our answers our answer of 1 3 & 2 into our answers our answer of 1 3 & 2 into our answers array so now we're going to return from this function call returning into the execution context where we had 1 & 3 as execution context where we had 1 & 3 as execution context where we had 1 & 3 as our answer set as our number set and we had 2 as our numbers we can use well I is equal to 0 so we've already iterated over that value we have no more iterations to make so we'll return from this function call back up to where we just have 1 in our answer set and we have 2 & 3 as numbers we can use well have 2 & 3 as numbers we can use well have 2 & 3 as numbers we can use well I is equal to 1 in this execution context so we cannot iterate any more over this array so we'll return from this function call back up into the original call to our function where I is equal to 0 and we still have 1 2 & 3 as equal to 0 and we still have 1 2 & 3 as equal to 0 and we still have 1 2 & 3 as the numbers that we can use so we will iterate we increment I and we will push 2 into our number set and we'll remove it from the possible numbers we can use so now we have 1 & 3 as the numbers we so now we have 1 & 3 as the numbers we so now we have 1 & 3 as the numbers we can use and we will iterate over this array so I is equal to 0 and we'll take that first number which is 1 and we'll push it into our number set and remove it from the numbers that we can use so now we just have one number left in our numbers array so we'll iterate over the out so I is equal to 0 and we'll push that into our number set and remove it from the numbers we can use well our numbers who can use it's now empty so we'll return from this function call but before we do that well push the number set to 1 3 into our answer set will return from this call back into the execution context where we just had 2 & execution context where we just had 2 & execution context where we just had 2 & 1 and we can't iterate anymore over this numbers array I was equal to 0 if we concur we increment I we have no more numbers to look at so we return from this function called back up to the execution context where we have to and our number set and 1 and 3 is the numbers we can use well I was equal to 0 in this execution context so we can increment I and we can now push 3 into our number set removing it from our possibility so if numbers we can use so now we will iterate over this number set here or this possible numbers array where we just have one item so I is equal to 0 and we'll push that into our number set and remove it from the possibilities of numbers we can use well now this is empty so we'll push this into our answers and return from this function call back to the execution context where we had 2 and 3 and our number set so we'll return from this call back up to the execution context where we just have to and our number set well is equal to 1 here we can't iterate over the array anymore so we'll also return from this function call back up to our original call to this function where I is equal to 1 and the number of possibilities are 1 2 & 3 well we can possibilities are 1 2 & 3 well we can possibilities are 1 2 & 3 well we can increment I so we'll do that is equal to 2 so we'll take 3 and we'll remove it from our possibilities so now we can our number of possibilities are 1 & 2 so number of possibilities are 1 & 2 so number of possibilities are 1 & 2 so we'll iterate over that where I is 0 passing in the number 1 so now we have 3 in 1 we need to remove one from our possibilities so now we just have 2 so we can iterate over that where I is equal to 0 pushing 2 in to our number set and removing it from our possible numbers we can use well now we can push this answer into our answers array and return from this function call so we'll move back up into the execution context where we just have 3 & 1 as our number where we just have 3 & 1 as our number where we just have 3 & 1 as our number set and we can't enter it anymore so we'll return from this function call back up to where we just have 3 and our number set well I is equal to 0 we can iterate once more so we'll increment I and we'll push 2 in to our possibilities of numbers we can use we need to remove it from our number set now we just have one so we'll iterate over that pushing 3 in to our number set so now we have 3 2 & 1 & 1 & 1 the numbers we can use are exhausted so we can push this into our answers all right so let's do that really quick so now we have three to n1 okay so now we've used so now we will return from this function call where we terminated here with an empty array of numbers we'll return from this function call here where we just have three and two we can't enter it anymore and we'll return from this function call here at the top where we just have three because I was equal to one we can't iterate anymore and we'll return all the way back up to the top of our tree where we have one two and three and I is equal to two we can't iterate any more so we will finally return from this original call our answers are answers array so I hope that was a helpful depiction for you of kind of what the recursive strategy of this function is and now I think it would be useful to just go over a little bit of the time complexity so what's the time complexity of this problem well the time complexity of this problem is a Big O of n factorial right and why is it n factorial well the first time we have three numbers in our and our answer in our possible numbers we can use so we have to make a function call for every single one of the possible numbers right so that's going to be three so we're going to make three function calls so each one of these function calls is now going to have to make a function call for each one of the left over items in the possible number set right so that's going to be two so that's going to be three times two function calls so we have one two right so each one of these is going to make two function calls so we had these two function calls here and then we're done right we're done accumulating them because there's only one left so there's only going to be one more function call made for each one of these items and we're done but you can imagine if we started out with the number four well each one of those would make n minus one function calls right which would be three which would then make n minus one function calls which would be two which would then make n minus one function calls which would be then one right so you can see how this grows factorial right so the answer here is 6 we have six answers here right but if we had six if we had if we were doing the number four well we would have 4 times 3 which is 12 times 2 which would be 24 so we would had 24 answers right so you can so this is a pretty terrible time complexity but there's no other way to grab all the permutations of this problem anyways so now that we kind of understand the strategy for solving this problem let's go ahead and see how we would implement this recursion tree in code we don't need any helper functions today to build this permeant function we'll build all the functionality that we need inside of this recursive call to this permutation function or permit so I have added a couple of extra variables here I've added an array variable which is going to be initialized to an empty array I have added an answers variable which is just going to be equal to our answers or just going to be an array that houses all of our answers so we'll be pushing our answers into this right we're going to initialize it to an empty right so when do we want to push an answer into our answers array well we know that if we don't have any numbers left to choose from if num cell length is 0 if it's false t then we know that we have exhausted all of our possible nums right so we can then push an answer into our answers right so let's start there so if not right if not num stock length so if num if not none salt length it numbs that length is 0 then we want to push a push in to our answers array a copy of our current set of numbers which is going to be represented by the array variable you know what let's change that to set to number set so let's do set we'll call it set so this is our current set of numbers so what do we want to do if this is not the case if nums dot length is truthy meaning we still have numbers left to use what we want to iterate over them right so we can create a loop so well let I be equal to zero and then while I is less than gnomes dot length what we want to iterate so what do we want to do inside of this loop well the first thing we want to do is we want to copy we want to remove the current or remove the current number right we want to remove the current number from our gnomes so we can create a Const because we don't want to mutate our current array of gnomes we want to pass in a copy so that we aren't mutating our current number set because we're going to be removing numbers from them at every function call so we'll create cons called new nums and we'll set that equal to numbs dot filter so we want to remove the current index so we'll say index and we'll just return that index does not equal I so we'll grab all the numbers that don't have that current index so that will filter out all of those values and then we want to do what we want to push in the current number into our answer set so we'll do answer push and we want to push in nums at I okay so now we've pushed in our current number that we've chosen and then we want to make a recursive call to our permute function so we'll call permute and we will pass in our new nums with the removed number and then we also want to pass in our current set of numbers which is going to be set we renamed that so it's going to be set so we want to pass in our set of numbers and then we also want to pass in our answers okay so that is going to take care of all of our recursive calls but what do we want to do once we return so what's our base case is we have no more numbers to iterate over so we can handle that by just returning the answers at the end so what happens when we iterate through all these numbers and we return from this function call what do we want to do after we return from this function call well we are using this set to keep track of our answers so we're pushing in a number before we make the function call but we want to remove that number after we return from that function call so if we had just used the number if we were starting with the number one and we had an answer set of two and three left we use the number two we push in the number two when we return from that final function call we want to pop the number two out and then do a function call where we use three as the second number right so we want to do one two and we want to do one three so we need to pop that number out so set that pop the last number out so we can add the next number is okay so this basically this is taking care of all of the logic for solving this problem so let's kind of go through what we did here so we check to see if we have any numbers left to use if we don't that means we know we can push in an answer to two our answer array now we're going to loop over the current num set so the current nomes right and we're going to remove the current number and then we're going to push in the that current number that we're on and then we're going to make a recursive call with that updated numbers that we have to choose from and then our set of numbers that we have picked so far and then our reference to our answers okay and then when we return from these function calls we're going to pop out that last item and add the next number in we're going to iterate and then add the next number in okay let's see how we did okay and let's submit this see if we have any bugs Oh looks like we do have a bug okay what do we got here unexpected token mmm I forgot a dot here okay let's try this again all right okay 88 milliseconds 71 percent that's pretty good I'm happy with that let's check out let's see what the distribution looks like you okay so we can see that the distribution here is pretty tight I mean it's a runtime a factorial so if you did solve this problem you had the same crappy run time as everybody else but anyway I wanted to cover also the possibility that the space complexity you could probably also represent as factorial I have seen some differing opinions on whether or not you include the answer as part of your space because you're not using extra space but the runtime complexity for sure is factorial so it's a pretty terrible runtime anytime you're doing a permutation problem so permutation string permutation numbers whatever any time you're getting all arrangements of something you are doing factorial work right so that is kind of the important takeaway of this problem anyways I hope that you enjoyed this video I hope that you learned something and I hope to see you in the next one
|
Permutations
|
permutations
|
Given an array `nums` of distinct integers, return _all the possible permutations_. You can return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\]
**Example 2:**
**Input:** nums = \[0,1\]
**Output:** \[\[0,1\],\[1,0\]\]
**Example 3:**
**Input:** nums = \[1\]
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= nums.length <= 6`
* `-10 <= nums[i] <= 10`
* All the integers of `nums` are **unique**.
| null |
Array,Backtracking
|
Medium
|
31,47,60,77
|
202 |
Have fennel seeds students from this question of list to division happy number is ok so basically it is a saying that if the number is not shifted then it is not there so we have to say that whatever number is there, cross it and add it while riding. Do it last, if he goes to the net mention number is happy and if he is not there then you have to print the pass and go to that place, now how to do it, I will understand one thing tomorrow that this number is ours otherwise it is fine yes then here. But as long as there is a number, this number is fine, do n't ask this question a little, you need observation and why observation is needed, you will know in the next statement in this lesson 5 that the end is not a fast when one day the force will return to you will say forcefully. What is the meaning of this, if you have written it, then you yourself check whether you take the thought, but here too, your test is on Tokas, it will be yours, and on Kass, sixteen, then the Oscar award will be yours, 3730 subscribe, let's go, never that last. Meaning, you will not reach one, you take the free like this, you take the four, it's okay and in the same way, you take the six, take your time, it will definitely come if you get these Akola, okay, how are the tests, okay, if it takes seven. So see, your one will definitely come last, okay, just give us the answer that the end is Sumit one or there should be an end lineage, okay see, that means from two to the toe, the end function is not confirmed, it is okay and if both these statements fail. So what we have to do is that I want to call a new number, this new number will be 10 houses, so Z plus post means new number, we will use the power function, we will take the picture of this water tank and okay and we will give it to the friend. Divide Baghwa number, we are calling, then what to do now, if you have a thought in your mind, check it immediately here and if it is Z1, then return it, chat, if there is no talk, then ask the question, then it means I am yours. There is no need to do this, we will do it, friend, use Karsan, take rest and single out that number here, it will not affect you much because in many such cases, if you click here something like plus one, then here your It has a lot of effect till it goes on, we will try the program in all things, then we will tell you, okay now it works, it means something like this in the program, so if it has to be done in between others and then after calling the number, we will join it. That means we will record part of the function, after recording it will be checked again and one day or the other we will get it. Okay, now when one is made, it will definitely be used. Okay, that's why I am doing it. Let's see whether it works or not. I will put it in the description and check it's my old one chapter, it's fine, so I need mercy, okay, I just wanted to say that I wanted to check, in which the question has more meaning, it will be good, then subscribe the channel, like and share, thank you. net
|
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
|
59 |
the question name is spiral Matrix second to understand this question uh very easily we have to just go through first a spiral Matrix one I have solved this question also so that question also the question is given a positive integer and generate an N cross n Matrix filled with elements from 1 to n Square in spiral order the interesting thing is question is we have to store the elements in spiral order what is parallel order spiral order is just we have to go in this manner okay first this then this and what you have to do we have to store the elements in a matrix which is a n cross end like FNS 3 we have to generate a three cross three Matrix where the value of the mat the value of the numbers are from 1 to n Square means 1 2 in this case from 1 to 9. and what we have to do we have to store the elements in this spiral order so one two three okay we have gone in this direction now for the order is 3 1 2 3 so we have to go now in this direction four five now column are also the row are also three okay now go in this Direction six seven now column R3 go in this direction eight here row R3 go in this direction nine so we have stored successfully we have gone in this Direction first then in this direction so we will easily solve this question we will take one four variables like row Row one this is the upper row is Row one the lower row is row two this is column one and this is column two we'll take four variables first is Row one row two column one column two and one is value okay so Row one is this row and Row 2 is last row is n minus 1 and row column one is this column zeroth column two is last column and value is zero and uh to store the answer we have taken a v now until uh when we will stop when this row this R1 is greater than this R2 or end or this column C1 is greater than this column seat so until this is true we will continue to run so first in which direction we will go in this direction to go in this direction we are moving from column one to column two and we are storing the value now what we are doing we are going in first in this direction so the end points of this directions are column one this is column one and this is column two so we will store the elements okay now we have to go in this direction but this row we have filled this is R1 to go to fill the elements in this direction we have to first increase the row from this Loop we have to increase the row we have to go in next row so we will say R1 plus and the end points of the this direction are from R1 plus 1 to or R1 to R2 so what we are doing we are simply first we are simply storing the elements from C1 to C2 Value Plus plus and then we are saying R1 plus 1 to R2 Value Plus plus now if we will check again if R1 is less than R2 and C1 is less than C2 then we will move in this direction and in this direction we'll move in we will move to left and we will move to up okay so this to move now we have stored to now what we have done we have stored this column now what we have to do we have to reduce the column we have to reduce C2 okay we have to reduce C2 so what we are seeing from C2 minus 1 to C1 we are going from C2 minus 1 to C1 and we are storing the value similarly we are going from now we have now what we are doing we have stored this row okay now what we have to do we have to minus the R2 we are going from we are going to previous we have to minus R2 by minus 1 okay so we are going from this R2 to R1 actually we have taken the effect of this Row in this value which value in this value we have increased the R1 so we don't have to take care of this R2 so we are simply saying from R to R1 when R1 is then I when I is greater than R1 we have to just store the value like what I am saying when I is greater than R1 because I have taken the effect of this Row in R1 plus 1 so I don't have to reduce it again it last in after this Loop what we have to do we have to just simply R1 plus 1 this row plus one this column this row we have to minus 1 and this column C1 is plus 1 and C2 is minus 1 according to the direction we have to reduce or we have to increase or increment to decrement the row and column you can run the code you can submit so it is submitting successfully
|
Spiral Matrix II
|
spiral-matrix-ii
|
Given a positive integer `n`, generate an `n x n` `matrix` filled with elements from `1` to `n2` in spiral order.
**Example 1:**
**Input:** n = 3
**Output:** \[\[1,2,3\],\[8,9,4\],\[7,6,5\]\]
**Example 2:**
**Input:** n = 1
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= n <= 20`
| null |
Array,Matrix,Simulation
|
Medium
|
54,921
|
338 |
Hello everyone, welcome, you must have given me a channel, okay if N = 5, then I have made a ray of size N + 1, N = 5, then I have made a ray of size N + 1, N = 5, then I have made a ray of size N + 1, okay, just what do you have to find out, if binary operation is done for each index, then how much forest will be spent, so see, first of all, what is the question? Brother, you don't have to do anything, just count the number of 1's on this zero in its binary representation and enter it. Here, if you want, you can write a separate function or you can do it in a building function. Ho but in popcorn, there is no number in it, dog, no Number one is not hard, I am a producer, you can do many things, it is okay and look at this, let's also check its time complexity. Look at the loop on the outside, brother, follow me. Now I have asked that brother, without building function, solve it and Try it in Off N. Okay, this is a very simple approach. Know how. I look at you like we take mother. If there is zero then there is nothing to be done. Make the return zero. Okay, make the return zero because the binary operation of zero is zero. It happens that there is no 1 beat in it. Okay, now let's see the rest. 123 4 5678910 I see you see this. 110 01 11 00 What will happen to it? What is the half of four? There will be number of bits whose value will be one. Look, there is only one, is it right? Is it true everywhere? Yes, now look at six, see how many numbers are fitted, whose value is one. Six by six, how much is three? Three is near three, which is yes. Look here also there are only two such sons whose value is one, this one has a value of one, here is only one, 8 / 4 this one has a value of one, here is only one, 8 / 4 this one has a value of one, here is only one, 8 / 4 is of 8 / 4, look, this is also the answer of one, is of 8 / 4, look, this is also the answer of one, is of 8 / 4, look, this is also the answer of one, okay, now look carefully, now let's take the mother and make it plus one. Will give, look, this is the proof, just look here, let me show you, I have to find out this nine, it is four, add one to it, add two, it will become two, look, here it is two, okay, now look at some other odd number, let's look at seven. What is the value of 7? If we do 7/2, how much will we get? If we What is the value of 7? If we do 7/2, how much will we get? If we What is the value of 7? If we do 7/2, how much will we get? If we get 3 then let's go to 3. Brother, you have two such sons whose value is one, add plus one to it, go to three. So look, here too there is 3. Okay, so look. Our problem has become so simple. Zero one, you three, hero, one, three, four, five, N = N = N = 0. I already know the answer. Okay, now let's figure out one, see what is one, note it down. Equal, you, zero, one is another number. No, okay, what was done in this, what was the answer to it, what was the result of I, whatever was the account of A/2, one's account was done in that, the story is over, there was a small code and it was all based on observation, this is mathematical in nature, it is applicable everywhere. It happens that if you look at any number, it will be absolutely correct. Let's look at 10 also. Okay, five has how many such fits, the one set has two such buttons, so look at this also, 10 also has two such buttons. Let's code the date quickly and finish it. See what is its time complexity. Let's make it simple and finish it. So let's code it quickly and do both our processes. First of all. So belt in account is the result of n+1 in account is the result of n+1 in account is the result of n+1 and take equal tu n i plus if n=0 then return result is n=0 then return result is n=0 then return result is nothing and then it is ok otherwise then result of zero will be zero in zero what does it mean Binary of zero beat s one is ok, directly put the same check here which we had inserted FI Percentile 2 Result of I what will happen next video thank you
|
Counting Bits
|
counting-bits
|
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`.
**Example 1:**
**Input:** n = 2
**Output:** \[0,1,1\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
**Example 2:**
**Input:** n = 5
**Output:** \[0,1,1,2,1,2\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
**Constraints:**
* `0 <= n <= 105`
**Follow up:**
* It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass?
* Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
|
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
|
Dynamic Programming,Bit Manipulation
|
Easy
|
191
|
71 |
everyone so today we are looking at lead code number 71 it's a question called simplify path so here we're going to be given a string path and it's going to be an absolute path starting with the slash to a file or directory in a unix style file system and we want to convert it into a simplified canonical path so in a unix style file system a period refers to the current directory a double period refers to the directory up a level and any multiple consecutive slashes ie are treated as a single slash and for this problem any other format periods such as triple dots are treated as file or directory names okay so a canonical patch should have the following format it should start with a single slash any two directories are separated by a single slash the path does not end with a trailing slash and the path only contains directories on the path from the root directory to the target file or directory i.e no period or double period and we i.e no period or double period and we i.e no period or double period and we want to return a simplified canonical path okay so this question actually seems a lot more complicated than it actually is let's just break it down and we can see that it's actually not too bad so we'll look at example four here we have an a dot b dot c so we are going into the a directory and then we have a single dot so we're doing nothing then we're going into the b directory then we're moving back one directory from b moving back another directory from a and then going into the c directory so here our output should just be slash c okay so how would we approach this so the way we want to think about this is if we can convert this input into an array we split it into an array on the slash and then what we want to do is iterate over it using a stack okay so let's just take a look at what are the three things we could come in that could be in that array after we split it if we have a single dot what do we want to do we just want to ignore okay if we have a double dot what do we want to move up okay and if we have a double slash or numerous slashes we just want to make that a single slash okay so let's say we took this input and we split it on the slash what are we going to get we're going to get an array that's going to be a dot b dot c okay and if we are ignoring this single slash we can just filter that out right so what we can do is perform a filter on this array after we split it and remove that single dot so we're going to have a b dot c and now once we have our array formatted this way we can think about this using a stack okay let's say i have a stack here and i go ahead and push a into the stack i push b into the stack okay now when i get this dot i pop out b i come here to this dot and i pop out a and then when i come to the c i push c into the stack and so what's left is what is uh the correct file that should be in the file path and then all i have to do is return just add a forward slash or a backslash and then add whatever is in my stack and join it with uh with that backslash okay so we can do stack dot join on a backslash okay now let's just do one more example here i'm going to erase this here and say what if we have two slashes what are we going to do what's going to get in that array when we split it and how does that all work out okay so i'm going to just go ahead and erase this here and we'll just look at one more example if we have double slashes okay let me just go ahead and get this all out of the way clear this all out okay so now if our input here let's say we just have a double slash here and a double slash right there okay well if we split this what's our array going to look like we're going to get an a we're going to get that dot we're going to get an empty string here we're going to get b we'll get dot another empty string and c and so all we want to do is when we get to our array after our split method once we split the array we want to filter out any single dots here or any empty strings okay because they'll represent any uh slashes that are more than one okay and once we filter all those out we can just go ahead and perform the same logic put the elements into a stack pop them out if it's double dots and then at the end join them all together on a slash okay so let's go ahead and move over the code and go ahead and try this out okay so here what we're going to do is we're going to go ahead and create a stack okay and we'll just set it to an empty array and now we want to go ahead and split this path and put it into an array so we can call this path array and what we're going to do is just do a path thought split on a slash here and then we're going to filter out any element that is not a single dot okay and then we're also going to filter out any element that is not an empty element empty string okay so that's our path array now what do we want to go ahead and iterate over this path array and push into the stack accordingly okay so we can say for let name of path array okay and if name equals a double dot what do we want to pop out of the stack okay else what do we want to do we just want to push into the stack we want to push that name into the stack okay and so now at the end all we have to do is we have the correct data in our stack all we got to do is just return we're going to start it with a slash and then we're just going to join our stack on a slash okay and that's it that's all we have to do for this let's go ahead and run this okay and yeah we're good and so let's just think about time and space complexity with this problem here we are creating space relative to the input because we are splitting it into uh an array a path array and also we're creating a stack so our space complexity here is going to be o of 2n which is going to simplify down to o of n so we can say space complexity is going to be o of n okay what about time complexity well we're performing a linear time operation with this split method and filtering that's going to be a linear operation and then we're performing another linear operation as we iterate over the path and we push and pop off the stack okay push and pop is going to be uh constant time but iterating over that path array is going to be linear time so our time complexity here is also going to be o of n all right so it's not too bad of a problem i think the main thing is really applying the pattern of using a stack thinking of this as a stack and having a clear idea of what needs to go into the stack what you need to filter out and what you push and pop out of the stack okay so that is lead code number 71 simplify path i hope you enjoyed it and i will see you on the next one
|
Simplify Path
|
simplify-path
|
Given a string `path`, which is an **absolute path** (starting with a slash `'/'`) to a file or directory in a Unix-style file system, convert it to the simplified **canonical path**.
In a Unix-style file system, a period `'.'` refers to the current directory, a double period `'..'` refers to the directory up a level, and any multiple consecutive slashes (i.e. `'//'`) are treated as a single slash `'/'`. For this problem, any other format of periods such as `'...'` are treated as file/directory names.
The **canonical path** should have the following format:
* The path starts with a single slash `'/'`.
* Any two directories are separated by a single slash `'/'`.
* The path does not end with a trailing `'/'`.
* The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period `'.'` or double period `'..'`)
Return _the simplified **canonical path**_.
**Example 1:**
**Input:** path = "/home/ "
**Output:** "/home "
**Explanation:** Note that there is no trailing slash after the last directory name.
**Example 2:**
**Input:** path = "/../ "
**Output:** "/ "
**Explanation:** Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
**Example 3:**
**Input:** path = "/home//foo/ "
**Output:** "/home/foo "
**Explanation:** In the canonical path, multiple consecutive slashes are replaced by a single one.
**Constraints:**
* `1 <= path.length <= 3000`
* `path` consists of English letters, digits, period `'.'`, slash `'/'` or `'_'`.
* `path` is a valid absolute Unix path.
| null |
String,Stack
|
Medium
| null |
918 |
hello friends today less of the maximum some circular sub-array problem we are some circular sub-array problem we are some circular sub-array problem we are given a circular array C of integers represented by a find the maximum possible sum of a non-empty sub array of possible sum of a non-empty sub array of possible sum of a non-empty sub array of see here a circular array means the end of the array connects to the beginning of the array so let's see example of a circular separate if the array a is 5 negative 3 is 5 we can connect to 5 negative 3 is 5 again so on the other buffer lengths of there a balance it's a circular sub array of the array C that means Phi negative 3 5 is a circular sub array and the negative 3 5 is also a circular sub array in the 5 4 3 is also or a circular sub array that means elective 3 5 next year 3 is not a circular sub array of the array C because it had the lens greater than a doll ends so it's not a socialist a beret so how do you find that the maximum sub array some you should know there condemns algorithm is use that you find that the maximum sub arrays some in a fixed array so that means for a given fixed array is 5 3 5 negative 3 5 we can find there is maximal subarray sum right we can tell use of these algorithms you find the max sum in their circular sub array how let's see some example if the given array is 1 negative 2 3 negative 2 we know the maximum sub array song will be 3 and we use the condemns algorithm to find the minimum separation which is negative 2 and we also calculates the sum of the whole array or we will find that there max separate some is just there is also their maximum circular separation because if you connect to 1 negative 2 3 negative 2 in the end though we will find the maximum suburb sign also these 3 how about this array if we connect 5 negative 3 5 in the end that we will find this is too far out netted so there should be the maximum separation in their circular array so how do we get this 5 actually we can get this 5 plus 5 by we first to find the maximum separation in the fixed array there shall be the whole array some that is 7 we also find a minimum separation which is negative 3 and the sum of the whole array is 3 by 7 and we will find out how we carry this a Phi plus Phi we just use a whole array some - this minimal sub a whole array some - this minimal sub a whole array some - this minimal sub array some so the left are shoulda beat their maximal subarray so which is 10 in this example we do the same thing we first find the max sub array some which is this sub array we care for and we also find that the minimum sub arrays which is negative 1 and we also find the sum of the whole array there is three and we calculates the sum - the minimum and we calculates the sum - the minimum and we calculates the sum - the minimum sub arrays on because on the opposite we will catch their maximum circular sub arrays I wish is for right so um we come compared this maximum separation and this sum - minimum subarrays and get 4 this sum - minimum subarrays and get 4 this sum - minimum subarrays and get 4 because they are the same the 4th this example if all the elements are negative we get the minimum separation with just the sum of this whole array so we know the sum and the minimum sub array will be the Eco right if we do the same thing we compare the some miles subarrays and we will get a zero but actually we cannot get zero so when there's some equal to the minimum sub-array so we know that all the sub-array so we know that all the sub-array so we know that all the elements in the array is negative so we should just return the maxis operation which is negative one so for so what if all the elements are positive we know the positive the max sub-array son we the positive the max sub-array son we the positive the max sub-array son we also know the minimum separation and we also know the whole son so we compare the max sub-array some and the sum minus the sub-array some and the sum minus the sub-array some and the sum minus the minimum sub ariza so we get this six so in conclusion our algorithm is user condemns algorithm to find the minimum separation and the maximum sub Arisa if the sum equal to the minimum separation we know all the elements are negative we just return the max sub erisa otherwise we return their maximum of the maximalism and the son - the minima sub maximalism and the son - the minima sub maximalism and the son - the minima sub ERISA because for this sum we minus the minimum supper is how we will capture their as larger and possible they're circular Sabha reason so that's right algorithm we first check if a equal to none or a dollar length equal to zero if you see the edge case check will return 0 then we will use four variables one is max heel here we first add a zero and then we also get a max in third hope there will also be a zero and the minimum heel here I will spend is full there afterwards and there will be minimum in turtle there will be a zero now we also need a some right at first it also is zero so what is what are this opus what do this for various links that means for this given array we will iterate the whole array so the max heel here means the max and there the negative 3 and the max in turtle means that the whole array max sub ariza when we try to calculate the max Q here we will compare their max skill here plus a current AI and the AI if max steel here plus AI is greater than a I will sum up these two available otherwise we just led to their Mexico here equal to a 0 because this is a sub array so that means all the elements should be continuous so that's the reason we compare the max heel here plus AI to AI we should at least contain the current element okay so we eat her each other left apart I quote you 1 I less than $1 I plus than $1 I plus than $1 I plus so if max heel here plus a I greater than AI will let a max steel here sum up AI otherwise the max heel here just equal to AI and every time updated there max in turtle equal to mass max in total there will be max heel here if minimun the same idea we try to get the minimum till here and the minimum in turtle plus a is less than a I make minimum heel here plus is AI otherwise write the minimum till here will just be a I because this is sub array so we at least should contain a current element I repeat again so minimum in turtle will you go to mass minimum minimal in turtle here right okay so we also needed to sum up this Oh there are elements so we adore faster check if some eco to do you go to a minimum in turtle that means all the elements are negative we just to return their max in turtle otherwise we return the max in there's some - the minimum in the max in there's some - the minimum in the max in there's some - the minimum in turtle and there is a max in turtle okay so the town complicity is just a bit linear okay thank you for watching see you next time
|
Maximum Sum Circular Subarray
|
reachable-nodes-in-subdivided-graph
|
Given a **circular integer array** `nums` of length `n`, return _the maximum possible sum of a non-empty **subarray** of_ `nums`.
A **circular array** means the end of the array connects to the beginning of the array. Formally, the next element of `nums[i]` is `nums[(i + 1) % n]` and the previous element of `nums[i]` is `nums[(i - 1 + n) % n]`.
A **subarray** may only include each element of the fixed buffer `nums` at most once. Formally, for a subarray `nums[i], nums[i + 1], ..., nums[j]`, there does not exist `i <= k1`, `k2 <= j` with `k1 % n == k2 % n`.
**Example 1:**
**Input:** nums = \[1,-2,3,-2\]
**Output:** 3
**Explanation:** Subarray \[3\] has maximum sum 3.
**Example 2:**
**Input:** nums = \[5,-3,5\]
**Output:** 10
**Explanation:** Subarray \[5,5\] has maximum sum 5 + 5 = 10.
**Example 3:**
**Input:** nums = \[-3,-2,-3\]
**Output:** -2
**Explanation:** Subarray \[-2\] has maximum sum -2.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 3 * 104`
* `-3 * 104 <= nums[i] <= 3 * 104`
| null |
Graph,Heap (Priority Queue),Shortest Path
|
Hard
|
2213,2218
|
759 |
hey yo what's up guys babybear4812 coming at you one more time uh today with problem 759 or the employee free time problem this one's ranked hard i think it's slightly on the easier side of hard problems but it's hard nonetheless um oops what did i do here past six months or zero to six months pinterest facebook microsoft bloomberg have all liked this one so it's a good problem to know it's a i guess it's relatively new it hasn't kind of attracted too much attention but i think it's a good problem nonetheless and i hope you guys will get something out of us covering it as always if you haven't tried it pause the video go run try it out go crazy on it then come back and you know where to find us if uh if you get stuck now without further ado let's have a look at what the problem says so we're given a list schedule of employees which represents the working time for each employee has a list of non-overlapping intervals non-overlapping intervals non-overlapping intervals and these intervals are in sorted order okay we need to return the list of finite intervals representing common positive length free time for all employees in the sorted order or in sorted order i'm sorry even though we were representing intervals in the form x y the object inside the intervals the objects inside are intervals not lists or arrays i'm sorry for example schedule 0 dot start equals one schedule zero dot two dot n equals two and schedule zero is not defined also we wanna include integrals like five in our answer as they have zero length uh they give us an example here i'll walk through it because i think i laid it out a bit more clearly on the whiteboard but what they're saying is we get a whole bunch of intervals and we're given these blocks of each array blocker list represents one employee and then within that employee block or the list we've got one or more intervals of working time and when we look at all these working times together there may or may not be certain times in between up from start to finish where nobody's working and we want to find what those times are we're also we're given this class interval definition so we're told that the items within these illicit they're not really uh they're not list they're not accessible like lists they're this type interval so it's an instance of an interval object which we can access with the start and the end property so that's just a bit of semantics when and we'll look at it when we implement the code but irrespective of all that our logic will stay the same so what i've done is i've moved this input and output over here to and then just to be clear that it's this schedule that i'm using here we've been inputted this schedule and the output we need to give us is three four so question is why is it before well i've gone ahead and labeled these as employees one two and three so i guess i have one index to here for whatever reason um with each of these inner loops representing one employee okay and i've color coordinated them a bit just because i felt like going back to the third grade and within each of these employee blocks we've got certain intervals so employee number one is working from one to two and from five to six employee two is working from one to three and employee three is working from four to ten if we were to write all these out somehow we would see that three and four is the only free time they have one way to think about this maybe is to say let me kind of draw maybe if this is one to two we'll say someone's working here and then maybe we got five to six over here and it's gonna cost one two uh this is somebody here is working one three so that's going to take up all this time uh this was five to six and then we saw four to ten so four all the way over here to ten that goes let's pretend this is ten diagram is not the scale uh we can see here quite clearly that the only free time is between three and four so if we draw this out if we see it on a maybe a microsoft outlook calendar type a visual it's pretty obvious to look at it to see okay wherever the intervals don't quite overlap then that's going to be free time now of course like every good problem here on leap code we can intuitively think about it maybe think of a real-life way to work it out think of a real-life way to work it out think of a real-life way to work it out but we got to come up with the set of instructions to tell our computer how to do it in a systematic way no matter what and that part's the more difficult part so let's think about how we would even go about doing something like this for the sake of this explanation as i'm going through the whiteboard i'm going to assume that each of these is a standard list i'm not going to be concerned with the fact that they're in uh inter i think it was called integral was it interval instance of the interval class because it doesn't really change anything in how we're building up our logic and so you know there are a few ways to think about this one and i think there's one that stands that kind of stands out it's the one that i want to address and really we want to think about the following um if i wanted to look at how these intervals overlap or if they overlapping and typically when we do want to know this it is very convenient to think about how you want the information of your input presented to you uh for instance just taking a face value like this is difficult to compare time intervals without actually taking every element and comparing it to every other element so getting some sort of high quadrature maybe even exponential run time technically speaking i guess that there would be a brute force way to do this by comparing every single element to every other one but again that not only would that explanation not really be accepted the code wouldn't run it's just it's not going to get you very far so back to what i was saying just about a minute ago the presentation in the order of the information we get is incredibly important in these questions for that reason it would be very convenient if we could actually look at every single work interval agnostic to which employee it falls under we don't care overall who is working during which period we just need to know that somebody is working because what we want to output is the net free or not the net free time but the time intervals where nobody is working if employee 2 or employee 3 employee 1 for that matter is working from 1 to 3 i don't give a you know what it doesn't matter all we need to know is somebody is working during that time period with that said one first step that we could take is to say why don't i take this input and i'm going to begin by sorting it by the beginning interval what this will allow us to do is to see where are they going to overlap and where's our start and end going to be sequentially one at a time as we walk through this time period of the day and what we're gonna do then is you know we'll run a quick sorting algorithm on this and we would end up with something like 1 2 next would be 1 3 then we'd have since we're going by beginning time 4 10 would come next and then 5 6. so we have 4 10. better to work during four to ten then on 420 i have to slip that in there and five six right over here all right so we've taken our input and we've put it on to one array again agnostic to who the employee is and now we can look at this piece of information in a sorted manner let me move this all the way down we can look at this in a sorted manner again sorted by the beginning time and so immediately right off the bat let's see i was to initialize some sort of result maybe i'll call this result over here and i'll keep track of what we find along the way if i was to keep track of a result array well i would start by acknowledging that basically from the start this employs this employee's working no matter what and what i'm interested in is this next employee who starts are they impeding on this time slot and when i say impeding really i think that's a wrong use of the word what i'm saying is there any overlap between this one and this one over here since we know that we've sorted them in ascending order we simply need to check whether or not this starting point happens before this ending point if so they definitely overlap in this case this shift the one to three shift happens at the same time as this one so we're not going to have any free time from one to two what we're going to be interested as we go along is going to be the latest ending time so every time i check a new interval i'm going to be curious if it's beginning is less than or the maximum kind of end we've had so far if it's ever less than the maximum we've had so far we know we are dipping into a previous time interval meaning that there is no free time that exists in that period simply put starting by starting with this first interval i'm going to say i'm going to call this variable maybe last end my computer's starting to heat up so that's where the writing is getting on my i do apologize the last and here we're going to set by default this first variable two or this first ending two i'm now going to start by looking at this next point over here i'm gonna look at one three okay i'm looking at one three and now i ask myself well one three is that is this one do i start before the last ending that i have the answer is yes i do so in that case i'm not gonna have any free time there's nothing i can add to my free time result already once i've checked that i now need to ask myself okay well does this change my latest possible end time so let's say that let's say this is a 1.5 let's say that let's say this is a 1.5 let's say that let's say this is a 1.5 somebody worked from 1 to 1.5 somebody worked from 1 to 1.5 somebody worked from 1 to 1.5 in that case this whole interval would be contained in here and so it doesn't matter that 1.5 changes it doesn't matter that 1.5 changes it doesn't matter that 1.5 changes nothing because if somebody were to come work at 1.75 uh you know this guy was to work at 1.75 uh you know this guy was to work at 1.75 uh you know this guy was to start at 1.75 of this gal start at 1.75 of this gal start at 1.75 of this gal then they would still fall within this last ending period and so this would change nothing however we have this overlap here now meaning we're dipping into this previous interval we know we're dipping it because we've sorted by starting my starting point remember now technically speaking the latest and that we have is going to be the maximum between this two and this three again i say the maximum because think about that example the 1.5 that i had if this was a 1.5 the 1.5 that i had if this was a 1.5 the 1.5 that i had if this was a 1.5 instead of a three then that would be relevant would change nothing so all of a sudden now i have no extra free time but now my last ending time is going to be at three all right now we start so we're done looking at this one now let's look at this next interval we're looking at four to ten this interval starts at four the previous interval ended at three this means that between three and four there is free time there is nothing happening between three and four the latest possible ending from everything that happened before where i am and then at three in the next one starting at four so cool we acknowledge that and then we realize three to four is empty awesome this is where we're having our cs though so three to four is in there as a free time now that we've done that within the same kind of loop for this iteration we will ask ourselves what happens now in my latest ending time well now we're starting from 4 to 10 okay and 10 is much later than 3 was so anything that happens before 10 will not it can't be included uh within any of our free time periods and again the reason this wouldn't happen is because any interval from here on outward so from the five on o even if this was a four it doesn't matter we've sorted this by beginning time the lowest this number could be isn't four right this could be anything less than a four if it's a four or more well it's not going to end in our result because we already booked our three times from three to four and so then when we check this last element right we notice that the five is less than 10 meaning we start during a working interval and this doesn't provide us with any additional free time and so by uh by the power of logic and algorithms we've actually come to our conclusion that 3 4 is the only free time that we have to quickly recap or briefly recap what we did is we said uh we acknowledge that we have these time intervals by employee but really doesn't matter which employee is what would also be convenient to know though is to have these times sorted so that we can sequentially you guys backwards sequentially look at them one at a time going forward such that we can see that if the beginning of one interval is smaller than the greatest end we've seen so far there's an overlap and we're not going to add that to our free time if there is no overlap though we can definitely add the previous maximum ending we had that was this three to our current beginning we know that between in this case between the three and the four nothing's happening everyone's on break and that's why we're going to append that interval to our result array i hope that explanation made sense if it didn't uh let me know in the comments down below i'm happy to elaborate as always but i think at this point we can jump on over that's all jump on over to the code and see how we would actually implement this so i'm going to move this over so we don't take up any space i've left this these definitions up here just to remind us that we're working with the intervals um maybe i'll start by doing some basic error checking and then what i'll do is we'll take those intervals so exactly what we did here is to break down and sort intervals so break down integrals maybe i'll sort intervals or not maybe i will definitely sort intervals and then after that we will loop through intervals uh to find free time and after all that we are going to return some result arena i'm going to define this result of course at some point but let's begin with the error checking we're only given a schedule here so all i'm really gonna say is that if we're not given anything that's an empty schedule then we're going to return an empty array now we want to break down those intervals and those that nested situation that we had into just a standard uh array or standard list and what i'll do is i'll call it some list intervals and what we're going to do is this is we're going to say for employee in schedule that's my first for loop and the reason i'm saying that is because if you look at each one of these main items within the array each of these represented each of these arrays represented an employee within each of those employees we have we can list through another or loop through another set of one or more arrays each of which represents an interval then i'm so then for that i'm going to say for interval in employee and that this will give us oh sorry damage he knows i always get when i record uh each of those will give us a an interval and again this will be of this type what we're going to want to do with these is we're going to say intervals dot append and we're going to want to append our own little list here and the thing to note is that in order to access this time so this looks like a list this is just one of these intervals but we can't access it with uh with zeros or ones kind of like they mentioned here but we would have to do it with a dot start and a dot end so we'd have integral dot start and interval dot and that's exactly how we would access the these instances of these interval objects and once we've done that we've taken all those intervals out and stored them as standard arrays and something that we can work with very comfortably to sort this what i'm going to do is i'm going to see intervals.sort intervals.sort intervals.sort and since i want to sort by sorted excuse me by specific element within this array i'm going to have to use a lamp function and so i'm going to say he is equal to lambda of any generic item in here i'll call it x and we want to sort it in ascending order by the first element so i'm going to sort it by x it's gonna say x naught x hat zero that first element or the de facto the starting time now this is this has been most of what we've done now we will actually loop through intervals and find free time so let me start by saying result is going to be some empty array here and so what did we say here we said that as we wanted to look through here we have a result then we'd have some sort of last end variable that we need to keep track of so i'm going to initialize this last end variable and what i'm going to initialize it to will be the end time of the first interval so initially we're going to say that this is the last n that we had in our example that would be intervals at the that would be the zero so the first entry of our intervals and that in and of itself is an array with two spots and the ending array or the ending would fall on that second or the one index i used an array here i guess hypothetically you could also use the tuple if that's what you prefer i don't see anything wrong with that but just for some purposes just by default not even for that's not even a good enough reason i just enjoyed the consistency with the arrays so for better for worse now we want to loop through the rest of the intervals so we've taken care of the first one we know the first one isn't going to give us any free time we just need to know when it's ending is we've taken care of that and so what i'll do is i'll say uh for i in the range of one uh up until the length of the interval so we want to go all the way to the end and what do we want to say the following so we wanted to ask ourselves maybe i'll say n time is equal to intervals at i and or sorry i'll say start and it's going to be the zeroth entry and so if we're looking at if we're iterating through this would now be the item that i'm looking at and start would be this variable right here this one what i'm going to say is if uh if start is greater than last end so basically if this one does not impede on here if it doesn't jump in here or in this case really it would be or sorry for so in this one yes if this one was greater than two that means we have a break and that break would be from between two to whatever this number was and in this case one that obviously doesn't make sense if the number was bigger and we see this through the next step in the iteration then it would work if this was the case then to our result we would want to append a in like a free time interval and in particular we're told that we need to return a we need to return an array of intervals so i'm going to want to append this integral and then we're told here by the definition that the interval will take a start integer and an end integer the start integer will actually be the last ending okay so when we got to this six when we looked at this example our last end was three and then this starting number over here four was the end to that interval because we're looking at the free time so that's why here i'm going to put my last end and then i'm going to put my start time here for this current interval that i'm looking at again this is only going to happen if there is no overlap meaning that we start after the previous one ends or after the previous maximum ends and then we have some time in between uh regardless of whether or not this is the fact so if there is an overlap or not we still need to check what our latest ending was so i'm going to potentially need to update my last n and set it equal to the maximum of the last end itself or um maybe i'll set an n here and i'll say n is equal to intervals of i one just to make the code a bit cleaner maybe if i really want it to be kind of anal about this i could call this curve start and cur end and just so i occur and or cursor just because i don't want to confuse you guys if the naming isn't clear and so what this line will allow us to do is just to say oh let's update the last ending so whatever the furthest kind of along we've gone uh whatever the outermost the furthest ending time is that's we're going to need to use as our benchmark to compare the next starting time too equivalent to this example here this would now be a three instead of a two right it used to be two but now we you know we notice that there's a later ending time which is three meaning that anything happens before that happens before three will not contribute to additional free time that we haven't already taken into account and that's actually going to be it this is all the code that's required if we were to loop through this one more time in the next step we would be looking at the four ten now and our starting time would be four so our current start with before our current end would be ten since four is greater than three which is our last end and that last then is this item over here right this three over here then we would actually append from three to four and then we would update our four which would be the max between four and ten our last then would be ten i hope that makes sense i hope i didn't go through that too quickly i will press the run button here just to make sure that um it's like christmas comes early honest to god like when you run your code the first time around and you just oops i want to get any bigger when you run your code for the first time and it just it works you haven't embarrassed yourself on youtube that's a good time very underrated feeling uh and so anyways just uh i'm messing around just to recap with you guys this was a hard problem again i think it's on the easier side of hard problems but a hard problem nonetheless we started by doing some basic error checking we then said i don't care about which intervals fall to which employees just give me all the intervals i'm going to lay them out an array in a format that i'm used to and then sort them by start time what this allowed us to do was to get a bit cheeky here with how we actually uh compared the start time of one interval to whatever the latest ending time was of all the previous ones again we i kind of talked about logic i think quite thoroughly in the first half of this video so if that wasn't clear that logic give it a view again if it still doesn't make any sense please drop a comment down below um i'm happy to help and address any questions you may have anything else you want me to answer as always drop the suggestions i'm always open to it i'm trying to do one of these daily so i always have a bunch lined up that i can do but if there's anything that's kind of higher priority that you'd like let me know as always like comment subscribe share i'm trying to think of who to tell you to share with um yeah you're uh i don't know your third grade teacher the one who thought you wouldn't amount to anything just show her this video tell her this is what you're working on right now and uh make her jealous that's about it guys um yes i said that was so cringe um that's it for me today uh i'll see you guys tomorrow and yeah until then keep studying hard peace
|
Employee Free Time
|
set-intersection-size-at-least-two
|
We are given a list `schedule` of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping `Intervals`, and these intervals are in sorted order.
Return the list of finite intervals representing **common, positive-length free time** for _all_ employees, also in sorted order.
(Even though we are representing `Intervals` in the form `[x, y]`, the objects inside are `Intervals`, not lists or arrays. For example, `schedule[0][0].start = 1`, `schedule[0][0].end = 2`, and `schedule[0][0][0]` is not defined). Also, we wouldn't include intervals like \[5, 5\] in our answer, as they have zero length.
**Example 1:**
**Input:** schedule = \[\[\[1,2\],\[5,6\]\],\[\[1,3\]\],\[\[4,10\]\]\]
**Output:** \[\[3,4\]\]
**Explanation:** There are a total of three employees, and all common
free time intervals would be \[-inf, 1\], \[3, 4\], \[10, inf\].
We discard any intervals that contain inf as they aren't finite.
**Example 2:**
**Input:** schedule = \[\[\[1,3\],\[6,7\]\],\[\[2,4\]\],\[\[2,5\],\[9,12\]\]\]
**Output:** \[\[5,6\],\[7,9\]\]
**Constraints:**
* `1 <= schedule.length , schedule[i].length <= 50`
* `0 <= schedule[i].start < schedule[i].end <= 10^8`
| null |
Array,Greedy,Sorting
|
Hard
| null |
874 |
Yes, hello everyone, I'm a programmer. Today I will introduce to you a mathematical problem with the following formulas: you a mathematical problem with the following formulas: you a mathematical problem with the following formulas: Build a walking robot. About the detailed problem as follows, we have a robot. placed in a two- placed in a two- placed in a two- dimensional space two-dimensional infinite space and dimensional space two-dimensional infinite space and dimensional space two-dimensional infinite space and this robot will start from point zero and its sides will face north this robot can receive one of three commands The control below the first control command is - 2, then the first control command is - 2, then the first control command is - 2, then the robot will now turn to the left 90 degrees. If it is - 1, it will turn to the 90 degrees. If it is - 1, it will turn to the 90 degrees. If it is - 1, it will turn to the right 90 degrees or command x with the amount x being one in the numbers from 1 to 9 and for the few orders it will go to x maybe it will go to the end that step is a lesson the empty cells in this in a lesson the empty cells are in this matrix out then it is before the day of the object, for example, the obstacle to the final position y then the matrix at the circle point y the zero part of the thing is the x line is the y line the work column of the object function matrix obstacle and y is the voice of y11 of kamen ceiling obstacle If this robot tries to go through these steps, it will have to stop at the pair of empty boxes in front of those steps. Instead of stepping through, our task is to return the cycle to an empty box that has the maximum area of e le distances that the robot will maximum area of e le distances that the robot will maximum area of e le distances that the robot will have and this robot can perform the following tasks. That initial point is zero or no, then on the path it goes, it will form squares and we will calculate back to calcium, that is, the distance at le maximum of the squares. Then for the distance to understand, we just need to take less squared plus y squared yes wife yes then we will go into the example one of the examples our robot will receive commands one after another. as follows 4 - 1 will receive commands one after another. as follows 4 - 1 will receive commands one after another. as follows 4 - 1 and 3 and the obstacle is no obstacle, we see that for the cold the four robots are facing north, right, then we will have the vertical axis y which is the vertical axis The vertical axis is y and the less axis will be the horizontal axis, which is turning my face to imitate that its face is turning in the same direction as the shutter. Maybe we also receive command number 4 which means it goes back and forward. 4 cell sure it comes from no it goes y increases once increases to 2 i increases to 3 goes increases to 4 let it stop at positions already zero four its position will be 04 then two We see that it has the next command - 1 is cold it has the next command - 1 is cold it has the next command - 1 is cold - 1 but we see above that the - 1 but we see above that the - 1 but we see above that the first direction is the right turn 90 degrees, which means it turns its face to look in this direction. is the least thing it will look in this direction is the little thing then it continues to receive orders three so you stay and go home awake at least three steps to strange new x1 = 4x = 3 then we see that = 4x = 3 then we see that = 4x = 3 then we see that its stopping point will be x = 3y = 4 so it can its stopping point will be x = 3y = 4 so it can its stopping point will be x = 3y = 4 so it can only go as long as it creates the correct square at point 3 4 then we will see that after the distance its stay cl3 squared species nine plus 4 squared is 16 which means the final result is 25 which is the square with the maximum air distance I will make you guys try giving example 2 to see the robot What is the direction of movement? In a good example, we have what we will do. We have a little axis. When we take a picture from the particle, I will copy it quickly. Okay, so that's an illustration. Illustrating the oxygen coordinate system, there's nothing complicated. Yes, then later it will be the x axis here and there. This axis is a low capture and this axis is a capture. Now we There is a starting point of the robot which is heavy. This must be the zero point. This point is the no. It hears this point. It is the zero point. You can see that it is now and the robot is standing here. It is facing here. Go back to the capture, it will receive the command 4, it will record and move up 4 units, it must go 1234, then currently the robot is walking, it is standing here, after it received the command 4 then two The next command is - 1 command minus one, next command is - 1 command minus one, next command is - 1 command minus one, it will face to the right, that is, at first it faces this direction, but if it turns 90 degrees to here, the robot will turn its face but after a while it will turn back. If you recognize four, then record this father, then it will go 44 squares ahead or right now that's the front it's following at 1234 here, it's gone four steps and has to stand here, then the coordinates At this position, it will be strange that it is 44, then it will receive - 2, but please note that it receive - 2, but please note that it receive - 2, but please note that it cannot go to 44 because here it is 24 a at position 24, that is, where is the address ? Here it has a ? Here it has a ? Here it has a guy that can't move, it's like a rock, so if there's an obstacle that can't move, then as I defined above, if it can't move, we'll stop right in front of the umbrella. Next to something, this collision is probably going to this Chinese chess game, passing by this department, right here, I see that at least it will stop in front of this warehouse. Inferred, it is at positions 24, then inferred. x is at position 14, which means x = 1 + y = 4. The x is located here for the x = 1 + y = 4. The x is located here for the x = 1 + y = 4. The x is located here for the iPhone 4, which is already located here because now it's new - 2 functions are that it rotates to the left, new - 2 functions are that it rotates to the left, new - 2 functions are that it rotates to the left, but it's not facing this direction. Turning to the left nine is called a leading vortex, guys, it's wrong again, the face is easily north, no matter what direction to catch next, we see that after turning the bowl's face, it goes on 4 more squares. So now at least it will go up? 1234 it goes up like this like that, finally there is less it lies down listen this is the last position then now we see how many things it has how much it has created how many squares and rectangles to calculate, here this one here one just see this one then here will be four squared plus you alone to 4 alone is 17 while That here is one squared plus eight squared, so the length is up to 8 more. If 8x is equal to 1, then it's one squared + 8 squared, 8x is equal to 1, then it's one squared + 8 squared, 8x is equal to 1, then it's one squared + 8 squared, so it's 65. Then 65 is asking for a bigger number than me, so we'll get Let it be the number 65. Well, I think after illustrating this image, you will understand the requirements of the problem. Now I will go through the introduction to the spread to solve the problem. For the problem, as you can see, in these problems, the first problem I will solve is the table or dimension and then these obstacles, this piece I find is quite difficult if we Just keep going because every time the child doesn't go, we have to move in this table to see if this xy is the same or duplicated, so I think it's best if we convert it to 1. The map, my friends, I will convert the map or dimension to create a map with my other one being a point a, hoping to make a point object, the point object will have 2 x values so and point object will have 2 x values so and point object will have 2 x values so and I There will be a stored value of that point which is chuh iphone equivalent is the whole face the whole label it will contain the periods which is the set of all the x and y points that we will have to worry about calling it an obstacle. So why do we have a cooler? We will leave it there. Next, we will have a second one, which is a piece consisting of bx and cy, which means we will have a dimension of x and y and we will give The directions it goes in turn are in the economic position , not the 1st north direction, the 1st direction is the , not the 1st north direction, the 1st direction is the , not the 1st north direction, the 1st direction is the east direction, the south direction and the west direction is the amount so there is a total of having my piece with four molecules up to less and to go ha after that, I just have a bag to help me keep all the boxes that translate all these calendars in order from left to right starting from that first element and the last technique then if When we encounter a number that is larger than larger or equal to the grave, we simply pay attention to get the current value, then we just take the xy at that position and add accordingly. The value of x and the current value of y, I let it continue, in the process of adding it, I also have to move the bottle so it doesn't touch this rock much, let alone 20 hectares left. There are millions of them, so as you can see, the north direction, if you already face north but minus one, it turns 90 degrees and right, it will become the east direction. When the bridge turns 90 degrees east, then it will become the south direction. The south direction turns 90 degrees to become the west direction and the west direction turns 90 degrees to the plan and it must become the north direction. I have a small trick. I will take the current direction, add one and then divide it. hundred by four with all your might, divide percent by 44, the number 4 is the four directions in the map in our strings, we have made east, west, south, north in that direction and for the - 2, in that direction and for the - 2, in that direction and for the - 2, it's the opposite, it will shine through. If that's the case, then I - 1 I - 1 I - 1 Okay then, that's the idea, I 'll proceed with the installation and explain slowly, 'll proceed with the installation and explain slowly, 'll proceed with the installation and explain slowly, the language I'll use to install is Colan programming language, so as I said: I'll change this to a I said: I'll change this to a I said: I'll change this to a two-dimensional array, but before this object two-dimensional array, but before this object two-dimensional array, but before this object becomes a map, I 'll have an alternative called fetus, 'll have an alternative called fetus, 'll have an alternative called fetus, these substances are called my embryo, there are few of them. just interior and then we will declare and start declaring the main molar, first we will have to tell society that this cooler we call boss is probably a set of points is what Eggs or objects then cool the system and tell us to cool a condensation tree, we will meet our khaki-shouldered mats, which will be the our khaki-shouldered mats, which will be the our khaki-shouldered mats, which will be the smear type and the fibroid suitcase, which will be the next type, and then we will send over all the elements of this constechco in the keyword section rain i love star wars ii i hope start box and then we will consider it we will try to consider the music to get the other one of it when we say we will create a new point, a new symbol with v, I will give the strange one will be v at position no and the acc lv at the 1st position and I will assign it equal to cycle then After we live independently, our boss map will contain all the points that are far away obstacles. Now the second step is that we have to define a furnace. According to the position, is it the East, South, West or not, then I will call this. Pay attention to the trend. This means direction is the direction of the Asus. In this case, I will have a grave and 4 princes and then type integer. then less but for the case in the north then if we move north then we will + x = not right then we will + x = not right then we will + x = not right because in the north the thing stands here it goes up Here, little stays the it goes up here it goes up Here, little stays the same and y increases by one, so it follows that it is equal to zero. If it goes east, the benefit increases by 1. If it goes south, the benefit also increases. No, it goes east. is to write - 1 then it's considered that I've east. is to write - 1 then it's considered that I've east. is to write - 1 then it's considered that I've got a strong direction a piece direction of little and you guys my direction is that I'll print leopard is similar to one a piece of information tiger consists of four elements and then Then the two of us will continue that if and y go north then it's y + 1 y if and y go north then it's y + 1 y if and y go north then it's y + 1 y if it goes east it's not plus y then if we go south it's y - 1 and if we go west we promise excitedly Oh yeah, go south it's y - 1 and if we go west we promise excitedly Oh yeah, go in the clock direction and then go west, right in the east, north, south, east, west, right now, why not? Here are two maps representing the two directions, so if we move, then how little when how then now I will declare some variables so that the first thing I do is this eye then I will visit the royal family without having to worry about this it will always keep the maximum value of The distance stays when we move to fish xy then at least will return to the x position of the robot at the current position when will return to the position of the robot at the current position and this will be the position That is, the current thing of the robot and now I will go through all the elements of this comment, the number of the completed comment with the key game comments yeah and then I will check if the comments but it is equal to -1, what if the comments but it is equal to -1, what if the comments but it is equal to -1, what if it is equal to -1 which means it rotates to if it is equal to -1 which means it rotates to if it is equal to -1 which means it rotates to the side it rotates to the right 90 degrees then now our direction will be the plus direction we rotate towards on the right side like from north we move to east from east we move to south from south see the point through the hand then that means the word is it just expensive not move to intek a wooden stroke move to you see or is that right then it must be The direction we are going is plus 1 to go in the current direction plus the direction in the first place which is the next time we divide by 4 unfortunately we can run 0123 but not 123 0123 I ran continuously at first so I paste it for you. The robot is equal to zero, which means it's this direction and this one too. Now we'll check the second one, which is the weak brother, but what about the c that's equal to the second sister? Yes, the open c is -2, then the direction of Yes, the open c is -2, then the direction of Yes, the open c is -2, then the direction of these companies it will be equal to y - 1 but these companies it will be equal to y - 1 but these companies it will be equal to y - 1 but minus the set because be careful that if it is located here in the north and it bears one then hanh - here in the north and it bears one then hanh - here in the north and it bears one then hanh - 1 divided by 4 then it will be negative then we are sure to win We choose this four so that it will always be positive, then we divide the percentage by four and then the last school is in this case it will move out the robot will move without rotation. If we move, how much does it move ? Let me add a for ? Let me add a for ? Let me add a for loop for a for y = no y will move and show a for y = no y will move and show a for y = no y will move and show that it is smaller than c. Go back to it c times then y + that it is smaller than c. Go back to it c times then y + that it is smaller than c. Go back to it c times then y + + and now we We will calculate what + and now we We will calculate what + and now we We will calculate what we will calculate the easy fish to calculate the small values at each step, then we small values at each step, then we small values at each step, then we will take the value of the current x plus dx at the position to notice the direction. ny will be equal to y plus dy at the small position in all those directions and then we will check if it is located there, it is located in common with the point that is the obstacle, just give me a little ny then We're going to series. We're not going to have anything else because that's an obstacle. That's why we have to have something to see. Below is we have to check. We have to add it into a variable. For now, let's check to see if it's because of an argument or not. If it's not blocked, then we'll do the second thing, but if it happens again, we'll hate it. Now if it does n't, then what do we both do? Paste it back to show me a little, we paste it back to make y = fa and then now calculate paste it back to make y = fa and then now calculate paste it back to make y = fa and then now calculate the box, we have to calculate the distance ae then you multiply x plus y times y but if it is bigger than your eye We will paste your eyes x times x + y times y and then after x times x + y times y and then after x times x + y times y and then after we finish running for this one encounter, the value of our eyes will have a value again that we need to return to you. When will the program return? This is the return value for the program. Let's try running this program with example one to see if it has any problems. Yes, this one is wrong so I copied it. Okay, okay, I asked. I'll try it out with example 1. You said so. In example 1, we have successfully solved the returned result of 25, which is the same as the required result of the problem. Now I will create an account. To solve other technical examples like that, I easily succeeded. All other examples of the problem, this is a quite interesting problem simulating a moving robot, we will analyze it a bit. Regarding algorithmic complexity, here we call the number of functions before the day the object is virtual. Now we have a cell with complexity times. Here, we call c the comment number. The number of comments is c times in c times then loose one more The thing is that the value of each comment is n, it is n times, I can deduce the complexity of the algorithm, it will be the store + c multiplied by of the algorithm, it will be the store + c multiplied by of the algorithm, it will be the store + c multiplied by me and the complexity of the storage space , we will be Who ah uh the , we will be Who ah uh the , we will be Who ah uh the ship owner recognizes a word that will be because what we have to use is one more map, this map has a quantity equal to the quantity of the obstacle and these two negative or resistive ones we We use two here and then when we use it has a fixed length, so we will also say it as a constant. Okay, then let's go down to your children. Let's finish it. If you think it's good, let us know. I would like 1 like, sub, like and share the experience. If you have any questions or comments or have a better solution, you can write them down in the comments section below the video. Thank you for watching. Goodbye. goodbye and see you again yeah
|
Walking Robot Simulation
|
backspace-string-compare
|
A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`:
* `-2`: Turn left `90` degrees.
* `-1`: Turn right `90` degrees.
* `1 <= k <= 9`: Move forward `k` units, one unit at a time.
Some of the grid squares are `obstacles`. The `ith` obstacle is at grid point `obstacles[i] = (xi, yi)`. If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command.
Return _the **maximum Euclidean distance** that the robot ever gets from the origin **squared** (i.e. if the distance is_ `5`_, return_ `25`_)_.
**Note:**
* North means +Y direction.
* East means +X direction.
* South means -Y direction.
* West means -X direction.
**Example 1:**
**Input:** commands = \[4,-1,3\], obstacles = \[\]
**Output:** 25
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 3 units to (3, 4).
The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away.
**Example 2:**
**Input:** commands = \[4,-1,4,-2,4\], obstacles = \[\[2,4\]\]
**Output:** 65
**Explanation:** The robot starts at (0, 0):
1. Move north 4 units to (0, 4).
2. Turn right.
3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).
4. Turn left.
5. Move north 4 units to (1, 8).
The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away.
**Example 3:**
**Input:** commands = \[6,-1,-1,6\], obstacles = \[\]
**Output:** 36
**Explanation:** The robot starts at (0, 0):
1. Move north 6 units to (0, 6).
2. Turn right.
3. Turn right.
4. Move south 6 units to (0, 0).
The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away.
**Constraints:**
* `1 <= commands.length <= 104`
* `commands[i]` is either `-2`, `-1`, or an integer in the range `[1, 9]`.
* `0 <= obstacles.length <= 104`
* `-3 * 104 <= xi, yi <= 3 * 104`
* The answer is guaranteed to be less than `231`.
| null |
Two Pointers,String,Stack,Simulation
|
Easy
|
1720
|
1,536 |
hi everyone welcome back today let's solve another decode weekly contest medium problem the mini minimum swaps to arrange a binary grid also it says it's a medium question but i feel like the difficulty is around median to heart first let's see the question statement so given an n times n binary matrix and in one step you are able to choose two adjacent rows of the grid and then swap them and then a grid is set to be valid if all the cells above the main diagonal which is uh this direction are all zeros and we have to return the minimum number of steps needed to make the grid a valid if it is not possible then we will just return a negative one so the first example for this grid uh first we will swap row one and row two so it will be look it will look like this and then we will swap row 2 and row 3 and finally swap row 1 and row 2 again so you can see that above the main diagonal you will become all zeros and the next example uh for the third row the third column because there's no zeros at all in all columns so in this case it's not possible to make the grid valid so the output will be negative one for this case any intuition to solve this problem is first we have to try to make a transform the 2d matrix into a 1d array and second usually for questions to find minimum steps minimum numbers we can think of either dynamic programming bfs or greedy algorithm in this case we have to use a greedy approach and it's kind of like doing a bubble sort underneath the hood so for example one the first step is to count how many trailing zeros are in each row so for this first row there's no trailing zero and second row there's one and there are two trailing zeros in the third row and our goal is to transform this grid to look like this two trillion zeros in the first row and one and then none in the third row so the actual problem will become how do we transform this array 0 1 2 to the array 2 to 1 0 and the actual steps are so for this array uh 0 1 2 we will have a target number for each indexes so starting from index 0 we have to try to swap a 2 to index zero so we will search uh the rest of the array and then once we find a two or the number bigger than two we will try to swap it into the into index zero and in this case we have to make two swaps to place a two into index zero okay then move to index one at index one we would need a one or a number bigger than one to place here so we search the rest of the array and then we find a one and we will make another swap so finally we will get the target array to one zero so totally we will have to make three adjacent swaps now let's see the code in action so the left part of the code is pretty self-explanatory so first get pretty self-explanatory so first get pretty self-explanatory so first get the dimension of the grid and then here we define account zero functions to generate the trailing zeros array of this grid and then we run the functions to generate zeros the trailing zeros array and then the right part is to do the searching and swapping on the zeros array this is more tricky so let's focus on this part okay and first we will have a for loop to go through every item in the array and at every index the target number we need is an n minus i minus one so for index zero the target is uh n which is three minus zero minus one so it's two in this case so if uh if the element at the index is already bigger or equal to target then we can just continue the for loop and here we will have a possible flag to check if it is possible to get a number for every index and here we have a inner loop that will search the rest of the array and once we find an element which is bigger or equal to target we will set the possible flag to true and then the number of swaps we have to make is j minus i and we will add that into the result variable and here is the trickiest part in the code so when you are swapping and moving the like for example two into uh to the first index zero it's kind of like pushing this sub arrays zero one uh one step right so we can do zeros the array zeros one plus one to j plus one equals uh zeros i2 i2j and then we will break the inner loop and finally check the possible flag if possible equals to false then we will just return negative 1 and finally return rest and finally let's do a quick review and to be honest i think this solution is pretty difficult to think of during a contest but the key points is first we have to transform the two-dimensional problem into a 1d the two-dimensional problem into a 1d the two-dimensional problem into a 1d array to solve it and in order to find the minimum number of swaps we have to use a greedy approach which is to find the first element which is bigger or equal to target and then swap and this solution it has time complexity big o of n square for two loops and the linear space complexity for the trillion zeros array okay that's all for today thanks for watching if you like this video please give it a like and subscribe to my channel and i will see you in next one
|
Minimum Swaps to Arrange a Binary Grid
|
customers-who-bought-products-a-and-b-but-not-c
|
Given an `n x n` binary `grid`, in one step you can choose two **adjacent rows** of the grid and swap them.
A grid is said to be **valid** if all the cells above the main diagonal are **zeros**.
Return _the minimum number of steps_ needed to make the grid valid, or **\-1** if the grid cannot be valid.
The main diagonal of a grid is the diagonal that starts at cell `(1, 1)` and ends at cell `(n, n)`.
**Example 1:**
**Input:** grid = \[\[0,0,1\],\[1,1,0\],\[1,0,0\]\]
**Output:** 3
**Example 2:**
**Input:** grid = \[\[0,1,1,0\],\[0,1,1,0\],\[0,1,1,0\],\[0,1,1,0\]\]
**Output:** -1
**Explanation:** All rows are similar, swaps have no effect on the grid.
**Example 3:**
**Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,1\]\]
**Output:** 0
**Constraints:**
* `n == grid.length` `== grid[i].length`
* `1 <= n <= 200`
* `grid[i][j]` is either `0` or `1`
| null |
Database
|
Medium
| null |
332 |
hey everyone today we are going to solve the readable question reconstruct itinerary so you are given a list of air running tickets where ticket I has from I and the 2i represents a departure and the arrival airport of one flight we construct the itinerary in order and return it all of the ticket Belong To The Man Who departs from JFK just the itinerary must begin with JFK if there are multiple valid itineraries you should return the itinerary that has the smallest electrical order when released as a single string so for example the itinerary JFK LGA has the smallest electrical order then JFK and the LGB so you may assume all ticket form at least one valid itinerary you must use all the ticket once and there are only once okay so let me explain with this example so example two so input ticket is like this and there are two sort of discussion I use stock and initialized with fast airport JFK and I also create a graph represented as a dictionary where each airport is a key and its destinations are valued and I sorted these values in like a reverse of lexical order so a must be last and S is the first value for JFK and J is the last value and the S equals the first value for ATM something like that so that we can take the value with a electrical order easily because if we pop the last of JFK we can pop like a data right it's easy so that's why we sort the value in device order okay next so let's go through one by one so now we are JFK so that's why look at the JFK and uh so we have two choice we can go sa4 and then ATL so but we need to go through like a airport with electrical order so in the case we pop ATL from JFK and then other ATL to stack so a yeah and then I'll remove this from graph so now we are ATL so where can we go so look at the graph so we have two choice sa4 and the JFK and so same reason we take a data from the last and the other JFK to stock so J if k and I remove JFK from graph and then next so now we are JFK so look at the JFK so we have only one choice sa4 so that's why the sc4 to stock and then they move sa4 from graph and then now we are sa4 so look at the sf4 we have only one choice ATF so our ATL graph and now we are ATL so ATL we have only one choice sa4 right we already visited JFK so that's why uh the sa4 to stock and then so we finish we visit all airports right so now we can create a stack like this and then we have to make this stack empty because uh um I use in my code I use a while loop and the condition is stack has data so in the case while loop continue looping so that's why if we don't make this stack empty while loop continue forever so that's why we pop the data from the last to beginning and then add each data to like a new list so now sa4 to JFK something like that and then in the end we have to return this list but this is a completely opposite we need like a like this oops like this and this right but now this is a completely opposite so again we have to reverse this order so from JFK to SFO so that we can return the correct answer yeah so that is a basic idea to solve discussion so we start being said let's get into the code okay so let's write the code first of all create a graph and I use a default addict and uh key should be list and for the departure yeah all right go thing so we need to sort values so tickets and a read last order so I call to and then graph and the departure dot append and arrival and then create a stack initial values should be JFK and a new itinerary so the error leave and with empty list so while stack has data so if so graph so current airport has like a destinations so St uck minus one is a current airport and current airport has destinations so we pop and our bands are stuck so create uh I copy this so and the pulp so we take the last airport and then append the stock if not the case so we use this list and then dot append and stack dot pop after that so now um this list is completely reversed so we need device again so in Python we can do like this so column minus one yeah that's it so let me submit it yeah looks good and the time complexity of this solution should be order of enroll again so where N is a number of tickets so we sold the ticket in reverse order so it takes order of and login and the processing the ticket using stack takes on time so that's why time complexity should be on the all in Logan and the space complexity is a single on so to represent the graph or when a space is required and uh also stack uh stuck is on yeah so that's why yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
Reconstruct Itinerary
|
reconstruct-itinerary
|
You are given a list of airline `tickets` where `tickets[i] = [fromi, toi]` represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.
All of the tickets belong to a man who departs from `"JFK "`, thus, the itinerary must begin with `"JFK "`. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.
* For example, the itinerary `[ "JFK ", "LGA "]` has a smaller lexical order than `[ "JFK ", "LGB "]`.
You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.
**Example 1:**
**Input:** tickets = \[\[ "MUC ", "LHR "\],\[ "JFK ", "MUC "\],\[ "SFO ", "SJC "\],\[ "LHR ", "SFO "\]\]
**Output:** \[ "JFK ", "MUC ", "LHR ", "SFO ", "SJC "\]
**Example 2:**
**Input:** tickets = \[\[ "JFK ", "SFO "\],\[ "JFK ", "ATL "\],\[ "SFO ", "ATL "\],\[ "ATL ", "JFK "\],\[ "ATL ", "SFO "\]\]
**Output:** \[ "JFK ", "ATL ", "JFK ", "SFO ", "ATL ", "SFO "\]
**Explanation:** Another possible reconstruction is \[ "JFK ", "SFO ", "ATL ", "JFK ", "ATL ", "SFO "\] but it is larger in lexical order.
**Constraints:**
* `1 <= tickets.length <= 300`
* `tickets[i].length == 2`
* `fromi.length == 3`
* `toi.length == 3`
* `fromi` and `toi` consist of uppercase English letters.
* `fromi != toi`
| null |
Depth-First Search,Graph,Eulerian Circuit
|
Hard
|
2051,2201
|
952 |
hey guys welcome back to another video and today we're going to be solving the lead code question largest component size by common factor all right so in this question we're given a non-empty array question we're given a non-empty array question we're given a non-empty array of unique positive integers a consider the following graph so there are a dot length node so the number of nodes are the same as the length of our area a and they're labeled starting from zero all the way to the length minus one so if you have ten nodes uh we're going to have sorry if we have a length of 10 for our array we're going to have a total of n nodes uh labeled from zero through nine okay and there is an edge between a i and aj if and only if a i and aj share a common factor greater than one return the size of the largest connected component in the graph so let's take a look at example two over here so we have twenty 15 ninths to n63 so over here we have one graph with 20 and 50 connected to each other so the reason they're connected is because uh they have several factors other than just one so they have two they have 10 and 5 and so on and so forth okay and over here for 9 and 63 they're not connected to 20 or 50 because neither of them share the same factors whereas 9 and 63 themselves share their own same factors which in this case is the number three so that's how we're gonna get it and in this case they both have the same length so we're just gonna output a length of two uh over here they're all connected so let's see how that looks like so four and six so in this case we have four and six so four and six share a factor of two then we have six and fifteen sharing a factor of three and then we have fifteen and thirty-five have fifteen and thirty-five have fifteen and thirty-five which share a factor of five so uh in that case everything is connected so we have an output of the number four all right so let's see how we can solve this so you can kind of split up our question into two parts so one of them would be what we're going to do is we're going to iterate through each of the numbers so we're going to go through 4 6 15 and 35 and after iterating through them each time we're going to get out all of its prime factors and we're going to store it in such a way that for each index we're going to have whatever its prime factors are so in this case for the index zero its factors are going to its prime factor is going to be the number two and so on and so forth we're going to do that for each and every number so that's one part of the question and the second part is how do you take that information we just have and kind of uh make these uh numbers into separate groups or sets so the answer to that is we're going to be using a union find data structure so this data structure is basically used to keep track of different subsets that we might have and how they're kind of interconnected with each other so i try to think of several ways to kind of explain this but i came up with was this visualization from visual i'll put a link to from visual i'll put a link to from visual i'll put a link to this visualization down in the description so do check it out okay so let's start off our first step is going to be to initialize our data structure so let's say we're so this initialization is going to have the same length as whatever the length of the array is so over here let's assume that the length of our array is 10. so let's hit go and what happens is we get a data structure with values from zero through nine so what you can kind of imagine is so we have this data structure of these nodes and each node is its own parent so the parent of zero is well zero the parent four is well four and one more thing you should notice is let's say we go to the fifth index so zero one two three four five the value of what's at the fifth index is the index itself so what do i mean by that the sixth index has the value six the first index has the value one so on and so forth okay so after this there's two more functions that are important for us okay so we kind of have two functions two main functions that we have are the find function and the union function so what the find function does over here it basically finds whatever subset our set is in so let's say we want to look for set 2 it's going to find whatever subset it is so let's say we run this right now in this case we're just going to get the value we're just going to get this value as it is because uh as it is right now each set is the root of itself so it doesn't really matter and after that one more function that we really need is a union set function so what this does it makes one of the sets a subset of the other one so instead of kind of talking about it let me just show you what it does so at the at i have two and at j i have zero so let's hit go so first we find the value two okay now we find found the value zero and let's see what happens so what happens is two becomes a subset of zero so in this case we're making for two comma zero we're making two the subset of zero so you could have it do whatever uh either way so you could have two become sorry zero become a subset of two but in this case we're just doing it like this so let's just look at another example so let's say uh union set and now let's do it on seven and one so let's hit go so first we find seven now we find one and now uh seven is going to become a subset of one so just to show you what i was talking about earlier now let's now what we're going to do is let's do find set but let's find the value of 2. all right let's find the subset 2. so what's going to happen is when you go to 2 first we go to 2 and then what we can do is we're going to recursively call until we reach the parent so i'll just run that again so find set and two so as you can see first we go to two and afterwards we go back up to zero since zero is the parent so similarly let's say you do find set seven it's going to do the same thing so first we get a seven and then we go to its parent okay so that's kind of how the find set function works and let's just look at one more thing so uh over here let's say we have i is equal to two and let's say j is equal to seven so let's hit go so just to summarize what happened real quickly is we called union set two comma seven and over here when you wanna when we looked for the value two we found its parent which is zero and then for 7 we found its parent which is 1. so now what happened is 7's parent which is 1 made 2's parent it's child so in this case 1 and then we as you can see that's 7's parents so that made two's parent which is zero it's child so this is how it ended up looking like and one final thing that i want to show you um let's say we do actually going to end up getting one so that's just kind of what i wanted to show you so we find the most the parent uh element so what's happening over here is something called path compression and in simple words all it's doing is it's making our data structure or the search a lot faster okay so previously to find the set two we actually ended up taking i think four steps and now let's say we call the same thing again so find set two and now it's only going to end up taking two steps so two what they're done so it just makes everything faster okay so now let's try to actually implement this in our code i'm not going to be going over it line by line but i'll just kind of show you the overall picture of it so over here i'm first making our union find class so in our union find class we're first going to start off by creating our uh area right so in this case the area is going to be so if our length is 10 it's going to be 0 to 9 so that's what we're doing over here so i for i in range n and n is going to be the length of our array okay and then afterwards we're also going to be creating another array called size so in the beginning so what this is going to hold the size of each of our sets so uh in the beginning they're all going to have a size of one and as we go down we're gonna change it accordingly so over here we have our find method and what we're doing is we're first gonna check if we're going to go to that x index and if that the value of that index is equal to x in that case we're just going to end up returning it if that is not the case what we're going to do is we're going to uh call that function on that again and that's going to help us find the parent so we're going to keep calling this function on itself so self.fine self.fine self.fine until we find the parent and once that happens once we do find what the parent is and what we're going to end up doing over here is called path compression so this is what we're doing here and all that does it helps us make our steps faster and at the ending of this we're going to return self.ufx return self.ufx return self.ufx which is the parent okay so and after that we have our union function so our first step is to find the root or the parent of x and then we need to find the root of y so x and y and now we're going to check if they're equal to each other so if the x root and the y range are both the same and in that case it's already where over the sets are already where they're supposed to be so we're just gonna end up returning and we're done with the function and what we're doing here is we're making the x root the child of the y root and what we're gonna after so after doing that since what we really want is the size of each of these sets and what we're going to do is we're going to go to our size of area which we defined over here and we're going to add the size of the x root to it and then we're going to go to the size of the x root and we're going to make it zero and the reason for that is because the x root has become a child of our y root okay so that's going to be it for our union find class and now let's see how we can integrate this into our solution okay so in our solution we're going to start off by defining an empty dictionary and we're also going to create an object of our union find and we're going to give it the length of a because that's what that's going to be the length of it so what actually is the purpose of our dictionary so the purpose of our dictionary is that it's going to store all of the prime values that we get and it's going to so that's going to be the key and its values are going to be at what index do those prime values exist so let's say we have a prime value 2 and let's say that exists at index 0 4 and 5 so those are going to be its values so that's what our dictionary is for so before going into this over here let's see how do we actually get the prime factors for each of our numbers in the area a and for the code for getting the prime factors i actually got that from geeksforgeeks which is another website and i'll put the link to that in the description okay so we're going to start off by having a set so i just called it out for output and this is going to be the set that we're going to that's going to hold all the prime factors of this uh number so what we're doing over here think of this as the first step and we're going to check if it's divisible by two and if it is divisible by two we're going to go inside of a while loop and we're gonna add the prime factor two to our set and each time we go inside this while loop we're going to divide our n value by two and we're going to keep going inside of this until our value is not even anymore so if it's divisible by two we know it's even so by the end of the step our value is not going to be even so it's going to end up being odd so now our number is odd for sure so we're going to end up going into a while loop where we're going to start off at the value 3 and we're going to go until the square root of n and each time and we're also going to be stepping by a value of two and the reason that we're stepping by a value of two is because after uh three all the prime numbers have a gap of at least two so uh we you could go by one but by stepping by two it just makes it a little bit faster okay so each time we go inside we're gonna check if our value is divisible by whatever the i value is and if it is we're going to end up adding that to our output set and we're also going to divide our number by that value okay so once we're done with this for loop we're going to end up with the final number so in our prime factorization tree is either going to be 2 or 1 or it could be any other prime factor so if it is less than 2 in that case we're just going to ignore it and if it is not less than 2 and in that case we're going to add whatever that prime factor is to our set and finally we're going to end up returning our output so this gets us all the prime factors of a certain number so that's what we're going to end up doing so in this for loop over here we're going to enumerate our list and the reason for that is because we want to get the index so we're going to do index comma each of the numbers so at each iteration we're going to first find all of the factors prime factors for our number for that specific number in the array so right now for the first number we're going to find all of its prime factors so once we get all of its prime factors it's going to be inside of our set and now we're going to iterate through all of those so over here we're doing for prime and prime so we're getting each of the prime numbers and over here we're going to check if our prime value is a key in our dictionary okay so if it is then in that case what we're going to do is we're going to go to our union find object and we're going to call the dot union method and we're going to call this method on our index whatever index is there at the value of this prime number so after doing this if our prime value already exists in our dictionary what we're going to do is we're going to change the key value to whatever our current index is and if it does not already exist in that case we're just going to add that key okay so if this is a little bit confusing to understand i'm going to try my best to drop this out all right so let's just go back to this example over here so 4 6 15 and 35 so that's what i'm going to be performing our function on so 4 6 15 and 35 that's our input area and i'm sure this should really kind of get everything together and i'm sure you should understand the question after looking at this okay anyway so after this we uh have to define a few things so we have our dictionary which in the beginning is just going to be empty so let's just have our empty dictionary and we have two areas so we have a sizes area right and in the beginning this has all ones so everything has a size of one in the beginning and the reason it has a length of four as well because our input has a length of four as well and since our input has a length of 4 over here we're going to go to our union find data structure and let's define it so when you initialize it we're going to have 0 we're going to have 1 2 and 3. so this also has a length of four so let's start off by doing the first thing which is well we need to find the prime factors of four over here and it's prime factors or well it's only two so one and two but yeah we're not going to count the one so two okay so now that we have two we're gonna add this to our dictionary so that's gonna have b2 as a key and its value is going to be whatever about the index of the number four and its index as well as zero so you have two zero as the key and the index okay so now let's move on to our next iteration and nothing over here changes for a size or for our union find okay so in the next iteration we have the value six and where it's prime factors well we have one two and three again we're ignoring uh one okay so two and three so first we're going to go to our dictionary and see if two already exists and the answer is two does exist so what we're gonna do is we're gonna find we're going to use the union function on zero comma one and the reason it's one and now we're going to perform the union function on one comma zero okay and the reason we're doing it on one comma zero is because one is the index of six and zero is the index two was at okay so now that we have this let's see how that looks like so let me just draw it out so uh normally uh in this case one comma zero and if you go back to our function zero it's becoming the parent right and one is becoming a subset of it so just to kind of visualize it we're gonna have zero and then we're gonna have one coming off of it like that but what we're doing is we're actually going to represent it in a slightly different manner so what we're going to do is we're actually going to get rid of this we're going to erase it and we're going to change its value to 0 and what it's kind of telling us so originally or how you would visualize it is one being a subset of zero and what this is kind of telling us is at the first index uh so the value one actually its parent is zero so that's why we change this value to zero one thing we're going to do is we're going to go to the first index and we're going to change this to zero so for the size sorry so we're going to change this over here to zero and before we do that we're going to change the zero its index size to whatever its current size is so one plus this size so this was one so it becomes one plus one and now this height has a size of two so you can keep going and kind of imagine how this uh changes and let me just finish this iteration over here so actually currently our dictionary is 2 0 and what's going to happen it's going to get updated and now it's going to be 2 1 and one more thing we're going to do is since 3 is not there we're going to add that to our dictionary with the current index which is well one so again once you go to 15 what's going to end up happening is you're gonna have three comma five as its prime factors and over here three already exists so you're going to end up calling the union function and we're going to call it on the current index of 0 1 2 and this index over here which is 12 1. so 2 comma 1 and what that's saying is that 2 is becoming a subset of one and in other words one is becoming the parent okay so when you're calling this union function let's just kind of look at our first visualization and how would we kind of be like so we had zero and one was this child and when you're doing this two would be its other child so that's how it will look uh normally but over here since we're doing this method uh so two comma one so we're gonna go to the second index and we're gonna change it to have the value of whatever is at the first index so now it's saying that two is actually a subset of the value zero so we get rid of this and now this is going to end up becoming zero and simultaneously what we do is we go to the second index here we're going to make this zero and we're gonna add a value of one year since this had a value of one and uh this ends up becoming three and if you do it for one more iteration let's just do it actually so this actually becomes five comma seven and i didn't add everything here so this um we'll see how our dictionary updates so this states that's two one and then it becomes three uh two so three two and then we end up having five two and yeah that's it so 5 exists over here and 5 already exists in our dictionary so over here we're going to call our function on we're going to call it on this index so 0 1 2 3 and we're going to call it on this index which is 2. so we're calling our function on three comma two uh in simple words this is going to end up changing to zero and afterwards uh we go to the zeroth index this value becomes four and this value becomes a zero and just to show you what that looks like in our as per our initial visualization zero is the parent root with the children being one two and three so those are all of its children and uh zero currently has so there's four elements over here so how do we end up getting our final result so all we're going to do is we're going to find the max maximum value in our sizes area so in this case we have the values 4 comma 0 and obviously our maximum value is four so we're going to end up outputting four so if you look over here and you look at the output it is four and yeah so that's how it is uh so i tried my best to explain it i'm sorry if it was a little bit cluttered uh do let me know if you have any questions and i will try my best to answer them i'm not an expert in this but anyways as you can see our submission is accepted and finally thanks a lot for watching guys do let me know if you have any feedback and don't forget to like and subscribe if this video helped you thank you
|
Largest Component Size by Common Factor
|
word-subsets
|
You are given an integer array of unique positive integers `nums`. Consider the following graph:
* There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`,
* There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`.
Return _the size of the largest connected component in the graph_.
**Example 1:**
**Input:** nums = \[4,6,15,35\]
**Output:** 4
**Example 2:**
**Input:** nums = \[20,50,9,63\]
**Output:** 2
**Example 3:**
**Input:** nums = \[2,3,6,7,4,12,21,39\]
**Output:** 8
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i] <= 105`
* All the values of `nums` are **unique**.
| null |
Array,Hash Table,String
|
Medium
| null |
894 |
hey how you doing guys it's ilya bella here i recording stuff on youtube share description for all my information i do all lit code problems uh make sure you subscribe to this channel give me big thumbs up to support it and this is called all possible fall binary trees a full binary tree is a binary tree where each node has exactly zero or two children return a list of all possible fault binary trees with endnotes each element of the answer is the root node of one possible uh three each node of each three is the answer must have no dot value is equal to zero you may return the final list of trees in any order well uh let's look at this example we got seven and we return this output right here um you know this right here means like zero right then null then again zero right here then again no right and 0. right here we can see that we 0 and 0. right here we can see that we got as well you know we got 0 then we have null then 0 and 0 as well here we have a bunch of zeros here it's 0 then 0 no right and null 0 no 0 n is greater than or equal to 1 and is less than or equal to 20. um well i'll show you how to solve this problem recursively uh we need to traverse through all the children and find all possible um combinations that's it we can cash um result the results right at each level and to do that we will be using uh map you know we can put the value into that map which is associated with a particular key we got the key which is uh the type integer and list of three node uh it's called just map and new hash map um again we can copy that real quick integer list the type integer next um at each iteration i mean at each recursive call all possible uh full binary trees we check first in the case when um n module 2 is equal to 0 means that n is even we return the result which is uh the list of the type 3 node the result new array list there is nothing to do with that because for example when n is equal to 2 that means that um we cannot generate a full um binary tree because we got only uh two nodes right and we need to have at least uh you know three nodes or just the only one node right zero or just two children means only one node with no children at all or just um you know or two children right here um next um in the case when we already found um children at particular level we can say if map dot contains the key which is and then we return this already computed result we say map dot get and we return the value the list at the position of n in the case when um when n is equal to 1 then we need to say result dot r 0 and return this result and minus because uh n minus because um we are already at the root at each call right so we already uh counted this note so say we just uh traverse its children here and here we create a for loop into i which is one i is less than n and i plus at each iteration we create the list of three node which is uh the left and we call this method recursively all possible for all binary trees we pass um i and right here we name it right and we plus n minus i we go you know left and we go right um we create another for loop and we are looking through the left the children to your left say left and through the children to your right three note right and at each iteration you create a new tree node which is the current uh which is equal to new three node we pass zero then we say current dot left is equal to l and current dot right is equal to right finally we add this current to the result then we need to um cache this already computed result we say map put the current level which is n and um let me check real quick um yeah like and notes and um this result and return this result that's it that's the whole problem uh we use map right here in order to cache uh the results um we create a new array list um in the case when n is even means has uh the tree has even number of nodes we cannot come up with this solution we just return uh the result right here and in the case when um they we already know already uh computed uh you know the notes the three for n we can get this result from that map in the case when n is equal to one we add zero we say oh okay we say new three node create a new tree node and we pass zero and we return this result uh then we say n minus because we already at the root at each you know you can imagine this root right here of this three this root right here of these three and this right here of this stream and you can think of that this way and then we iterate through all the children to your left and to your right and we um create when we are at the bottom we create a new tree node we say current.left is equal to current.left is equal to current.left is equal to l and current dot write is equal to r result r the current and put that into our cache into that map and return the result let's run this code accept it let's submit success good um thank you guys for watching leave your comments below i want to know what you think um follow me on social medias i do all little problems um follow me on instagram add me on snapchat uh give me a big thumbs up to support my channel um yeah i think i explained it pretty good you know that's pretty obvious what we're doing here we just use the recursion right we go let we go left then we go right we compute all possible uh combinations uh with that children and we add that combinations to that result right and we return the output i'll see you next time bye
|
All Possible Full Binary Trees
|
random-pick-with-blacklist
|
Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`.
Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**.
A **full binary tree** is a binary tree where each node has exactly `0` or `2` children.
**Example 1:**
**Input:** n = 7
**Output:** \[\[0,0,0,null,null,0,0,null,null,0,0\],\[0,0,0,null,null,0,0,0,0\],\[0,0,0,0,0,0,0\],\[0,0,0,0,0,null,null,null,null,0,0\],\[0,0,0,0,0,null,null,0,0\]\]
**Example 2:**
**Input:** n = 3
**Output:** \[\[0,0,0\]\]
**Constraints:**
* `1 <= n <= 20`
| null |
Hash Table,Math,Binary Search,Sorting,Randomized
|
Hard
|
398,912,2107
|
318 |
today we're gonna be working on date code question number 318 maximum product of world lens given a string array words return the maximum value of length of word I multiply by length of word J where the two words do not share common letters um if no such two words existed and zero so in this example the two longest strings which do not come and just share we do not share the common letters are actually a b c w and xdfn and the product is going to be equal to 16. the way we're gonna be implementing it is basically so let's just say that the length is basically equal to the words dot length so the total number of uh strings we have in the words array and then we're gonna have a an array of integer called set which is equal to Nu and the length of that is going to be equal to length what this set is like it keeps the numeric so numeric representation of that string what it means is like we're gonna go through that one string and we're gonna look at every single character of that one string by first creating that string to a correct character array okay and what we're going to be doing is like we're gonna be saying that once you look at that character Crea change it to an integer for that we're gonna say that a minus a is going to be the integer representation but in order to put it because we are going from left to right every single time it is gonna be shifted to the left right and then we're gonna or it to the uh like to that number which we are saving at test a set of I we're gonna keep ordering that thing while we are going while we are iterating through the characters so we are just ordering um every single time every single character so the whole uh once we're done with one word uh we're gonna be setting at set of I there's the integer representation of that string okay so once we have that we are gonna say is like end Max is equal to zero as we are looking for the maximum product uh we're gonna iterate through uh all the characters and the strings so for that I is equal to 0 I is less than length I plus okay and then for N J equals to zero Which is less than the length J plus okay uh so if the set of I add set of J is not equal to zero that means we had a duplicate if it is equal to 0 that means the two strings so far do not uh do not actually share uh and do not have if the product is equal to zero once when you add it that means there is no way that they have any character which is uh which is a shared character if that is the case we're gonna update our Max by saying math dot Max of the Max uh the words of I dot length multiplied by words of J dot length that should do it better than the max oops okay so this is gonna beat this and then this art of I cannot find the symbol because we are looking at a string here looking good and it works
|
Maximum Product of Word Lengths
|
maximum-product-of-word-lengths
|
Given a string array `words`, return _the maximum value of_ `length(word[i]) * length(word[j])` _where the two words do not share common letters_. If no such two words exist, return `0`.
**Example 1:**
**Input:** words = \[ "abcw ", "baz ", "foo ", "bar ", "xtfn ", "abcdef "\]
**Output:** 16
**Explanation:** The two words can be "abcw ", "xtfn ".
**Example 2:**
**Input:** words = \[ "a ", "ab ", "abc ", "d ", "cd ", "bcd ", "abcd "\]
**Output:** 4
**Explanation:** The two words can be "ab ", "cd ".
**Example 3:**
**Input:** words = \[ "a ", "aa ", "aaa ", "aaaa "\]
**Output:** 0
**Explanation:** No such pair of words.
**Constraints:**
* `2 <= words.length <= 1000`
* `1 <= words[i].length <= 1000`
* `words[i]` consists only of lowercase English letters.
| null |
Array,String,Bit Manipulation
|
Medium
| null |
1 |
What's up geeks and welcome to the channel! Today we are going to tackle one of the most asked problems in coding interviews, I was actually asked to solve this problem myself, and it is the Two Sum Problem. To do that suppose you are given an array of integers, what you need to do is attempt to find the two numbers that add up to a specific given "target" number, let's say 20, it is guaranteed to have a single solution. So, in this example we should return 5 and 15 as 5 + 15 = 20. Okay, the first trivial brute-force solution that comes to mind consists of two nested loops which will allow us to traverse every single possible combination of element-pairs and check their sum. If the sum matches the target number we are looking for it and great we return these numbers. If not we keep on looking. This solution is quadratic, and surely isn't the optimal way to solve this problem which is by the way what you should always strive to find in an interview. Now if you recall in our two pointers technique introductory video we kind of solved a similar problem to this one except in that video our array was sorted. As a reminder suppose we have the same array but sorted and we want to find the two elements that add up to "target", if we were to use the two-pointers technique we will have two pointers left and right and every time the sum we obtain is smaller than the target we increase the left pointer leading to an increase in the total sum and every time the sum is bigger than the target we decrease the right one leading to a decrease in the total sum up until we find the elements we are looking for and return them. Okay great we already covered that but here our array is not sorted so how does this help us? Well, sorting an array has an O(n logn) time complexity which is better than the quadratic solution we just wrote. So, even if we manually sort the array and then make use of the two-pointer technique we just saw, we will still obtain a better algorithm in terms of complexity than the Brute Force one. Now what if I told you that we can still do better, what if I told you that there exists a linear solution to this problem, how do we even come up with such a solution? Well, the first hint you can think of is in my question itself, I just told you that the solution I am looking for is linear, and to write a linear solution given an array the only choice you have is to loop over that array once, right? The second hint lies at the core of every algorithm you will write in your life: time and space trade-off. We want to reduce the time complexity of this algorithm to its maximum which means that maybe we will have to make use of some sort of data structure to store values thus increasing my space complexity. So, we're at this point where we know that we will need a way to store some data and that we will make use of only one loop but what are we going to store? Well, it is safe to start with what the response will actually be in this case we are returning integer values so let's start by storing integers in a list. Okay, the last part is figuring out how all of this is going to play out, what we are actually going to write inside this loop. Now, remember the only check we are doing in all previous implementations is making sure that the target number is equal to the sum of the two elements we are currently traversing, but in this implementation at any point in time in the loop we only have access to only one of the two elements needed to make up that condition, right? Well, think about it, if what we are looking for is 20 and currently I am iterating over element 15 then no matter what, my previous condition is true if and only if that third element is 5. You see, 5 is the only solution to this equation or in other terms the equation is solved if 5 is present in the array. So, if every time I traverse an element, I insert it into this list, then my condition will only have to check if the target minus the current element is present in that list as well or in other terms we will check if there exists an element in the array such that the current element you are standing at satisfies our sole condition. Okay, our current implementation is concise but is still quadratic because the contains check is linear in time. However and as we saw in previous videos if we make use of a Set instead of a List this search will be done in constant time making our overall complexity linear in time, and there you have it the linear solution for the two sum problem! Now, if you check the LeetCode problems linked in the description, you will notice that they're not exactly like what we just solved. LeetCode asks us to return the indices of the two sum numbers instead of their actual values. How does this affect us? Well, that's what we'll cover in the last section of this video. First, concerning the two pointers approach you won't be able to return the indices directly because these indices will be modified after the sorting, they do not point to the same initial element as provided to the method. This can be solved in many ways one of them being Maps. So, before sorting the array we will have to store the element index pairs in a map and after finding the solution we use this map to retrieve the initial indices and return them to the user, however this exact solution only works if no duplicates are present in the array. If you have duplicates like LeetCode has, a lot of test cases will fail. Now, concerning the last approach we wrote, we also do not have the index of the value are retrieving from the Set, so how are we going to return it? Well to tackle this problem as given on LeetCode what you need to do is make use of a map instead of a set, the keys of this map will store the same data we were sorting in the set and will be used to make the same checks, however the value corresponding to each key will be its initial index in the array provided to the method, then when a solution is found this index is retrieved and returned. Okay, after you solve this the interviewer might scale up the question and ask you to find the three elements that sum to a given "target" value, and this problem is called the three sum problem and will be the subject of the next video of the series so stay tuned! That's it for this video, I hope it was helpful thank you guys for watching take care and I will see you in the next one!
|
Two Sum
|
two-sum
|
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_.
You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice.
You can return the answer in any order.
**Example 1:**
**Input:** nums = \[2,7,11,15\], target = 9
**Output:** \[0,1\]
**Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\].
**Example 2:**
**Input:** nums = \[3,2,4\], target = 6
**Output:** \[1,2\]
**Example 3:**
**Input:** nums = \[3,3\], target = 6
**Output:** \[0,1\]
**Constraints:**
* `2 <= nums.length <= 104`
* `-109 <= nums[i] <= 109`
* `-109 <= target <= 109`
* **Only one valid answer exists.**
**Follow-up:** Can you come up with an algorithm that is less than `O(n2)` time complexity?
|
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
|
Array,Hash Table
|
Easy
|
15,18,167,170,560,653,1083,1798,1830,2116,2133,2320
|
452 |
uh we will solve this problem today 452 minimum number of arrows to burst balloons we have spherical balloons taped into flat wall that represents X Y plane okay the balloons are represented as 2D integer array points where point of I is X star and x and denotes a balloon whose horizontal diameter stretches between X star and x n okay so what is being told is that we have a plane x y and there are balloons taped into that wall okay and we have been given uh these coordinates okay this points the starting and for a balloon has some diameter okay balloon will have some diameter and for every balloon we have been given the start index starting point of that balloon in x coordinate and the ending point Okay so x dot and x and for each and every balloon so we have a 2d array okay and what we need to do we need to shoot arrows vertically up so that we have so that the balloon pops and we have to pop all the balloons that there are okay so for example if we have these many balloons then we have to shoot arrows like this and this balloon will pop this Arrow will pop all the balloons on its way okay so here if we shoot an arrow over here we shoot an arrow this will pop these two balloons similarly so we can pop balloons and our problem is to find the minimum number of arrows that must be shot to burst all balloons and also we have been given that uh that balloon that Arrow will keep on traveling till Infinity okay so there is no cap to how many balloons uh Arrow can pop okay so balloon Arrow will keep on moving till infinity and it will pop all the balloons on its way okay so let's see so first of all I've already plotted the diagram so let's see let's abstract it a bit and see so suppose these are our starting and ending index of balloons okay something like this okay for example this can be some starting point ending point of some balloon okay some balloons so now when we see this problem we can think that like we can shoot an arrow here okay we can shoot an arrow here and we can shoot an arrow here so what we can do is we can pop all the balloons into arrows okay I can't see any more Alternatives maybe we can shoot an arrow here but when we do that we have to we require two more okay like this and maybe one more like here okay so this is not preferred okay so we should this is preferred okay in this problem so we can like find two different things here or two very important points that we can note from this diagram first is that we need some kind of ordering in the problem the array that we have been given there is no ordering okay like uh 10 16 and after that 2 and 8 comes okay so but in this diagram we can see that it is very easy if we like if we put all the balloons who are closer together nearby each other okay so for this is a balloon which starts at this point and ends at this point similarly this balloon starts at this point and it's at this point we are keeping the balloons together which are together okay so this is one thing we can note so now we can realize that maybe what we can do we can sort the array okay that we have been given we can sort it okay we can sort it and one more point that we can like find is that suppose if we shoot a point balloon here okay we had something like this right we have some things like this and we had then I made something like this so we can maybe pop use this one here okay this arrow and then but then we realized that we have to use two more arrows okay just to pop these balloons Okay so when we think about it then it is very apparent that we are getting an overlapped region here okay we are getting an overlapped region here and there is no point in skipping this okay we should means we should try to find out if there are more balloons that are coming on its way they are on its way okay means are there more balloons that overlap in this region so that we can shoot Arrow but when that is not the case we should pop we should shoot an arrow here okay we should there is no point in like searching for other areas where we can shoot because if we skip this nonetheless we have to shoot Arrow here okay to pop this one so whenever we get an area that is overlapping with some balloon we should shoot an arrow there and we should not wait okay and so what we can do in this problem is that first we need to sort and then we can move we can Traverse the area and we can find the overlapping regions all the balloons that are in a particular overlapping region okay and we need to shoot that Arrow there and whenever uh for the next balloon if we don't see that it is overlapping with the previous balloons what we can do is that we can consider is at as a new region okay this is our new region and then we can continue further finding over finding the balloons that are overlapping with this balloon and we can shoot an arrow there so now how do we find if two balloons are overlapping okay so suppose this is one balloon okay and we have one more value we can say that when this point the starting point of the next balloon is somewhere in between starting and ending of the previous balloon we can say that there's an overlap similarly there can be other conditions as well for example if the starting point can be at the starting point of the previous balloon even that can do okay or end point okay so this can also be a condition or even this can be a condition right so these are all the conditions this was my like the previous balloon and these are all the possible overlapping balloons okay so now let's try to solve this problem first of all we need to sort the points okay arrays Dot sort points comma P1 of 0 minus P2 of 0 okay so what I have done is I've sorted my points array by the starting position okay in the sending order so now let's initialize some variables integer left equal to points of 0 comma 0 teacher write equal to points of zero comma one okay so now we can also Define a variable overlap equal to zero this will count all the overlapping balloons okay so suppose this is our first balloon and this is our next balloon so if we find such kind of overlap then our count will be increase our count by one okay in like we have a initial balloon and if we find that some balloon is overlapping with that balloon we will say suppose if one more balloon comes here then like first this one this balloon came and then after that this came so there is an overlap so I will increase the account by one and again if one more volume games and again it is overlapping okay so we'll increase the count further okay for that we have used this overlap okay now we will iterate through these points for integer I equal to 0 I is less than points DOT length plus okay so now if points of I and 0 is less than equal to right okay so this is the condition of overlap if we have an overlap okay so this is our this was our previous point and this is our new one and this point is somewhere in between okay before right this was our right and this is before that so we'll say yes there is an overlap and what should we do we should put left equal to math dot Max points of I and 0 comma left okay similarly for write equal to method should be Min okay Max because left should be Max okay this point if this is a previous mind this is a new point so this would be the max okay and similarly for right it should be Main for min us of I 0 comma right okay and we can say overlap plus and for else if there is no overlap we will say left is equal to points of I and 0 okay so this is at the current point that we have we are defining our new position okay new region well we will find overlapping balloons later on okay so for that we are redefining our left and right okay write equal to points I and what okay and then we will say return points DOT length of points DOT length minus we will say overlap okay these are the total Point balloons that we had and these are the balloons that were overlapping so we did not consider those okay or you can even think that we think it has like arrows we can put arrows here and you can say that arrows plus every time like you find a new unit you reset the region you say that you shoot an arrow at the previous region and for that you can say arrows plus here and you can remove it like from here okay and you can see just return arrows but this is more intuitive for me so I am doing like this now let's run okay so there is some problem overlap okay let's see okay so actually I think I've done a mistake here should be points of I and one right yes so now let's run okay uh Max should be left for Left what should be my current left so it's a so okay so the problem is that I am starting it from zero but I've already considered the first point okay so because of that my count is getting incremented by one okay let's see so for every value it is getting incremented it is less than one okay it's it is less than one so that is the problem so now let's see if it works yes and this is a case that I want to like highlight what I'm doing is I'm sorting okay this is where I'm sorting but when I'm sorting uh since my X and Y X points are to the very stream of int okay I'll mean value and max value so what is happening it is overflowing so for that what should I do I should not put it like this I should rather put compare okay teacher Dot compare I should do this and this will work fine okay let's see comma run yes now it is fine now let's submit foreign thank you
|
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
|
85 |
hello folks in this video we will see how to solve the maximal rectangle problem which is a hard problem on lead code so we'll be given a binary matrix like this and from this binary matrix we have to find the rectangle with largest area okay the rectangle containing only once okay so how we can solve this problem previously in one of the problems we have seen how to find out the rectangle with maximum area from a histogram right so from this binary matrix if you are able to make out a histogram then we can find out the answer the same way right so what we can do is from this binary matrix we can consider one row at a time okay uh one row at first then we can consider two rows then we can consider three rows likewise we can consider and all the n rows at last okay so when we consider a combination of rows uh in order okay we'll be considering rows in order first we'll take one then two then three likewise okay so during each step we'll be taking rows from this binary matrix and we will be converting it into a histogram okay from that histogram we'll find out the rectangle with maximum area okay now that is something we have already done in one of the previous problem so uh if you want a detailed explanation on that you can what you can watch that video i mean you must watch that video to understand how we are calculating maximum area from a histogram okay so we'll be using that particular code in this solution along with a few extra things okay so what we can do is first we can consider one draw from this binary matrix and convert it into a histogram and from that histogram we will find out the maximum rectangle possible okay after that we'll consider two rows together and we'll convert it into a histogram and same way we'll try to find out the maximum rectangle from that okay so like that will repeat till we till at last we will be considering all the rows together and converting it into a histogram and we'll find out the maximum rectangle possible okay so somewhere along our uh iteration okay at some point we don't know in some cases maybe when we were considering three or four or when we were considering some amount of rows together some number of rows together we may get a maximum rectangle okay uh this rectangle can appear anywhere in the binary matrix okay that's why we are cons considering uh we that's why we are generating histograms like this and trying to find the rectangle with maximum area okay and uh one thing to note here is when we are converting this binary matrix into a histogram there can be cases where 0 comes in right so when a 0 appears in a column that means everything above that 0 can be ignored right because when we say histogram means all the columns must be attaching the bottom line of the histogram right if it is floating above we cannot consider that as a histogram right so uh one thing to note here is if at all we encounter a zero while generating histogram or all the values all the heights height of the column we have calculated so far can be ignored okay for that particular column because the height or the column should not be floating above okay it should be touching to the bottom level of histogram okay so with that let's start coding uh first we can have uh first we can start with uh let's say uh we are given a binary matrix right so from matrix we can take the number of rows first okay so rows equals len of matrix right so that gives number of rows in that matrix okay in that given matrix now uh as i said we'll be first considering one row then we'll consider two rows likewise we'll be uh keep on adding num number of rows till uh till at last we consider all the rows together okay to generate a histogram okay so we'll be generating different histograms and from each histograms we'll be trying to find out a rectangle with maximum area okay so we'll use a for loop for that so for i n range rows i think we can call this r for r and range rows what we can do is we can use a variable to store the final result here so max area equal to zero let it be zero initially here we can write max area equal to max of max area or uh here we have to find out the result okay we have to generate a histogram and find the maximum rectangle we could find we can find from that histogram okay so i think we can write a separate function for that for finding the histogram and finding the area finding the maximum area okay so what we can do is we can write a function definition here uh let it be get histo area okay get histo area and to this will be passing the combination of rows okay that would be rose uh we can come to this later let it be there so here we'll call that function get histo area of uh to this function we need to pass rows right so we have to pass matrix of zero till uh the current index we are iterating okay that is r right so what this does is the during the first iteration it will send the first row during the second iteration it will send two rows together the top two rows okay during the third time iteration uh it will send uh three rows together okay so uh as we complete this iterations at last we'll be uh sending all the rows together and among this among these result there will be a maximum rectangle right so we will take that so at last after the loop what we can do is we can return max area right that will be the result okay so now let's go to this function get his histogram area okay so uh in this function what we are what we will be doing is we will be generating histogram okay from the rows uh here we have rows as a parameter so from rows we'll generate a histogram okay so he's let it be histogram equals zero into what is the length of histogram uh that is if a row has c columns then this histogram should have c columns right so i think we can type calls equal to len of rows of 0 right so we know the number of columns here so we can initialize an array of length calls and set all the values to zero initially okay histogram now what we can do is uh we have to add up right this is a binary metric so there will be one nine zeros right so uh to this histogram array we are generating a histogram here so we have to add the rows right i will first take one row and if there is one we will add that okay so as we iterate through all the rows uh we'll build up this histogram okay at last we'll have the uh his uh one single array which can be represented as a histogram okay so we can use a for loop here for row in rows we can say for call in range calls right we need to we'll be have we'll have to do the addition for all the columns right so for calling range of calls uh what we can do is histogram of histogram of chord equal to or if it is uh now uh from the row uh we can say if it is zero what does that mean as i mentioned before if it is zero that means uh there is a zero coming in between that means or if at all there were ones above that row all that can be avoided or uh we can discard that right because when a zero comes in that means there is a gap in between the column that is in the middle of a call in somewhere in the middle of column there is a gap that is some value is floating okay not touching the uh the ground level of his histogram bottom level of histogram right so we can uh ignore a previously calculated value there that is we can directly set zero there that is histogram of call equal to zero if a row of call equal to zero right if it is zero that it can be directly zero right else what can we do else we can add uh this is a binary matrix right so if it is not zero then it will be one that right we can add that one plus uh the already existing value okay so we are just trying to increase the height of the column okay as we go if it is zero then uh that is not possible like on the values on top of that will be avoided if it is one we can add that okay and try to reach to the bottom okay so here one plus the previous value histogram of call okay now uh that is done so at last uh after this nested for loop we'll be having a single variable histogram which will which can be represented as a histogram okay so uh so once we uh so since we have found out the histogram what we have to do is we need to find the rectangle with maximum area from this histogram this is something we have already discussed in one of the previous problems so i request you to go through that video and understand in detail how we are solving that okay so the same logic will be used here same code will be used here okay so what we can do here is we can return uh the rectangle area maximum rectangle area right we are going to find so for that also we can find we can write a separate function okay let's say let it be def get max area history okay so to this we will be passing histogram we can come to that later so we'll be returning that get max area history of histogram right so here we have found out the histogram that will be passing to this function get max area histogram where we will be finding the maximum rectangle area possible okay so uh here whatever i am writing is something we have discussed before so please go through that video okay to understand it better i'll be just writing the logic here okay so n equal to len of histogram that is we are taking the length of the histogram first then what we can do is we need to find the uh left to how long it can be extend towards left and towards the right okay we need to find the width okay height we have now we need to find the how to how much we can extend okay so for that we need two array left limit equal to zero into n and right limit equal to zero into n okay we have two arrays uh for storing the information like to till whatex to which index it can extend towards left and right and uh for the first element and last element it cannot extend towards left and right respectively so for that scenario we can store here left limit of 0 equals 0 minus 1 and right limit of n minus 1 that is for the last element will be n okay the limiting index will be and for the last element now after that uh we need for all the elements we need to find the limiting indexes right so for that we can use a for loop for i in range 1 2 n what we can do is we can use a pointer equal to i minus one initially let it be let it start with the first element okay so while uh we can say the histogram right histogram of pointer is greater than or equal to histogram of i that is if the neighbor on the left side is greater than or equal to the element under consideration then uh in that case uh we can say this element can be extended towards left okay and also one more step mean we have to do is uh we should not it should not result in index out of bounds error right so while pointer is greater than or equal to zero okay and this okay so during this we can update the pointer to the neighbor's result okay that will be left limit of pointer right left limit of pointer okay after this while loop will have the result for the left limiting index okay so we can say left limit of i equals pointer okay similarly we can write the for loop for finding out the right limit as well so in here we'll be moving from right to left backwards okay and minus two till zeroth index will be going in backward direction okay and here we can write the same logic point or equal to i plus one it let it be at the last index first then while pointer is less than n and histogram of pointer is greater than or equal to histogram of i in that case what we can do is we can update the pointer to that right neighbor's value already calculated value okay we are speeding up things uh by doing this okay so that will be the right limit of pointer at last we can assign the result to right limit of i equals point now by this we have found out the left limiting index and right limiting in limiting index that is we have found the width of the his histogram element okay element under consideration now for all the elements we have found the width also we were already knowing height like in this function get histo area we were finding height right till what extent it uh the column can expand above the uh bottom left bottom level right so we were finding height in this function and now uh here we have found out the width also now what we can do is we can loop through all the elements of histogram and we can find out the area of the rectangle with maximum area okay so for that we can use a for loop again for in range and what we can do is height is histogram of i write and with this right limit of i minus left limit of i minus 1 that will give the exact width now the area will be heightened width right so uh here again we need one variable to store the maximum area max is to area equal to zero let it be zero initially so we can say access to area equal to max of max's door area or the currently calculated height into width okay so at last we will be returning that result that is return max histo area now during each iteration uh during each combination of rows we'll be calling this function and we'll be finding max uh his area max rectangle with the maximum area from the histogram okay so at last ultimately this result will be coming here right to the calling function that is here max uh that is the result will be stored to max area right so after all the loopings like after considering one two three and etcetera like uh considering all the rows together and generating a histogram and finding a rectangle with maximum area the max area variable will be having the final result okay so somewhere in the binary matrix there would have been a there is a uh rectangle okay with the maximum area so that will be stored in max area variable that will return at last so uh let's try running this okay uh there is some error in this lesson 932 yeah sorry actually i wrote something wrong here uh it should be r plus 1 right because the end index is exclusive right yeah so uh here r plus 1 then and one more thing we can do is if at all a number of rows that is a number of rows is less than 1 that is we are given an input array with no rows that is an empty input error uh we can return 0 directly right we need not go for go further right so what we can do is we can write a condition if rose less than one return zero okay so let's try running it again yeah it's working see you in the next video
|
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
|
212 |
hey everybody this is Larry this is November 4th um the fourth day of the legal daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's problem I'm trying to see if there's a free um thing does not so I don't know if you know where it is let me know I don't know if it's consistent is it sync course for everybody or is it just like random per person I feel like someone told me this once but I didn't verify anyway today's problem is word search too so given a Empire and board return over it's on a board so what does that mean um okay so that means that you have a dictionary and you're trying to find the words okay I think these problems are always a little bit tricky um to do um because you have to really look at the constraints very carefully um I think a lot of these problems um in that sense is kind of you have to read the mind a little bit I mean in terms of let's say you have you're on an interview um these times are okay in the sense that you're able to communicate with the interviewer right be like hey okay what kind of assumptions can we make here is it a regular library is it oh it's a regular dictionary is that um you know there's a dictionary that contains like a lot of weird cases that you know chew up different games are there different things we can assume and the reason why I say all this is because the answer is going to be some sort of first um you could you know you could talk about branch and uh um branch and bang or you can do you know there are a lot of sort of optimizations that you can talk about um implementing a try which I think we're going to end up doing and stuff like this um that's you know that's all these things on the other hand um you know you could always find a case that makes these things not run um because in you set you know in essence at the end of the day everything is going to be exponential right um to some degree so yeah so these problems always require a little bit of a mind reading and if you don't have the person here in front of you the mind reading is always going to be a little bit difficult which actually is a something that I probably complain a bit about on the recently go contests um where you know I think more than a couple of times I don't know I don't there's not gonna be a long thing but more than a couple of times in a recent contest um you know we went into time limit exceeded because I didn't mind read the problem the right way right such as life I mean I don't you know I don't care about my rating I it's clear that you know like uh I know I could solve it so that's all that matters right it's not a big deal but you know but these are the things that um you would look out for a problem like this on an interview um I think that mostly the things that I want to say about this um the so the thing is just doing so again what I mean by brute force uh maybe it's not quite clear but is essentially a search everywhere along the way and able to see whether you're making progress right um and you know just something along the way so I think that's pretty much the idea and here you can I assume you can have reused letters so yeah so this is just going to be a straight up you know um you know we could type out the skeleton and then we could figure out how to optimize it but for example directions we just do up down left right this is actually not in that order just to be clear I just fight it to be honest I don't I write this in some random order I usually um if you want to go back and see whether that's consistent let me know but then yeah um basically maybe you have a used for it where it's just fours times right and then maybe some sort of like you know because you know um yeah just I'm using used but also x y and maybe if we end up using a try we'll put that in the parameter as well um yeah and then basically I mean and you know there are a lot of ways you can do this that's why I'm not really you know but that's basically the structure and then you do something like DX Dy interactions and then Sunrise you're going to express the X Y plus t y and then just making sure that you know they're within bounds the autocomplete is really annoying still because this actually slows me down I wouldn't anything I turn it off still nope still won't need you turn it off for some reason okay um yeah and then maybe something like you know this cell is the next whatever then you know so we have to do some if some function that's true then we recurse uh NX and Y used or something like this right and then the part of the backtracking is just sending this to true and then afterwards setting this Force right something like that um okay so that's basically like the structure and this is backtracking um you try one thing you put it uh and this is recursion based backtracking you could of course do this with a stack this is just using the implicit core stack to represent a stack right so that's a thing um okay right so that's one way you can do it and then um depending on the performance of you know trying to optimize for this F function and stuff like that you can uh you know put down a base case and so forth um yeah so let's play around with that way let's say we have a try I have a weird thing that I'm trying to do maybe I don't know if I should do it uh let me talk it out um I usually actually for these videos I actually usually um type out a try class with a node class and so forth um which is fine it's actually what you should do in an interview um and you know definitely if you're at home and you're listening to this and you haven't done that yet actually tried to do that abstraction make it so that you have very clean code um and if you really want to go um overboard with it if you will or maybe just like regular board depending on how far you want to go um you know you can add unit testing to your libraries and so forth on your try libraries one thing that I am actually trying to um be a little bit better at and this is something that I would not recommend um but for me you know I've been doing this lead code weekly contest um typing out all that stuff is a little bit long so I'm trying to figure out how to optimize the typing speed uh just for specifically for contests so this is my warning to you don't do this at home uh but I am doing it because I because you know at the end of the day these lead code uh problems daily or otherwise um they're used the resources for you to practice on what you want to work on um and you know and for most people it is probably writing cleaner code to be honest um me here is just like you know that guy that is on these videos that'd be like hey don't try this at home unless you really know what you're doing so don't try this at home unless you know really know what you're doing and also as a result of that the code might not actually be that clean so we'll see uh at least like you know I'm still working on this I'm still learning and we'll learn together how to write a very fast type in try class and technically actually also it's a little bit faster and the reason why I say that is because uh python is just there's um there's a considerable cause to a lot of these functioning things uh method costs so you know depending how many times you do these things it may get expensive and unfortunately I have in the past where I type out the tricrest and the time's out and then I remove the tripods and replace it with some ad hoc dictionary e thing and it was much faster right so or like was fast enough to uh um to ex get accepted during the contest so I don't know so again remember to practice for your own goal and don't do what you don't do what I'm doing unless you know what you think you want to do this is not a good template especially if you're going into it um I don't know what the template will end up looking but that's what I would say um okay so yeah so that's let's see so let's say we have a route to a try and then we can do something like um let's see where that goes right so here will return the node and then now we can say um if a board of NX and Y is in node meaning that this is an edge defining on this node then we could do this um yeah that sounds okay but now we have to go back and populate this first this I don't know this is quite right we might have to change it a little bit and we have we haven't even done the base case yet um so yeah also if this is the case but also not used NX and Y I guess that is a you know that's definitely a requirement but then we have to do something like forward in words um we want to say add something to root um so yeah so current is equal to root um for C and word for character and word Charter character um so if Kern is in uh if C is not in current then current of C is equal to new hash table otherwise current of what I mean in both case now there's an invariant is equal to new um is that true oh um what am I doing here okay so let's say otherwise this is you go to a new node which I guess is this wait man might be my fingers is nothing okay so then currency you've got a cone of C is what I meant to do and then there are a couple of ways to do this sometimes when I use the uh the class structure I will I still kind of vary I mean there is a sort of a notation where you can use the dollar sign as the end string so I'm going to do that here um and maybe just set this to well you can go down it so I guess just empty string I don't know if this is good but yeah like I said this is a work in progress so please do not judge me by it quite yet um okay so here every time we do a recursion um if node uh if dollar sign and no then that means that we've reached the end then we can do answer dot append uh oh I guess we have to carry this right so yeah let's do another current uh word um yeah okay and that'll be in a way anyway so yeah and here again we do something like current.append uh board something like current.append uh board something like current.append uh board and x and y and then pop right of course you can do it another way but that's you know um that's the way I'm doing it so yeah um and of course yeah and we could still go so this does not it's not so we can contain you in that World um okay so then now uh maybe we'll call it search it's too late whatever um and then now we just kind of elevate through all of it right uh used and noticed okay I think this is roughly right but maybe I'm wrong so let's uh let's see um and of course the other thing I have to do is to um the answer I was actually debating putting it here but maybe fine maybe just do it this way then um and using a global thing uh let's give it a spin I mean it's you know there are possibly a lot of typos so then we can kind of see and of course uh we kind of added a lot of stuff um did I not check oh no yeah okay so then we go to the next node okay I forgot to modify some of these things index hour of away huh can I messed something up probably right but oh um no we would hmm oh I see did I mix up the X and the Y foreign did I mess this up oh okay at least they tell you what the NX and Y is or stuff like this but that's okay I guess we just pointed out zero two hmm wow did I miss something kind of confused to be honest but did I mess up the r in the sea oh I see wait no oh wait what am I doing wow huh I think I just did this on autopilot whoops forgot to check again okay that is a very silly mistake to kind of do a bit uh way typical I mean um I still like to get away that's why now it's a Moment of Truth see us with fast enough I mean correctness is pretty okay but did we have to sort it I guess not but it's not created just as fast enough per se so we'll see seems like it's too slow huh oh no huh oh I don't use the first character do I ever so this is like a fake first character thing it kicks off and then it goes adjacent to the first character wow that's a guy's mistake to be honest um yeah okay fine yeah I probably should have done this anyway but uh so okay so if part of I in that is actually pretty silly but it is what it is um let's see all right um and used in this case would I mean we could also re-rend this I mean we could also re-rend this I mean we could also re-rend this another way but that probably should have tested that took that long to one test that's really weird hopefully this one goes a little bit better and I don't get time limit we're aware about the time I thought I should test that though like another one answer okay well only 30 out of 64. that means something so everything's just all A's hmm I mean see now this is where we're getting to um this is getting to a point where like well like what is the um how I guess this because this exists we just keep on going right huh I mean this is getting to a point where it's a little bit awkward foreign and the reason why I say that is because I think there's just a lot of things that we can do but I don't know that so this is where we get the case where we optimize these things and there's no guarantee that this is going to be good enough for example we can maybe do something like no uh like we could delete this note so then it doesn't you know this is slightly faster but wait let's see if I can come on test cases you don't let me just copy this test case this is silly okay fine like I thought there was a button or something but let's add one but now we're like mind reading a little bit right so this took two seconds after adding that what if we didn't add that foreign three seconds right so like is this enough tough to say right to be YOLO oh man now it's even slower so um one of the things that we can do well another thing well I was gonna say we could keep the bounding but I mean in this case this doesn't have to be a set anymore but so maybe but we're only adding this like 10 times right so it doesn't actually you know shouldn't really matter but I don't know that there's a all right let's give it some interest because I'm I don't know what else am I doing here um I mean correctness I think the correct bit uh actually play not very good oh we are probably correct but in terms of timing still probably not because it was 38 out of six so that wasn't even that close to be honest now we made the 42 and we have a lot more weird libraries or a dictionary um what should I do here um I mean we can't make the recursion a little cheaper but that's just like more linear time optimization things so that kind of really uh I don't know not what I want to do per se but hmm foreign this is kind of just like really weird do I change language yeah well to experiment at least for this point I think I you know we proved it okay I don't know what I'm am I so I don't know that um and like I said part of this is going to be some kind of like mind reading thing so yeah what can we uh what can we do eat you know okay so I don't think I missed an assumption I think we're correct so far um this is implicit 10 but it can really be curse past that just because I can't really recurs past that because we uh so it's 10 depth is four to the ten or something three to the ten hmm why is that too slow do we do the 10 should be fast enough may give or take that is weird am I doing something weird or am I just doing this in a really expensive way never done this before I apparently I've done this before am I missing something obvious I mean it's only 12 by 12 so it's not even that big but what is Woods oh this is the number of words in the dictionary but we'll just put in a try so I don't know that the try is this the weak point here so that number doesn't matter after the processing should we just like Twitter yeah we might um thank you can I do anything to try something similar to this where we just get rid of things I guess so but that's just like seems so hacky meaning that um here we go okay well there's a thing so once we think like almost like okay now that we've done this and this word is not possible kind of thing let's see if we can do that okay let's say we delete this then what um then we start on this recursion if we um okay so that means that if length of node is zero meaning that just we delete it then we delete um no I just this node is a different from the recursion curse node so if basically if this node is zero then we delete this is so hacky though I don't really like it but let's see if it's faster oh you gotta be kidding me is it that much faster all right let's give it some return this is such a really silly optimization though and apparently it beats 90 degree percent just having that one I'll explain this one in a sec because I don't I just kind of tried it on a whim to be honest so yeah um like I said this is gonna be exponential let me see what past Larry did um I said it doesn't seem like you know it doesn't seem like past Larry did anything different actually I you know minus like what I said about uh having a try class everything is pretty straightforward and note class everything is what I just did so that's a little bit weird that we need to add a new optimization for it doesn't seem like I used a new optimization the other cases but the idea here that I kind of just yellowed on and one of them again this is one of those things that um there's really no way to know whether it works out until you submit it right so that's why it's kind of you know uh yeah I don't know it's just uh typical lead code things but I mean so the idea here what I wanted to do was that um let's say we create a note I'm gonna actually draw this out to hang on let me set up the drawing thing it's very weird for sure foreign so basically and you know and I'm just going to draw any random tree I mean obviously this is a try so you know you could play around with that oops something like that right uh this is just like a random try um okay so then now um let's say you know one of these has a dollar sign thing um so the idea that I initially did was that okay well we only have to match each word once right so if we get rid of this let's say we match this word you know all the way down already let's say we already match this then we don't have to match it again so then we get rid of uh this node right we just kind of delete this node bye right um and then so that was my first instinct and then you just kind of you know and you could assume that in this whole try there's all these you know other ones and eventually they get cut out right and then the next thing that I did and I'll show you in code in a second was that I go okay well let's say we got rid of you know the end nodes right so then do we do a recursion back you know we do a recursion down and then we do a recursion back up right like popping the stack and okay if this only has one node meaning that it has or if this note has no child then we can also remove it right because nothing because if it doesn't have any child there's no words underneath that tree right um and you know and then this goes back up and they go okay maybe there is a thing here right on the left side so then we get rid of this but what that does what that means for us is that in it eliminates it part of the search tree because we're not searching for them anymore so you know on a recursion thing let's say you have a um let's say you have the entire thing being a AAA or whatever right um you know and that was one of the cases and if you want to do five A's now after you do five A's um initially it would still try like after doing this it will try to do this and then I'll try to do this and I'll try to do this right like in all three directions right but now after if we move to fifth a and now we only narrow it down then now it no longer does it for every Branch so that's probably why it's faster but like I said this is like a um like a rare lead code special of um like a linear time optimization that or constant uh optimization that you have no control over and you don't know the inputs and whether you know it's going to be fast enough because it's not really you know um it is kind of a cute idea though in isolation I just don't like the logic uh in terms of you know making you guess all these things it also apparently in the past that was okay but I don't know um like I said this is gonna be exponential no matter what but now we kind of eliminated a little bit more so I don't know how you want to go but at the end of the day it's still um it still proof voice recursion uh I think all right this one let me know what you think let me show you the top of the code again and I'll see you later stay good stay healthy to good mental health uh you know I'll see you today then good night bye
|
Word Search II
|
word-search-ii
|
Given an `m x n` `board` of characters and a list of strings `words`, return _all words on the board_.
Each word must be constructed from letters of sequentially adjacent cells, where **adjacent cells** are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
**Example 1:**
**Input:** board = \[\[ "o ", "a ", "a ", "n "\],\[ "e ", "t ", "a ", "e "\],\[ "i ", "h ", "k ", "r "\],\[ "i ", "f ", "l ", "v "\]\], words = \[ "oath ", "pea ", "eat ", "rain "\]
**Output:** \[ "eat ", "oath "\]
**Example 2:**
**Input:** board = \[\[ "a ", "b "\],\[ "c ", "d "\]\], words = \[ "abcb "\]
**Output:** \[\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 12`
* `board[i][j]` is a lowercase English letter.
* `1 <= words.length <= 3 * 104`
* `1 <= words[i].length <= 10`
* `words[i]` consists of lowercase English letters.
* All the strings of `words` are unique.
|
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier? If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.
|
Array,String,Backtracking,Trie,Matrix
|
Hard
|
79,1022,1433
|
329 |
hey everybody this is larry this is day 10 of the april eco daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's file the longest increasing path in the matrix we're given m and n return the longest increasing path in the matrix okay so yeah i usually solve this live so it's a little bit slow fast forward or skip ahead or watch another video it's up to you uh okay yeah uh for each cell you can move up down left right you cannot move diagonal outside okay so n on the number of cells in this case is 200 square um so you can do this in a couple of ways i'm going to do it recursively uh the key thing to know for this problem is that this matrix is going to be a dag uh and because this is uh strictly increasing and because this is strictly increasing that means that because it's strictly increasing that means that there's no cycles and yeah and because there's no cycles then you know you can just do it recursively by uh and caching it um because it is the longest path in the dag and that is basically the standard way of doing it is just doing dynamic programming um yeah i don't know if i have a better way of explaining it but basically the question you ask and the question you ask is very important in dynamic programming in general uh in this case it's a little bit straightforward and it is that uh for each cell what is the longest path beginning at the cell um and then you know the answer is going to be the max over all the cells um so sorry i'm talking a little bit awkwardly i've i have the sniffer so like my i have some uh congestions i can't really talk that well but uh but yeah i think that's pretty much it uh with most dynamic programming one is recognization and then two is just trying to figure out how to um you know how to get in a good place and you know here we can and go just like start by uh electrical uh rows as you get the link up matrix uh columns as you go to length up make sure zero so we don't have to worry about uh numbering zeros and then we just got longest of x y say and yeah and then we can just literally start with best is equal to zero we return best at the end that's the thing uh we also want to construct i'm doing this in a weird order of course it's just whatever comes to my mind because it is uh is in uh with my card this is live uh man i am not very super well today because you can hear me being a little bit uh not coordinated i don't apologize for that but yeah and then now we just go through you know each of the four directions and then making sure that it is in an increasing kind of way so i have four dx dy in directions uh i usually do like the next nx and y is equal to x plus dx y plus t y and this is very um standard grid looking uh graph grid graph e stuff uh that's how i usually write it but you know you can write it however you like and we make sure that it is inbound so this is for rows and this is for columns and then once we do that then we know that uh we can do this we make sure that this is strictly less than n x and y and if this is the case then uh best is equal to the max of uh best or the longest of n x and y um one thing to note is that you know in a lot of cases when it with backtracking or exhaustive surge or something like that you have to do some sort of like making sure that you don't go in cycles and then go back or revisit the same cells um in this case the reason why you don't have to do that is because there are no psychos um so then we just ask ourselves um you know this question recursively of okay this is the case um you know oh i messed up wow this is plus one um because this is the okay what is the longest path at a given cell well the longest path uh starting from this given cell is just you go to the longest path of its neighbor assuming that you know it is going in an increasing order um plus one right so that's basically the idea here and this is roughly like 95 of the code uh we can and then as we said we'll just max over all the x and y possible x y so uh let's just do a starting x in range of rows applying y and range of columns it's also quite fast it's got the max of best longest and then we can rest uh this is roughly right i mean i know it's not because i didn't do the memorization part don't worry i know that i forgot this time oh i didn't forget right i didn't want i'm not doing that quite yet but that's uh that's one of the cases it should still be fast enough but we'll uh we'll beat it up with a better case up i guess this is this plus one because you have to count the starting cell which i forgot okay so this will look good but it's going to give us timeout exceed uh time limited exceeded uh because you know there's just 200 times 200 it's gonna be very slow um and we can kind of play around with that for a second yeah let's just say we have a bigger way and this actually may be fast enough because it's actually a non uh whatever graph that i'm too basically constructive a case from scratch so you might have to take my word for it yeah so this actually happens to be fast enough because like i said um the graph you know like it does it terminates really early but you can imagine a case where uh i'm too lazy to type this up um but you can imagine a case where it's like one a two uh you know something like this and then so forth right and then if you just you know construct that then you're gonna recognize that this is like pascal triangle uh or you know binomial uh sequence or whatever and from that you know that this is gonna be exponential so this is gonna run in exponential time which is not what you want uh assuming that you know you keep it strictly increasing and stuff like that and this actually this kind of um test case comes up a lot in similar problems so it's why i keep in my line and um and as you recall from fibonacci uh from binomial numbers uh you know it does grow really quickly exponentially so uh so this is a no-go we want a cache so this is a no-go we want a cache so this is a no-go we want a cache so yeah if you have to hear then you know the thing that you can do is just realize that okay the longest path on x and y uh will always be the same after you calculate it right like you only need to do it once um so with that observation like because every input x and y is always going to give you the same answer every time and that's the key part of memorization or dynamic programming and because it does then all you have to do is just want to um save it so that you don't do it more than once um and then we and we can do that very easily by just having oh let's just call it cache as you go to i don't know it doesn't and i just like writing this out explicitly for education purposes and you know but if you're at home if you're still a little bit fuzzy about dynamic programming i know that there are a couple of hacks especially in python so that you can uh do this much quicker and easier but i really urge you to kind of write out these arrays and matrixes so that you can understand the you can understand um both the complexity and analysis and also talking about it and also not in an interview people will probably ask you about it uh and it becomes more intuitive once you realize that uh but yeah uh so here we can so if as cash of x y we return cash of x y otherwise at the very end we set as cash explain true cash x5 okay so this looks good it's slightly faster but you can't really tell uh usually i do an example about it but uh but yeah let's give it a submit hopefully it's right well uh yeah so this looks good so what's the complexity here right the complexity is and you know this is why i have these things it makes it easier to kind of analyze and i would also say that to be honest um before you even program it you should be able to think about complexity because otherwise you're not really solving problem you're just guessing the solution right which sometimes it's okay for a contest or something like that but obviously on an interview you have to be able to explain it so you know um guessing is fine but you still have to be able to explain it uh but yeah but here x obviously goes from zero to rows y goes from zero to columns so therefore uh that's the number of inputs the total number of inputs is equal to uh over let's call it r times c which is that's just quite often now let's see for now uh yeah and then for each one for each possible input each input takes over four work which is obviously all one uh because this direction thing only has you know it has only four entry and i guess i didn't explain this because i take it for granted uh which is that this is just you know up down left right in some way for the dxdy um but yeah so total uh time complexity is of r times c which is linear in the size of the input um and of course in the in for space we just look at the total number of inputs and because we also take over one space for each input this is also going to be over r times c which is again linear in the size of the input because the input is r times c right um and you can kind of obviously also see this a little bit which is why i like to throw it out but yeah um that's all i have for this problem let me know what you think uh yeah is that it yeah that's all i have for this problem let me know what you think hit the like button hit the subscribe button join me discord tomorrow's saturday or today is saturday yeah i'm really tired um today's saturday so hope y'all enjoy the contest and google program and all those other stuff and good luck have fun and yeah stay good stay healthy and i will see y'all later bye
|
Longest Increasing Path in a Matrix
|
longest-increasing-path-in-a-matrix
|
Given an `m x n` integers `matrix`, return _the length of the longest increasing path in_ `matrix`.
From each cell, you can either move in four directions: left, right, up, or down. You **may not** move **diagonally** or move **outside the boundary** (i.e., wrap-around is not allowed).
**Example 1:**
**Input:** matrix = \[\[9,9,4\],\[6,6,8\],\[2,1,1\]\]
**Output:** 4
**Explanation:** The longest increasing path is `[1, 2, 6, 9]`.
**Example 2:**
**Input:** matrix = \[\[3,4,5\],\[3,2,6\],\[2,2,1\]\]
**Output:** 4
**Explanation:** The longest increasing path is `[3, 4, 5, 6]`. Moving diagonally is not allowed.
**Example 3:**
**Input:** matrix = \[\[1\]\]
**Output:** 1
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 200`
* `0 <= matrix[i][j] <= 231 - 1`
| null |
Dynamic Programming,Depth-First Search,Breadth-First Search,Graph,Topological Sort,Memoization
|
Hard
| null |
7 |
in this video we'll go over leak code question number seven reverse integer given a signed 32-bit integer we need to given a signed 32-bit integer we need to given a signed 32-bit integer we need to reverse the digits and return the result but if reversing it causes the value to go outside of the signed 32-bit integer go outside of the signed 32-bit integer go outside of the signed 32-bit integer range then we just return 0 instead and lastly we have to assume that the environment does not allow us to store 64-bit integers only 32-bit so first 64-bit integers only 32-bit so first 64-bit integers only 32-bit so first I'll do a quick review of how bits work in case anyone needs a refresher so a bit is short for binary digits and can only either be a 0 or a one if you wanted to use bits to represent integers then with only one bit you'd be able to encode two integers which would be zero and one if you had two bits then you would have two options for the first digit and two options for the second digit which means you could encode four integers which would be zero to three if you had four bits then buy the same logic you could encode 2 to the 4th power integers which would be 0 to 15. so here we're working with 32-bit so here we're working with 32-bit so here we're working with 32-bit integers which means that you could encode a total of 2 to the 32nd power integers which would be 0 to 2 to the 32nd power -1 however this only applies 32nd power -1 however this only applies 32nd power -1 however this only applies to unsigned integers which means only zero and positive numbers if we wanted to include negative numbers we'd have to use signed integers with signed integers the leftmost bit indicates the sign of the number so it'll be one if the number is negative and zero if it's positive this means that we only have 31 bits left to work with so the maximum integer is 2 to the 31st power minus one and the minimum turns out to be negative 2 to the 31st power now in languages such as Java or C the int data type corresponds to a 32-bit integer if you needed a to a 32-bit integer if you needed a to a 32-bit integer if you needed a wider range of values you would have to use the long data type which is a 64-bit use the long data type which is a 64-bit use the long data type which is a 64-bit integer so this problem is basically asking you to assume that you can only use the int data type now we're going to be using python to solve this which works a little differently because python will actually adjust the size of the integer for you but we can still solve this problem by just assuming that we're unable to store anything larger than 32 bits now let's look at the code and solve this let's say that the given integer X is 123 so we'll need to reverse the digits and return 321 as our final result the first thing we'll do is establish the maximum and minimum range of 32-bit the maximum and minimum range of 32-bit the maximum and minimum range of 32-bit integers which we discussed earlier and I've also written down the full numbers for reference then we'll create a variable called reverse and initialize it to zero and this is what's going to hold the Reversed integer we'll then enter a loop that will transfer each digit in reverse order from X to reverse and this will keep going until x equals zero now since we're assuming that the environment cannot hold anything larger than 32-bit integers we need to check if than 32-bit integers we need to check if than 32-bit integers we need to check if there's going to be overflow before adding a digit to reverse not after so here if reverse is greater than Max int divided by 10 then that means that when we add on the next digit to reverse it'll be greater than maxint and it's similar Logic for Min int as well if reverse is less than Min int divided by 10 then after adding the next digit reverse will be less than Min int so in those cases we would just return 0. you'll see an example of how this works later but for now I want to focus on the reversing part of the algorithm so first we'll extract the digit in the ones place of X by using the modulo operator remember modulo will return the remainder after division so here X Mod 10 is the remainder of 123 divided by 10 which is 3. now the reason why I have this if else statement here is because the modulo in Python Works a little differently from other languages and we actually need to use negative 10 instead of 10. if x is negative I'll go into more detail in the next example when we use a negative number but for now let's finish up this example so then we're going to transfer that digit over to reverse and the way we'll do that is by first multiplying Reverse by 10 to make room for the new digit and then adding on that digit so in this case 0 times 10 is still 0 and then we'll add three so now reverse is three the last step is to remove the digit we just transferred three from x and we'll do that by first dividing X by 10 and then using the trunk function from the standard math Library so truncating a number will simply get rid of everything past the decimal point so 123 divided by 10 equals 12.3 then truncated will just be equals 12.3 then truncated will just be equals 12.3 then truncated will just be 12. now you may be asking isn't this the same thing as using floor Division and rounding down well for positive numbers yes but the reason why we truncate instead is because of negative numbers for a negative number we actually want to round up towards zero not down away from zero again I'll show you an example of this using a negative number next so let's carry on for now we loop again and make sure that there will be no overflow we then extract the ones digit by doing 12 mod 10 which is 2. then we'll add it to reverse 3 times 10 is 30 and 30 plus 2 is 32. then we'll get rid of the 2 from X by doing 12 divided by 10 which is 1.2 then truncated is just one at is 1.2 then truncated is just one at is 1.2 then truncated is just one at this point we've successfully reversed two digits and brought them over to reverse and we only have one more digit to go so one mod 10 is 1 and 32 times 10 is 320 plus 1 equals 321. finally 1 divided by 10 is 0.1 and then truncated divided by 10 is 0.1 and then truncated divided by 10 is 0.1 and then truncated is just zero now X does equal zero so we exit the loop and return reverse and as you can see we reversed 123 so that it's now 321 and we're done now let's do an example with a negative number let's say it's negative 456 so when we're done we should return negative 654. again let's establish the Max and Min integers and set reverse equal to zero X does not equal zero and reverse is not less than Min int so let's go ahead and extract the ones digit X is negative here so we'll have to do negative 456 mod negative 10. now the reason why you need to use negative 10 instead of 10 is that in Python a modulo operation will always return a number that is the same sign as the divisor which in this case is the 10 or negative 10. so if we want the digit to be negative 6 then we would have to do X Mod negative 10 and in fact if you try to do negative 456 mod 10 you would actually end up getting 4 as your result now I know that seems weird and if you want to know why python does this I'd encourage you to look it up and read all about it but for this video I'm just going to say that when using the modulo operator with negative numbers if you wanted to behave the same way as it does with positive numbers but just have the result being negative you need to make sure that the divisor is also negative and again other languages like Java or C don't behave this way so this is kind of a python-specific thing a python-specific thing a python-specific thing so moving on zero plus negative 6 is negative six and lastly negative 456 divided by 10 is negative 45.6 and then divided by 10 is negative 45.6 and then divided by 10 is negative 45.6 and then truncated is just negative 45. now if we used floor division here the negative 45.6 would have been rounded down to 45.6 would have been rounded down to 45.6 would have been rounded down to negative 46 which is not what we want so that's why it's important to truncate the number instead of using floor division so next negative 45 mod negative 10 is negative 5. then negative 6 times 10 is negative 60 and negative 60 plus negative 5 is negative 65. then negative 45 divided by 10 is negative 4.5 and then truncated is negative four 4.5 and then truncated is negative four 4.5 and then truncated is negative four and it's the same thing for the last iteration the digit is negative four reverse becomes negative 654 and X becomes zero then we're done and we return negative 654. now for the last example I wanted to do one where reversing the integer results in overflow let's use this really long integer here which when reversed turns out to be 2 billion 147 million 483 651 so it's just above the maximum integer so by now I'm sure you're familiar with how the reversing algorithm works so I'm just going to let this run so we can get to the end the loop will keep running and reverse each digit and reverse doesn't go over the maximum integer until near the end okay so now that we're almost done let's slow it down we've gotten to the point where X is 15 so there's two more digits to reverse the digit to extract is five and then we'll add that on to reverse then X is updated to be one now on the final iteration when we check this condition Max int divided by 10 is 240 million 740 364.7 but reverse is 214 million seven 364.7 but reverse is 214 million seven 364.7 but reverse is 214 million seven hundred forty eight thousand and 365. so this condition is true so that means that if we added one more digit to reverse it would result in overflow and be greater than Max int so we'll stop here and just return zero which means that reversing X is not possible because it results in overflow now before I end this I want to address one last thing that some of you may be asking you may be saying when we check this condition don't we also need to check the value of the last digit in other words what if the reverse digit is less than Max int divided by 10 so we think it's fine but when we add on the last digit is let's say eight so now the new integer is greater than Max int and the Overflow goes undetected is this possible well thankfully we don't need to worry about this because if the last ones digit was a 8 or a 9 then that means the original integer which was reversed was already out of the 32-bit reversed was already out of the 32-bit reversed was already out of the 32-bit range so it would have been impossible to receive this number as an input since the environment doesn't allow us to store 32-bit integers the lead code store 32-bit integers the lead code store 32-bit integers the lead code question also explicitly tells us that the input will be within the signed 32-bit integer range which is why we 32-bit integer range which is why we 32-bit integer range which is why we don't need to check to see what the last digit is and so the reason this works is because the rightmost digit of the maximum integer is greater than in the leftmost digit because of this I know that even if the original integer has the same number of digits as Max int the leftmost digit must have been two or less therefore when the original integer is reversed I know that the last digit to be added will never be greater than seven so I know that this will never cause overflow so because of this property we don't need to check the value of the digit that we add on to the Reversed integer but I wanted to mention this because if you were to do a similar type of problem where your maximum or minimum value didn't have this property then you would have to check the value of the digit in order to avoid going over the maximum or minimum value
|
Reverse Integer
|
reverse-integer
|
Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`.
**Assume the environment does not allow you to store 64-bit integers (signed or unsigned).**
**Example 1:**
**Input:** x = 123
**Output:** 321
**Example 2:**
**Input:** x = -123
**Output:** -321
**Example 3:**
**Input:** x = 120
**Output:** 21
**Constraints:**
* `-231 <= x <= 231 - 1`
| null |
Math
|
Medium
|
8,190,2238
|
1,994 |
hey what's up guys uh this is sean here again so lead code number 1994 the number of good subsets okay so this one is another like subsets uh or subsequences problem right so this time you're given like integer array numbers because subset numbers of good if it's a product can be represented as a product for one or more distinct prime numbers right so for example we have this one two three four uh these three are good subsets because uh the product can be represented as two times three this one but this one is not because four itself is not like a good candidate because this one can be basically this one is like uh it's a it's not distinct prime numbers right it's like a duplicated one same thing for what for 9 right 9 is also not good one because 9 equals 3 times 3 right and then 16 is another one right 4 times 4 and then 25 is another one right equals to 525 so something like this so these numbers are by itself are not good candidates which means we cannot pick those numbers regardless right so that's one thing and then return the number of this blah right and then the uh so and again right this one is a dp problem right so but this one so how do we get started basically you know we have solved some of other like subsequences or sub subsets problems you know if everything basically if there's no constraint right the uh the total number of subsets or subsequences is going to be 2 to the power of n right so this one including the uh the empty subset so for this one i think yeah i think it does not allow empty that's why we have to do a two minus one in the end okay but we can deal with this one later so the uh the base of a subset is that you know if we don't if there's no constraint at all right so every time i think i've already talked about this several times we have this one right the uh let's say we have a and b right a b so the subset for this one is going to be a b and empty string right so every time when we add a new one right it's going to be a ac a b c and a c right basically the total number of subsets will be doubled right but this one is like uh either constrained a unique or like uh like a good subset i called i call this kind of problem it's called i think we can call it a constrained subset right basically you cannot blindly get whatever you want you have to delete something right from it or we're not add current number so for this one the constraint is like uh we want all the numbers we pick in the subsets has the unique distinct prime numbers can be the product can be that right and how can we do it right so first right so first let's say we have you know the prime numbers are what like what the prime numbers are like 2 3 5 7 11 13 right so on and so forth right so let's say for number let's say we already pick a number right the card number has already uh used the sub the prime number this one and this one right for let's say for the for all the previous number we have already picked those numbers have already used these three uh prime numbers and then when we try to pick up the card number right we want we need to know the current number does not have any of this uh previously have already used prime number in it right so let's say if the current number is what it's 10 then definitely this is not a candidate right because 10 we have two and five right so if we add 10 to the current subset you know since we already use two and five then we'll have like two times 2 and 5 times 5 right but i think 21 is fine but 21 is fine right because 21 is a it's a prime number prime like for 3 times seven right so we can use this number because by using these numbers you know we have three and seven later on right which does not uh result to a duplicated uh prime number okay so now so and then so basically this dp is like a knapsack dp problem so basically with the card numbers we have two options we either pick this one or we don't pick it right based on what are the prime numbers we have used and what are the prime numbers these new numbers we're trying to pick will be added what are going to add to the prime numbers uh set right cool so in that case oh let's go back to the problem here the constraints right uh so the constraints is like the number is pretty long 10 to the power of five but see the number itself is pretty small only uh within 30 right cool so in that case um we can just start from this one and regarding this kind of all the numbers we can do a frequency we can do a count for all the numbers okay because you know let's see if we have uh 5 2 if we have 5 2 here you know we can simply in the end right so no matter okay so let's say by adding this two into the uh we'll have like uh ten more uh sub subsets right and since we have five tools right we can simply do a ten times 5 equals 50 which means that for all five twos we will have like in total we'll have like 50 news subsets right this is because you know let's say we have different numbers okay and we have two we have another two right another two okay since it's all subset right we don't have to we can pick any two from this numbers because it says uh the two subsets are different if the chosen indices to delete are different basically if we pick these two it's different as we pick these two is these two are they are totally different but by picking any of them we're adding like the same base count here as 10 so that we don't have to worry about this long array all we need is like do the frequency right of each number and then let's multiply the frequency in the end so that's another trick right and then okay so now how about so how do we check right how do we check if we can pick the card number right so remember we were trying to say if we can you we want to know if the current number does not have any uh prime factor factors that has already been used before right so which means for each of the number right we need to get its prime factors right and then we need to do like cross comparison with the previous one and what we can do is that we can do use a bit mask right so you know since the number it's pretty small right only within 30 right we can have like a beat mask to tell us the uh what are the uh prime numbers we have already used right so let's say this one corresponding to 2 3 5 7 11 13 next one is 17 i guess right then 19 yeah so whenever this one is a one it means that okay so we have already used this prime number has already been used right so let's say for example this two has been used which means we cannot use those two numbers again right and then that's the current mask and then we for the card number right we need to basically uh also make a new mask for the card number to tell us like what are the prime numbers that this new number can will i mean will contribute right so for example this number will contribute to this two right it's gonna be this two zero right and how do we check if this two does not have any intersect we simply do an end bit wise end if the bit was n equals to zero it means that okay there's no intersection right if it's one if it's not equal to zero that means that for example if this one also has like this as a one right and then the final end big twice n will not be equal to zero right that's yeah so that's how we tell we can quickly check right so that we don't have to like do a cross uh for loop here we can just use a one uh of one time to check if this one it can be added or not okay and that's that so and there is one last thing we need to be careful is that the number is the number one right remember so for all this kind of prime numbers we can only add a one uh those numbers once right for example if we already add one three here we cannot add another three but one is different you know because let's say if we have multiple ones here you know we can add at as many of them basically we can freely add these ones regardless we can add a one or two one or three one or four one because it doesn't really matter because it will not affect the final product and since the index for this ones are different that's why you know we need to consider them separately which means this is going to be like what so when whenever it comes to 1 it will be like a full subset without any constraint which is what which is going to be the 2 to the power of n where the n is equal to the count of 1 right because like when it comes to no constrain uh subsets every time we add the numbers here right the total uh count will be doubled right so that's the last thing we need to be careful cool so i think we can start our implementation then okay uh first uh let's do a prime right so because we since we need to cr build like a bit mask for all the primes numbers we need to find all the primes within this range right so how do we do that uh of a street four ways like this right we simply just start from 2 to 30 right because prime numbers start from 2 right and for each number uh we do a check right uh i is going to so we do i equals to 2 and y well i is the square of i is smaller than number right so uh if the number to a modular module of i is equal to zero and that means that it's not then it means it's not prime okay and then we break right so if the is prime is true then we add this primes to the prime list okay because the definition of a prime number is that the prime number can only be divided by one and itself right that's why you know we uh we start uh we stop when the basically we only try it uh square root times of this number if any of them can be divided by this i then we mark it then it's not prime right there's no way there's no need to go over that right go over the square root number okay cool so now we have that we have a prime list right or you know what since this one is pretty small you can just at least manually write down the list it's up to you and then we have a count right so the column is going to be a counter dot numbers okay and uh and then our dfs right dp is going to be the i and mask right so this means that you know we are processing this number and the mask means that you know the mask is representing what are the uh how many prime numbers we have used so far okay and none right cool and to start with uh you know what let me do a keys i'm going to conver get all the keys so that we can uh loop through from by index okay and then we have n is going to be the length of count right and then here we return the what we return the dp of uh starting from zero and the mass is zero because at the beginning everything is it's uh it's not used okay and we do a minus one right we do minus one to remove the empty subset right and then we have a mod knight plus seven okay but you know here uh we okay you know uh i'll handle this last part later let's implement this dp because we haven't uh i know that one case but we'll do that later so let's finish this dp part okay so now we have that right and uh oh how about so basically so whenever i is equal to n it means that okay we have reached to the end basically we have a traverse to all to everything and then it means that okay we find one subset possible subset right by either like picking some numbers or don't pick at all but regardless we have already traversed to the end of all the numbers okay and then we have this number right so number will be what will be the keys of i right sorry keys of i okay so first one is not peak okay not peak current number which is we're going to be the answer equal to the dp of i plus 1 dot mask which means we're not doing anything that's why well the answer will be the same as the previous as the uh as the next state right so if we don't pick the current one it'll be whatever uh we will be whatever we have right of this one okay else we pick the card okay peak current number right but to pick the current number um but the peak current number we need to check something right and then we return the answer in the end so first we need to check oh we need to have like the mask so the prime mask right so the prime number is mask for the current answer five star for the current number and how can we do it right uh we can do this so basically we try to for card number we try each of the uh we try each of the prime numbers okay we try to divide it uh do a modulo with each of the prime numbers if any of the if the any of the modular is equal to zero and it means that okay so the current number uh will have that prime number right and then in the end right because you know in the end we want to like uh accumulate everything together right because so let's say we have 2 3 the prime is 2 3 5 7 11 13 right so let's say okay so let's say the current number is what the current number is it's like it's 35 okay so we need this two number to be marked as one okay and how do we do it right so since we already have the prime numbers here right we simply just need to do uh like so basically we'll get for each of the numbers whenever it's like it's we know if there's a prime number for this one we're gonna do a bit wide a bit shift okay so when we see five right we'll have what we have zero one zero right because the index for this primary is we already know that right and then what and then the uh how about seven then probably with seven we're gonna have like zero one zero right and then we want to accumulate them together right which is going to be a x or where sorry not i not x one but or we do a sum you know because or in the bitwise is equivalent to the sum right that's why we can do a sum of this uh for what four i dot p right the prime numbers in enumerate of primes okay if the num if num divide a modular p is equal to zero okay so we have what we have this kind of this one right that's how we get the beat mask for all the prime numbers for the current number okay and then we can do our check here so first we need to make sure the card number itself is not a it's not a bad one right so what are the bad ones so for example i already talked about that so 4 9 and 25 they are bad right and anything that's can be divided by these three numbers are also bad right so which means if we need to make sure if this one is not equal to 0 and the number of this 9 is not equal to 0 and number to a modular of 25 is not equal to 0 right and the last one is this and the last one is mask at the end of this prime mask it's also equal to zero right then this one means there's no intersection of the prime numbers which means we can use the card number and which means we can accumulate this one to the dp of i plus 1 dot mask prime mask right because after choosing these numbers we need to mark those prime numbers to be used which means we need to mark them into one right and then don't forget to do a count right multiply by the count if we have multiple numbers right and then in the end we return the answer i think that's it right uh okay cool but there is like a special case we haven't uh i know yet which is one right so all this stuff they are for at least this part is for none one numbers right because for none what numbers that's when we need to uh do this mask checks right but when but whenever it is one right whenever it is one what does it mean it means that okay so for one actually we're assuming that we are pres uh we're assuming that uh we're not going to pick once we're not we're basically we're completely ignoring one because we'll be when we do a two to the uh two to the a power of two and then we do a count of one right and then we do a modular because this is what we'll be doing in the end to handle once which means we should we will completely ignore a one in this main dp function here then how can we do it right so basically here it's not picking current one you know we cannot do this if number is equal to one we simply return here this is wrong because we still want to continue basically we want to ignore it right it means that here we're ignoring the current card number right but here we're trying to pick it so all we need to do is we simply just ignore it here right we add one more statement if the number is not equal to one and then we continue if it's one we always skip the current one okay i think that's it or i think there's another way that i think you can maybe sort this key right basically you can store this key from the smallest to the biggest and then you simply just start processing from uh we are just processing from let's say we have one two five and seven we can just start processing from two right instead of one yeah i think that's another option but anyway i think if we don't sort it you have to add one more statement here to include to exclude one in this case in the peak pick the call number case okay and the last thing is like this i think okay so let me try to do this so we uh we do it like 2 to the power of n the reason we do a like power with modular is because if one is pretty big right let's see if the ones we have 10 let's say 10 000 right they're all ones right then if we do a 2 to the power of 10 000 this will be too big that's why uh we in python we have this kind of power function with a modular that can give us like a reasonable answer for the for this power and then in the end i will do another modular right and i think that's it uh run it oops okay run codes accept it okay what did i uh let's see uh i thought this should work let me see the prime are we doing okay all right here power right i times i alright i should do this i times i right let's try again okay cool so this one works right um yeah i think that's it right i mean as for the time complexity uh we have a what so let's say this one is n right so we have n times uh the mass is like what is also 2 to the power of n right so the mass is the length of the what length of the prime numbers right which is i think which is also 2 to the power of n okay yeah the prime number will be a little smaller than n but i think it's still in the scale of n right and then here we don't have anything right we just either we pick or we don't pick okay yep i think that's it for this one and yeah another subset problem another constrained subset problem right and in this case the constraint is from the prime numbers right basically uh the each subset can only have distinct prime numbers right and in order to do that we uh we create a bitmask right for the prime numbers we have already been used and then for each of the number we created like another bitmask for the for prime number that will come from the new number right and then we check if this 2 doesn't have any intersect and then we use this number okay and then we also want to make sure the current number itself is a good number it's a good number to use and lastly this is this kind of constant right we have to make sure we need to know uh instead of traversing everything we can just do a count in the end and then the last thing is this one thing right so yeah a lot many minor uh traps there right but there you go that's it okay and thank you for watching this video guys and stay tuned see you guys soon bye
|
The Number of Good Subsets
|
minimum-number-of-swaps-to-make-the-binary-string-alternating
|
You are given an integer array `nums`. We call a subset of `nums` **good** if its product can be represented as a product of one or more **distinct prime** numbers.
* For example, if `nums = [1, 2, 3, 4]`:
* `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are **good** subsets with products `6 = 2*3`, `6 = 2*3`, and `3 = 3` respectively.
* `[1, 4]` and `[4]` are not **good** subsets with products `4 = 2*2` and `4 = 2*2` respectively.
Return _the number of different **good** subsets in_ `nums` _**modulo**_ `109 + 7`.
A **subset** of `nums` is any array that can be obtained by deleting some (possibly none or all) elements from `nums`. Two subsets are different if and only if the chosen indices to delete are different.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** 6
**Explanation:** The good subsets are:
- \[1,2\]: product is 2, which is the product of distinct prime 2.
- \[1,2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[1,3\]: product is 3, which is the product of distinct prime 3.
- \[2\]: product is 2, which is the product of distinct prime 2.
- \[2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[3\]: product is 3, which is the product of distinct prime 3.
**Example 2:**
**Input:** nums = \[4,2,3,15\]
**Output:** 5
**Explanation:** The good subsets are:
- \[2\]: product is 2, which is the product of distinct prime 2.
- \[2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[2,15\]: product is 30, which is the product of distinct primes 2, 3, and 5.
- \[3\]: product is 3, which is the product of distinct prime 3.
- \[15\]: product is 15, which is the product of distinct primes 3 and 5.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 30`
|
Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n.
|
String,Greedy
|
Medium
| null |
991 |
hey everybody this is larry this is day 23 of the march lego daily challenge hit the like button hit the subscribe button join me on discord let me know what you're thinking let me know how you're doing and all that good stuff and today's problem is broken calculator uh okay so you can multiply the number on two or this subtract one okay uh x and y can be really big so you have to be careful though you should only need to double not that many amount of time let's think about it i feel like this was a problem we've seen recently but in another variation i think the um let's see so there are a couple of things that i like to play around with um and i would also say that breakfast search is maybe too slow no um at least the naive version of it uh one thing that i'm thinking of just like okay let's say we can multiply by two and then keep one multiply by two and then subtract one right but you may have some like weird thing like this one where you may double and then decrement and then double so that's not super good um and then another thing that i always think about when i see problems like this is see if i can go backwards right so instead of going from two to three or three to ten you go from ten to three um and in that case obviously you just um you just um sub you just divide by two and then you add um and i think one thing that i am also trying to prove to myself is that um and also one thing in general is that sometimes these examples are definitely meant to mislead you and what i mean by that is that yeah you can double decrement and double but you could also uh recommend double or something like that right you could um maybe not for this case but that command double maybe not maybe i'm lying on this one but what i mean in this just don't trust the example to give you i mean trust it to give you the right answer an optimal answer but the explanation may be misleading that's what i'm saying um and in this case i would say five and then let's say you go to five right from target i think it's easier to go backwards for the reason that your search space is smaller because every time you because it's very clear is that true maybe not i feel like this is a weird like math problem i mean like i also feel like the code's gonna be like five lines of code or something like that or ten lines of code or whatever but um but yeah so let's say ten we go to five um i think there is some math in which it makes sense but five well you can there's no so you have to add one you get six and you subtract you go to three i mean this one maybe makes sense but i don't know if that's always going to be the case well so we go backwards then now we have delta by 2 and add 1. so then here we can i guess the math is easier right because for 8 to go to 5 um well let's say okay let's say we have x and y right let's say 2 times x is greater than y um and we're going from y to x say well in this case it always makes sense to dirty by two right just because well it takes one operation and even if x is one or something it doesn't matter right like this is just easier to do right so this is the case where greedy makes sense let's say 2 times x is greater uh you go to y well obviously in this case you just take the half and then you get to x so that also is a good idea but what if you have 2 times x is greater than y right then what happens well what happens is that you have just one math calculation right you have x plus some constant c is equal to y or you have x um you have x plus uh well let me i think i didn't explain this particularly so let me step back a second so the reason why you always want to go half is because then now you can get the question of whether you want to go half again on the smaller one um and that will all be optimal because by definition um you know you can write this as x plus x is equal to y uh less than y and obviously if you take x operations on the other side um because this will take x operations which is way more than one operation even if it's equal to one right and then you could do it again um and you could do some math about repeat doublings or something like that so i think now um and this is i think i have the idea but now i'm trying to prove it right and then now um let's say this is the case that means that x plus c is equal to y that means that um you only have two ways you can do it right you either you add you um you subtract c it takes c operations right or you do something like your x divided by two which takes one operation um is that right maybe i'm wrong on this one uh no because then you have yeah and then you do the math on that i guess maybe that's the answer uh i don't think i did a great job explaining this is where you mathematical and like i think for you to prove you just have to list out all the cases i think i'm a little bit shaky today because i'm a little bit tired uh my apologies for my viewers at home uh but definitely if you i think it is just listing out every possible case and then prove to yourself that is the optimal okay so let me play around that right so operation oops so let's just say count is equal to zero and then while target um yeah also if the top if your current target meaning you're going backwards if it's odd then you have to add one because well um you have to add one because um let me think about this for a second hang on well because you can't get to target without um without doubling and then subtracting right so yeah i would say though another way of thinking about it is i think is that true maybe that's not true because if you want to go to nine for example however you go to six no you got two four eight i don't know that's awkward okay fine uh yes this one is kind of tricky to explain but the reason why all right let's just do start while you is well i guess just you that's 10 right so if the target um if this is odd right what happens well that means that you have to double the previous time right so that means we add one we have and then count we increment by two then else target two um and then now your answer should be count obviously but then the difference between the count and in this case we guarantee that the target is smaller than start value um so then start your minus target i think that's roughly right i think my explanation is terrible though dude because these mathematical problems are a little bit tricky um but the idea is that if you have one operation you always want it to be halving because you have to get you want to get the target to be smaller than the surviving value so then you can add to it um so then you're basically getting the optimal starting value um yeah i think this is one of those funky problems this is greedy as hell but uh it's also hard to bring an expert i'm trying to think about a better way to explain it but it's just that um i think if you list out all the cases the um the path to a proof is that you can almost always prove that um well you can only increase by doubling and you want to do the doubling the latest as possible to get it as accurately as possible otherwise you're going to overshoot right so then the idea is you know if you could double or if you increment and then double a double moment and then increment um you want to get the one that is closest to the target and the target is always going to be the one where you increment an outside decrement and then uh double because that is going to be closer assuming that they're both greater than the target um just by definition because otherwise you're adding two instead of adding one so it gives you more position and so forth i don't know this is a great explanation let me know what you think in the answers on the comments uh it seems like the last time i did i also spent a long time trying to prove to myself how did i do it last time um yeah i don't know how to explain this one i did the same thing last time i guess except for that actually my last quarter is karina but i don't know let me know what you think um i think the idea is also if you look at it backwards you want target to be the biggest value that is smaller than starting value uh and then in that case having it uh as early as possible gives you um that possibility i don't know anyway of course if you look at this code though in terms of analysis even though i don't think my explanation is great my apologies come back well go to the discord and ask someone uh but uh this is gonna be linear time linear being of course the number of bits into the input and the number of bits is gonna be log n and of course you divide by two every time pretty much or every other well in this case the way that we write it this time is that you divide by two every time so this is going to be at most uh linear time of or one operation per bit in terms of space i guess you could stay the same thing technically as linear space because that is the size of the input uh cool that's all i have for today uh let me know what you think stay good stay healthy to go mental health i'll see you later and take care bye
|
Broken Calculator
|
array-of-doubled-pairs
|
There is a broken calculator that has the integer `startValue` on its display initially. In one operation, you can:
* multiply the number on display by `2`, or
* subtract `1` from the number on display.
Given two integers `startValue` and `target`, return _the minimum number of operations needed to display_ `target` _on the calculator_.
**Example 1:**
**Input:** startValue = 2, target = 3
**Output:** 2
**Explanation:** Use double operation and then decrement operation {2 -> 4 -> 3}.
**Example 2:**
**Input:** startValue = 5, target = 8
**Output:** 2
**Explanation:** Use decrement and then double {5 -> 4 -> 8}.
**Example 3:**
**Input:** startValue = 3, target = 10
**Output:** 3
**Explanation:** Use double, decrement and double {3 -> 6 -> 5 -> 10}.
**Constraints:**
* `1 <= startValue, target <= 109`
| null |
Array,Hash Table,Greedy,Sorting
|
Medium
|
2117
|
1,688 |
all right let's talk about tons of message in tournaments so you are given integer and the number of teams in the tournament that has a string rule so it's determined it's even team or all team so there are different rules so return the number of matches playing the terminal into the winner until the winner is decided so if you have 17 so one two three four five six of them if you have 17 how many match do you have so this is 17 uh two teams have had to match which is here another two team has another man another two team has a match but this isolated team is actually just move up which is exactly the same thing right and this student has another match and the win winner match is actually between these two right you have a winner so how many things do you have uh how many match so how many match do you have one two three four five six and this doesn't count as match because uh you just move up right you from here you move up this is due to my r so i'm going to replace this is rc so you don't get confused this is a match overdue and they just start writing so i have to say in smash which you can do and while earn is greater than one the reason why i say greater than one is because we have to keep dividing by two because for two teams you have one match right so we just actually divide by two and your match will become the number of team based on the number of teams right if this is all right you'll earn mark 2 1 if this is all how many match do that so this is seven right away right so how do i know the number of match in the number of teams or the number of thing on the second level seven mod two is actually one right so how do i say this is four right the second level is four and this is seven so seven divided by two plus one this actually sounds pretty good so um you go by two plus one this is for all numbers how about the even number so if there's even a number then you do have uh 18 right 18 you have four teams on the second level which is a divided by two is four right and this will be the third and they just return back and let's just run it yeah this is straightforward and all right it's good so how do i determine the timing space complexity for this one space capacitance is constant it's you don't have okay space and time is actually logger in line like you keep dividing by two every single time right that means time is an open and this will be a solution but i will have to give you a quick solution the most efficient solution which is returned and one and if you don't believe it like if you want it which is cool right so if you look at the math like it doesn't matter like it's all or even it's actually just divided by one 14 and then 13 uh 14 teams and there are 30 match so uh you can just draw it up on your paper and you can do it and the timeless base complexity for this one is actually constant which is all one and this will be a solution and if you feel helpful subscribe like if you want comment if you have any question this question is pretty easy but you just have to figure out what is the constraint why is the strength rule for the other event and this will be this is pretty much really easy and i will see you next time bye
|
Count of Matches in Tournament
|
the-most-recent-orders-for-each-product
|
You are given an integer `n`, the number of teams in a tournament that has strange rules:
* If the current number of teams is **even**, each team gets paired with another team. A total of `n / 2` matches are played, and `n / 2` teams advance to the next round.
* If the current number of teams is **odd**, one team randomly advances in the tournament, and the rest gets paired. A total of `(n - 1) / 2` matches are played, and `(n - 1) / 2 + 1` teams advance to the next round.
Return _the number of matches played in the tournament until a winner is decided._
**Example 1:**
**Input:** n = 7
**Output:** 6
**Explanation:** Details of the tournament:
- 1st Round: Teams = 7, Matches = 3, and 4 teams advance.
- 2nd Round: Teams = 4, Matches = 2, and 2 teams advance.
- 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner.
Total number of matches = 3 + 2 + 1 = 6.
**Example 2:**
**Input:** n = 14
**Output:** 13
**Explanation:** Details of the tournament:
- 1st Round: Teams = 14, Matches = 7, and 7 teams advance.
- 2nd Round: Teams = 7, Matches = 3, and 4 teams advance.
- 3rd Round: Teams = 4, Matches = 2, and 2 teams advance.
- 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner.
Total number of matches = 7 + 3 + 2 + 1 = 13.
**Constraints:**
* `1 <= n <= 200`
| null |
Database
|
Medium
|
1671,1735
|
108 |
Hello everyone, you are on the Lagovsky channel, here we solve slitcode problems. Don’t forget to we solve slitcode problems. Don’t forget to we solve slitcode problems. Don’t forget to subscribe, write your comments and let’s subscribe, write your comments and let’s subscribe, write your comments and let’s go to problem 108 today, we need to convert a sorted array, a binary search tree, which means the conditions of the problem, we are given an array of nums where all the elements are sorted and we need to convert it into a binary search tree let ’s immediately remember what a binary ’s immediately remember what a binary ’s immediately remember what a binary search tree is, this is a tree that obeys the following rules: if you take some following rules: if you take some following rules: if you take some note, then all the nodes on the left will always be less than this note here 0 Everything on the left will always be less than zero, this applies to each level That is, if here 9 on the right is greater then on the left should be less than 95 minus 3 minus 10. How will we decide since our array is sorted, then immediately a binary search comes to mind, that is, we simply find the middle of this array with a binary search, this will be our root, then everything to the left of our array will be by the left side is everything that On the right from the right we repeat the same operation on each radio. Let's write the code, which means we set up a left index that will indicate the beginning of the array, we set up a right index that will point to the last element of our array, then we need to calculate the MID of this MID after that we set up our tree and we say that its value will be equal to the average value of which we found and its left branch will be a recursive call to our function But with values only to the left of Mead with values only to the left of Mead with values only to the left of Mead for the right we do the same but cut off all the values on the right, that is, we will Here all the values on the right, that is, we will Here all the values on the right, that is, we will Here for these values at the course call for these values at the course call for these values at the course call And after that we should just return our Root Let's try to launch yes We should have also provided a Corner case When we have a completely empty array Let's add such a check so after that everything worked perfectly Let's click ourselves there the problem was solved correctly thank you all for watching Don't forget to subscribe to the channel everyone See you again
|
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
|
240 |
hey guys today we are going to solve the problem search in a two-dimensional problem search in a two-dimensional problem search in a two-dimensional Matrix 2 in this problem we are asked to write an efficient algorithm that searches for a value Target in an M byn integer Matrix and we are being told that the Matrix has two properties each row is sorted in ascending order from left to right and each column is sorted in ascending order from top to bottom okay that is pretty clear how can we solve this problem The Brute Force way would be to Simply have two for loops and iterate over every possible location in The Matrix and every time we are at a certain location i j ask is the Matrix at this location is the same as Target if yes we're going to return to if we didn't find a location in The Matrix that holds the value Target we are going to return false so the complexity of this algorithm is going to be n by n because sorry M by n because there are M rows and N columns and we are going to go over all of the Matrix but of course we can do better than that because in this solution we didn't even use the fact that each row and each column is sorted so what if we were only told that each of the rows is sorted so let's say we add this given to us but we didn't have the fact that the columns are sorted how could we solve this problem then well still we could have a pretty simple solution we could iterate over each row and search only inside that Row for the value Target and how are we going to search for the value Target we are going to perform a binary search so this solution would also work so we would start at the first row and we would check for Target equals 5 in this case we wouldn't find it and we would go to the next row and then again we would perform a binary search and we would find five so we would return two the complexity of this solution would be M because that's the number of rows times each binary search cost us logarithmic time in the number of columns so that would be the complexity of this solution and the space complexity of this solution would be constant H the same applies to The Brute Force solution it would also be constant space okay but how can we also use the fact that each of the columns is also sorted there are many ways to use uh those two facts there are also other ways to solve this problem with binary search but there is another solution that I really like because I think it requires you to think outside of the box but in the same time it's not too hard to come up with so let's clear the board and explain the next solution let's look at the following example in this example we are looking for the number 20 inside of our Matrix and we can see that 20 is indeed in The Matrix imagine for a second that you are standing in this Matrix and you are beginning from the bottom left you are seeing the number seven and you ask yourself where should I go from here well seven is smaller than 20 so you know for sure that 20 is not going to be anywhere above you why is that well because the columns are sorted you also know that 20 is not going to be to your left in this case it doesn't matter so the only logical thing to do is to go one square to the right now you are looking at 21 and again ask yourself is 21 our Target if yes then of course we find the target but if not we know for a fact that 20 cannot be to our right why is that well because again the rows are also sorted so the only logical thing to do is to go upwards to nine now we are at nine and we see that 20 is bigger than nine so again it doesn't make any sense to go up because Target is not going to be there so we should go to the right and again we should go to the right and now we at 27 is bigger than Target so we know that the target could not be to our right in this case it doesn't matter because we are at the edge anyways and we are going to go up and now we found Target what so as I said when we are looking at a certain element we can safely know that it's not going to be above us so why should we even try to go up we know that at some point we are going to have to go to the right so let's go to the right now this is a kind of a greedy algorithm and in this case you can see that it works I think it's pretty clear what is going to be the time complexity of this one this solution is much more efficient because at each step we are just going one step to the right or one step to the top and obviously we are going the worst case is we are going to end up somehow it doesn't matter in which kind of root we are going to end up at the top right so that in the worst case would be n + m that in the worst case would be n + m that in the worst case would be n + m steps so the time complexity is going to be linear in n and M and the space complexity is still constant there is one more thing I want to explain about this algorithm and I thinks it will also help to understand the intuition behind it so we decided to start from the bottom left but could we start our traversal over the Matrix from the top left or maybe from the bottom right or top right could we and the answer is we could start from either the bottom left or the top right why is that well again when we looked at the bottom uh left we knew that for sure the answer is somewhere in The Matrix so somewhere above us and somewhere to our right we knew that there is some type of traversal that each step we only go to the right or upwards and if the target exists then we will get to it and then when we looked at a certain element we knew that if it is smaller than the target then it couldn't be that the target will be present inside of this element's column so we knew that the answer is going to be somewhere here and for that reason we knew that you can know we can go to the right and still have some type of boundaries that the target is going to be inside of them if it exists in the original Matrix so at every step we kind of cornered the targets that we want to find but what about if we didn't start from the bottom left but instead we started from the B from the top left so we would have the same property in the beginning we would know that okay in the beginning the target if it's in the Matrix is going to be inside of the boundaries that we'll begin with but what about now if we compare one to the Target we are going to see Target is bigger but we have no idea if we should go to the right or we or if we should go down because both the rows and the columns are sorted in ascending order so if 20 is bigger it could be both to our right or to our left so for example in this case 20 could be here and if 20 is right here then we must go to the right we can't go to the down downwards but if 20 was here then we had to go downwards and we couldn't go to the right because then we would eliminate 20 because we would only look at this part and why is that the case because when we start from the top left or from the bottom right both the rows and the columns are sorted in the same manner in contrast when we looked at the bottom left or if we have looked at the top right then on the one hand the rows are sorted in ascending order if we are from the bottom left and the columns are sorted in decreasing order so we had like two options either Target is bigger than us and then we would want to increase the current value so we could for sure go right our Target was smaller than us and then we wanted to decrease the current value and we could go up I hope it's clear now so this is both explaining why you can start from two of the other corners and also I think it kind of explains the intuition because this is kind of what helped me to solve this problem and now let's move on to the code is extremely simple I promise so just hang tight and we are getting over it soon okay so as we said we are going to start at the bottom left of the Matrix and now we want while we are in bounds to every time ask if the coant element we are looking at equals to Target if yes then of course we found the target if not then we're going to ask is the target smaller than us in the last case is when the target is bigger and if we didn't find the target while traversing The Matrix then we know that it's not there so this should do as you can see it walks by the way I will mention one thing which is kind of funny the solution is actually practically at least in the test cases that you are given by Le Cod less efficient than the solution that the second solution that we talk about I will just show it for fun but one solution that we said is we could travel all of the rows and for each row we could have a binary search so we will have to write some function that performs binary search so the binary search function will return us through if the row in The Matrix if the specific Row in The Matrix has Target in it so what we are doing is for each row in The Matrix we are going to run binary search to check if the target is inside that row and if we didn't find Target in any of the rows then we are going to return false and as you can see it works and it's actually yes slightly faster but this is the better solution in a job interview it's always good to give out all the solutions that you have so every solution you have and it's working then it's worth pointing out so in a interview I would for sure talk about the Brute Force approach of course you would only talk about it for maybe 10 seconds and then I would actually also explain this solution and I would maybe say that if only the rows were sorted then I would use this solution If Only The Columns were sorted then of course you could do the same solution but on the columns and yeah so as I said these Solutions runs in M time log n and you could also do the same solution for the columns so you could do n * log the columns so you could do n * log the columns so you could do n * log M and we also have the more efficient solution at least by the time complexity that runs it's here that runs in N Plus um which is the best solution for this uh problem as I pointed out there are a few more solutions but I think it's too much for one video and they are also a bit more complicated and not as good and there are solutions that use both and the fact the rows are sorted and the fact the columns are sorted but they are actually not really better than this solution they have different time complexity but not necessarily better and that's it guys I hope it's clear and I hope you enjoyed and see you next time
|
Search a 2D Matrix II
|
search-a-2d-matrix-ii
|
Write an efficient algorithm that searches for a value `target` in an `m x n` integer matrix `matrix`. This matrix has the following properties:
* Integers in each row are sorted in ascending from left to right.
* Integers in each column are sorted in ascending from top to bottom.
**Example 1:**
**Input:** matrix = \[\[1,4,7,11,15\],\[2,5,8,12,19\],\[3,6,9,16,22\],\[10,13,14,17,24\],\[18,21,23,26,30\]\], target = 5
**Output:** true
**Example 2:**
**Input:** matrix = \[\[1,4,7,11,15\],\[2,5,8,12,19\],\[3,6,9,16,22\],\[10,13,14,17,24\],\[18,21,23,26,30\]\], target = 20
**Output:** false
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= n, m <= 300`
* `-109 <= matrix[i][j] <= 109`
* All the integers in each row are **sorted** in ascending order.
* All the integers in each column are **sorted** in ascending order.
* `-109 <= target <= 109`
| null |
Array,Binary Search,Divide and Conquer,Matrix
|
Medium
|
74
|
215 |
Hello friends, welcome to your channel, today is our day 35. I want to discuss something before starting the question challenge to the lead. I did n't realize that the challenge has reached 35 days, but a very interesting journey is going on for you guys. We are getting a lot of support. Okay, so keep supporting like this and keep connecting with us. We are going to bring many more things. Okay, you will gradually come to know about the things. Keep a little support and a little motivation. To give, write in the comments that today's challenge is completed or whatever your thoughts are, write them in the comments, this motivates us, it is okay that we bring more content, okay, let's start. Today's question goes directly to the screen, so when we have come to the screen, the number of our first question of the day is 215 and the name of the question is ' is 215 and the name of the question is ' is 215 and the name of the question is ' Largest Element in NRE'. Okay, so Largest Element in NRE'. Okay, so Largest Element in NRE'. Okay, so basically we understand what the question is saying. Okay, we are given an integer array nam, okay, and we have given a value, okay, we have to find the K largest element, okay, note that the K largest element is in the sorted order, not the distinct element, okay, sorted order. We need the largest element inside K. Can you solve it without sorting? Okay, let's see if you can solve it without sorting. Otherwise, first of all we have given an array. 3 21 56 4 Okay. We have given an array and the value of K. We have given two, so we have to see the second largest element. What will be the second largest element F? Okay, so F should be the answer. F is the answer. Now let's talk about what is in this array. 3 2 3 T Four F. And sis is okay and we have to see the fourth largest element. If we want to see the fourth largest element, then it should be shown first if it is a shirt, then what will it look like, n is two, and after that, th is one, two is also two times, in this, after that, my four aa. I went again twice, I have five, I have ff and six, okay, so we need the fourth element, so I went from behind, I got the fourth element, so my four should be the answer to this, okay, so I have my four, the answer is okay. Now after sorting, it is quite easy to sort the array and then see the answer from it, that is quite an easy approach, okay, we can do that also, okay, but it is written in it, Can you solve it without sorting, according to me, sorting. You will do this yourself, it is okay to just see the element from the last, whatever key value element you want to see, it is okay, you will do that, so to understand this, let us move forward, first of all, how can we do sorting on our white board? In this, basically we will use a data structure, the name of which is Priority Key, which we will use, okay, what is Priority Key is a key, basically inside which the elements are added, I show it like this. That the elements are added to it, I have written the element from let's 10 40 30 20 60 70 90 I have taken these elements from let's, now when I add these elements, what happens to add inside the priority cube like from let's The name of this element is p. Now you will understand it better, it has a function p. It is ok and whatever element I put inside it gets added to it, so it is like I have added all the elements in it. Add it in any random order. Lately, I would have added it in this order. 10 40 30 20 60 70 and 90 are there in any order. But when we remove its elements, how is it removed? The function is Puck Remove. Whenever we remove, it is removed in which order. Do you know the ascending order means first 10 will be removed, then 20, then 10, then 20, after that 30 will be removed, after that 40. After 60, after 60, 70 and 90 are okay, I write 70 and 90 together, okay, so with this type, there is a remove element in it and there is another function in it, peak element, what does it mean that if Now in this priority also there are two parts, one min heat and one max heat, we are not going to go much into that now, rest of the things we are talking about, those who talk about min heat, what is the meaning of mind, what is the meaning of priority. The priority and heap are the same. Okay, so what is the meaning of min, like the element inserted in it is late, 10, 40 and 5, so what will be the meaning of min, which one is at the peak? Element five will always be visible. The smallest element will always be visible. So we are going to use min priority in this. Max priority would be k. If this was the maximum element we would have come out in descending order, for now we have used normal. We have used min priority. Why do we have to use it here, then five will come out or if we look at the peak function, what will we see? Just to see which element will come out, then okay, so we approach it like this, approach from priority A. Okay, now let us understand how we enter the approach of our question in it. Okay, so first of all I go to the next page and create another array. Lately I have created the array 6 7 3 0 1 2 Na 5 4. Now what is the first thing? It is possible that I told you about the priority part, so you can think that if you put all the elements in priority, then how will you put all the elements in priority, put anything from 6 in order, doesn't it mean order? It is also possible that the order of exit is different, so it is okay, when I exit, I will not reach the size of priority K, we have the value of K, the value of let K is set, so till the time priority K is reached, the order of exit is different. Till the time I keep removing the size of '3', I will keep removing. Let's time I keep removing the size of '3', I will keep removing. Let's time I keep removing the size of '3', I will keep removing. Let's see. Yes sir, who will be the first to remove? Zero, after that one, after that two, after that three, there is still size after that, now what will be the size of Q? So whatever element I will have it, I will check it and if my answer is ok, then I will check it. After that, I will get my R. This is absolutely the right approach, but because of its space complex, can we do it in even less complex space? Yes, I can do it. I try to do it in O-K. I can do it. I try to do it in O-K. I can do it. I try to do it in O-K. I understand how to approach it. I remove it once and then do it again. Now what is the purpose of doing it in Off-K. The approach to do it in O-K is doing it in Off-K. The approach to do it in O-K is doing it in Off-K. The approach to do it in O-K is this. First of all, make a priority K and if there are as many K values as there are elements in it, then and if there are as many K values as there are elements in it, then no element less and now what to do, let's compare it with its peak. Now, which value is there in its peak? Which will be the smallest value that will come and keep comparing it with the next element that we have, that is, if we understand it from the story line, then let 's say that there is a football match in my college, 's say that there is a football match in my college, 's say that there is a football match in my college, in the football match, we have to send three people out somewhere. Those who will play football, okay, so now what do I have to do, I have to make a strong team, so first of all, what did I do as soon as I left, I took any three people, after that, the next player who came to me, I compared them, did I have zero weeks with my best player? Or if it is three weeks then it is zero week then I will not take zero in my team, ok very good one came one, I compared one with my week one player, even one is not able to beat three, my week one player is not able to beat two. Two also came, my sister Nine came and said brother, I want to come, there are three in the team, we had three weeks, so we told Three, brother, you go away from here, are you okay and what about us, we told Nine to come. Took in the team means that we checked our peak, what is the peak, my element is that small, from which my element is coming, so there was my we cast element, what happened to six, okay, after that came five asked that I am the team. I can come, we refused, because our VK player is also stronger than this and to the four and four also, we said, brother, our VST player is also stronger than this, so we do not need you, otherwise you will see right now, if you have me. The three strongest players are the three biggest numbers. What will I do now? If I check the peak, will I not have the third largest number? The largest number is ok, so this type of approach is going to go into this. Once we do the code, we will understand it better. So I came, first of all I wrote priority k of type integer j after that p k e new priority q in this way priority q is defined then priority q is created now what to do basically I need to iterate the array in the loop. We have to iterate through the loop in i = 0 i < nums dot in i = 0 i < nums dot in i = 0 i < nums dot length and i + p Now length nums dot length and i + p Now length nums dot length and i + p Now what I have to do is basically first take my three players inside my priority then what will I do if here one Size is a function of priority. Priority is called size. This helps us to know the size of how many elements. As long as the size of priority is smaller than what, then what will I do? I will just put elements in it and will not check anything. Is it small or big ? Otherwise, add a dot of priority. ? Otherwise, add a dot of priority. ? Otherwise, add a dot of priority. I have added the element by the names of the elements and now by adding the elements by the names of the elements, now if else, then I will check which one is at the peak of the priority, which means which is the smallest element. Is it small somewhere inside Priority K? Which one of my names is there? If it is small then first I will remove it from Priority K. I will remove it first. After that, I will delete it in Priority K. Whom will I add? Dot name I Removed my weakest player because I got a strong player from it. Okay, and now where will be my answer, where will it be at the peak, so I caught K, then I also returned the previous answer after running it once. Let's see that we run it and it is working perfectly. Let's submit. Once it is submitted, we will drag it and it has become a very easy approach. It is okay to use it, so it is quite correct. Once we take it on our white board and Let's check, okay, so we have something like this, now what to do, basically I write some values here, basically I write some values here, basically I write some values here, 7 6 3 5 4 8 no 10 no, okay, so I have given some values and let's no, okay, so I have given some values and let's no, okay, so I have given some values and let's take the value of K, four is okay. So let's see how this code will work. Okay, first of all, as soon as it comes, I make the question a priority. I drop it in this way. Now as soon as it comes, what is the first thing I have to do. Basically, until the size of the question is not equal to K. Till then, all the elements in K, all the elements in the question, that is, I start adding four elements to 6. Now what will be the whole comparison, who will be the best player, who is the best player? Okay, now four is telling me the team. If you take him in, then we said, what is the puck's peak, what is the lesson four, yes, he is big, he is a big player, so what will we do, basically we will remove our players from the team and keep them with us. We removed it and placed our four on Y. Okay, now the four is our custom pair. Now there is a problem with the four key that if anyone comes with it as a strip player, then it is the first one and then it is checked on Y. It will be checked again and clear. What should we take 8 then this is also true. True condition means now we have removed the four and made it a but now who is my worst player, now my player who has become five is fine, now has come nine. Asked if I can come in the team, we said brother yes, if you beat our VK player then you can come in the team, then F in the team, nine beat five, so what, nine came and our VK player too. Now who has become our VK player? Now it is six. Okay, do you see how a strong team is being formed? Now 10 came and 10 asked if I can come to the team. We said VK player is our six, you defeat him. So come and he also defeated because six is small, six is small, six is small, instead of s, 10 has come, let's see what will happen now, who is left who is our most powerful player ? Neither said can you come in the team, we said ? Neither said can you come in the team, we said ? Neither said can you come in the team, we said no, why because brother, you are very weak compared to our best player, then he came to you, now again asked Prakash said that you are very weak from our best player. So you too can't come so in this way my strong team was formed of four people look what happened this 7 10 8 and nine is ok and now the answer I returned was peak pe kya tha seven hai Okay, so seven is my answer. Okay, and here you must be seeing what is the fourth largest number. If there is seven, then seven is my answer. Okay, so I hope you have understood very well that in what way we have It is okay to ask this question. If you have any doubt in this matter or any suggestion for us, then you can ask on our Tegra channel or write in the comment of the video. Thank you. See you guys tomorrow.
|
Kth Largest Element in an Array
|
kth-largest-element-in-an-array
|
Given an integer array `nums` and an integer `k`, return _the_ `kth` _largest element in the array_.
Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element.
You must solve it in `O(n)` time complexity.
**Example 1:**
**Input:** nums = \[3,2,1,5,6,4\], k = 2
**Output:** 5
**Example 2:**
**Input:** nums = \[3,2,3,1,2,4,5,5,6\], k = 4
**Output:** 4
**Constraints:**
* `1 <= k <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
| null |
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect
|
Medium
|
324,347,414,789,1014,2113,2204,2250
|
1,639 |
Hello everyone my name is Gitanjali and today we will be discussing daily need code problem so today's problem is number of waste form a target string life en dictionary so basically what is the problem statement if we understand through an example then according to the problem we There will be a word 'airgun' problem we There will be a word 'airgun' problem we There will be a word 'airgun' which will have some strings and the length of all those strings will be equal and together we will have a string ' we will have a string ' we will have a string ' jivan', the target. What we have to do is to construct the target string by combining the 'jivan' strings in these words. jivan', the target. What we have to do is to construct the target string by combining the 'jivan' strings in these words. Now how can we find the characters from these words? Regarding what we have to do, we have been given some rules by following which we have to construct the target strength, so what are those rules? First of all, the first rule says that the target string should be left, you are right, today it is bunny, meaning we will start from the first character and the last We have to construct the target strength till the character and the second condition we have to live is that if we tighten any particular character i.e. we tighten any particular character i.e. we tighten any particular character i.e. from any word, from any of these strings, from any word, if I tighten any character thing then I can select it from the string and not any character preceding it, infact not only from this string, but also from all the other strings, I can select any character before the index and not any character before that index. If I need it, I will always check the index after the particular index, I will not search from the index before that. The next condition is a type that we have, we can search any number of characters from a word in a string, but Keeping in mind the conditions that we have for life, if I explain it to you here, then the target string is this life and we have three strings of life, A C, one four times 20, and by using these strings, I get this target string. If I want to construct then what should I check? In the beginning, I have not done any character thing, so I have the choice to check any index. To find my character, first of all I have to find a character. What I will do is now I will check all the indexes that you want me to start the first test to see if I can see a character, then I see a character in the first word here on the first index, so if I do this character thing So what I did was I did a character thing at the zero index, out of all the words, I chose the character of the opposite index, so now I have a condition that now if I do the next character thing, then I will select the string up to the zero index. If I do n't do something from any of the string then it means that now I will not be able to do zero character of this nor will I be able to do that of zero character of this, so now if I have to check any character later, suppose now I have to check b then I Now I will have to search from the previous index also and if I were to do this A thing, then what condition would I have? I would no longer be able to choose from the string till the first index. I only have to check the string after that, so the conditions are set like this, so basically I have to construct the target spring based on the index of all the strings and at the end I have to tell how many numbers of sends I can have to which By doing that, I can construct my target string, meaning I can do this A thing and to do the next character thing, I will go back three characters. Out of all the strings, I will look for B among them, and then I will find that among them. Further, I will check A again. It is possible that instead of choosing this, I may directly choose this A. From the third string, this can also be a possible way, so till the last I will have to check whether in this basis or in any particular. My target string is being constructed from the base and if we are getting then I will return one. If the field means then there will be one possible way. Now in this sample test how we could have 6 possible ways. Earlier what could they have been? That I index the string till 0 which I just told you and after that because I have tightened the zero index, now I only have the choice of indexing from one to three because I have tightened the zero index. Done, now I cannot take zero or the preceding characters of any string from any string and if I had first taken its first character i.e. the first taken its first character i.e. the first taken its first character i.e. the first index, then after this I would not have taken zero and any other character of any string. Now if I have to check the further characters then I will always check the index after the first one of all the strings so basically this was now let us see the approach how can we solve this question now what should I do What I have to do is to find the characters of the target string. So the brute force is that for the index of each particular target, I check all the strings with the help of a loop to see if I find that character. After that, according to How should I proceed, but our time complexity increases a lot, so to optimize it, I made a frequency error. Basically, what I did was, I gave a frequency and created it in which the number of characters is in a particular string, because of which we have this condition. Life is that it will be equal to the length of all the strings, this is also four, we have to construct this target string, so I created a frequency array in which what I did is that 2d array is the corresponding 26 of each index. Hey, it means 2D. Hey, it will be the size of four, which means there will be four columns because I have four, the length of each string and the tax of each column will be 26. Why is this because I have 26 characters and I want to store the frequency of those 26 characters, so first of all the frequency of A will be stored, so I checked the zero character of all the strings, I checked the zero character of all the three strings, I checked how many times the same frequency of one B is there. How many times is the frequency of once and what is the frequency of C? One and similarly proceeding in this direction I have what is the frequency of S. Zero then similarly I will store the frequency of 26 characters. Give the corresponding index of each of the strings. I checked. Second index of each string Second hand next of each string Checked and stored their frequency Similarly goes on index on third index And now what I have to do is I have to construct the target spring so what I do is I pass two points in the function. I will make whatever record I create in the function only, I will pass two pointers in it, Ai and K. My painter will always point to the index of these strings, meaning the strings which give us life in the word Hey, check which index character of them. I am will represent i and k will represent the index of the target. Now which character of the target index do I have to find from the word. So now I will have 0 at the beginning so that I can check all the strings that I have created which have zero character. I am doing this and right now i.e. none of the zero character. I am doing this and right now i.e. none of the zero character. I am doing this and right now i.e. none of the characters have matched the target so I am just at the beginning so now I have to find A and I am on this index. I checked all the strings because the frequency of all the strings is same. I saw that this one has the frequency of A. What is life, so there was the frequency of A, then I came to know that if from any word, from any string, I have to select the character A from the zero index, then I can do it because If its frequency is more than zero then I have A present in a particular string, so in this first string I know that A is present, so now I have two options, Shakti or I will do this, take this one quietly. And move on to the next index and also from the remaining child indexes 1, 2 and 3. Should I find the child characters from these three indexes or the second option is that I should choose A from this index and then go to the next index. I will see if I get A and do A thing among them and then I do the rest of the characters from the rest of the child index. So first, what option can I have that I have done this A thing. Now here, let's have only one string. I am A, but it could have also happened that if A was here too, then here you are the frequency, you are the caste, so how many options did I have that I can do this thing with the string, now I can do this thing with the string, so I can do this thing with the string. What I will do is I will multiply all the frequencies I have with the function calls so that because I have a lot of options, if there was A in all three places here, then I would have three options to take the A of this string. Should I take 'A' of this string or 'A' of this string, take 'A' of this string or 'A' of this string, take 'A' of this string or 'A' of this string, so I will have to keep multiplying the frequency along with it, and what is the other option if I am not taking character from this, then if I am not taking character from this. So now I will quietly check the next index to see if I get A in it, otherwise I will simply add + 1 to it I will simply add + 1 to it I will simply add + 1 to it because I have incremented the index of strings but will not increment K because I have just found A in the previous index. I have not done style, I want to find a, so my next it will be this and first how because I have done my thing from this, okay, I will take it from here and I will find it from the child characters children index, so how My KB will be incremented because I have done one character thing, now I have to find the bed among the child characters, similarly my rest of the function calls will also be there and what will be the base condition in this that if while doing my index reverse, I will The first index completes the target string, meaning its value should be equal to or greater than the length of this string. Let me silently return one. Why because it means my target string has been constructed. Whatever I mean, I have tightened it. It was possible that it was the correct way because my target string is completely constructed, so I will return one in it, but if someone becomes such that the painter has not been able to complete the string yet, but my painter has seen all the characters. And now it does n't have any character to see. Children, I have tightened all the indexes, so how will I return zero to make it possible for me to not construct my string? So now I have to code it a little bit. If you understand with help, then basically what I have done in the court is, first of all, I took the length of any string, like here all the strings of mine have a length of four, so that four will be the value in M, then I created a frequency area. Which will have the number of rows as many characters as there are in a particular string and each character's correspondence is 26, which means a further 2d is because each index will have 26 corresponding columns, because we have 26 characters, we need to store their frequency. Now I have given the frequency with the help of loop. Hey, I have stored the frequency of all the characters and finally I have returned the function. Yesterday I passed two parameters in it. The variables i and g are now both i and k are zero. Also I have passed the key as my target string is words and frequency and I have done that because it is possible that the key function of the comma comes from the corresponding function of the value of the comma and if tomorrow I have to do it again then instead of solving. Which de recursive functions again, then I will store the value of I comma K card responding in DP Are. With this, if I ever have to perform the function again only for I comma K record, then I can repeat the functions from all the records. I will not solve it directly with DP, I will return its value like this is our base how the conditions are, what is the condition that if the value of K is equal or more than the size of the target length, then I will simply return one that my target string has been created. The advice is that if the value of I is more than caste then I will return zero. Now I have taken the answer variable as long so that the meaning does not go out of the range, hence I have taken long and stored zero in it. The first option is that I will take the character, it does n't matter whether it is in the particular index or not, but I am not taking it, so I simply incremented i that now I will check the next index of all the strings and did not increment k because k is the target string. Also, when I have not selected the character, then I will pass the parameters again and after passing all the other parameters, the second option left with me is that I will check that yes, that character is present in all the springs on the particular index of the story. Which character do I need for my target spring and if that character is presented then the second option is given that I will select it and silently check the second next index of the target, now what happened in that, I gave the answer plus and also Count means how many characters do I have, how many options do I have, how many times does that character 'A' occur at a particular index in all the strings, how many times does that character 'A' occur at a particular index in all the strings, how many times does that character 'A' occur at a particular index in all the strings, multiply it by the next digit, in which I also incremented 'I' so that now I can call it the 'A' of the index. I have incremented 'I' so that now I can call it the 'A' of the index. I have checked the index of all the strings of strings and also made it K plus one that now I have to check the next index in the target string Jiva, so simply and lastly I added my answer mode and returned which we get in the question. Told you now let's run it and see thank you
|
Number of Ways to Form a Target String Given a Dictionary
|
friendly-movies-streamed-last-month
|
You are given a list of strings of the **same length** `words` and a string `target`.
Your task is to form `target` using the given `words` under the following rules:
* `target` should be formed from left to right.
* To form the `ith` character (**0-indexed**) of `target`, you can choose the `kth` character of the `jth` string in `words` if `target[i] = words[j][k]`.
* Once you use the `kth` character of the `jth` string of `words`, you **can no longer** use the `xth` character of any string in `words` where `x <= k`. In other words, all characters to the left of or at index `k` become unusuable for every string.
* Repeat the process until you form the string `target`.
**Notice** that you can use **multiple characters** from the **same string** in `words` provided the conditions above are met.
Return _the number of ways to form `target` from `words`_. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** words = \[ "acca ", "bbbb ", "caca "\], target = "aba "
**Output:** 6
**Explanation:** There are 6 ways to form target.
"aba " -> index 0 ( "acca "), index 1 ( "bbbb "), index 3 ( "caca ")
"aba " -> index 0 ( "acca "), index 2 ( "bbbb "), index 3 ( "caca ")
"aba " -> index 0 ( "acca "), index 1 ( "bbbb "), index 3 ( "acca ")
"aba " -> index 0 ( "acca "), index 2 ( "bbbb "), index 3 ( "acca ")
"aba " -> index 1 ( "caca "), index 2 ( "bbbb "), index 3 ( "acca ")
"aba " -> index 1 ( "caca "), index 2 ( "bbbb "), index 3 ( "caca ")
**Example 2:**
**Input:** words = \[ "abba ", "baab "\], target = "bab "
**Output:** 4
**Explanation:** There are 4 ways to form target.
"bab " -> index 0 ( "baab "), index 1 ( "baab "), index 2 ( "abba ")
"bab " -> index 0 ( "baab "), index 1 ( "baab "), index 3 ( "baab ")
"bab " -> index 0 ( "baab "), index 2 ( "baab "), index 3 ( "baab ")
"bab " -> index 1 ( "abba "), index 2 ( "baab "), index 3 ( "baab ")
**Constraints:**
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 1000`
* All strings in `words` have the same length.
* `1 <= target.length <= 1000`
* `words[i]` and `target` contain only lowercase English letters.
| null |
Database
|
Easy
| null |
129 |
welcome back everyone we're gonna be solving Lee code 129 sum of root to Leaf numbers so we're given the root of a binary tree containing the digits from zero to nine each root to the leaf path and the tree will represent a number for example root to Leaf path one two and three represents the number 123. and we need to return the total sum of all of the root to Leaf numbers so we can take a look at example one they give us a tree of one two and three and they want us to return 25 because the path from the root to the leaf two is going to be the number 12 and the root to the leaf 3 is going to be the number 13 and the summation of 12 and 13 will equal 25. so this is going to be pretty similar to a problem we've solved on the channel before where we had to find all of the root to leaf paths in a tree we're going to be doing essentially the same thing except uh we'll obviously be returning a summation of the root to leave so we're going to do depth first search to solve this so we will have a stack and on this stack we will contain the node which we'll start with the root we will have a visited Boolean which will be initialized to false and we will have an array which will represent the path so far and it will be a string uh and it will initially contain the root dot val and we are also going to want a resulting number containing the value of the summation we want to return so now all we have to do is just run depth first search right so while the length of our stack is not equal to zero what do we want to grab the node we want to grab the visited Boolean and we want to grab the path we can do that with stack.pop the path we can do that with stack.pop the path we can do that with stack.pop okay now we need to grab the left and right sub paths because we will be building them on each iteration so the left path is going to be equal to our path and it will be a copy the right path will be the exact same okay now we need to check if our node is uh null or not so we'll say if node is not none we want to do something what do we want to check if we have visited this node before if we have we want to do something so we'll say if visited is true what do we want to turn our string path into a number so we'll say actually we also want to check if the we have to check if we're at a leaf node right so how do we do that we say if node.left is none and node.right node.left is none and node.right node.left is none and node.right is also none right meaning we found a leaf node then we can turn our path into a number and we're going to do that by just saying value is going to be equal we should actually write this out value is going to be equal to an integer of the string join of our path variable right so if we have 1 2 and 3 that this line here is going to turn it into the number 123. okay now what do we want to add this value onto our resulting output so we can say res plus equals the value okay now we need to check the cases where we have not visited this node before so uh we can say what do we want to do we just want to append the values onto our stack so we want to say if node that right is not none then we want to say stack dot append the node.right child we want to append the node.right child we want to append the node.right child we want to append the Boolean of false and we want to append the right path be right path but what do we have to do to this path before we put it on here we have to update it with the node.right have to update it with the node.right have to update it with the node.right value so we have to say all right path dot append the node.right.val and we can do the exact node.right.val and we can do the exact node.right.val and we can do the exact same thing for the left child so if no dot left is not none we want to update our left path to include the uh left node's value so node .left.val .left.val .left.val and then we can append this information onto our stack the node.left child the onto our stack the node.left child the onto our stack the node.left child the visited value of false and the left half okay now we also need to make sure we append our visited node to our stack so we can always hit this case when we run into it so we will say stack dot append our current working node and the visited value of true along with the current path and then after we exit all of this we can just return our result so let's get rid of some spaces and run this expected a string instance okay what did I do wrong aha right here I appended an integer value instead of a string because that is what we were working with when we made our stack up here right our path variable contains string values so let's update this we want to append string values and the other one should be right here okay now let's run this perfect we pass both test cases so we'll submit and it does run awesome so time and space complexity time complexity is going to be o of n we have to Traverse all of the nodes in our tree and the space complexity is going to be bound to the length of our stack so we can say stack dot length all right that'll do it for Lee code 129
|
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
|
171 |
uh hey everybody this is larry this is day 22 of the february lego day challenge hit the like button in the subscribe button join me on discord let me know what you think so my voice is a little bit better today hopefully maybe not let me know what you think about that but thanks for people who have been wishing me well uh i mean i'm mostly healthy just i don't know talk too much or whatever especially the day before that obviously you know i do the double contest which takes uh a lot of talking and so forth uh but hopefully i'm better i boost myself from the boat why uh and uh i don't know what that it's like saying that i don't know what that means uh but yeah um sorry if you're joining me just for this video it may be a little bit awkward way to start um but i usually just talk it's like a pseudo vlog uh just kind of give you an update i'm still in cartagena i'm i stayed an extra day i'm just today i actually did a very um culturally educational educationally cultural thing um follow my instagram to kind of find out more but it's just about um yeah i'll post them on my instagram stories um about like um basically more about you know we talk about colombian and cartagena there's a lot of history about the slave trade and so forth um so i mean i don't want to you know there's a lot of new ones to our stage so i'm not gonna go over here and also this is you're here for this farm so anyway uh and for the rest of you i also have some drone videos at some point so you'll enjoy it hopefully and so forth but anyway today's problem is 171 excel sheet column number okay so this is pretty straightforward i think if i remember correctly um the first thing i would do maybe still a little bit of a cough um is to check the number of characters i mean i think the formula is going to be a little bit um yeah should be okay this is oh they give you the column and then they give you a number so okay so i mean i think this is just a pattern uh guessing in a way and pattern matching i think once you get uh maybe a three letter one um and you get it correct i think then that should be good enough um first thing to notice though the pattern matching or whatever is just by seeing that okay so the number of characters there's gonna be 26 for the for one line uh one character and then for two characters gives me 26 times 26 of course and so forth um so we can figure out that so then here then we can start by saying let's call it offset is equal to zero right maybe one i don't know um or that's to go to okay and then for i in range of n maybe something like that and it's got the length of the column title um maybe this is off by one but basically you want to say okay let's do 26 to the i right so then uh yeah so that should be okay let's start at one just to be sure uh and we don't want yeah they should not include n so that should be okay um because for the last one we have to do the real offset right this is just the offset for the prefix right meaning if there's three characters then you get rid of all the one characters and order two characters and so forth and now you have you know you do this and then yeah and then after that it's just return offset plus i don't know some math number right so uh what do you wanna do let's say answer maybe um and then here is just now you could represent the rest of it as a base 26 number right um so that should be i think that should be okay so that now for c and column title uh let's see so coordinate of this minus ordinance of a right um yeah and that should so now you have okay i should say answers your zero uh you have answer you add this thing right um now uh well you shift and add is what i was going to try to say so that should be good i think this is off by one but that should be good let's give it a spin we'll be sure that i'm off by one but that's okay uh yeah see the reason is because i was actually debating whether to correct off by oneness by uh i was debating whether i should correct off by not oneness by counting zero digit numbers i don't know that's a confusing thing to explain or not um because i actually all i have to do i mean obviously you could just add one but um but you actually also do this as well because then this would add a one here and this looks like it's okay um so that's what i was thinking about when i was typing it but i wasn't sure how i would handle it and how to explain it because it's a little bit awkward uh mathematically this makes more sense which is why i wrote it this way um because of the zero digits but i don't know maybe not maybe i'm wrong here um but yeah so what's the complexity well let's say this length is n well in that case this is going to be n and this is going to be n so this is going to be linear time and space we just have variables so constant space um yeah linear time constant space that's right for this one it is supposed to be easy but that said um you know if you have if you run into issues with this one just um you know slow it down you know um and play around with some examples to get the answer uh or like not to get the answer like as in solution but again like okay they for example work out you know manually for example uh you know typed in some random stuff said yb like what is the answer for that one and then see if you could um you know figure it out right how the pattern between you know the dynamics um that's pretty much what i have does i submit i did not submit it huh that's a little bit awkward why am i talking about it before submitting it uh okay cool uh 693 day streak that's great um yeah well that one maybe a sloppy if i forgot to submit but yeah that's all i have for this one let me know what you think stay good stay healthy good mental health and i'll see you later bye
|
Excel Sheet Column Number
|
excel-sheet-column-number
|
Given a string `columnTitle` that represents the column title as appears in an Excel sheet, return _its corresponding column number_.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
**Example 1:**
**Input:** columnTitle = "A "
**Output:** 1
**Example 2:**
**Input:** columnTitle = "AB "
**Output:** 28
**Example 3:**
**Input:** columnTitle = "ZY "
**Output:** 701
**Constraints:**
* `1 <= columnTitle.length <= 7`
* `columnTitle` consists only of uppercase English letters.
* `columnTitle` is in the range `[ "A ", "FXSHRXW "]`.
| null |
Math,String
|
Easy
|
168,2304
|
65 |
Hello guys welcome oil hot time when will be discussing question number in this question definition of world number one official appointed loot-loot no problem subscribe number which problem subscribe number servi canteen that deserts minus plus yacht and which oil no duty on the spot On Varden Adher Due Servidor Vidron It's Subscribe The Channel Number At Number Yearly Falgun More In Which Need To Return Channel Subscribe Miding Twitter - Festivals And Returns Miding Twitter - Festivals And Returns Miding Twitter - Festivals And Returns Subscribe - Not Worked With Minor Account Vidmate Apps Ki II 800 Id For Prohibition Number idli half hour subscribe mode on this number subscribe this Video plz subscribe Channel to that discussed minute free live web design web banner-01 minus plus sign in chief and Video subscribe The Video then subscribe to the Page if you liked The Video then subscribe bittu and electronic dharamveer v9 plus minus during its capital lootin middle aged person video flu subscribe The Channel subscribe and subscribe the that is already and this bold scene dot in both cases which cannot be valid notes will return for not doing away with Video Working with synonyms for Subscribe Pimp and Subscribe That They Have Already Seen That They Can't Be Chief When Dean Appointed Do n't Forget to Subscribe to the Channel and Values and Vid Oo n't Forget to Subscribe to the Channel and Values and Vid Oo n't Forget to Subscribe to the Channel and Values and Vid Oo E Agree Things Work Find End of the President's Rule That Then If only half of them are subscribed then they will get 8 Plus Minus Acid Dependent and Naroda Midwife Input Subscribe Channel subscribe The Channel Please subscribe And subscribe The Amazing subscribe to quite important statement that which will be easy for you to interact with so that note down it's a Ki Canteen A Plus And Minus Edit Of The Amazing Have To Do Subscribe - - - Ki And Will Put Option Question 501 History Can Adjust In Order To Decimal Point Contains Only Daughter With Distinct In The Distinct subscribe The Channel subscribe our Mode Of But Not Likely Due To Her Not To Withdraw Take One Or More Than For All The Best For Decimal Operation No Vinod Ji Operation Point This Point Is The President Number One Day And Unlimited Subscribe Luta Do Subscribe My Channel Subscribe Withdrawal - 9 - Which Can Be At Least One Son - 9 - Which Can Be At Least One Son - 9 - Which Can Be At Least One Son Purva Block Cannot Be Present in the Subscribe Mere Set Ke Right Result Do Laddu Sameer Wa Putting in Front of a Daughter subscribe and subscribe this Video a kar do
|
Valid Number
|
valid-number
|
A **valid number** can be split up into these components (in order):
1. A **decimal number** or an **integer**.
2. (Optional) An `'e'` or `'E'`, followed by an **integer**.
A **decimal number** can be split up into these components (in order):
1. (Optional) A sign character (either `'+'` or `'-'`).
2. One of the following formats:
1. One or more digits, followed by a dot `'.'`.
2. One or more digits, followed by a dot `'.'`, followed by one or more digits.
3. A dot `'.'`, followed by one or more digits.
An **integer** can be split up into these components (in order):
1. (Optional) A sign character (either `'+'` or `'-'`).
2. One or more digits.
For example, all the following are valid numbers: `[ "2 ", "0089 ", "-0.1 ", "+3.14 ", "4. ", "-.9 ", "2e10 ", "-90E3 ", "3e+7 ", "+6e-1 ", "53.5e93 ", "-123.456e789 "]`, while the following are not valid numbers: `[ "abc ", "1a ", "1e ", "e3 ", "99e2.5 ", "--6 ", "-+3 ", "95a54e53 "]`.
Given a string `s`, return `true` _if_ `s` _is a **valid number**_.
**Example 1:**
**Input:** s = "0 "
**Output:** true
**Example 2:**
**Input:** s = "e "
**Output:** false
**Example 3:**
**Input:** s = ". "
**Output:** false
**Constraints:**
* `1 <= s.length <= 20`
* `s` consists of only English letters (both uppercase and lowercase), digits (`0-9`), plus `'+'`, minus `'-'`, or dot `'.'`.
| null |
String
|
Hard
|
8
|
829 |
Oh consecutive numbers some 829 given a positive integer n how many ways can we write as a sum of consecutive positive integers okay this seems like a very mouthy thing thanks to five random Walker okay so I think okay so I mean I don't know I don't have an immediate win for this I think something about is that well you know 1 plus da 1 plus 2 that I present and as you go to you know this is a great screw type thing where and again x and minus 1 over 2 as I'm like that right so well obviously the other thing is you know X dot or expose dot a dot plus and you go to just let's call this F of n this is just f of pig and major F of n minus f of X minus 1 or something like that - one night 1 or something like that - one night 1 or something like that - one night so those are the two maps I would do and then the question is how many ways can you write it as a sum of consecutive positive integers well I think this I mean this is a very Matthew palm so I'm just gonna play around some ideas but I think there's some like I mean I'm doing this stuff I think there's a easier factorization so I think okay I'm gonna get to the even numbers in a second but I think 15 give me an idea because that's not 15 because well what are the factors of 15 my 1 3 5 15 Oh obviously and then we just let's just say before away the 15 and the one just cause the for reasons that may be is maybe I'll have to explain it I on it but that means that you know that's it because 3 goes into 15 that means you know and 15 divided by 3 is 5 so then that means including 3 tears you know one like you know you won yeah 3 times 5 so you want to replace 21st we first worry obviously that's my definition but I know I've another way of wearing this obviously is again this is given in the example so that's when joy my information from and in similar way with 5 is that you know 15 2 by 5 is doing so you have something like this which is also obviously you could rewrite this as you know so that's the odd numbers or rather when these are odd things well acnes in general ok but and this is trivially true for when both of them are odd but that's the point well I'm another number that's hy and you have 1 2 4 5 10 20 let's just skip to mine 20 because cuz you're only gonna have actually maybe well yeah you skip to one in the 21st about 20 on one numbers is not consecutive and one you always gonna run the negative so I guess that's a educates and to think I thought about it we have to talk about it because in this case well you have to it so now you have ten things right and obviously you just reject this because you can't have ten things about two and again this is even number so I don't know if they're quite the same logic works I'm glad to see but now if one and okay so I say for ten right well there's no way to do this that's you go to dirty so that's not really work how do you even them I mean they're stepping even numbers here I like four plus five for example so okay I could look at well you in 15 I skipped the case so eight plus seven how do we get in verse seven so I mean do we just brute force check that's eighty just for two numbers then obviously I which is somewhat five so everyone 7a but how do we form a late this and I save it for four numbers then well tinder wife for 3.75 so this only tinder wife for 3.75 so this only tinder wife for 3.75 so this only happens so this can only happen if the division so then you checked it thoroughly I guess like as to the parity has to be like three times by two I mean for two is obvious but I'm just also thinking of like other cases like before I asked to be such that so 2 times X has to be a an integer number so in this case you have dirty and then which is to you know it works so then you're 15 which what am i doing I mean I'm gonna wait track I just this is a very mouthy problem obviously and the coding is going to be like oh not that interesting or fast or not that slow but yeah ok so times 2 and then you don't like - okay so that means is as don't like - okay so that means is as don't like - okay so that means is as good guy it means now 15 means it's good to go and okay so the integer division means a seven meaning the other one is eight so okay let's see if I could do another okay I guess twenty maybe it's a good case now okay so for 21 I must fit into it we do the we do a quick check 42 by four even need twenty or so you do it like forgiven is something that's bad case but then now you so the average for each one is oh sorry the sum of each pair is four numbers the two pairs where the sum of each pair is five so that means there's two three and one for now doesn't make sense anger I don't know we won four groups not four numbers so and you group is yeah we want four groups of five so this is actually not possible I guess in that sense because it would go into the negative way so I was why you just wanted to be fun and we need that's two groups so there's no way to yeah maybe and now try tell you by five well that's for the average so now this is saying that each group has five numbers and then the beginning is four so now we could do three to six so yeah and died he goes to 20 so that's good so we just added to the stack that's why for again actually we won for and um because I messed it up a little bit because we run for number is that some 220 that's what we're trying to say here yeah and that means each pair should sum up to ten and that's not possible why don't we do the time flight to Finland no right give me a second so we want four numbers and you so the average is five four numbers with the average is five not that the sum is five and in this case because there's even number of digits we cannot count because five is an even number so actually we want this to not you want this to be split in the middle to be between two digits right so 4 doesn't have a number okay I think I have most of the rules in place maybe I'm gonna do some debugging and pointing out and then yeah I guess we don't actually need this except for maths hopefully that your flower here hopefully that's why I mean I'm kind of working in my you know I'm actually working through it as I go but yeah and the number of factors is you generally have to check up to the square root of the number so yeah that's quiet oops and I just add one for kicks just to be sure and now we check let's say that's quite a coop size yes you go to three do one now we don't do so from two to the upper panel it's just in case I mean we could check anyway and we only start doing this and much group size zero okay and now we checked it differently if the group size is odd then we just do this math so average is equal to this and then we just want to make sure that the average - group size total by 2 is bigger than 0 - group size total by 2 is bigger than 0 - group size total by 2 is bigger than 0 somewhere down that's five so you want to go for example if it's fire then you go to numbers so yeah okay that should be yes great well you go to one as you started one for positive yeah and then you just incremented care in that case got the other juicier but trickier to do one is else 22-month else 22-month else 22-month so we wanted to actually be exactly on the 0.5 how do you express that the 0.5 how do you express that the 0.5 how do you express that means times 2 is a whole number so okay so if and my group size isn't on them but then the other part is but that happens here we are going to be exactly Oh point five how do we do that another five one is the reduction and we just do like okay well I guess it has to be okay and it's good it's actually not civil right cuz if it is zero then it already goes into given each time instead which is a whole number okay so then average it's just quite this ouch - because it's how much times this ouch - because it's how much times this ouch - because it's how much times two is equal to n times Micra sighs oh sorry just keeping everything doubled for now and you count this one hmm and we count this one if well let me do this first I don't know that's efficient but we definitely need it and then obviously zauj too so that's just multiplied this side by 2 so this is you know - this may actually be times 2 as know - this may actually be times 2 as know - this may actually be times 2 as well so yeah but it's not sufficient actually I don't even know if this is true maybe one for half no she'll be okay and I think it's equivalent anyway because everyone gets one why to Saturday that's one a quick test not confident about this to be honest that's caused it these ones don't always edge cases but so you never know okay I don't know just square root it is fine actually I don't think I've ever done square William I've Python before right okay fine negative two I shall know the order of operations so that's to this well cut to those side drop about as well make sure just a fun debugging portion of your episode okay so the holdup about one why is that it's my square root thing one to the negative to negative 1/2 or to the half negative to negative 1/2 or to the half negative to negative 1/2 or to the half man I can't do math these days you should be flow okay I mean I used to bounce our way dish I didn't get the right answer unfortunately okay let's start the five in Italy well I didn't count it yeah so now we get half two factors but we don't have to count the other half what on the other side of the square root let's try this we only do this if this is true so let's put it under here actually but it's still I think missing a thing otherwise it should still show something maybe but that we can consider this and then you have to worry about a case race and square I think we could worry about that once we get any results oh yeah I don't know what you are right I am just being a little weird today with the mass right I think I would just focus on this point that's why but still why am i pointing what am i pointing am I putting multiple places why they're floats how because this is not a I have to do this that is the one thing coming from ninth I find is that sometimes I do stuff like that okay that makes sense I mean I know I have to check for square roots that's why I mean our perfect squares but it seems like that's not the issue anyway now I think I mixed up my odd in even cases yeah because we were talked about a bit well it is a answer that is inferior less wrong okay getting a kiss how 15 and 2 okay yeah I didn't do the 15s - and here I only oh yeah okay I mean we're making progress I'm going to wait for Esprit but also I should check hmm laughing wait we're on the right track there's just a lot of weird edge cases or not weird just weird for me to watch because one is well we have to make sure that these two can double count if it's I got the pace why am i missing on the Florida now 15 yes 15 one of them oh I guess I'd we do count to pace one but in that case we're wrong on the other cases I think that's fine right no expect Zeus after okay so we had one case by battering we're just double counting on the nine for sure because that's what I was as we do that we twice which is probable how do I do try to be the clever bit but instead maybe this is a mirror well right now I'm just trying to think about how to do it isn't a pythonic way okay fly this so feels like an overkill to be honest I guess be just too okay one step closer am I getting on the first one I'm putting way too much stuff now that's the point where we count one file of 2 and then 5 - so we double one file of 2 and then 5 - so we double one file of 2 and then 5 - so we double can get 2 because this is true and now we do it for 2 and this is 2 right phase we actually we just need well such a hack - mmm okay well such a hack - mmm okay well such a hack - mmm okay but I try to pick numbers first at least don't know how I feel about it okay I'm actually okay about at any time still worried I'm missing educate so we'll see with just being I'm just not confident about it but I think I would well okay I guess we should have tried one that's all that's an edge case I'm more confident about like I'm confident I could figure that one out whoop still hmm oh it says new I guess I just mmm I just special K so this special case it for now and then we can test out the numbers oh no I agree stiff one which one is that oh that's one two - yeah that's it oh that's one two - yeah that's it oh that's one two - yeah that's it that's why I'm just a component of what happens when the group sizes one yeah okay so that's wrong because we counted a square root so you're always going to miss some weird things possibly anyway why was this gonna man in it some group size this one all right let's try this out just a little Queeny from now it's going to zero over somewhere so weird reason you know when you stop about two so possible cup size don't care fine that's I also feel like this is like gonna only show for very small numbers where so it's primarily just 1 & 2 to be honest it's primarily just 1 & 2 to be honest it's primarily just 1 & 2 to be honest right why is 202 to upper bound to so choice 1 and then 2 you know are the two numbers that's about 2 1 Pisces math longer let's take a look at this just doesn't get pointed out so it does the one twice because instead of because my one of my fundamental assumptions is that we only count both sides of the square root or in this case because we do this square wood plus one thing we end up counting it multiple times curse you like okay let me just rewrite this way I mean I think this is and I think if I was in a contest oh it actually just like a hard-coded screw it actually just like a hard-coded screw it actually just like a hard-coded screw it but here I'm trying to be a bit of a bet about it well I guess what we can just do this I believe even get rid of all this stuff and I had to I don't know there's a easy way on Dakota to move everything on intent of events of I may even to this form-fitted the mo yeah thanks for form-fitted the mo yeah thanks for form-fitted the mo yeah thanks for following Patsy Oi okay let's see this is better checked of one first nothing else but now I just have one but should be faltering the same other than we move into from the candidates it's this white dough he won his fight what is it three worried about this being not true actually maybe I should double-check this hmm okay I guess I didn't matter it's just weird in general not I think about it but okay I guess also this bit how is to Sochi and this as fire is a hard problem I suppose have another half an hour is a paragraph - right - actually so maybe I paragraph - right - actually so maybe I paragraph - right - actually so maybe I was so bad - is 1 & 2 like one number is was so bad - is 1 & 2 like one number is was so bad - is 1 & 2 like one number is just 3 that's obvious but - should we just 3 that's obvious but - should we just 3 that's obvious but - should we listen up these small numbers I just have edge cases around the square roots in this case it does check for two so for a group size of two it should be 1 plus 2 right so them in 6 2 by 2 is 3 and 6 by 2 is a note we might - is not and 6 by 2 is a note we might - is not and 6 by 2 is a note we might - is not zeros that's true so we do go here so 620 I 2 is 3 so 3 - this is 1.5 - group size or just 2 which this is 1.5 - group size or just 2 which this is 1.5 - group size or just 2 which is 1 so 3 minus 2 yes that's where yeah I guess it did matter I was really sure about this one but I guess you need this because your because you're counting it from point 5 space away in between points so that's wise one because the difference should be okay right but you could justify anything will - correct without justify anything will - correct without justify anything will - correct without so I don't know we'll see okay now let's see it crossed my fingers well I'm just inputting a lobster to forget it okay I always try to remove the print before somebody in fury doesn't Maddox there one time where I was a course io2 and it gave me a time limit because I printed too much toboggan stuff to screen even though oh no I did I touch this man a lot of weird I am just really bad at this so it expected and this okay let's see Nev this is one of those farms you belong on like off by once so one two three and seven nothing goes home or factors okay I'm happy about this so let's see why it's well I always returning I was we're talking dream I should be too okay one number is always right seven two numbers is three plus four right three number is why do I test for doing this came back to buy me because three is not a factor of seven I've I mean two is an item but then at least two this thing is true so okay I knew I should have kept it and also this is like a weird thing okay cuz for odd numbers okay so I think I just need to be more careful about this so if it's odd number so this only happened for even number but I think I was thinking about it right it I was like a maybe to some with mathematical property where that implication is true but it doesn't always happen that way now this is getting messy too okay hey I was just careless to be honest I don't actually there's nothing to do it I mean these are things that I was finding about and then I was again maybe they'll be okay so I was just not careful and then that's what happens so that we write this so that's a wave it's a over to eat even numbered and this is true because we want it to be on the 0.5 otherwise if it's odd then we wanted to we owned average to be zero or sorry we want average to be a whole number so that should go into G : that should go into G : that should go into G : then okay no it's just lazy yeah how was it mess anyway not that to anyone watching like maybe this is also still a mess but wait this is slightly mathematically prettier maybe yes fewer edge cases yes they say okay I mean everything got accepted the last two times so I still have very low confident that this is right I'm lucky I need some attack right okay it's just a one Oh No Oh like solving at cases one at a time I'm not being consumed enough okay these are good twice time this one seven numbers around 20 so it goes to what that's not like that's why right okay yes they're no seven numbers round three because it goes to two one and zero and that's that counts I'll be on the side of that's case so maybe there's another even number that I'm forgetting like two is ten past eleven progress and past eleven so just for then what happens before well then you know it's five point two five but it's the average number so you can't do that sex you know lose the last them oh yeah I'm just missing a case but also maybe uh it's tough no yeah I did all the candidates so I don't think I'm wait three that's not right I love you six wait to that 42 by 6's in there are there six numbers that sum to 21 let's see so six number yeah I mean what three and a half can't do math so 1 plus 2 Plus 3 and then 4 5 6 is that right I guess so that's just three times seven give me that's how I should think about the pairs are the three numbers ready three numbers so that's what I'm missing I thought this would add us in 21 upper bound is I mean just possibly a slicker way of expressing it six is not added because 4 squared is 16 so it only checks up to 4 and then it never goes here I mean Justin it's not a candidate set what do I do in this case just sum of each part is 7 but which we don't do 7 either I mean we do 7 only because the way maybe that's the way to think about it hmm each number that is an that's definitely a case start to think about me having everything files full but I do not consider it as part of the thing and you have to do something in square root of n because otherwise you just run out of time I just assumed that it would work but we have six numbers damage of three pairings of seven that's fine so I just had to check up to the enter test oh no I won't give me two things today no but I mean I was hmm I don't know about any more covering and last time well maybe slightly more but not really oops I say what I mean why is that giving me an issue because it's possible it is oh I suppose we'll just take a look why would tap user I'll cuss now we're doing just can we just simplify this as a problem of just doing n times - in general because on this side or the map still works out and now this map is easier except from just one I might have to fix some math bow but let me just keep it the same for now but now I think maybe that's good enough it's this stuff still holds don't think that changes is this section for checking and this is still technically true well like that which is times two which is this awesome so maybe just two maybe that's on difference now we don't have to do some weird math look a little bit so now maybe actually we're still in the county I thought it would be over counting so I don't need to care about this anymore maybe just till one wait time man oh wait let's just uh by two so then maybe now okay this is been a sad day for me mm-hmm I feel like I got most of the mm-hmm I feel like I got most of the mm-hmm I feel like I got most of the fundamentals for this farm but just issues one ain't we now you were lost a seven there's two time to average this is two times a good size which is 6 alright that's having Chris I should definitely not be right but where is just 6 yes 6 is here well maybe just one hour should make them oh yeah I'd like to do this for the night actually I mean actually now I don't need this maybe well tell you how much I know one number tried to announce my three numbers right group size of six averages seven should be okay now maybe this is because I have to make sure that this number is different because okay so that's the only friend I need to think about if it's okay if the coop size is odd and we need their yes to be a to start at a number so this should be this its and since all the my office with this with plus one crease Oh nose is just not catching this 6 mm tube judges 6 which is even so then oh now which is 7 oh did backwards yeah like I got this wow we go I am 13 minutes into debugging okay I got time with my baby Chris to tell to the third case why is it not showing me maybe it's plenty springs ago there's everyone at the group sizes 110 average would be 2 and 2 minus 1 this is just this may be my first bad I mean acquittee is bad can i guide await approach it's just goodbye just special case to one I was trying to do stuff with it I don't special case but should we move oh I don't know anymore why'd I get 54 I was so close right now I feel like I'm even further apart happily without a check this eight what's average group now that should be clear no it's a group sizes eight maybe my generalization isn't like of just time so they bite - and into it just time so they bite - and into it just time so they bite - and into it that my weightlifter math was I think my odd numbers a little weird now cuz we want average to be dis and it's group size times to maybe give me in this case hmm because now you want just gaps up to instead of I don't know anymore we didn't do the group size cuz the average is doubled and now we won the gaps between it to be so man also hmm also to be honest I've been needing to really use the bathroom for like the last 10 minutes that's why I'm like trying doing things instead of taking it deliberately I thought I was so close right also everybody tried to be too clever to stuff about I should just do the thing 2x times X okay let's just do it that way who Oh God this is what it I even get to 21 right and one hoop why well nothing is 6n we have to get back to the fundamentals real quick right that's why one what they're uh well I guess that's true but let's try some because that we like well that's funny liquid once what is this given 55 and the answer should be 10 okay let me start over and not do this end I'm just ooh and then now just do the math in a real way but never to do that thing with the fractional things again whatever - hmm fractional things again whatever - hmm fractional things again whatever - hmm how do we get six captured in this and guys my question well that's my question for 21 all right yeah still try to figure it out I think I just try to uh I'm trying to work okay I'll be right back I need to use the bathroom I think that's why I've been just fooling stuff at the ward to see what works because I was just like uh maybe I could get it done and then use the bathroom real quick afterwards but I'll be right back Oh I'm back friends okay now okay I was definitely spending like about ten minutes of this problem just like because I thought I was very close I was just trying to get it out okay but now let's uh let's really think about this a little bit and then I could okay yeah so we I mean the thing I want to do is as long as we get it to check six I think this porous plate but tundra by two is clearly flowing something really off like so I think this is right because for a big enough number this okay I was well I had something that was right hmm because just stuff checks now as well it's just that this is based off the other thing whether I get back to the was in this a few seconds ago right that was a while ago okay I just get back to this solution real quick so I get had to fix this is just way weird or like it led to some silly edge cases okay let's just test my hypothesis that this is at least collect okay why me that's fine this is wrong but in 1 billion shippi okay vodka no good thought it was 10 but I think maybe I put in the wrong number but in any case or a different number anyway then the promised oops what did I click on farmers for 21 we want to check sex / on farmers for 21 we want to check sex / on farmers for 21 we want to check sex / wheat or not so how do you get sex we don't get 6 because we want we pairs there's six numbers but three pairs and three times seven so do check away three checked three and then three times two as a mech sensor and I would say I probably would not get this problem on the contest but I feel like I've solved this before a variation of it I guess all the math forms always look similar I suppose we have to think about this a little bit more just a coupe of 16 I mean it I guess for you to odd number we should test three six and then just and then twelve maybe I think that would I was worried about I could definitely hacking something for three times to four and even numbers I guess we just it would just be doubling our numbers which well in this case would be one I think that's point oh I would think about it okay let's see if that works okay now let's write this as a candidate and then we also want to that's expressed Alice because one so it was a human number that's fine no I mean I think this is we appended and then we check six oh yeah sorry I'm just like dippin dots usually I'm more talkative so yeah and why did I get rid of it I thought I was just hacking around this idea but I but the more I think about it I think like I mean for me it was just a hack like I didn't really make made sense it was just to kind of get an up figure out but BAM but I was running into other issues so it was kind of like a Hail Mary type thing where I was just trying it out so I don't mean any good recent protectors to begin with but yeah definitely feel free to go over expression sorry I was just in the bath or really need to use the bathroom earlier sir this one weird like this said you insufficient and we worked with this case but my coven about it well we do have to kind of fill up being able to random numbers well just do it we to the just have a calculator tweeted it 20 it's not too big yeah that's the week that's right just humble I already had three one submission so now wow that was 40 minutes ago when I have roughly to decide it what's cold then don't underestimate it okay well we'll see give me a long answer or give me a test case I guess Oh what do I don't even understand okay well me right hmm okay yeah that's at least capillary right I guess from what did I have here cuz I didn't take care of one but so this was my co from half an hour ago and now I used to only think I added was this so I spent 40 minutes on this essentially no maybe and some weird math one even so maybe that's worth it okay well yeah okay let's start a little bit from the beginning you could I talked about in the beginning but I was like an hour ago unfortunately an hour ten why does this work I don't even know anymore you know just thinking about how to incorporate even numbers into it carthoris seems like I didn't hmm I don't know normally have a great intuition on this one I think in general the way that I attack this problem I think I was roughly right but I think I know we think the even given group sizes and kind of getting them into the mix I think there's some proper here I think the thing that I was thinking about is that well the odd numbers are pretty straightforward to understand I think in that you know given a number say 15 you could you know excuse me given an odd linked sequence you know the average of the sequence is just the middle number and therefore it's just you know x times y is equal to 15 and you check all of them and this math I think it's this point I think for now is very straightforward in the sense that you know like this is pretty straight for and you could understand why and these move quick everything's coming out today yeah so I think for our numbers this district forward what I'm running it well where I was running into it was meant to be even numbers and putting them into even considering it so the so number given numbers under and the square root of n is straight for it but I was having issues of numbers that the given numbers that are over the square root of n because in the case of six and twenty one was my case what I had this actually but I guess I didn't know but I was in the other one but because 21 the obvious one is 21 and then there's sort of ten plus eleven and then three is six seven and eight well there's also a six numbers said where well the I would just three point five and this is why I try to do this thing with times two so then I moved to buy everything but you know being even more weird but yeah the answers 1 plus 2 Plus 3 plus 4 plus 5 or 6 so you have three sets of things and that might be I also wasn't sure on like whether you like in a bigger number like would you need 12 I don't know I'm not quite sure about that one I think in some one way I might have to like we now for any kind of things about it but that's how I attack the problem basically in this case this is three point five and that's how you would come up with the numbers well I'm quite that this was not a well maybe I had to practice the contest but oh yeah that's how I kind of thought about it you know some weird thing with odd practice I wonder if there is a not given these pairings do they have to be an odd number of them like what's probably not way because you have to 3 plus 4 plus 5 I guess I'll always be I guess that's what this tries to do is calculate just like numbers of pairings to begin with maybe like I've done everybody actually just times this by two instead of uh I guess they seem unnecessary I don't know just consider two times I don't know to be honest maybe that would be good enough also I did this in the wrong order I just realized maybe but like why just do this but this happened okay don't know so yeah but that's kind of the philosophy I was attacking this farm we were and I thought I got most he had something similar but yeah this was way annoying yeah kind of sad cuz I feel like I had most of it I have to look at the logs at some point but I had most of it like an hour ago right I just was all fired like these edge cases but uh cool all right well that was a no I guess I should look at this a little bit I didn't actually go over the farm I just kind of went over what I messed up yeah well I mean I think for and this year you're interviewing to be like a math PhD I really hope that this is not part of your interview and even if it was I feel like if you're able to demonstrate some of this breaking it down like maybe some of these things are not okay yeah and this is obviously given a number N 1 sin square root of n times because that's the number of maximum were possible factors in terms of bits then it's just n over 2 which is obviously off and where n is the number of bits and whoever sent this number I don't miss extra storage well I actually I guess I end up too but not that much listen because they're not diamond a factors of a number that's like they're a Phi function we're free function Phi function well yeah no it was a contest yeah I could see it I've been very sad about so I mean ship Connie oh I would have to kind of look at some maps later but uh oh yeah I guess my advice for this problem when a contest is wish you don't get this on a contest I mean in interview and I can tell you just a little earlier today we're cool
|
Consecutive Numbers Sum
|
subdomain-visit-count
|
Given an integer `n`, return _the number of ways you can write_ `n` _as the sum of consecutive positive integers._
**Example 1:**
**Input:** n = 5
**Output:** 2
**Explanation:** 5 = 2 + 3
**Example 2:**
**Input:** n = 9
**Output:** 3
**Explanation:** 9 = 4 + 5 = 2 + 3 + 4
**Example 3:**
**Input:** n = 15
**Output:** 4
**Explanation:** 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5
**Constraints:**
* `1 <= n <= 109`
| null |
Array,Hash Table,String,Counting
|
Medium
| null |
735 |
Hello Hi Guys Welcome To Dad Today's Questions Asked About Pollution In This Question Being In The History Of Interior Representing Asteroid In Rock Reduce Darkness Present In A Single Road Avoidance Sign Representing Erection It Means 16 Near Your Parents Here The Number Sew Sentence Painted A Movie Idi Things Moving In A Single Channel Don't Forget To Subscribe One Pipe Is This Negative Number Editing One Left Dixit Samay Jab Talent Hai Abhi Right But BJP Demonetization Colitis Molarband Stress Molar Mess Will Be Stopped Midway Removed And Shame Is Pole Dance rise to short to west side and the lord of the mess in will get in both kids and to return the result of the remaining asteroid scene in a temple for b id that and one more thing you noticed a and magnesium row and demon With Same Speed Irrespective Of Famous Mirch Switch Off But Ofton And See The Very Positive Beautiful Very Beautiful Sushil 500 - Subscribe Not Decide 50 Hours 1 A Huge RKS 510 - Vinod Addison More A Huge RKS 510 - Vinod Addison More A Huge RKS 510 - Vinod Addison More Se Hindi Same Road Distance 505 Doctor Panch Restant And They Both You That SIM Speed And - 500 Also A Movement Same Spirit But And - 500 Also A Movement Same Spirit But And - 500 Also A Movement Same Spirit But In This The Director Directly - 5 - To Be In This The Director Directly - 5 - To Be In This The Director Directly - 5 - To Be Destroyed And Subscribe My Channel Subscribe To In Divinity Street Money Abroad - Test In Divinity Street Money Abroad - Test In Divinity Street Money Abroad - Test Series Pay Order Really Matters For Peeth Dated 25th Shabbir Video 8 And Withdraw All Currency In exchange for the result subscribe Video subscribe this Video subscribe That Bigg Boss - And Will Move Into That Bigg Boss - And Will Move Into That Bigg Boss - And Will Move Into Liquidation Let's Go To - - - - - 11th Liquidation Let's Go To - - - - - 11th Liquidation Let's Go To - - - - - 11th Similar Peeth Mein Chhura International That To 8 9 10 11th Sudhir Normal Point Where They Can Meet Each Other BUT SIM LIST ON THE AB KE SAUNTH EACH SIDE LEFT SIDE SUBSCRIBE Mid-Day-Meal This SUBSCRIBE Mid-Day-Meal This SUBSCRIBE Mid-Day-Meal This Question And Remedies For Positive And Negative Role Play Thanks For This Question The Amazing Intercepted Step By Step With This Very Intuitive Who Will Take You To the last element which can be applied with current elements in the last element current element and the last 50 years - - - A last 50 years - - - A last 50 years - - - A Kuch Der Already Mandir Addiction And 128 Terminal Mention Patience 120 Se March And Safe Badher Mujhe Director Sudhir Vijay Normal Point Where Way Can deny they can meet each other and politely sleep this job channel take place WhatsApp Web वाजन के स्वर This take place WhatsApp Web वाजन के स्वर This take place WhatsApp Web वाजन के स्वर This type of which type of secretary C Joe hair don't give this lineage Sushil life Vve action and avoid A I bank account minus two degrees left Side Akshar Student - To Be Glad left Side Akshar Student - To Be Glad left Side Akshar Student - To Be Glad End Result 2013 - 118 to 128 Minutes and End Result 2013 - 118 to 128 Minutes and End Result 2013 - 118 to 128 Minutes and Purple - 10 - One Will Get Creative World Purple - 10 - One Will Get Creative World Purple - 10 - One Will Get Creative World Outside and Scheduled Tribes Have a Comment Point m.a. Comment Point m.a. Comment Point m.a. That in this case also a division will happen and answer b0 emergency better listen let's start it cold have told you that will loose but in this case let me 10 minutes developed ok software architects fixed the intent is no what will oo will try to uniform Strides in time table 2017 the students ki i plus main naseeb dera to kaisi hai main a firm already this day positive 5 hindi state bank wanted aa bhi android 2.2 morning minutes ago discuss five android 2.2 morning minutes ago discuss five android 2.2 morning minutes ago discuss five is movie hydration and in the last 2 Years In This Direction Towards Giving Back When E I Stories Bandh Hai That Test Mein West Indies Team Spirit And When The Movie Hindi Test Book In The Same Direction Will Never Meet President 500 Hindi Sanctions And Tourism Minister And Actions Will Never Meet Darshans Romantic Playlist Listen Simply Add Will Simply Add Are To Hindi I Will Simply Do Start That Soiled Nutritious S Another K Cystitis MP3 All Posts In This Practice mp9 Encounter In Difficult Five Withdrawal Forest Dept Activities Should E Do Not Belong To Any Good To The Latest Episode Which Can Form A Coalition Services Simply Insult Affair Lots Of Obstacles And Encounter Minus One Support - Yorkers Encounter Minus One Support - Yorkers Encounter Minus One Support - Yorkers Login Seat Wherever Most Recent Decades No's Arrangement Consent And Then That Asteroid A The Student Is Better Than Zero Idiots Positive What Do You Simply Add Happy that such rides have come in return of Diwali Simple Bandi Star One Arrested Positive Administrative and Traffic Jam TV Simply Ask-Ask Rs.60 Notification Middle-aged Acid Attacks Happen Will Be Truly Want to Hear No Evil Resident Evil Forces Delhi Into Top of the Video then subscribe to the Page On this suggestion of job take place issue, compare first chief minister of Delhi office track suit of but to s.no's office track suit of but to s.no's office track suit of but to s.no's new effects of increase top 10 top it's a little thought rates like this that not support second Take Is Changes Top 5 That In The Us Of Political System - 49 - 3 That In The Us Of Political System - 49 - 3 That In The Us Of Political System - 49 - 3 Hair Soft Will Happen C - 49 - Sunil Hair Soft Will Happen C - 49 - Sunil Hair Soft Will Happen C - 49 - Sunil Darshan - Will Also Included Within Two Darshan - Will Also Included Within Two Darshan - Will Also Included Within Two Weeks To Believe In The Same Direction And Vinod Addison Section Job Hours Place Suggestion Simply Apps Posts That Asteroid The Streets Is In Its Full Simply Posts - 3 In To Subscribe To I Will Posts - 3 In To Subscribe To I Will Posts - 3 In To Subscribe To I Will Simply Posts - * Given Simply Posts - * Given Simply Posts - * Given That And What Will U Will Break From This Will Break 100MB In Directions Value Notification Top Is Blind Race Canceled In Condition Apply To Understand All Time Top To My Channel Subscribe Vinod Ne 1999 Sapoch Title - 5 Laptop And Cystitis Sapoch Title - 5 Laptop And Cystitis Sapoch Title - 5 Laptop And Cystitis 500 A Non Stop Dalit Office File Is Equal To - After Asteroid A - After Asteroid A - After Asteroid A 8 - Strike C Pradesh's Sitapur 8 - Strike C Pradesh's Sitapur 8 - Strike C Pradesh's Sitapur District Top Is Face And - Episode 285 District Top Is Face And - Episode 285 District Top Is Face And - Episode 285 10 - 5 - - - - - 509 Press subscribe button 10 - 5 - - - - - 509 Press subscribe button 10 - 5 - - - - - 509 Press subscribe button subscribe The element in this life what we do that with poppy element and pomp and vent back to meet oo's notification minute possible to negative restaurants notification's top is greater than A Top Is Great Dane - Restaurants A This Is What Will Happen See That Suppose It Was Headed To Assistant Now Vinod Jet Airways Pod Taxi Stand And Have Wasted - Service Taxi Stand And Have Wasted - Service Taxi Stand And Have Wasted - Service Colliding With The Wedding Stand Vinod Bhatt Banner Small Amounts To Read This Column After Straw and will get collide with higher mother skirt small amounts to be exported but will happen in this can be done nothing will just have to do a break from looted bye-bye back record seat too far note bye-bye back record seat too far note bye-bye back record seat too far note required s - if any one of the bus Stand required s - if any one of the bus Stand required s - if any one of the bus Stand Compare To - 50 Compare To - 5 Dil Result Compare To - 50 Compare To - 5 Dil Result Compare To - 50 Compare To - 5 Dil Result In Can Only So As Not Any Point From Distant And Did Not Any Such Thing In Distinct Suggest Simply Pregnant Mothers Enhanced Free Condition Which Is Known For Its Top Is 2012 Laptop Imo That And It Should Stop this simple test White hat used to put pressure on dance Conventional ear when you a topics loosening to destroy e suppose that without top is Lansdowne also is stored support to this hair - Foreign tourists where know what will happen if they see that support to this hair - Foreign tourists where know what will happen if they see that humor and bring to front Takes Place Where Does Compare To Negative - 5 Days To Negative - 5 Days To Negative - 5 Days Back To My Father Complaints To End 5 2012 Result Hindi Bread Notes22 Vitamin Dead Body Hide Behind You To Inspector And Manipulative 15 Back To Black Spots And Five Welcome In Its Place What Will Happen C s .no the immediate top office text to know one country is to reduce fans in nature protest will be split into being made to remove this to 100MB to pocket 11 that auspicious AB constitution Batla House Kajra that auspicious AB constitution Batla House Kajra that auspicious AB constitution Batla House Kajra case consider this proposal of this to a Tree And For See Consider This Weapon Now Knows You Will Get Your Truly Believe On This mid- Subscribe Anxious Does Not Want To Talk To mid- Subscribe Anxious Does Not Want To Talk To mid- Subscribe Anxious Does Not Want To Talk To Me Top Camp - Runtime Error Subha Mintu Top Camp - Runtime Error Subha Mintu Top Camp - Runtime Error Subha Mintu In This Case Which Does Not Mean That Will Check Weather s .no s .no s .no that one such 2016 kiss mp but will do victim please post this element that henna check status that ash kush a straw and that aishwarya it came that i will break from where e and suresh ji hall reliable heart condition which can find of to This question is that is a guy to take on samadhi condition so after elections and after three for lips android also element idea present in distic president dr output result world will form factor that cant and output against same of advt5 that a from this so zero shah Vinod Reddy Element in this track and reverse order should you think is difficult-2 Advertisement difficult-2 Advertisement difficult-2 Advertisement - 118 daily 120 i plus - 118 daily 120 i plus - 118 daily 120 i plus and output of pi who is equal to add whatsapp that hand will come here you that and after that hand will come here you that and after that hand will come here you that and after that will be town On whatever all posts are o Uttar Pradesh and tagged not just let's do and e cold not late from castor code 168 chapter note summit on Monday decode accepted ayogya select video thank you now input t solution reception exile the solution from the rate thank you two happened
|
Asteroid Collision
|
asteroid-collision
|
We are given an array `asteroids` of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
**Example 1:**
**Input:** asteroids = \[5,10,-5\]
**Output:** \[5,10\]
**Explanation:** The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
**Example 2:**
**Input:** asteroids = \[8,-8\]
**Output:** \[\]
**Explanation:** The 8 and -8 collide exploding each other.
**Example 3:**
**Input:** asteroids = \[10,2,-5\]
**Output:** \[10\]
**Explanation:** The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
**Constraints:**
* `2 <= asteroids.length <= 104`
* `-1000 <= asteroids[i] <= 1000`
* `asteroids[i] != 0`
|
Say a row of asteroids is stable. What happens when a new asteroid is added on the right?
|
Array,Stack
|
Medium
|
605,2245,2317
|
1,424 |
we can discuss question from lead cold we click on dist 186 diagonal travel - we click on dist 186 diagonal travel - we click on dist 186 diagonal travel - you are given a list of lists of integers numb return all the elements of numbers in diagonal order in the following diagram as shown so as you can see this is the tabular in the diagonal form and you have to print out this output array this is the matrix you're given filtered input is 1 + 4 - 7 5 3 8 6 & 9 but the input is 1 + 4 - 7 5 3 8 6 & 9 but the input is 1 + 4 - 7 5 3 8 6 & 9 but the trick here is here portion is all the length of the rows are not equal the row the length of this row is 5 - 1 3 5 so the length of this row is 5 - 1 3 5 so the length of this row is 5 - 1 3 5 so you cannot just do a simple terrorism because let's see if you firs you a traversal till here which is very simple but now if the length of this is 3 you will go through 3 1 2 3 but this length can be too large which does it occupy in this thing so the trick here is we cannot do this simple diagonal traversal but we can find out some pattern so I've drawn this matrix what is this index it 0 comma 0 what is this index it's the first row and 0 column and this is welcome Lu so as you can see the sum of their distance is 0 for this it's 1 for this if you do the same for this it's 2 comma 0 1 comma 1 and 0 comma 2 so the sum of all the indices for this arrow is 2 then this / indices for this arrow is 2 then this / indices for this arrow is 2 then this / 3 4 and so on okay so now as we know first we have to print out all the elements with the sum of the indices total equal to 0 then 1 then 2 then 3 but we have to first also see that if we have two elements of the same total value of loop last column we have to first print out the element which has the least column size the column and column zero column one so we can easily make a vector regarding these properties and we can sort it firstly according to the total of route plus column because if any element has a row plus column equal to zero it will come first and then one then do and if we have to row plus column elements same we can sort it by the column spitzer okay so that's the simple logic we can just simply use the sort function if in the sort function you have multiple entries it first sought by the first entry and if two of the same entries are there it will sorted bus ticket entry if the second entry also same it will sort without entry and so on so we can just input in the sort function accordingly okay so we first make first find out the number pi size because the size is the total this length the row length can be different but the total number of the first end or number of columns number flows we can easily find out because it is fixed okay then we can make a vector all vector here in which first entry is du plus column second entry is this column and third entry is none so okay so now we can iterate over I is equal to zero I less than equal to n PI plus and for each row we have variable row lengths so what we can do is J is equal to 0 J is less than endure for that we can find out number of i sized by its to length and a plus then here dot push back what we have to pull back you have to put the I plus J then J and then dumb so I and J okay so as you can see if we now for this it is easily can be sorted well by the first entry which is I plus J and then if I plus J saying being sought by J they are okay so now we will make a final on selector to finally output dancer for I is equal to 0 we will iterate over this error which solves all the elements and with which back in answer here I - because in the third in answer here I - because in the third in answer here I - because in the third in the this is a zero point one and second the second entry stores the value on your proton in check okay fine later it's accepted I understand the logic it's a simple problem if you still have any doubt please meant to know and thank you for watching this video
|
Diagonal Traverse II
|
maximum-candies-you-can-get-from-boxes
|
Given a 2D integer array `nums`, return _all elements of_ `nums` _in diagonal order as shown in the below images_.
**Example 1:**
**Input:** nums = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,4,2,7,5,3,8,6,9\]
**Example 2:**
**Input:** nums = \[\[1,2,3,4,5\],\[6,7\],\[8\],\[9,10,11\],\[12,13,14,15,16\]\]
**Output:** \[1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16\]
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i].length <= 105`
* `1 <= sum(nums[i].length) <= 105`
* `1 <= nums[i][j] <= 105`
|
Use Breadth First Search (BFS) to traverse all possible boxes you can open. Only push to the queue the boxes the you have with their keys.
|
Array,Breadth-First Search
|
Hard
| null |
387 |
Ki Where Her Again With Jeetendra Video Only These Problems Solutions Will Be Coming Discuss Loot Code Problem Changes First Unique Character In A String And Yet Started On Ki X Video Problem Description Which Says Give String For In The Forest Lawn Repairing Credit And Determine Its Index Love You To Find For Defeating Character And Vitamin C The Index Web Title Exciting Edgbaston Taste One Minus One Switch Off To Cash Withdrawal Best Actress's Share Is So Let's Get Duplicate For Rent In Main Suraj Example Loot Ek News Exit Chahiye Such Question Read And Agree The First Unit Kunwar Program 0 Jadse Indexes 0 Torch Light 100 Index Example Which Can See And Authors Who Want To Thank You Kurti Time Aap Pio Karz One Time CEO Kushvansh Wendy But All Is The First Character Of E Tried To Travel From Left To Right In Se That This Is Verify Troubles From Left To Right The First Character Will Bell Vijay Serving Character Contest Phone Rate 100 Collided With To Find At Stake One Another Example Which Has Given Year Love List To Dwight That Idea Vacancy Hello Course Want To Students Show More That if the scope course were the first two times a view code I want and this scene from left to right badod this previous Srikant product fashion Shiva air tight twist is 2000 the end of our string length and you will be able to say we if it is the Character is the first one vision one contest one year wikinews map to store the character account surya's will be the character and value will be then contact character button is time pods increment 100 to again a great the map and b2c back under character akers 1528 butt They Can Also Used One Another Destroys The Landless Map Characters I Will Give Link Badli Different But Let's See Near Howrah Bridge A Look Like Show Will Be Taking Anti Are Off 2036 Tractors Because 06 Characters And Have Also Mentioned A Quick Detention String Contains Only Lower Case English Letters Udhar 286 End Tubelight Verdict Eclipsed Officer V Will do tawsif alan - scheme of whole V Will do tawsif alan - scheme of whole V Will do tawsif alan - scheme of whole territory a lesson because a right way will get to will get ashraf al solid say if it is si - and eggs ki si - and eggs ki si - and eggs ki cars 97 ki and share ki batteries 29th so will get to ok and a Grateful Nation Will Increment Form But Amla Ko Boil 200 20121 Equations With Tried To Feel Our Entries Are Like Waste And Again Will Spread Through If We String And Will See From Here If It Account Of The Territories One Will Just Returned The Character Of And Listen Accident These days the code to do it is the time complexity of defiance and space complexity of become passed them technique one meanwhile the government vehicle the strike to the police tried to see perfect hour juice conductor - Malik the test's support loot lo that conductor - Malik the test's support loot lo that part of if That's exactly the election and that is presented in this MP3 I seth hero country's system is in the essay in vitamin E that nor will be taking a 210 case scrubbing from it and the length of scan b b0ht loot packing fifty six capital cities are The main ulta balls babbar loot ko toot ka use pe kar do the reader movie dub chf is not carat yes brother yes ki that english a1 ki sudhish pending hai the effigy der 880 - apps and what ever dare effigy der 880 - apps and what ever dare effigy der 880 - apps and what ever dare plus0 veer va intermediate 212 300 meters This for loop will be happy new and the interior field will also be something like this hongi board hair san ko khol do uske tung with her but from zero 226 intake it on again way to it is a hua hai em bbc site a ch ajay Ko A Similar To This A Hua Hai Ko And Effective To-Do List Loot Records On Who Is That And Effective To-Do List Loot Records On Who Is That And Effective To-Do List Loot Records On Who Is That Bulandshahr A British Bring It Is Not Repeating Character And Has Been Traveling From Left To Right With Four Street Show Vaikunth Index Ride Point Actor Will B I Don't Ouch And Let's Unite For The Spirit Of Dudli Hai The Factors In This Is Difficult Bank That This Frill Double - Must Win All The Best That This Frill Double - Must Win All The Best That This Frill Double - Must Win All The Best Restaurants Code Main Soft Plant 600 800 Give Milk
|
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
|
286 |
hey everyone in this video let's take a look at question 286 walls and Gates only code this is part of our blind 75 list of questions so let's begin this is actually a premium problem on Lee code and that's why we're doing it on the lint code website and why the number here is different but otherwise the question the test cases and the solution will be the same so let's take a look in this question you're given an M by n 2D grid initialized with the following three possible values minus one which means a wall or an obstacle zero which is a gate infinity means an empty room and they use a value 2 to 30 first power minus 1 represent infinity as you may assume that the distance to a gate is less than infinity we want to fill each room with the distance to its nearest gate if it is impossible to reach a gate that room should remain filled at Infinity okay so let's take a look at what this question exactly is saying so go ahead and copy this and again for this premium type problems we like to use send code because they allow us to do it for free let's take a look Okay so in the example we're given all of these values over here and what we essentially want to do is that we want to transform all of these Infinities essentially to a value possibly remains at infinity or it should be greater than zero but it simply has to be the distance to the nearest gate and the gate is represented by a zero for example in the case for this one over here where is the nearest gate well it would be you would go down and then here so that's why it's a value of three the negative ones don't change so we leave them at them as they are what about for this one over here for this Infinity well the nearest one is actually right and then up right we also have another one left down and down but notice how this is three spots away this is two spots away similarly for this one it's just one spot away and so in this question essentially what we're asked is that we want to find the nearest element so that we don't actually go into the into this like obstacle over here so we can go through all four directions and then figure out where we want to go and there's also like another example over here so we can take a look at this one so in this one we just actually have looks like two values right so we have like a zero a minus one or maybe I'll draw like this zero and then minus one and we have infinity and so really for this one the shortest distance is actually just going to remain what would it remain at well it would remain at one it will go to one because there's a distance above here and then for this one we would go left and then we would go up and that's how we would arrive at a one at a two okay so we understand what the question is saying now how might we go about doing this problem well in this question like there's numerous approaches we can take right we could maybe do a DFS we could maybe do a BFS what's kind of like the appropriate thing to do and why might we even want to do a BFS or DFS well first of all it's a graph type problem right and anytime you kind of have like a 2d graph and a 2d Matrix and you want to Traverse it maybe find the longest path in a matrix or you know like shortest path or something like that you want to kind of think of DFS or BFS okay so we know we want to do that and the question is here like what exactly might we want to do and which one would be better now but both of them would work right a DFS would work maybe in the sense that where would we start off I guess that's like the first question right where would we start off at the zero or would we start off at the infinity and this question is actually very similar to a question we did before and that question it was called the question was called zero one Matrix on the code which is pretty much identical to this question that we have here in that for all of the zeros we want to find or maybe it was the other way for all of the zeros we want to find like the distance to the closest one and we'll replace that in the Matrix and we'll return that so this question is kind of exactly similar to that one and in that approach we actually use the BFS and we're going to use the BFS here as well but why do we want to use user BFS well the thing about a BFS is that you can do something called like expanding breath first right so what does that mean well what it means is that for example let's say we have all of these values inside of our BFS right and I'll go ahead and remove do this and I'll actually just put this over here okay so the first question is if we want to do a BFS where can we do it from should we do it from either the Infinities or should we do it from the zero because we can't do it from the minus ones right because these are like they're like obstacles so I want to make sense to do it so we have two choices right we either do it from the zero or we do it from the infinity what do we want to do well in this case I would actually say that it makes more sense to do it from the zeros why the zeros well because if you think about it from the zero if we start off and maybe we add in both of these to our BFS calls we could expand breadth first we can expand level by level what does that mean well in the first BFS code what we'll do is we'll try to expand so these two will be in the queue and we'll try to expand to this entire area over here right this entire area over here really in this case we'll actually just go ahead and we'll add in this infinity and this Infinity because this minus 1 is here and we don't have anything on top and then similarly when we're processing this one we'll actually just go ahead and add this Infinity but what does this mean that we're expanding breadth first and we're expanding level by level well what it means is that in the first iteration of my queue in my breadth first search I will just go ahead and handle these two items in the queue right and if you think about it the items that these two can reach right the locations in The Matrix that these two can reach they have to be the closest ones they have to because if you think about let's say like we had like a bunch of let's say we had like a bunch of values here maybe x maybe an x I'll just try to draw my grid just like here and let's say we had these two values inside of my BFS maybe we had a value here maybe we got a value here and I want to know what is the closest distance of like this value here like how can we reach this value in the closest distance or we can do it through our breadth first search right because if you think about it we're expanding breadth first we're kind of expanding in like a circle around the point here and we're expanding in a circle around the point here right so if you think about it if we're expanding level by level which means in the first iteration we just go ahead and we expand on these two then if I can reach this circle this ending point then I know that this has to be the shortest distance because it is right beside me or it is like the closest one beside me if I was to do it from here I would go here and then from here I would have to go here so notice how if I do something like that it's actually two iterations right it's two iterations the breadth first search in the first iteration what do we do well we can visit this one and from here we can only visit like kind of this one right and then the next iteration well from this bottom one here we can go ahead and visit this top one but we notice it's already been visited by this first iteration over here and so when you expand breath first and you do it level by level which basically means that you only process the elements inside of the Queue at a specific level so for example when we do this breadth first search the first time we will just process this zero here and this zero here the next time we do it we'll process this Infinity this infinity and then this Infinity Etc so we'll only process level by level or only process the amount of items that are on the Queue at any given time and so that's why we can guarantee that our distance will be the shortest distance and we've done this in a couple of other problems for example um Word ladder I think it was one of them was Word ladder zero one Matrix and so if you want like more insight into this definitely check out those videos but without further Ado we can write the code in this one and really if you think about it all we need to do is we add in all of the zeros and then we keep track of like the levels right and when you arrive at Infinity then we just replace the Infinity with that specific level that we have for example if we start off from over here then we expand well this is like level one and so this will be replaced by the value one which is exactly what we have here okay let's take a look at how we can write the code for this okay so what do we have go ahead and remove this and I would just call this grid I like to name these grid and now what do we need well we need to keep track of the rows and the columns so length of grid and length of Grid at zero now what else do I need well I need my Q and in a BFS I also need like a visited set which I'll call scene and now what well we argued that we want to add in 0 to the Q why do we want to add in zero because if we start from zero and you expand the breadth first then when you arrive at Infinity we can then just replace the Infinity with like the level or like the iterations of breath research that we have processed so what might that look like well first of all what we need to do is we need to go through the list or the Matrix for Row in range and then for calling range and then if grid a row and call if this is a value of zero then I will add this to my Q and I'll also add it to my well actually I don't want to add in the value itself I want to add in like the row and the call right the row and the call I know like where I am and then I also add it to my scene so now what can we do well now what we can do is we can start our BFFs so we started with y o q okay yoq and now this is how we expand level by level what we do is we keep a size which is the length of the queue and then we only process the amount of elements as per the size so initially in this first iteration here we'll have one two elements and then the next time we process it we'll add in this Infinity We'll add and this Infinity wide and this Infinity next time we'll have three elements right so in that sense we're expanding level by level so really in the start my level is zero and then every time I finish this for loop I can increase by level by one okay so now what can I do well let's say I'm in my Loop now so what do I need to pop for my queue right so I will do I guess roll call is equal to Q dot pop and I'll pop from the front because that's what we do in Q and now what okay so I can check actually if this value is an Infinity if it is infinity then I can just go ahead and replace it by the level so I can do if grid a roll call if this is equal to Infinity which I don't know how they're actually are they actually representing it as is 2 to the 31 minus one they might be representing it like that okay so if this is the case then I want to replace gridet row and call put simply the level itself right now what about the other case what if this is not Infinity right what if it's like a different value for example maybe it's like um maybe it's like a minus one I guess we can handle the minus one after but let's say that it's some sort of different value right for example if we start off from the zero here and then I go to the infinity here or maybe let's say we go to the infinity over here so then we'll go ahead and we'll update this Infinity to 1 right but then from this Infinity call I also need to kind of go down here and then update this as well right so if you think about it like we'll update Infinity like many times but we just because we have Infinity doesn't mean we need to stop our breadth of our search we still need to breath research on potential lower like elements right or like potential elements that are outside our boundaries so actually like the only replacement I need to do is right here because we're only replacing the Infinity but now what I need to do is now I need to go ahead and see all the neighboring elements that I can add so can I do in this case so basically check if we can add neighboring elements so how can I do that well we need to explore the four directions right up down left and right so I can maybe have like a directions and what I would do is I will set it equal to something like 0 1 I guess one zero and then minus 1 0 and then um zero minus one and so what this allows me to do is I can do for DX d y in durs and I can do Nu X as equal to rho plus DX New Y is equal to call plus d y so this will basically allow me to Traverse all four directions and now what well now we need to make sure that first of all I'm in the boundaries and second of all so let me start with that so let's maybe start with make sure I'm in the boundaries right so we can check and there's a simple way to check this we can basically check if new X I guess we don't need the bracket if new X is less than zero or new X is greater or equal to rows or Nu Y is less than zero or New Y is greater equal to cos if this is the case then we're actually out of bounds right so for example it's like we're starting off in this first row here and we try to go up so in that case we're out of bounds now what else can we do well if this isn't the case then what well do we have a couple of other cases to consider right first of all this value that we're visiting right new X New Y we want it to be an Infinity right like we don't want it to be another value we don't want it to be a zero right we don't want to it to be a zero because we would have already actually processed all the zeros so we don't want it to be a zero we actually also don't want it to be a one a negative one either so we only really want to add this value if it is an Infinity right if it is an Infinity so what I can do here if it does not equal infinity and maybe actually I can just um 2 to the 3 and 2 to 31 minus one maybe I'll just store my Infinity like this if it does not equal Infinity then I'll also continue because I only want to add it if it is infinity now what else well what if this value here is actually in my like visited set right what this might look like for example is this value over here this one over here that we're trying to find in the first iteration we'll actually add it to our queue based on like this location here but we'll also add it based on our second iteration like when we process this element over here so really I only want to add it to my visited set if I haven't visited it before so what can I do here what I can do if new X knew y if it's invisited that means I've already found a shortest distance to it so again I will continue now if all of these cases are false then I can go ahead and add it to my queue so I would do Q dot append ux New Y but I'll also append it to my visited ux new y and that's basically all there is to this question so let's take a look and we can just run it to see if we run to any problems visited is not defined and I believe I call it scene so let me just change all of this to scene and I'll run it and okay so this one passes let's go ahead and submit it and also it passes so don't really worry about this one this is just false but basically this is how we can go about doing this question so what we did is we took a BFS approach similar to what we did in zero one Matrix and word letter what we did is we started off at the zeros and then we expanded breadth first but we made sure that we only expand level by level and so when we do something like this it guarantees that the node you visit it has the shortest path to whichever node like code it right and we can calculate that shortest path based off of this level variable over here and so that's essentially what we did if we arrived at Infinity we set the equal to the level but we notice that we can't just like continue we have to actually add on more elements even if this current element wasn't Infinity we still have to add on more elements because it's possible that we haven't reached any of these elements so far right just to kind of illustrate like what I mean in that point for example for this negative one we'll add in this Infinity but then we will never reach this Infinity unless this one adds it to the queue right and so that's why we actually need to add it and so once we do that we do some error X and if it's all good then we go ahead and append it to our scene and queue and we'll Revit the answer so what about the time and space here well if you think about at the time we're just going through the entire grid so it's m by n and I like where rows and then calls and then same thing for the space because we might potentially add in everything to our q and our visited set so the space is the same thing okay thanks for watching
|
Walls and Gates
|
walls-and-gates
|
You are given an `m x n` grid `rooms` initialized with these three possible values.
* `-1` A wall or an obstacle.
* `0` A gate.
* `INF` Infinity means an empty room. We use the value `231 - 1 = 2147483647` to represent `INF` as you may assume that the distance to a gate is less than `2147483647`.
Fill each empty room with the distance to _its nearest gate_. If it is impossible to reach a gate, it should be filled with `INF`.
**Example 1:**
**Input:** rooms = \[\[2147483647,-1,0,2147483647\],\[2147483647,2147483647,2147483647,-1\],\[2147483647,-1,2147483647,-1\],\[0,-1,2147483647,2147483647\]\]
**Output:** \[\[3,-1,0,1\],\[2,2,1,-1\],\[1,-1,2,-1\],\[0,-1,3,4\]\]
**Example 2:**
**Input:** rooms = \[\[-1\]\]
**Output:** \[\[-1\]\]
**Constraints:**
* `m == rooms.length`
* `n == rooms[i].length`
* `1 <= m, n <= 250`
* `rooms[i][j]` is `-1`, `0`, or `231 - 1`.
| null |
Array,Breadth-First Search,Matrix
|
Medium
|
130,200,317,865,1036
|
81 |
hey everyone today we are going to solve the readable questions such in rotated sorted array2 so actually this question is almost same as such in loaded distorted array one so difference is we have duplicate number in the input list so in that case I'm giving an array lens after rotating an integer Target and the return to if Target is in numbers or false if it is not in numbers and you must decrease the overall operation steps as much as possible and then we have follow-up question so this problem have follow-up question so this problem have follow-up question so this problem is similar to such you know that is sorted array and but nouns may contain duplicates would this affect runtime complexity and how and why okay so let me explain this follow-up question so me explain this follow-up question so me explain this follow-up question so this problem is similar to searching rotated sorted array but nums may contain duplicates would this affect the runtime complexity and how and why so um actually the main concept to sort of discussion is the same as yeah this question and I have already video so I put the link in the description below so you can watch later and so about this follow-up question so about this follow-up question so about this follow-up question um so to solve this question um before we um execute binary search we have to check so one is a if a middle pointer middle value is um equal to Target in that case uh we should return two right so this is a simple condition and uh so yeah description set we have a duplicate so this second question is uh to handle a duplicate if a middle Loop value equal left value in that case um we add plus one two left value left pointer and then continue and then if not if both conditions are false and then finally we narrow the range for binary search so in that case if input array is like all one like one in that case every time we um and the target is like a two in the case every time we go to like a second condition right so first condition is always false and second question is always true because uh middle pointer definitely um middle value is definitely equal to left body right in this case so that's why we know the range like a one by one so in the end we iterate through all our values so that means um so usually a binary search is a order of log n right but if um all every time we got the tree from condition two so time complexity should be order of n because of e 3 like one by one yeah so that is a basic idea to solve this question so with that being said let's get into the code okay so let's write a call first of all initialize Rift pointer and right pointer so left point should be zero and the right point should be your last index so length of num minus one and start looping y left point is less than or equal right pointer and first of all calculate the middle pointer so left plus right divide two and first of all check middle value equal Target in the case we should return true if not the case so we take the second condition as I explained earlier so numbers meet equal numbers left in the case uh we increment left pointer y1 so plus equal one and then continue so if not the case um uh we narrow the search range for binary search so numbers left greater than or equal nums meat in the case if numbers left greater than or equal Target and less than uh numbers meet in our case um we move right pointer equal with minus one else opposite so left equal meet plus one and then else oops if nums and their meat is less than Target and the target is less than or equal numbers right in the case um update left pointer equal middle plus one and else and a right pointer middle -1 middle -1 middle -1 so after that we if we don't find the target number so we usually don't false yeah that's it so let me submit it looks good and everything algorithm and the time complexity of this solution should be order or log in usually but the last case like uh all values are same and there's no target number in that case uh we narrow down the searching range like one by one so in the case time complexity should be order of n and the space complexity is o1 so constant time 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
|
Search in Rotated Sorted Array II
|
search-in-rotated-sorted-array-ii
|
There is an integer array `nums` sorted in non-decreasing order (not necessarily with **distinct** values).
Before being passed to your function, `nums` is **rotated** at an unknown pivot index `k` (`0 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,4,4,5,6,6,7]` might be rotated at pivot index `5` and become `[4,5,6,6,7,0,1,2,4,4]`.
Given the array `nums` **after** the rotation and an integer `target`, return `true` _if_ `target` _is in_ `nums`_, or_ `false` _if it is not in_ `nums`_._
You must decrease the overall operation steps as much as possible.
**Example 1:**
**Input:** nums = \[2,5,6,0,0,1,2\], target = 0
**Output:** true
**Example 2:**
**Input:** nums = \[2,5,6,0,0,1,2\], target = 3
**Output:** false
**Constraints:**
* `1 <= nums.length <= 5000`
* `-104 <= nums[i] <= 104`
* `nums` is guaranteed to be rotated at some pivot.
* `-104 <= target <= 104`
**Follow up:** This problem is similar to Search in Rotated Sorted Array, but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why?
| null |
Array,Binary Search
|
Medium
|
33
|
556 |
Hey guys welcome to waali dhundhi si today going to see the question elements and subscribe - The Video then subscribe to subscribe - The Video then subscribe to subscribe - The Video then subscribe to the Page if you liked The Video then do final number to hi Arvind number hello this tenth digit ka peene to update in this quest bittu quest bittu quest bittu Hello Viewers Welcome Back Once Installed Wherever I Find Another Decreasing 2340 Button To So This And 10 To Ram Mode Turn Network Inside Meaning Numbers How Do We Need To The number will give number in values have already subscribe bluetooth of the question is different number and to the number you to this is know what if done with this question so let's codings one number long equal to the pure spirit or The counter digit from 12922 real state to the current number of water and free number complaint on Jhal to initial and setting show to minus one animals that many valuable in this great country phone that is a greater than CR oil find the current man that display Give me the current last digit number and see how long will update the student one sa week digit oil increase till account of the digits in quantum as noida previous number great and current number which is where winny too opted for the other operation set is that Tv cement a begum cigarette undercurrent amir wa for some operation otherwise what we do it is paste reminder to front are na the witches that taaj from current treatment plus 1995 number activate mintu updated with you need to find number of greater than or equal To the number to the number from back into the account the world's account of name is equal to zero oil 299 plus and getting from going on is not that tight Dual high two account number - is not that tight Dual high two account number - is not that tight Dual high two account number - minor and said is number to my channel number to the number This is viral vihar account of judge we do the return of the year - 1410 and mother - the return of the year - 1410 and mother - the return of the year - 1410 and mother - o that acting android result left right immediately this code for the example it so alarm set time 10 court that I am a whatsapp letter thank you Connect with For Watching My Video
|
Next Greater Element III
|
next-greater-element-iii
|
Given a positive integer `n`, find _the smallest integer which has exactly the same digits existing in the integer_ `n` _and is greater in value than_ `n`. If no such positive integer exists, return `-1`.
**Note** that the returned integer should fit in **32-bit integer**, if there is a valid answer but it does not fit in **32-bit integer**, return `-1`.
**Example 1:**
**Input:** n = 12
**Output:** 21
**Example 2:**
**Input:** n = 21
**Output:** -1
**Constraints:**
* `1 <= n <= 231 - 1`
| null |
Math,Two Pointers,String
|
Medium
|
496,503,1997
|
219 |
um hello so today we are going to do this problem which is part of lead code October daily challenge contains duplicate 2. so the problem says we have an array of numbers and then integer K and we want to return true if there exists two distinct indices I and J such that the numbers at that position at those positions are equal and also the difference between the two numbers in absolute value is less than or equal to the 2K which is given to us here right so for example if you take a look at this um these two numbers are equal and here the position is zero and then one two three this is three so three minus uh zero minus three absolute value is three so it's equal to K so it's valid so we'll return true um if we take a look at this one um we need the difference to be one and if you take these two they are equal and zero and this is a two well the difference yeah maybe we can take these two instead so these two they are equal the difference is zero so it's smaller than K so it's a good right um with this example the only two equals are this and this um and the difference between them is not small or equal to K okay and this as well so we're return false so that's the idea now how do we solve it um we can definitely do a Brute Force where we go through the entire array to find that index I um and in the loop again to find an index J and check if they are equal and check if this is less than or equal to K that would be our event squared not so good because the length can be 10 to the power of 5. um and so what we want to do is instead just use a hashmap to record the values we've seen before and recall that their indices and every time we find a value that was already added in the map we check for this property um and that should work right um so how do we do that so let's say we just need to go through indices of the array right and then we need our map that will record the values so maybe let's just have it like this um maybe I'll just call it occurrences or something and then we want to check if this number already exists right that means we already seen the same number that means we have this first property right now we just need to look for um the difference between indices right um and now we need to look for the indices so absolute value of I minus what is the previous index we will put the previous index in the map right so we to obtain it we just get the same number right um because we will hear say occurrence of that number is equal to I right so every time we store the okero's position and that's why we can use it here okay so this is our J sort of um and if this here is small or equal to K that means we have an answer so return true I but if we go all the way to the end and we didn't find two pairs that have that property then we return false okay now one thing to mention here is that actually we don't need to take absolute value here because we are going in the increasing order I would be only later than the ones stored in the map because those are from previous iteration so I is guaranteed to be bigger than whatever this number is right and so we can just then this here is guaranteed to be positive so we just um we don't need the absolute value right so let's run this and let's submit foreign complexity we are doing over and time here right um and the space we are doing also open space with this map because it will contain at most the number of elements in the array um yeah so that's pretty much it follows this problem uh please like And subscribe and see you on the next one bye
|
Contains Duplicate II
|
contains-duplicate-ii
|
Given an integer array `nums` and an integer `k`, return `true` _if there are two **distinct indices**_ `i` _and_ `j` _in the array such that_ `nums[i] == nums[j]` _and_ `abs(i - j) <= k`.
**Example 1:**
**Input:** nums = \[1,2,3,1\], k = 3
**Output:** true
**Example 2:**
**Input:** nums = \[1,0,1,1\], k = 1
**Output:** true
**Example 3:**
**Input:** nums = \[1,2,3,1,2,3\], k = 2
**Output:** false
**Constraints:**
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `0 <= k <= 105`
| null |
Array,Hash Table,Sliding Window
|
Easy
|
217,220
|
1,656 |
hey everybody this is larry this is me going number q1 of the recent weekly contest 215 uh design and audit stream uh so this one is pretty straightforward except just a lot of reading uh so while you're reading it hit the like button to subscribe and join me on discord now let me know how you feel about this one but basically you just have to follow the rules and it's just a lot of rules to read uh and or like i just kept on misreading it but the idea is you just kind of you know make a data structure that listens to the world and just be really careful that you don't go out bounds and in either this way and that you know you have somewhere marking the point of being false um it's gonna you only look at each node at most once so it's going to be linear time no matter what even though you advertise it so yeah so this is going to be fast enough especially for n is equal to a thousand uh let me know what you think and you can watch me solving during the contest now what this is way weird but okay hmm okay oh got this one steam that is i guess i had it right the first time that's why i used to mess up some double checking but hey everybody uh yeah thanks for watching hit the like button hit this subscribe button let me know about your questions about this problem other problems anything and i will see y'all next problem bye-bye
|
Design an Ordered Stream
|
count-good-triplets
|
There is a stream of `n` `(idKey, value)` pairs arriving in an **arbitrary** order, where `idKey` is an integer between `1` and `n` and `value` is a string. No two pairs have the same `id`.
Design a stream that returns the values in **increasing order of their IDs** by returning a **chunk** (list) of values after each insertion. The concatenation of all the **chunks** should result in a list of the sorted values.
Implement the `OrderedStream` class:
* `OrderedStream(int n)` Constructs the stream to take `n` values.
* `String[] insert(int idKey, String value)` Inserts the pair `(idKey, value)` into the stream, then returns the **largest possible chunk** of currently inserted values that appear next in the order.
**Example:**
**Input**
\[ "OrderedStream ", "insert ", "insert ", "insert ", "insert ", "insert "\]
\[\[5\], \[3, "ccccc "\], \[1, "aaaaa "\], \[2, "bbbbb "\], \[5, "eeeee "\], \[4, "ddddd "\]\]
**Output**
\[null, \[\], \[ "aaaaa "\], \[ "bbbbb ", "ccccc "\], \[\], \[ "ddddd ", "eeeee "\]\]
**Explanation**
// Note that the values ordered by ID is \[ "aaaaa ", "bbbbb ", "ccccc ", "ddddd ", "eeeee "\].
OrderedStream os = new OrderedStream(5);
os.insert(3, "ccccc "); // Inserts (3, "ccccc "), returns \[\].
os.insert(1, "aaaaa "); // Inserts (1, "aaaaa "), returns \[ "aaaaa "\].
os.insert(2, "bbbbb "); // Inserts (2, "bbbbb "), returns \[ "bbbbb ", "ccccc "\].
os.insert(5, "eeeee "); // Inserts (5, "eeeee "), returns \[\].
os.insert(4, "ddddd "); // Inserts (4, "ddddd "), returns \[ "ddddd ", "eeeee "\].
// Concatentating all the chunks returned:
// \[\] + \[ "aaaaa "\] + \[ "bbbbb ", "ccccc "\] + \[\] + \[ "ddddd ", "eeeee "\] = \[ "aaaaa ", "bbbbb ", "ccccc ", "ddddd ", "eeeee "\]
// The resulting order is the same as the order above.
**Constraints:**
* `1 <= n <= 1000`
* `1 <= id <= n`
* `value.length == 5`
* `value` consists only of lowercase letters.
* Each call to `insert` will have a unique `id.`
* Exactly `n` calls will be made to `insert`.
|
Notice that the constraints are small enough for a brute force solution to pass. Loop through all triplets, and count the ones that are good.
|
Array,Enumeration
|
Easy
|
2122
|
1,657 |
Jhal Hello Guys Welcome Parivartan Video subscribe and subscribe the Channel Please subscribe and subscribe the Video then subscribe to The Amazing Forest at 2nd Anniversary Celebration of Loot Jadhav Awal Kantirva Problem subscribe to subscribe the subscribe and share and subscribe this Video Return Forms Will Write Back A Visit To Find The Frequency Of Each Character And The Giver Of Subscribe Button Adhik English Improve With Oo Kar Do Loot Kar Do Ke Nav Vihg Find The Frequency Of Every Word For The Two Friends Na Subscribe Kar Actors In Wave 991 That The Frequency Of Value In Forest Land Is 204 But 1980 Settings Friend And MS Word Is Like That I Probably Spring And Closer And Exit Polls From Her Now Visit All The Character Of Frequency subscribe Video then subscribe to The Amazing Liquid Account Will Be Used At present the intent on and navmi have this map ready will be using this app and start discriminating account from this point when skin ko and tell that whom you note hour inspector its dhanvi 68.80 other wise inspector its dhanvi 68.80 other wise inspector its dhanvi 68.80 other wise pimental value that also app ki dravya and belcoms viro devi remove Dirt from you and the map the reader anti date means where are you spring roll frequency of this will return true avoid a man with this code one if it is alphabets from left to ten if it is immediate access play the time complexity of this approach Of Space Complexities Of This Code For A Long Can Reduce subscribe And subscribe The Amazing spider-man 2 And Not Any Way You Will Function For The Best Wishes Not Win This Code A Little Space Laptop Major Iqbal Se WhatsApp Web Screen System In Place Complexity Still Remains Same Time Complexity After Complexity Click Here To
|
Determine if Two Strings Are Close
|
find-the-winner-of-an-array-game
|
Two strings are considered **close** if you can attain one from the other using the following operations:
* Operation 1: Swap any two **existing** characters.
* For example, `abcde -> aecdb`
* Operation 2: Transform **every** occurrence of one **existing** character into another **existing** character, and do the same with the other character.
* For example, `aacabb -> bbcbaa` (all `a`'s turn into `b`'s, and all `b`'s turn into `a`'s)
You can use the operations on either string as many times as necessary.
Given two strings, `word1` and `word2`, return `true` _if_ `word1` _and_ `word2` _are **close**, and_ `false` _otherwise._
**Example 1:**
**Input:** word1 = "abc ", word2 = "bca "
**Output:** true
**Explanation:** You can attain word2 from word1 in 2 operations.
Apply Operation 1: "abc " -> "acb "
Apply Operation 1: "acb " -> "bca "
**Example 2:**
**Input:** word1 = "a ", word2 = "aa "
**Output:** false
**Explanation:** It is impossible to attain word2 from word1, or vice versa, in any number of operations.
**Example 3:**
**Input:** word1 = "cabbba ", word2 = "abbccc "
**Output:** true
**Explanation:** You can attain word2 from word1 in 3 operations.
Apply Operation 1: "cabbba " -> "caabbb "
`Apply Operation 2: "`caabbb " -> "baaccc "
Apply Operation 2: "baaccc " -> "abbccc "
**Constraints:**
* `1 <= word1.length, word2.length <= 105`
* `word1` and `word2` contain only lowercase English letters.
|
If k ≥ arr.length return the max element of the array. If k < arr.length simulate the game until a number wins k consecutive games.
|
Array,Simulation
|
Medium
| null |
449 |
Jhaal Hello Hi Guys Welcome To Special Today's Question Is Serial Light And Utilize Binary Search Tree In This Question Web Design And Told Them To Se R Lives And This Sewing Lowest Rate Is No Restriction On How Are Se Religion And Civilization Gautam Footwork Press The British This leads woman candy cereals to strings and destroying central home news 26 DEC 08 2018 entry morning also basil reaction is date for the dividend transfer sequence of but so that can us to dinner for all member so for example C's explanation tree with root note superfast Her releases were true added value to first converted into your strength format and again using string for maths back to b c cardamom ye bahe sustained ball urinal tree recommendation sample hair given in only and only her life and divides first reaction in footage also root of The Tree Souls in This Root and Distributor First Convert Date Free Interest Serial Interesting Format and Letter Using Spring Personality Green Hornet Also Original Tree Suzy Whole Procedure of Doing This Realization and Utilization Election Let's Look at a Glance of This Question on Om Namo Supporters During Its 2134 According to Saudi Forest Ministry to this report will be given letters to only be given Friday three and a response so further steps to see real history dates back to convert this tree interesting format and stored and steps to beat it means just history in which way Have Formed During This Civilization Culture Civilization With Ra Format And Again You Think That Same Spring The Same Thing To Generate Again Generator Tree Software To Convert First Step To Find Preorder Traversal Retrace And Convert Into A String For Maths In The To Generator 225 Tree To Generate - Tree From Date 225 Tree To Generate - Tree From Date 225 Tree To Generate - Tree From Date Particular Spring Only In the area after format so they should deposit reversal of history will be first t20 dynasty with three and will be 400 prevent yourself mystery solve wishes node in per traversal tuesday recruit fruit bean left element diet elements so difficult reversal review 2134 just visit to this place Was informed on string research hindi terms will look like to vansh 1234 second time repo rate reverse of distic birthday reservation slide mistake in this that in dispute reversal that is the value of two notes that is not getting separated be written as single bed only servi notes20 Pilot 202 A Separate and Two Step Cornice at Perpet Subah Doing This Case to Separate the Value of Two 9 Inch Width Fashion Between Faith in Between All the Value of Two Notes Pure Vegetarian Family Traversal Hindi A Production in Distinct from Admin Light of History's First This is the part Validations Prohibited Output Traditional Indian God Promise Deluxe Output Select Light to turn off This section only the first world were to back to testing camp in which will restore the preparation of 350 MP Singh now will again that maker I will again makeup Function Solid In This Wick In This Deep Reversal Sweet Will Win This And Paw And Will Pass Dip Hands Free Mode Start Root Hair And Will Pass Dia Strings And This Time With Story This And Inner Idol Pass That Reference Evolved Changes The Amazing Distic Narrate Dysfunction Denial Per Function Will Help Us And Will Give Your Travel On History Choice Where Is The Best Is Fruit Is That 112 Not Dominant Vighan Regional Point Per Bank Liye To-Do List Nothing In Return From Her Bank Liye To-Do List Nothing In Return From Her Bank Liye To-Do List Nothing In Return From Her But In Truth Is Not Well Ventilated Dhoop Back To A View To Append Key Value Update Roots Value In Diploma String Fennel Will Do It Sunil Converted Into Two Strings Function Root Well As I Soft Again In This Case Which Was A Strange Story Free Travel Lodging Key Second Function Between Count By Converting The Roots Value Interesting And Paintings Were Painted During Spring 9 Vid Sports Also Evidence Initially A String And Point To Phone Inside MP To Ladies Route Note In The Morning Doing This Step Will Have Converted Routes Value * Spring Latest To End Routes Value * Spring Latest To End Routes Value * Spring Latest To End Up In Return In 2yr Answer String And After 10 Chapter 61 verses 23 24 He also said that they can develop separately two notes Swapnil Jain Fairer Penda Her into Distinct Plus is equal to know the job and different no display and nov1 valve one time in the left side and vitamin e right side so that They can repeat this process Sorry Question Solve Limited that Avadhi right side pass on its website First and in this right side Thanks Time Novels written in this function after being transformed this function will make a call to the self function in male functions in a series After Function And Will Pass Drought And The Temples Spring Wish To See Answer And Independent Will Return From Near This Time Which To Are You Release That Day Deposit River Of The Tree R X2 He Was Born In The Next Three I Harsh And For All His Sudarshan sick person time after being called given on function morning return times to make such disease and civilization where converted and finally Bigg Boss tree interesting format and now with spring from where and you have to and using spring only way to generate a meaning original Palmistry That Arab And It 22 History Subject Generate Divine Institution History Election Bills DBC Is Function Word Civilization As Doing Now Na After Selection Best Thing Is Like These Studies Which Contents To Have One History Lesson For It's Not During Distributor Non It Back To Again Generator Original Tasty Vinod This is the order in which date elements present and easy pre-order free water hitter reversal pre-order free water hitter reversal pre-order free water hitter reversal so gaya to generator best using preorder traversal saunf will do it surya string of Twitter distic and generate all the notes value possible so like vacancy date sheet 2017 new and accept when he sees which one this a21 three and four half note value has debate shoot me two for literature whole spring and whenever and is probably swagger so all the elements before this house half all the elements were not equal to is HR is equal to our notes value is equal to Spinoza value before the will be only value now note and every candidate value to computer - - note and every candidate value to computer - - note and every candidate value to computer - - History Nor Will Move Ahead Withron It's Not Equal To I Ignore Not Equal To The House Should Be Considered Such Note Value Next Invented In Height Suni Values From Previous Next Invented In Height Suni Values From Previous Next Invented In Height Suni Values From Previous S2 This Contest All Will Be Is Equal To One Note Value To Make More Clear Let's Take Care Within 11th It Is Equal To 3433 Sapoch Sunao Let's Friday Side By Side So Let's You Can Understand Any Logic See Left Side Reaction Of Course Not Taken In Tie 2000 Helps In Treating Spring Not Difficult Satta Aakhri From Distic Of West Virginia the root node to your tree to meet from sweet dream in which lies with general a tomorrow morning oil and i is less dent data dot length developed in is traveling are spring and end Vinod and all the values of 9019 and end Vinod and all the values of 9019 and end Vinod and all the values of 9019 presented during holy morning will Extend Difficult Extract the values of particular Extend Difficult Extract the values of particular Extend Difficult Extract the values of particular notes Late Mr Is Nobody Will Do Will Form A String Temporary A To Interest Or Digestive Particular Notes Wb Hot Story C File Arise Ladden This Is Good But Length And So A Data Of I That Not Equal To Face A is but will develop and up and dependable of Vidyapati conduct in a temporary spring temple data i that i plus knowledge by r native when oo a c n initial ri8 bro midnight disposition sleep i love story parties boiled egg white and data is not equal To his son the software is related to length vital role in this very large 1508 laxative value of I will not is not equal to hearts in this case which will be considered a feather Twitter these tempering sure times ringtones MP3 love with you will happen this value IN TIME SPRING 209 TEMPLE BEGUM 2ND YEAR DENA I PLUS I HAVE COME ON TRAI PLUS YESTERDAY MORNING HERE DISH LOGIN ID SEND A GLANCE BUT IS SATISFIING AND DATA IS NOT EQUAL TO HUS NOT BEEN CONSIDERED A DATA IS EQUAL TO HIS SOON BUT ALSO BUT MAIN get value hindi type new delhi hindi time is the value of particular node of the best e saw this water will do e will again function held at kolahala is it again help to function which will use this value and e root of the great Root of Inner Duties Mishri Null It Will Take a Chief Argument Root of Inner Anti Value Visit to Insert in D Binary Search Tree Early in the Morning Equal to Which B Temples in String for Redmi Y2 Give Elementary Teacher for Maths Will Do You Daddy Oye Function And will convert attempt * interior form * interior form * interior form tomorrow morning nearby root of the tree and will end festival interior form of time sweet will again vitamin a new root and hear after 10 chapter country call withdraw we temple you in this post e love stories interested in The street no CR is currently shooting game started but we need to point method is next validity one so that will do will simply do I plus and development ji know that and is setting on essay pollution so one condition is and vanity van I Plus Seat Win Again Starting Point In To The Value Of The Note Servants Loot Healthy Ring Temp Will Be Necessary Lies With This A Spring Temple Also Turned Out Is Rebellion Noida Traffic Jam That Anti A And Sunao This Look Children Boil Ashes Length And Data Is Not Equal to his participation data is not go into history of candidates appeared in temperature i plus president again tempo pie dance yes son date of i is notice ko to hai late pandit temperature and vitamin e plus hai na bhavai naiharva vikram of this point look withdrawal Aka And Will E Will Use This Value Develop Temperature New Notes Value And Will Form Now Best Years In These Don't Dare Devil Inside This Value In Array PHP Using Your Help To Function And They Need All This Over Dr Renu Over Evil Returns Root From Here In All it's right how insert update this winters value day updates t&c the value day updates t&c the value day updates t&c the return type is tree note star in help tuesday function and arguments every woman note star root and e will you to insert in this bst possible it is crazy form is channel it means study for The tree is mt morning will do mills for new route notes p-notes are name tamping to new a new train old and will party value hind is note morning panday new notification so travel anti a to finish national very mp not be appointed new head and Have that in cardamom value of the rupee note value should be medium to initiative was to shoulder tasty current looking like this is to go or so and vitamin is deep 10th over time because of its ancient history notes with in this regard to her personal and they will Return Times and Function Arun 12323 New Root Sunao Root Will Be Too Daily Point to Two to Hai Na A Green Beans Function Will Be Called Sunao Viruddh Will Not With Root Will Not Been Has Been Quite Positive Element Sunao How Will You To Find a Correct Position of how to find a correct position of this value in binary search tree now possible check is a value so on this day equal to key roots value and above values to recruit sullu it means that is it will and above values to recruit sullu it means that is it will and above values to recruit sullu it means that is it will live in the left side of baby laptop also Root This Value Will Right Livelihood By Root Subah Doob Fifth Call To The Life Function Sohail Pattu The Root Left Kama Value Hai Are Basis For Decades In The Court To The Right For Right Function A 123 Help To The Root Right And Weep Half Value On That And Indian will return roots to participate in English newspaper values in this root Sallu it means that values in this root Sallu it means that values in this root Sallu it means that reliance industry and values but entry roots reliance industry and values but entry roots reliance industry and values but entry roots oily food and allied live only right three to understand this battle of body maker video and my channel that is this how To insert values in binary search tree this insert values in binary search tree this insert values in binary search tree this function is doing nothing but integer value in the street show episode the whole criteria of releasing ki ministry and such lies in the street on ki election lada randi code a ki suji rights passing vande custom test case knowledge submit A The Sensitivity Accepted Heritage Hundred Percent Aviation Core Suicide I Hope You Like The Video Thank You To
|
Serialize and Deserialize BST
|
serialize-and-deserialize-bst
|
Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a **binary search tree**. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.
**The encoded string should be as compact as possible.**
**Example 1:**
**Input:** root = \[2,1,3\]
**Output:** \[2,1,3\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `0 <= Node.val <= 104`
* The input tree is **guaranteed** to be a binary search tree.
| null |
String,Tree,Depth-First Search,Breadth-First Search,Design,Binary Search Tree,Binary Tree
|
Medium
|
297,652,765
|
1,574 |
hello everybody welcome to my channel let's solve the lit code problem sorted sub array to be removed to make arrays sorted so given an integer array and remove a sub array can be empty from the array such that the remaining elements in array are non-decreasing a summary is a are non-decreasing a summary is a are non-decreasing a summary is a continuous subsequence of the elements return the length of the sorted sub array to be removed so for example 1 we have these elements 1 2 3 10 4 2 3 5 so if we remove this contiguous element 4 10 4 2 then the remaining part of remaining array is our sorted in non decreasing way so the minimum answer is 3 and if array is sorted in decreasing order so then we need to remove the n minus 1 element at least so this the answer in this case n minus 1 and if the array is increasing strictly then we do not have to remove any sub array so we will return 0 and in case of one element is sorted by default so how we will solve this problem so first of all we can look two sub arrays like from the starting to right like left to right we will check how long we are getting a increasing element so if we see 2 is greater than 1 yes 3 is greater than 1 2 yes 10 is greater than 3 years then 4 is not greater than 10 so it will break here so our s starting and s we will keep s from the 0 and continue increasing if it is satisfied then s will be here and total number of element in this array is n which is eight so the length of the array we need to remove this part so this will be n minus s plus one so this will become ah so n will be index on three so this will become eight minus three plus one so if one of the solution like we can remove the four element like this and the remaining part of the sub arrays is strictly like non-decreasing sorted similarly we will non-decreasing sorted similarly we will non-decreasing sorted similarly we will come from the right and check like start e from n minus 1 and continuously check if a of e is greater than equals to a of e minus 1 so if this is the case then we will decrease e y 1 and we will also keep like e should be greater than or equal to s the original as we already traverse by left to right so once we get then we will get another part so if we start e will be break here so this part of the length we will say we need to remove the e element so this is five element we need to remove so we will take one of this from this minimum over these two so in a result variable so the result at least if we remove the four element we will get the sorted array indication but there is another case if we combine like if we delete from the center like we tried from the removing sub array from the right and the left now look for the center so how we will decide the elements from the center so what we will do like we already got know the sorted like from the left to right we will get the array from zero index like i zero to as only the sorted left array sorted increasing basically and similarly we know from index j let us say e to n minus 1 basically last element of the array is also a increasing element now we will compare between these two elements and continuously update our result from the minimum how so we will check if a of j let's say array of j is greater than or equal to array of i'm i the element which means we can include the i because the current j let us say we have this array in this so let us draw it like this ah so this we have let us say sorted this and right array is sorted like that and we have somewhere here let us say j is running from here and i is somewhere here so we are checking like if this element j value at j is greater than value at i which means we can include these elements correct i element and also the remaining these elements so we will update our result from the previous min either from the previous one or the minimum from like these if we are taking these many right elements so this is j and from the starting if we are taking these i elements so this will be i and the error is this we is the index so we need to do plus one so this will be i minus one hence we will try for all the cases till the i reach the s or the j raised to the n so this is how we will solve so let us quickly implement the code for this problem so first of all we will create n which is the length of the array length and then now one variable s from start from 0 and e from n minus 1 so now while the s is less than n minus 1 because we are comparing with one f i had elements and the array of current elements so this is s so if s is less than or equal to array of s plus 1 then we will increase s and we will check also the case where like if it is strictly increasing array which means s will become n minus 1 then we will return simply 0 there is no need to anything similarly this is for one part and then we will also try for and so if e is greater than s or equals to s this can go till there and we will check array of e minus 1 if array of e basically array of e is greater than or equal to array of e minus 1 then we will decrease e by 1 and also here check if e becomes 0 basically the decreasing array then we will return n minus 1 in case of strictly decreasing array so this is the two cases we done now we will combine the i from 0 and j from the e we will create two variable and while i is less than or equal to s and j is less than n so we will also come by now we will check first if a array of j is greater than or equals to array of i then we will update up so we also need a variable result here so this will be int result which will be math dot min of either the n minus 1 minus s or the e and there we will also update result y math dot min ah current result and the value from j minus i minus 1 so this is how and we will also update i and try for other cases in case of else if it is not then we will increase the j so this is how this simply we will check and then we will return so this will be return the ah result so let us compile the code first whether it is passing or not and it is passing let's submit the code and see if it is ac so it is accepted so what is the time complexity of the solution so if you see this loop may run for n time this group like sequentially running may go and time similarly this loop can run for n time so overall we are running theory and time so the time complexity is o of n and this phase complexity is constant we are using like fewest variables only if you like my solution hit the like button and subscribe to my channel thanks for watching
|
Shortest Subarray to be Removed to Make Array Sorted
|
maximum-product-of-two-elements-in-an-array
|
Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**.
Return _the length of the shortest subarray to remove_.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** arr = \[1,2,3,10,4,2,3,5\]
**Output:** 3
**Explanation:** The shortest subarray we can remove is \[10,4,2\] of length 3. The remaining elements after that will be \[1,2,3,3,5\] which are sorted.
Another correct solution is to remove the subarray \[3,10,4\].
**Example 2:**
**Input:** arr = \[5,4,3,2,1\]
**Output:** 4
**Explanation:** Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either \[5,4,3,2\] or \[4,3,2,1\].
**Example 3:**
**Input:** arr = \[1,2,3\]
**Output:** 0
**Explanation:** The array is already non-decreasing. We do not need to remove any elements.
**Constraints:**
* `1 <= arr.length <= 105`
* `0 <= arr[i] <= 109`
|
Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1).
|
Array,Sorting,Heap (Priority Queue)
|
Easy
| null |
11 |
hey guys welcome to private key and in this video we'll be solving a very interesting lead quote question called container the most water so the problem statement is actually quite simple you'll be given a array of heights so this is basically the array and consider each one of this value to be a pillar so the value one you see is basically a pillar of height one the value eight you see here is a pillar of height eight the value six you see here is a pillar of height six so you get the pattern so i would and each one of these pillars is spaced one unit apart from each other so this pillar and this pillar uh the distance between these two plus unit one resistance between this pillar and the third pillar you see here is unit two uh so we have to find two pillars such that the area between the two pillars is maximum specific more specifically the area of water which these two pillars can hold the maximum so it basically forms a structure like this is one pillar and this one pillar so the water can be up to some certain point and it forms like a rectangular kind of shape as you can see here so if you consider two pillars here for example we consider a pillar of height eight and the pillar of height seven which is basically the two red lines you see here uh the maximum water which these two pillars can hold is basically the blue portion you see here so the blue portion is like in a form of a rectangle so as you know rectangle's area is base into height so the base in this case is the difference between both the indexes so the index of this red second red line you see here is eight and the index of uh the first red line you see here is one so the base is eight minus one it's the sun and the height we have to take here is the lowest one of the heights the reason is after the lowest one of the pillars the water will start overflowing so the water can maximally be filled up to the lowest one of the both the pillars so in this case uh the area is seven into the base of seven so seven into seven which is 49 which also is the maximum area so our job is to find the maximum possible area and return it so before watching this video i highly recommend to check out my friend charm studio where i explain this program logic beautifully the link will be right on top meanwhile i'll just keep waiting so the coding part of this is actually quite easy the most important part is the logic which goes beyond solving this problem so first let's talk about the most obvious logic which is brute posing so in brute forcing we are trying basically trying out uh almost all possibilities of the two pillars so first let's uh take the left pillar to be zero and right two to be one and find the area next let's increment the right pillar we want and find the new area and it goes on till the right reaches end next we try to increment the left pillar by one and uh do the same procedure over and over again till we find every single possibilities of area and we get all the area so the time complexity in this case is n square because we are kind of trying out every single combinations in pair of two so it will take us two loops to solve this problem which makes it n square uh now let's talk about uh the best logic to solve this problem which is using two pointers so using two pointers we can solve this in o of n complexity so first we need a pointer left and pointer right the pointer left is going to be pointing at the zeroth index and the pointer right is going to be pointing to the last index so as we know the area is based into height where the base is basically the right index minus the left index r minus l and the height is minimum of both the height of pillars because already totally white it should be the minimum because uh consider a container like this so for the water to be uh within the container the maximum height it can be is minimum of both the pillar as you can see here we have a pillar of height three units and height eight units the maximum height in which the water can be without overflowing is three units so which is the minimum of both the pillars so in this uh using this solution we can do two operation one is to increment the left pointer by one so the left pointer basically moves from uh one index to the next index or decrement the right pointer by one so the right point to move from one index to the previous index so the most important logic lies behind deciding which operation to do when so let's uh i'll show you example and you can easily figure out when we have to do which operation so first we uh have the left pointer pointing to the zeroth index and right boundary to be bonding to the last index and we just compute the area so the area is basically the base which is eight minus zero so eight is the base and height is a smaller of both the pillars which is uh which has the value one so the maximum area is eight so far now we can do two things we can either increment the left pointer or decrement the right pointer so what should we choose so let's talk about decrementing the right pointer first so if you decrement the right pointer the new height can either be larger than uh what it once was or lesser than what it once was but doesn't matter because if the so okay the right point is pointing to a height uh eight so if it we decrement by one now it's pointing to index seven so what if the index seven has a height hundred or something it doesn't change the area at all because the area will uh still the height is still the smallest of both the heights so it will be height will still be one but we are finding a way to basically decrease the base so we are essentially uh reducing the area which we don't want so incrementing or decrementing the pointer which has the bigger height won't essentially help us improve the area because we're basically uh decreasing the overall base while the height still remains the same so we have to uh move the pointer which has the lower height so in this case the pointer which has lower height is the left pointer so moving the left pointer so the left pointer now points to the index one which has the height uh eight and the index eight has the height seven so the new area is basically the base which is eight minus one seven and the height which is the minimum of both which is also seven so the new area is 749 so which is the max area so far and now the same procedure we need to find which has the lowest lower height now the pointer right has the lower height so we are decrementing it by one so the right pointer only operation we do is decrementing and left pointer only operation we can do is incrementing so since right pointer has the lower value now we decrementing the right pointer by one so this is a new scenario uh the base is reduced by one and the height is reduced uh to the lower height which is basically three in this case and new area is computed which is 18. so 18 is obviously less than the maximum area so far which is 49 so we can just keep the maximum area at 14 and not change it so the new case uh now we have to find the smaller height which is the right index again so we have to decrement the right index by one so this is a new scenario uh right index is pointing to height eight so the minimum height is eight again eight here because both the pillars has a height eight and the base is has the uh a base of one two three four five so the new uh area this scenario is 40s which because it's 8 into 5 and 40 is still less than 49 so we can just move on so since uh both the point is pointing for the same height it doesn't matter which pointer you move so in this scenario which is moving the right pointer and uh the new area becomes uh the same procedure in this case it's 4 into 4 16 it's still not greater than 49 which we had so far so it is moving and we keep doing the procedure till the i is just one away from j uh so the time complexity for this problem is often because we basically just uh need one loop to do is just one while loop and every instance of while loop we are either incrementing i or decrementing j till they both meet so the time complexity is often it's a very good time for complexity and we actually don't need any extra list or array to solve this problem we just need an extra variables in form of pointers so now let's try to code this using python so the first step is obviously initialize both the pointers i'm having pointer left which points to zeroth index the pointer r which points to the last index which is length of height minus one and we need a variable to keep track of the maximum area in each iteration so i'm having a variable m which i'm defaulting to zero so m is basically the maximum area and while the left pointer is less than the right pointer so we always want the left pointer to be right less than the right pointer to find the area and if while the loop is running we have to check if the left pointer height is less than the right pointer height if that's a condition uh we have to increment the left pointer by one if that's not the condition it means the right pointer height is lesser so we have to decrement right point over one so while the incrementing and decrementing is going on we need to check to find the new area and compare the maximum area so far so we can just use an extra variable current area which the area is height into base so the height is the smaller height in this fifth condition it's the left pointer height and the base is basically just r minus l and the maximum area we have to check if current area greater than m if that's the case we have to update m to be current area or you can just use the inbuilt max function to do this which is max of current area and m and the same thing also goes for the else condition here except in this case the current area has the height uh the right part responding to because uh the ls condition the right point has a smaller height and after doing all this we can just return the maximum area and we can run this code so as you can see uh this program runs and in order to make it a little more faster you can probably avoid the use of maximum area variable here and copy the same thing to the function directly but it doesn't really matter because this is actually the fastest way you can actually run this code and the time complexity for this is open because we're just using one loop and the space complexity is over one because you're not using any extra array list we're just using three extra variables so thank you for watching and stay tuned for more content
|
Container With Most Water
|
container-with-most-water
|
You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`.
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return _the maximum amount of water a container can store_.
**Notice** that you may not slant the container.
**Example 1:**
**Input:** height = \[1,8,6,2,5,4,8,3,7\]
**Output:** 49
**Explanation:** The above vertical lines are represented by array \[1,8,6,2,5,4,8,3,7\]. In this case, the max area of water (blue section) the container can contain is 49.
**Example 2:**
**Input:** height = \[1,1\]
**Output:** 1
**Constraints:**
* `n == height.length`
* `2 <= n <= 105`
* `0 <= height[i] <= 104`
|
The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container.
|
Array,Two Pointers,Greedy
|
Medium
|
42
|
278 |
what is up you guys my name is max and in this video i'm going to show you how to solve first bad version on leak code so in the problem description it says that we are a product manager and we are working with a team to develop a new product however the latest version of our product fails are quality check and since each version is based on prior versions that means uh any versions after the one that filled the quality check are also bad so for this problem it says suppose you have n versions of a product you're developing and you want to find the first point of failure that causes all the subsequent versions of your product to be bad and so they give us this api that returns a boolean value when we pass it a version of our product it'll say whether it is bad or not and we can imagine that this api call is expensive it takes a lot of time and memory to call it to do a check on our product version so we want to minimize the number of calls to that api so in this example let's say we have five versions of a product and looks like the bad version is four so we would want to output four because that's the first bad version the first point of failure but what our function would look like is it would call our api so it'd be let's just say it checks once um we'll return false because that's uh before the bad version five will return true when we call the api because that's after the first bad version and four is the first bad version so return true and this guy right here looks like it's just one version of our product the first one's bad so we return the first version and so the way i'm going to approach this is i'm going to whiteboard a little bit in ms paint and then i'll hop into vs code and debug and show you guys how i solved it in javascript so to hop over to ms paint the first way you could think of this problem is if you have five product versions that's pretty much just like this array we have one the first the second third so on version of our product so uh the first way you could approach it is you could make just iterate over that array of product versions and call the api you set you call the api here you say is this one bad nope it's not bad you call the api again call it again you call it again until you find the first api call that returns true but that wouldn't be very efficient what we could do since this is basically an ordered list is we can implement binary search and find the first point of failure but and i'm going to show you how we do that so in binary search essentially you have this start and end pointer and while start is less than or equal to end we are going to implement our binary search so um to do that we would take the starting pointer plus the uh the starting value plus the ending value divided by two and floor that to get our midpoint essentially here we would make an api call and say hey is this version bad and if it isn't bad and also keep in the back of our minds for is the bad version from our first example it's going to return the api is going to return false so that means not only is we don't have to check this version anymore we don't have to check any of these versions prior to it because we know that um this version is based on the other versions of our products so it's good and you can kind of think of this as like if you're looking for uh someone's name in the phone book and you're checking last names like let's say their last name starts with m and you're searching like in the c you could once you check c you can already immediately eliminate uh the rest uh before that because uh their last name is uh the last letter is greater than c pretty much so i will so once you determine that three is good you just you don't want to even check three or anything before it so you just move the starting pointer boom you move it here to mid plus one so here you calculate the midpoint again and you'd say all right five plus four divided by two we floor that we get four all right we make a call to our api and say hey is this a good or bad version it returns that this is a bad version and so in that case we would move the ending pointer to our midpoint minus one but in this case we said we were only looping while the start is less than or equal to the end so that means that we've already found our first point of failure because end is less than the start um and or start is same thing start is greater than the end ending pointer and so i'll show you how we could implement this straight up in javascript so if i hop into my vs code i kind of just copied over the solution and the inner function and i wrote my javascript code here because we're writing the function that calls the api what i did was i basically made my own test api and it takes in a version of a product and it will return it just returns true if uh the number is greater than or equal to four which means four is our point of failure and we're doing the same example i showed in paint where um we have five versions and four is the point of failure so let's get started and start debugging so first we will initialize that solution variable and pass it the api then we are going to call the inner function with this parameter 5. so we have n is equal to 5. we have 5 versions of a product the starting point is then 1 and the ending point is 5. and we're going to check using binary search where the first point of failure is so we calculate the midpoint and then we call the api we um and so we call it on that midpoint we say hey is three a bad version and it is i stepped in it is going to not return true so we would take the starting pointer and move it past that midpoint because we don't need to check anything to the left anymore we just want to keep honing in until we find that first bad version so we go and we iterate again um we have our start is at 4 and n is 5 we calculate the midpoint which is then 4 and we make a call to the api it's going to return true because true 4 is our first bad version we then reposition our ending pointer and now and start is greater than end so we are going to stop and return the start and essentially that would be four and that's what we're looking for that's the first bad version um if that didn't make any uh sense basically i were to um all right so here the starting pointer will always be ending on where we find the first point of failure because it ex it basically exits the loop at that point so we know that this guy was the first bad version so um let's go and go ahead and paste our solution into leak code and see how it does all right so we will paste our function for calling the api here we'll run it on our the first test case they have we get the expected answer we'll submit and boom so um for this problem it seems that the um time complexity would just be the time complexity of binary search and space complexity we honestly just need to store these two pointers uh here so um and uh and mid would also have to be in memory so it'd be a constant time pretty much for any array of product versions that um is given to us so that is the solution for first bad version i hope you enjoyed and i hope to catch you in the next one alright see you guys you
|
First Bad Version
|
first-bad-version
|
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have `n` versions `[1, 2, ..., n]` and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API `bool isBadVersion(version)` which returns whether `version` is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
**Example 1:**
**Input:** n = 5, bad = 4
**Output:** 4
**Explanation:**
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.
**Example 2:**
**Input:** n = 1, bad = 1
**Output:** 1
**Constraints:**
* `1 <= bad <= n <= 231 - 1`
| null |
Binary Search,Interactive
|
Easy
|
34,35,374
|
1,319 |
hello today we will be solving lead code problem 13:19 number of operations to problem 13:19 number of operations to problem 13:19 number of operations to make network connected this is a medium level problem n was available through weekly contest number 171 it's also available through the problems page so let's begin basically given on network of n and computers and each computer is labeled from 0 to n minus 1 now these computers have connections between them namely connections I is equal to a comma B where and B denotes a connection between computers a and B now we have the problem as follows connections is given and we have to figure out the minimum number of times we can remove an edge between two computers and replace it between two computers that didn't have an edge between them already such that the network is connected so each of those removing and replacing is called an operation and we have to find the minimum number of operations such that the computers the network is connected if it isn't possible return negative 1 so let's look at some examples in this example the 3 is not connected and by connected we mean this all computers can reach any other computer so almost like an undirected tree so except it can be more general because it can have extra loops if you have extra edges so let's take a look this 3 isn't connected in the network so let's take this edge from 1 and 2 and let's replace it here which is 1 operation this is now connected network and so we can output 1 as we can see n is 4 because there's 4 computers and connections 0 connects to 1 and vice versa and euro connected to one connects to 2 now let's take a look at this example where you have two computers that aren't part of the connection well you can take the edge from 1 to 2 connect it between 1 & 4 take the connect it between 1 & 4 take the connect it between 1 & 4 take the connection from 0 & 3 and put it over connection from 0 & 3 and put it over connection from 0 & 3 and put it over here therefore we get a connected network in two operations minimum so let's think when is this not possible well from data structure theory we know that the minimum number of edges we need to create a connected graph of V vertices minimum edges is V minus 1 because that's a tree in essence so the minimum number of edges we need is a V minus 1 in this problem we don't have V minus 1 edges we can't solve it so imagine you have three vertices and you don't and you have one edge that's impossible to connect them all with one edge you need to at least so assuming these computers are vertices and the edges are the connections between them we can see here that N equals 6 vertices and we have 1 2 3 4 pairs or 5 edges which means it's fine so 6 minus 1 and V minus 1 is 5 that's enough but if we have 4 edges and 6 vertices that's not enough we need 5 so we can check the constraints and then start some code so the constraints seem fairly normal except there's two cool ones there are no repeated connections and no two computers are connected by one or more cable so that's cool it summarizes that we don't have as much redundancy in here but the duplicates aren't here so for example 0 1 0 won't be here so that's great it just reduces the size so let's get started with the fact that we know so we know that it's impossible if the number of edges we have is less than n minus 1 therefore the number of edges is the number of pairs in connections since the problem said they're unique so if Len connections is less than n minus 1 we return negative 1 now let's think of the real problem so the problem comes down to this can be considered as a graph with computers as vertices as I said edges are the connections so the real problem is how many graphs in this big graph are isolated or disconnected sub graphs in a way for example 3 is a disconnected sub graph and 0 1 & 2 is a disconnected sub graph and 0 1 & 2 is a disconnected sub graph and 0 1 & 2 is a disconnected sub graph now together you can connect them with one edge so we can connect to disconnected sub-graphs with one edge taking a look sub-graphs with one edge taking a look sub-graphs with one edge taking a look here there are three disconnected sub graphs or three disconnected parts so one part two part and a third part so forth five and these now you can connect the four with this sub graph in one vert in one edge one operation and then you cannot connect to that new super part with the five in one operation so all this is telling us is if we find the number of disconnected sub graphs and subtract one that gives us the number of operations we need to do at minimum so it's summarized over here that for every two disconnected sub graphs we need on one edge to connect them therefore return the minimum number of disconnected sub graphs minus one cool so now we reduce it to the problem of finding the number of disconnected sub graphs how do we do that by noticing something interesting a problem can be solved using graph algorithms because we already reduce it to a graph problem let's try DFS or depth-first search we let's try DFS or depth-first search we let's try DFS or depth-first search we do depth-first search on let's say do depth-first search on let's say do depth-first search on let's say any node zero for example and we keep a visited set and we can say the following zero depth first search populates visited 2 0 1 & 2 great now when we move visited 2 0 1 & 2 great now when we move visited 2 0 1 & 2 great now when we move on to 1 if it's in the visited set that means we could we got to it through a sub graph already which was the zeros sub graph and that means we shouldn't think about it so let's just continue and pretend it didn't happen to same thing it's already been visited let's continue now 3 hasn't been reached and since the depth-first search at a node since the depth-first search at a node since the depth-first search at a node hasn't visited this one we know this is disconnected from this 1 we know that the 3 is disconnected from this sub graph of 0 1 2 therefore we know that there is one more disconnected sub graph so we can have a count of number of disconnected cell graphs and count up by one and from there we can search 3 and check all this depth-first search check all this depth-first search check all this depth-first search populate visited and then when we get to another node we can check if it hasn't been visited its another yet another disconnected sub graph because both of these haven't seen it and we can continue from there so we have to perform DFS on every node and if it's unvisited add one to the counter visit it DFS that node and loop for all nodes so we have to do this for every node to verify for example here we'll do DFS on zero it's not visited number of disconnected sub graphs is now one so we visit all of zeros depth-first search visit all of zeros depth-first search visit all of zeros depth-first search and then we move on to one its visited continue to visited continue same with three now when we get to four we say okay it's not visited so now I have to increase my disconnected sub graphs to two and visit four so now visited is four now five is all the way five is unvisited increased the disconnected sub graphs and visit five no more nodes disconnected cell grass is three and hence we returned minus 1 which is 2 as seen by this so let's look at the time complexity and space complexity of this approach for time complexity we have to perform depth-first search on have to perform depth-first search on have to perform depth-first search on potentially the entire graph where V is the total number of vertices or n in this case and plus the number of edges which is the complexity of depth-first which is the complexity of depth-first which is the complexity of depth-first search for an entire graph because we have a visited set we won't duplicate depth-first search so it's all a V Plus depth-first search so it's all a V Plus depth-first search so it's all a V Plus E and another thing to note is we need to also populate an adjacency list or an adjacency matrix to store the values of the graph to store it as either vertex is tab to other vertexes or an adjacency matrix so the way we do that it depends strongly on this complexity so we'll take a look at why it's still all V plus C terms of space complexity we need v-space which all the vertex is we need v-space which all the vertex is we need v-space which all the vertex is for visited potentially we can visit all of them and the stack for depth-first of them and the stack for depth-first of them and the stack for depth-first search is o of V now we can use an adjacency list to get all V Plus e space because we have e edges and we have V nodes therefore we have all V Plus E space complexity for an adjacency list now to populate that adjacency list we'll also take all of the see or in essence it would just take oh of a so I'll add that in here and so a V + O V plus C still remains a toe of E + O V plus C still remains a toe of E + O V plus C still remains a toe of E Plus E and the complexity for space is now again o of E Plus V cool let's get started with the approach let's it started with the approach over here I'm just going to add what I've written before so I create an adjacency list and that adjacency list is an empty list for all the vertices and for each vertice I append to its adjacency list the vertex is connected to so of each pair of connections the first pair append the second pair and the second pair append the first pair which means zero added to existing connections to one and vice versa now we add logic of visited so after we visited we have a set so we have also disconnected count as we said before and for every vertex we check if it's not visited increase the disconnected count by one and perform that first search which changes visited in place now return the disconnected count minus one which is all this logic and so we need a depth-first search and so we need a depth-first search and so we need a depth-first search function so I'll write that here my depth-first search function is the my depth-first search function is the my depth-first search function is the exact same as my previous step is similar to my previous depth-first similar to my previous depth-first similar to my previous depth-first search function in my other video where I start with the stack and while the stack is on empty check if the last element of the stack when it's popped is in visited if it isn't added to the visited and this changes visited in place so the set will now be different the next iteration and so for every other vertex adjacent to this vertex if it isn't visited added to the stack to be examined later and so we return disconnect to count plus one again I'm going to add this to our time complexity so we get at our time complexity is o V plus C and our space complexity is o V plus C which looks very nice for a graph problem so let's run our code and we get one and one which is nice and promising I always like to run the code before submitting and we get our submission as ninety four point four percent faster than Python solutions 100% astron butter and Python solutions 100% astron butter and Python solutions 100% astron butter and space solutions so less memory so that's a very nice result very promising and again it looks like a great problem so we've just tackled number thirteen nineteen thank you for watching I urge you to strongly understand this code and there can be many other ways that you can solve this problem so please reach out in the comments below and let me know how you solved it thank you very much and have a nice day
|
Number of Operations to Make Network Connected
|
unique-number-of-occurrences
|
There are `n` computers numbered from `0` to `n - 1` connected by ethernet cables `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between computers `ai` and `bi`. Any computer can reach any other computer directly or indirectly through the network.
You are given an initial computer network `connections`. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected.
Return _the minimum number of times you need to do this in order to make all the computers connected_. If it is not possible, return `-1`.
**Example 1:**
**Input:** n = 4, connections = \[\[0,1\],\[0,2\],\[1,2\]\]
**Output:** 1
**Explanation:** Remove cable between computer 1 and 2 and place between computers 1 and 3.
**Example 2:**
**Input:** n = 6, connections = \[\[0,1\],\[0,2\],\[0,3\],\[1,2\],\[1,3\]\]
**Output:** 2
**Example 3:**
**Input:** n = 6, connections = \[\[0,1\],\[0,2\],\[0,3\],\[1,2\]\]
**Output:** -1
**Explanation:** There are not enough cables.
**Constraints:**
* `1 <= n <= 105`
* `1 <= connections.length <= min(n * (n - 1) / 2, 105)`
* `connections[i].length == 2`
* `0 <= ai, bi < n`
* `ai != bi`
* There are no repeated connections.
* No two computers are connected by more than one cable.
|
Find the number of occurrences of each element in the array using a hash map. Iterate through the hash map and check if there is a repeated value.
|
Array,Hash Table
|
Easy
| null |
144 |
hey everyone today we'll be doing another lead code 144 binary tree pre-ordered traversal what is the pre-ordered traversal what is the pre-ordered traversal what is the pre-order traversal first of all pre-order traversal first of all pre-order traversal first of all a pre-order is a traversal in which a pre-order is a traversal in which a pre-order is a traversal in which a root come first and then we will go to the right side and then we will go to the right left side then right side root left right so in this case we have one two and three we have one as a base root node so we will go to the left we have nothing on the left so we'll go to the right and see we have two we will check if this two has its own left and right and yes it does have so the root come first the parent node comes first always like this and then at the end we will be appending the leaf node one two three this is the output so we'll be implementing it so first we will be checking our base case like we always do written empty list if we have no root to begin with if we have something in our root as a root so we will append it to the stack and make an empty stack and now while there is something in the stack we will make a root and we will append this in our result now if we will check if this root have its own right we will append it to this order is very important i will explain in it in a minute that why we are going to the right first and then to the left stack a band root.left and after doing all of this we root.left and after doing all of this we root.left and after doing all of this we will just return result this should work fine let me see if this works fine then i will explain the whole code yes this works fine yeah this works so what is happening here is let me draw a binary tree you can see and three here four here and five where six and then seven this will be our stack and this will be our result so at first we have root in our stack like this okay stack is not empty we will go inside the whole loop while load we will pop the stack and append it to the root okay this is done now we will check if this root have its own left and right it does have its right we will go to the right first and then we will go to the left okay so why we are going right first because this is stack the first the element going earlier will come at very uh later like you can say the element going first will come out at the very last so when we will pop again for two we will pop it two like this and we will check if two itself has its own left and right yes it does we will go right first and then left and now we have four on the top of the stack we will pop four is gone and after that we can see that four does not have its own left and right we will again go into the loop and pop five also so now we will see that we have three we will pop three also and check if appended to the stack and alongside this we will check that if three has its own left and right yes it does so we will be appending them first right and then left why we are doing this again i am explaining so we left at the very last because what comes last will be popped out earlier so six will be popped out earlier and the right will come at last so after that there is seven and seven will also be eventually pop out of the stack and stack is empty there is nothing in the stack we will just return the result so you can see we have our root node first root at the left first at the left 4 and then 5 then we go to the right we have our parent node first and then left and then right so this was it this was the whole code
|
Binary Tree Preorder Traversal
|
binary-tree-preorder-traversal
|
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[1,2,3\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
**Follow up:** Recursive solution is trivial, could you do it iteratively?
| null |
Stack,Tree,Depth-First Search,Binary Tree
|
Easy
|
94,255,775
|
209 |
hey guys welcome to a new video in today's video we're going to look at a lead code problem and the problem's name is minimum size subarray sum so in this question we given an array of integers called nums and we are also given a positive integer called Target and our task is to return the minimum length of a subarray whose sum is greater than or equal to Target so this is important greater than or equal to Target and by definition a subar is a continuous non-empty sequence of characters within non-empty sequence of characters within non-empty sequence of characters within a string so for example 231 is a subarray whereas 232 is not a subarray it is a subsequence because 232 is not contigous whereas 312 is continuous so 312 is a subarray and if there are no such sub arrays we have to return zero instead so let's take a look at these examples and see how we can Sol this question so let's take the first example we given the target seven and this is the input array given to us we need to find the minimum length of the subarray whose sum is greater than or equal to Target so we need to keep track of the size so I create a variable called Min length which will be our output so initially the length is equal to zero and we also have to calculate the sum right so that we can compare it to the Target so I create another variable sum which is also initially zero now I need to find the length of the subarray I need to keep track of the starting limit and the ending limit of a subar so I take two pointers left and right so left and right both will be starting from the beginning which will be are the left bound and the right bound of our window so initially left and right both are pointing at zeroth index now right pointer we start ating till the end so that we keep track of the sum and compare it with the target so initially we add the value at right which is two into the sum so the sum is now two now check if this sum is greater than equal to Target no so we keep the right pointer moving forward now add the value at right into sum so three will be added and the sum is now five now check if this sum is greater than equal to Target no so keep moving the right point forward now add the value at right into the sum so the sum is now six now check if the sum is greater than equal to Target no so keep moving the right poter forward now add the value at right into the sum so two will be added to six and the sum is now eight now check if the sum is greater than equal to Target yes 8 is greater than 7 so it is meeting our condition of the subar now how do you find the length of the subar you have the right index and you have the left index so right is three and left is 0o so right minus left 3 - 0 + 1 because so right minus left 3 - 0 + 1 because so right minus left 3 - 0 + 1 because index position start from 0 so 4 - 0 is index position start from 0 so 4 - 0 is index position start from 0 so 4 - 0 is 4 so the length of the current subarray is 4 which is this subar so four will be updated with Min length so now we find our left and right index now the value is eight now the length of the subarray is four now we can see if we can form a subarray of length three to decrease the subarray we need to move the left pointer forward right so left will move forward so left is now at one now we move the left pointer right so whatever value was at left previously should be subtracted from the sum so that we get the sum of the new aray we subtract two from the sum so six is our current sum so here you can see six is our current sum now we check if 6 is greater than equal to 7 no so we keep moving at right po so add the value at right into the sum so sum is now 10 now check if this 10 is greater than 7 yes 10 is greater than 7 so find the subarray length so subarray length is right is at 4 so 4 - 1 + 1 will give you the length 4 so 4 - 1 + 1 will give you the length 4 so 4 - 1 + 1 will give you the length of the subar which is 4 check if the current subar is length no both are same so 4 will remain as the M length now we have to check if we can decrease the length of the subar we move left to the right so left is now move to the right so this value should be subtracted from the sum so we subtract three from sum so sum is now seven now check if seven is greater than equal to 7 yes 7 is equal to 7 so we have to check greater than equal to Target right so 7 is equal to Target so the condition is satisfying so find the length of the subarray so the length of the subar is Right - left + 1 length of the subar is Right - left + 1 length of the subar is Right - left + 1 is equal to 3 so length of the current subar is 3 and check if this length is minimum yes 3 is less than four so we found a new subar size so three will be updated now again try to move left and check if you can find a more or less size now left is at three so remove this value from the sum subtract one from the sum is now six check if 6 is greater than 7 no so we move the right pointer now add the value at right into sum so three will be added and sum is now 9 check if this value is greater than Target yes 9 is greater than 7 so find the length of the subarray length of the subar is Right minus left that is 5 - 3 subar is Right minus left that is 5 - 3 subar is Right minus left that is 5 - 3 + 1 which is 3 and the current value is + 1 which is 3 and the current value is + 1 which is 3 and the current value is also 3 so 3 will remain the same now check if we can decrease the length of the subarray by moving left one step forward so left is now at four we have to remove this value from the sum so subtract 2 from 9 so sum is now 7 check if 7 is greater than equal to 7 yes 7 is equal to 7 so this condition is satisfying so find the length of the subarray is Right minus left 5 - 4 + 1 is equal to 2 check minus left 5 - 4 + 1 is equal to 2 check minus left 5 - 4 + 1 is equal to 2 check if this 2 is less than 3 yes 2 is less than three so update the Min length value to two now check if you can move left again now left is now at five subtract the value at previous left have the value four so subtract four and the value is three check if three is greater than 7 no so move the right point so right is now at six which is greater than the length of the subarray so we end the iteration and whatever is present inside the Min length value will be returned as the output so two is returned as the output so initially you start Min length with the maximum possible value not zero so that next time you update the length of the subarray that value will be overridden to the size of the subarray so initially the size of the subarray was four right check if four is less than the max possible value yes so four will be updated to Min length and from the next time the max value is four and whenever you find a lesser subar size that will be compared with four and you update the value finally you get the value two as the output now let's implement the same steps in a Java program coming to the function given to us this is the function name this is the input Target given to us and we are also given the integer array col nums and our task is to return an integer represent presenting the minimum length of the subarray whose sum is greater than equal to Target now first let's start off by creating our output variable I'm going to create output variable called Min length which is initially the max possible value that is 2^ 31 minus 1 now possible value that is 2^ 31 minus 1 now possible value that is 2^ 31 minus 1 now we create a variable which will keep track of the sum and now we need the two pointers left and right so right pointer is going to be the for Loop iterator whereas left pointer I'm going to declare it here which is starting from zero now let's iterate through the array using the right pointer starting from the zero index the last int right is equal to zero and right is less than the length of the nums areay and right will keep on incrementing there a typo here now we add the value where right is pointing so right and left are starting here right will be iterating through all the elements so first we add the value which uh right is pointing to into the sum so sum plus is equal to num. right so the element pointing at uh right index will be added into the sum now we check if the current sum is greater than or equal to Target so we use a the Y Loop until current sum is greater than equal to Target we can keep on finding our minimum by moving the left Pointer while sum is greater than equal to Target we find a probable answer so first calculate the Min length so Min length will keep on updating which will be the minimum possible among the current wind length value or the current Windows value is Right minus left + one this will give Right minus left + one this will give Right minus left + one this will give you the current window value and you'll compare it with the minimum length value and whichever is minimum will be updated to the Min length now for example here you can see we have found our Target so this is the first window 2 312 the sum is equal to 8 which is greater than equal to Target so we find your first window so first window you find the current LA value right minus left + 1 current LA value right minus left + 1 current LA value right minus left + 1 which will give you four so Min length is currently four now you can eliminate this value right how will you get this value so you remember left is pointing at that index so from the sum remove the value where left is pointing so sum minus equal to nums of left and once you remove that value this is a while loop right so you can move the left pointer so left pointer will now be pointing here so that we can check if we remove the current value at left if this condition is still satisfying we can get a new value for minimum length so until this condition satisfies left will keep on incrementing So You increment left if this condition is not satisfied you add the value at right again now the right pointer will move so this y Loop is for moving the left pointer and calculating the minimum value and now this for Loop will happen for all the elements once right reaches the end of the array you end the iteration and you have your answer present inside Min length but here they mention another condition that if uh there is no such subarray which meets this condition then in that case Min length will still remain this value right so we have to check that so return so we use a tary operation so first we check if Min length is still equal to this you copy this and paste it and you have to use equal to inside if conditions right so if Min length is still this we return zero else we will return whatever is present inside Min length so if zero hasn't been returned then it means we have updated our Min length value so that will be returned here which has been updated here now let's try to run the code the test case are being accepted let's submit the code and a solution has been accepted so the time complexity of this approach is O of n where n is the length of the input array given to us and the space complexity is constant o of 1 because we're not using any extra space to solve this question that's it guys thank you for watching and I'll see you in the next video
|
Minimum Size Subarray Sum
|
minimum-size-subarray-sum
|
Given an array of positive integers `nums` and a positive integer `target`, return _the **minimal length** of a_ _subarray_ _whose sum is greater than or equal to_ `target`. If there is no such subarray, return `0` instead.
**Example 1:**
**Input:** target = 7, nums = \[2,3,1,2,4,3\]
**Output:** 2
**Explanation:** The subarray \[4,3\] has the minimal length under the problem constraint.
**Example 2:**
**Input:** target = 4, nums = \[1,4,4\]
**Output:** 1
**Example 3:**
**Input:** target = 11, nums = \[1,1,1,1,1,1,1,1\]
**Output:** 0
**Constraints:**
* `1 <= target <= 109`
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 104`
**Follow up:** If you have figured out the `O(n)` solution, try coding another solution of which the time complexity is `O(n log(n))`.
| null |
Array,Binary Search,Sliding Window,Prefix Sum
|
Medium
|
76,325,718,1776,2211,2329
|
1,465 |
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 daughter's I'm coding they've been explanation near the end and for more context they'll be a link below on this actual screen cats of the contest how did you do let me know you do hit the like button either subscribe button and here we go to two maximum area of a piece of cake at horizontal vertical cut so this one is basically up some cuts and then after you're cutting them you try to find the biggest slice of each one way so from here you could recognize from here and the explanation would be later on feel free to skip ahead but basically what I recognize first that okay you can always choose the biggest cut in the dimension it doesn't have to be vertical or horizontal so you just really do them independently of each other and that way you just go straight from that sense you saw the Vertigo and then you sort the horizontal cuts so I was also double checking whether we can put we could so another way to think about this problem is that I wouldn't send those where there's a cut on 0 and a cut on H a cut on 0 and I cannot W right so that's what I'm doing here so I just put it in so that I can lay this sort and then look at adjacent elements so that you don't have to worry about educators with like the first element and then the last element or something like that so that's what I do here I have a little bit of a typo here and that cost me a couple of minutes because I think I confused horizontal cuts with H so I knew that if you cut on the age you it goes the other way right or something like that I was very confused so I just got the signs wrong but uh I fix this later there is another mistake unfortunate because I while I was double checking this I forgot that you have to mark this because it doesn't seem like that big cuz everything should fit in a long so I did not think to mod it but that cost me five minutes so that was the wrong answer for this problem but otherwise I did this one pretty quickly I wish they'd just give you one answer why am I gonna trick it's q2 why mcmutt like yeah but I looked at this I was like ah this is the wrong answer and I double checked to make sure that my understanding is correct and then I was like oh it's probably because I mixed up to H and W and once I fixed that I submit but it was the wrong answer because I forgot them on that face oh and as soon as I started I knew it well so at this time I don't know what's running on my computer but it was really running slowly so I had to close some windows real quick and that also cost me some time that's what I was doing now try it instead normally I would copy and paste this straight and then just one and again because that's my usual pattern but yeah now I'm just closing some windows and that took some time next time I should be prepared on closing everything first oh yeah see now when again just to make sure I get to right wrong answer and then I was like Aria the mod I knew about the mod because I remember reading it so I knew how I need to solve this immediately but it's just sad I was going to just copy and paste back if they use the same constant so I didn't have to run it real quick there's some lag because my computer is slow today I really need to go somewhere this let's look at this it's not even been doing but ok once I see that it gets to come against I submit and I think I also cause more windows now but yeah that's cute boy like you to sign queue to maximum area of a piece of cake after horizontal vertical kicks cut so this one I did pretty straightforward I spent 4 minutes because I think I was mixing up 2h ended W I wasn't sure that horizontal cut I guess makes sense uh I think I got a little confused about H in the horizontal to be honest and then I confused him of height because then I was like now it is H then you want to cut because if you cut hide you cut the other way someone like that's right I mixed up these two variables but that fool me off for like a couple of seconds and I was like ok maybe that's wrong so that but the idea here is that the dimensions to vertical and horizontal they're independent of each other and what I mean by that is that you could use greed and what I mean by that is that you could choose the widest order yeah like the longest on the height or the width and then you take the longer you always choose the maximum version of that and once you do that you just multiply them together and this one was kind of annoying because the marginal stuff I mean I think they really could have just made this slightly smaller so that it doesn't have to require modulo because it also fits in a 64-bit int so because it also fits in a 64-bit int so because it also fits in a 64-bit int so that's why I in a moment I forgot about the mine and I got a wrong answer you recall but I asked them when I saw it I saw I when I first read the question I did see this and usually I would immediately go down to the solution and write down the mod but this problem I guess I was a little bit of Westie and not you not coherent to my usual thing oh yeah but basically I just take I saw it there were cuts and I take the two adjacent cut where you cut it and then you just take the fattest piece of both the width and then the height and then you just time them multiply them together to get the result of the biggest slice yeah so this album the way that I did it is all of and again dominated by the sword that's pretty much it the space is also over and the way we did it kind of depended how if you want to count us modifying the inputs but yeah
|
Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
|
maximum-product-of-splitted-binary-tree
|
You are given a rectangular cake of size `h x w` and two arrays of integers `horizontalCuts` and `verticalCuts` where:
* `horizontalCuts[i]` is the distance from the top of the rectangular cake to the `ith` horizontal cut and similarly, and
* `verticalCuts[j]` is the distance from the left of the rectangular cake to the `jth` vertical cut.
Return _the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays_ `horizontalCuts` _and_ `verticalCuts`. Since the answer can be a large number, return this **modulo** `109 + 7`.
**Example 1:**
**Input:** h = 5, w = 4, horizontalCuts = \[1,2,4\], verticalCuts = \[1,3\]
**Output:** 4
**Explanation:** The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.
**Example 2:**
**Input:** h = 5, w = 4, horizontalCuts = \[3,1\], verticalCuts = \[1\]
**Output:** 6
**Explanation:** The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.
**Example 3:**
**Input:** h = 5, w = 4, horizontalCuts = \[3\], verticalCuts = \[3\]
**Output:** 9
**Constraints:**
* `2 <= h, w <= 109`
* `1 <= horizontalCuts.length <= min(h - 1, 105)`
* `1 <= verticalCuts.length <= min(w - 1, 105)`
* `1 <= horizontalCuts[i] < h`
* `1 <= verticalCuts[i] < w`
* All the elements in `horizontalCuts` are distinct.
* All the elements in `verticalCuts` are distinct.
|
If we know the sum of a subtree, the answer is max( (total_sum - subtree_sum) * subtree_sum) in each node.
|
Tree,Depth-First Search,Binary Tree
|
Medium
|
2175
|
92 |
hey everybody this is larry this is day 21 of delete code daily challenge hit the like button oh no three points hit the subscribe button join me on discord let me know what you think about today's prom it is a thursday hopefully everyone's doing all right i am sweating raise weight hot here in new york probably not as hot as i hear from in europe i have my air conditioner on so we'll see um yeah i'm also very tired right now so we'll see how that goes we have a less farm it seems like i see the image but i am i played a lot of softball and also i got stuck on a train for like an hour and a half because this is new york and l train sometimes it's sad uh i did get a taco bell because you're wondering not sponsored i just i hate it in case you're curious because nothing else was open in the area but uh i let's think about this we first linked list two given the head of a linked list a singly linked list left and right reverse the length um the notes from left to right okay um yeah doing one passes silly i mean i really don't like these kind of uh linked list problems just because they're always like some weird thing that you don't really use with like you know it's one pass but you use four pointers at the same time or something you know like does that really count as one pass yeah technically but then your memory assets are not like optimal anyway so i don't know okay so let's see left and right um so you know the two pass is just doing the regular reversal after getting the length n right um i think you can do something like to get the left and right how do you get the left and right so getting left and right is easy because you just start the left let's say that and this is just me thinking it through i don't know the answer or whatever because you know who knows these things but um yeah but basically you know the left and the right you just start the left pointer uh you know x or the delta amount so that part i think we get and then the question is how do you get it from the end i always forget about how do you get it like x to the n um if you have n then you could have whatever right but if you don't have n then how did it how does it work and i'm sweating in here it's uh it's actually a struggle for me okay so let's say yeah um okay so left and right makes sense head right so um let's see i forget about this part oh wait no i'm just being dumb am i think i'm trying to be uh sorry friends my head is clearly wrong um because you only need left and the right because they're from the beginning not from the end what am i thinking of you just go right number of times right so i know that there's a one pass solution but we let's just write the two pass for now to get the left and the right and then do it um i think it's actually like way trivial to do it and to convert that to pass into one pass maybe not trivial but doable so uh so let's do that um yeah actually we could just do it in one pass maybe okay we'll see so yeah let's just say current is here to head right uh and the head is the first one maybe is that right yeah okay so then now while current is not none you know current is zero current next set um and then we do some magic here maybe we have a counter so i just go to counter because i'm lazy uh it's at one because that's what this one is um so then here we go and i am really silly sometimes okay so if counter is equal to left then yeah then left pointer is to go to current if counter is equal to right white pointer is equal to current right um kind of i mean yeah we i know for a fact that we have to set this up so yeah so let's just leave this here for now don't have to do some more minor things to do in one pass the idea here is that okay on the left plus one counter so we don't do anything with the left pointer yet in the beginning because yeah because we set it to right point as next so we can do that later um and then the counter plus one which is in this case the three i'm looking at this diagram in the counter plus one what do we do well um that's the like usual reverse linked list type thing right so then yeah so if calendar is greater than left right um at least for now we'll do the we'll add a conditional to the right side um okay so it's greater than enough what do we do uh that means that okay so you have to keep track of the previous pointer as well i think that's something that uh i've been sloppy about yeah something like that and then now then the um we want to say the current pointer right we couldn't point it down next is equal to previous something like that so you point at the previous um but of course you can't do it quite like this because you have to increment it later right so then here we go um how do we want to say it let's just say yeah i mean yeah okay i just say change me i don't know naming is hot is it going to cur current right uh we do this in this is kind of weird actually so we want to move on maybe we just do it this way maybe this is easier to think about instead of trying to pre-optimize the pre-optimize the pre-optimize the logical statements um yeah so and then here change me here that next is your previous and then yeah and then previous is equal to oh wait i have to change uh this is so like yeah okay fine new previous is equal to current and then previous this you go to new previous or something like this right um okay so then now basically if this is right and i should be right uh maybe it should be but it might not be uh in this case um everything should go backwards um well and this is looking at right yeah okay i think this is right but now we have to do a previous left pointer so that it points to the four if you will so yeah um previous left is equal to none previous left is you go to previous or something like this and then yeah and then now at the very end if previous left is not none then previous left.next then previous left.next then previous left.next is equal to the right pointer right and then in general the left pointer instead of looking at the next one that next will be equal to right um it should be like something like this but it but that's not quite true only because we updated my point over here um so okay so then next one let's get another this is such a mess uh yeah next sprite is you go to write pointer.next pointer.next pointer.next and then yeah right do i have to return anything we have to return the head oh i guess it may not be head right because if you reverse it then you may not return this head so actually we need to do like a fake head this is such a mess i don't even know if it's right so we'll play around with this but um yeah so then now this is new head and then now we start to count at zero instead okay and now we return new head.next new head.next new head.next not gonna lie i have no confidence at this at all so we'll see where it goes wrong and then see how we're debugging um okay what point it didn't record that do we oh huh we don't say that point either but why is that shouldn't that always be true is that for the first one or the second one oh i forgot to increment this one inside the loop that's why uh okay that part i think we can put out safely so let's do it that way uh yeah okay that actually somehow worked right the first time i tried to well this one is a very basic one so let's do one five one two and two five and four five maybe all right if this is right then i'm kind of confident i don't think i have any like weirdness with rg events or anything like that so all right let's give it about zero notes okay and it has to be one note the note value doesn't matter so yeah all right let's give it a quick spin this is very easy to get wrong i'm very happy that i get it right very low confidence about this in general because this is frankly quite a mess but you know what an ac is an ac and i'm not talking about air conditioner so that is helping a lot right now i'm still sweating um so yeah um that's pretty much all i have for this one let me know what you think oh yeah what is i mean we did in one pass as you can see just a lot of teaching that's all it is with linked list forms usually it's just like a lot of keeping track about which pointers should be rare at any given time and if you do get it on an interview definitely feel free to slow down and talk for your i mean you should be talking for your thought process anyway but don't watch it make sure you get it right and then you know um hopefully you have what i did this time yeah um yeah that's pretty much all i have for this one so yeah linear time one pass linear oh sorry constant space we just have like 10 pointers or something like this a lot of pointers but not but uh but not linear number of them so yeah uh cool that's pretty much all i have stay good stay healthy to good mental health i'll see you later and take care bye
|
Reverse Linked List II
|
reverse-linked-list-ii
|
Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], left = 2, right = 4
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[5\], left = 1, right = 1
**Output:** \[5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= n <= 500`
* `-500 <= Node.val <= 500`
* `1 <= left <= right <= n`
**Follow up:** Could you do it in one pass?
| null |
Linked List
|
Medium
|
206
|
47 |
hello so today we are doing this problem called permutation 2 which is very similar to a problem I did before called permutations problem 46 I will put the link in the description for the solution for that one I think you should watch that one first and this problem says that we get a collection of numbers that may contain duplicates and want to return all unique permutations so for example with these numbers we can have 1 2 so you can see here 1 & 1 are 1 2 so you can see here 1 & 1 are 1 2 so you can see here 1 & 1 are duplicates contrary to the previous problem where the permutation problem where we had that it's a collection of distinct integers but here we may have duplicate integers and when I return all the possible unique permutations so we don't want to keep the same permutation twice because that may happen if we is the same method as the previous permutation that assumed that we had in district and distinct integers so here the permutations for 1 2 are 1 2 1 & 2 1 and so we want to do that do 1 & 2 1 and so we want to do that do 1 & 2 1 and so we want to do that do them we generate all the permutations but only the unique ones ok so let's see how we can do this problem so to solve this problem permutations with the numbers being duplicates plus first just revisit the template that we have for solving backtracking problems so I will post the link anyway for the guide to just over template to solve all or most at least most backtracking problems and so right now what we are going to see is I'm just going to quickly go through it which is the way to do that it was that we just need to find to model the solution as a vector of partial solutions and at each step we need to find the candidates that can extend that vector solution and then we will check at each iteration if we find a solution if we did we want to process it and add it maybe to a result list or printed or anything we want and so the template was that first we check if we have a solution then we process it we add it to a list of resource or something otherwise that means we don't have a full solution yet and so we are going to look and say ok at this step what could be my possible next steps and then we are going to get all of them and go through each one of them one by one which is this candidate and take each founded at and add it to the partial solution which is a and then do a move make a move and then backtrack to the next position in the partial solution a and then and make the move and that's pretty much it and so we need to find these templates and if you remember for if we look at this the way I solved the initial permutation problem which is not the one with duplicates I will also post a video of the social for this one in the description but for this problem which is very similar the only difference is that we in the new problem we have duplicates the we generated a vector solution which was that we put the element that would pick it so far in the permutation and so we said that for work at each position the partial solution our next step would be to pick any element that we shouldn't pick again so to pick any element that we haven't picked yet right because that is there is a possible armed element because if we picked an element before we don't wanna repeat it so we didn't pick it and so you can see here if we picked an element before we don't pick it again so that's a problem here because here we have a duplicates and so here we can have one two and so if we pick one we still can next step can we can still pick one but with this with our construction of candidates in this problem we can't do that anymore in the new problem and so but everything else is the same we find the solution when the length of our partial solution becomes equal to n which is the length of the permutation that we are looking for and processing the solution is just adding to some output array or output list and then to make a move we will need to append to the solution vector and am making mooney to still part from the solution vector because we want to go back and add more to the solution vector and so these ones we need to keep this one we keep this one but we need to change this one a little bit because we can't just pick any elements not picked yet because we have duplicates and so how can we change that so that's why what we need to change to make this solution to solve this problem and so one thing we know is that we can have duplicates and so if we have duplicates like this we don't know how many so what we can do is just have a counter of how many of ones we have right so for one we have three ones right so if we have this what we can do is so what we had before in the construct candy that was without the duplicates what we did before was pick and pick any element not pick it yet but since now we have the possibility that the element exists multiple times what we can do is change this to pick any element right that for which the counter is not zero right because so that means that we will pick one and then decrement the counter and the counter becomes two don't pick one again decrement the counter become one and then when we decrement it again we can pick another one but after that we have to stop we can't pick it anymore because now the value is zero right and so our the change we are going to do is that we are going to need to for construct candidates here we can basically go for all the element in the counter which will be just the keys which would be just the elements in the array any value in V that has the counter value bigger than zero that's a candidate right because if the body is 0 that means we already pick up all the elements available and so we shouldn't pick it again right because it doesn't there is no other clearance right and so to do that though to be able to decriminalize so in our make a move function from the template we will need to change that a little bit so the make move and make move only to change a little bit so before make move was just appending to a the value V and in the M make we just pop it V right and so what we need to do is determine the counter now because we have a duplicate and we wanna count so that when it reaches 0 we're no longer included in the candidates and so what we need to do for that is decrement the counter by 1 and now since we decrement the counter if we are all back in backtrack to this one that means now we can pick this one right and so we need to in the M make move we 2n do the operation that we want to do so this is something to always keep in mind whatever operations we did in the make move we should undo them in the M make move and so now that we have the Constructicons D that we have the new make move and M make move and the other methods which are is solution and process solutions we already we have the same as the previous problem permutation we can just use all the combination of these and solve the problem and so let's do that then so what I need to do here is the template of backtracking which was we will need to check if K is equal to n which would this is basically that we have a solution then we need to process the solution right which means just take the output array and upend the partial solution that we have so far and since k equal to n that means we have a partial full partial solution now and then after that so this is process solution step and now so you can notice that I'm no longer putting them in functions because now that we know the algorithm we can't in the template we can just apply it in line without needing to UM to write in functions and then align it again and now we can just do else we are going to go through the values in the counter and what I will do it here is before executing this function I would have counter that will just contain like compute I will show you how to easily do that in Python but it just confuses the count of occurrences of each number in the list of numbers right so this is just says for this one basically something like this it says that it's a counter that says that one occurs two times two occurs three times and three okay one time so this is what I want this function to return to me and now for constructing the candidates I go through the elements in the counter and then I check if the counter is bigger than zero doesn't mean this is a candidate and so this portion here for me is construct candidate function the next step is to do the make move and make move so the make move as we said is just these values here and so I can just put them here which is a append V and then we need to determine the counter because we used one value and then we need to call the BACtrack function which is this whole function here so this is just backtrack with the partial solution we have so far and going to the next index which is K plus 1 and then we need to only and do or and make the move which was just pop the element that we lost add it to a and then increment the counter to undo this step here so that would be counter V plus 1 and that's pretty much it at the end we can just return this output here so you can see we have we applied the template we just changed it the way we are doing construct candidate before we are just checking if the value is already in the punctual solution but now we are checking the counter because we have duplicates and still applying the same template ok so that's it for this explanation I'm going to code this up now and see if it passes the test cases okay so now let's cut this solution so first checking if it's absolutely first let's just find the BACtrack function that will pass through the partial solution and the index of where we are and then we'll call that here and the partial solution starts out empty the index ourselves zero and we need the output or the resolve list will put all permutations and then we will need to return that and so the backup function first check if it's a solution and that means basically that this is equal to the length of NIMS that means we have a solution we have a for-profit ation and solution we have a for-profit ation and solution we have a for-profit ation and so we can process it and processing the solution is just adding the partial solution which by now complete because K is equal to the length here so does a otherwise we need to construct the candidates and so we need the counter keep track of how many we have still not used in the permutation and so the function that does what I said which was the for each element putting each element as the key and the number of its occurrence as values in Python there is a method that does that which is called just counter so we are going to put that to import that from collections and then we can just use it here counter of Nimes and now you can just say if this is if the counter is still not zero which means there are still values we can pick then we are going to make them move which is attending to the partial solution first and then decreasing the counter occurrence here and then say backtrack to the next step which is K plus 1 and after that we need to unmake new which means pop and counter see please buy one and then that's pretty much it the only thing we need to be careful of here is to copy it because otherwise it will get modified again and we will modify all the previous ones that we added to the list and that's pretty much it so much London's ok so this looks good another thing we can do here is we don't actually need this K value because we already have a list here that has the value so we can just check the length of a and instead here we don't need this case because we have a where the last index is just K and we don't need this K yeah so let's just run this it's a bit okay so this passes and yeah so basically this is the East solution top method this is the process solution this is constructing the candidates this is making them move and this is backtracking and this is am making the move and that's pretty much it I will try to solve this with another method next okay so let's implement that be a fast solution for this problem and so first we have the initial lover Lucia's empty a pipe and then I'll go through each element and determine the permutations that included basically so this is basically the permutations at position K which was called or called I here and so this is as follows maybe okay so that this becomes clear so this is okay pretty much so we are going to generate permutations of position K and to do that we are going to so these are the permutations at local PK some URIs is actually let me just call it PK for this to be super cleaner so these are the permutation at the previa and the current level which is K and then we are going to take all the permutations in the previous level which are K minus 1 which are currently in rests and then we are going to go through each possible position right and insert in it which is here we want to stop one way encountered the element basically because if the elements are identical wanna accept two just before and not after it because itself before and after it will end up with 1 and 1 right and so what I'm going to do here is to do that it's just basically this here will just say stop when you encounter the element don't add at that position and so take the index at na plus 1 and the reason we are adding this here is because if there is no appearance of the number we don't want to have this index return minus 1 and have this be 0 and then basically not an insertable not itself at any position because range will stop if its range 0 to stop at minus 1 well basically two and start Moines right it will start from zero but now I get to zero because it starts at zero so we want to add this one so at least if the element doesn't exist in the previous level we can insert inserted like at least because I'll say with empty if we have start with the poly one it's not in this previous red light because it's empty and so if we do if we don't do this ad now it will be minus one plus one and we want enter given into this slope right and so this protect us from the duplicate case and does work with the case where it's not a duplicate and then we will just add to the new set of permutations at this local which are just inserting at position J which means just doing something like this before J the list before J then add the number and then continue the list after j @j and then continue the list after j @j and then continue the list after j @j basically and then PK becomes so PK minus 1 because they can't be k because we are going to increment K right and then we haven't returned right so it's not pretty stress it's this one previous reputation yep so basically this is reception because that's what we wanna return at the end and became a swan will go through all those in pique mimes want permutations this is whether it's permutation P K minus 1 is the tile list and rest and then each permutation of that previous level is each element of the each list in the list of lists address out here okay so this versus so to understand this a lot better I think you please watch the video and description for the problem 46 permutations without duplicates and then watch it is after that I think that would be more clear and thanks for watching and see you next time
|
Permutations II
|
permutations-ii
|
Given a collection of numbers, `nums`, that might contain duplicates, return _all possible unique permutations **in any order**._
**Example 1:**
**Input:** nums = \[1,1,2\]
**Output:**
\[\[1,1,2\],
\[1,2,1\],
\[2,1,1\]\]
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\]
**Constraints:**
* `1 <= nums.length <= 8`
* `-10 <= nums[i] <= 10`
| null |
Array,Backtracking
|
Medium
|
31,46,267,1038
|
1,743 |
hi friends uh welcome to followup in this video we are going to look at problem 1743 restall the array from adjacent pairs on our purpose for this video is to explain the concept degree in graph Theory so here this concept is associated with undirected graph so our plan will be the following first we're going to digest the problem requirements and then we explain the logic and finally we share the code so first the problem digest so here we are given that integer AR cols that consists of n unique elements but we have forgotten it so we do remember every pair of adjacent elements in nums so our goal is to recover the array right so we are given a two the integer array called adjacent pairs of sides n minus one where each adjacent pair I equals U VI indicates that the elements UI and VI are adjacent in nums so actually if you notice that there are n elements so we can regard them as n Nos and we have n minus one edes so this is actually a tree right so it's guaranteed that every adjacent pair of elements um will exist in the um 2D array so the pairs can appear in any order so we want to return the original AR nums if there are multiple Solutions return any of them so for this example the first impression is that um the return is not unique for example um we can return 1 2 3 4 then we can also return 4 3 2 1 at least because the graph actually is a undirected graph right so if you look at example two so it provides another um example so here is one way and then we can reverse it to get another way right so in example three so this very simple just have two elements just return the two elements as a list so here actually n is at least two right because we have at least one Edge right so here the number nodes can be as large uh as 10^ 5 so there exists some large uh as 10^ 5 so there exists some large uh as 10^ 5 so there exists some nums that has adjacent pair as its um pairs right so basically it's that the solution must exist right there exist at least one solution if it exist at least uh one due to the Assumption n is greater than or equal to two so it actually exist at least two right because you can consider the reverse so that's the problem digest so our goal is to explain the concept degree so here we are talking about an undirected graph so in a undirected graph that's called G with uh vertices wi and EDG is e the degree of a node V is the number of directed edges connecting with v so in this example actually the nodes of degree one can be used as the start of the array or if we want to use traversal algorithm so this um the note uh with degree one can be used as a SCE of the traversal in the coding but you know due to the Assumption of this problem so actually we have two nodes of degree one so for example in this one and four both have degree one so similar you can look at -2 and-3 in example two so with look at -2 and-3 in example two so with look at -2 and-3 in example two so with that side we are going to um look at the coding so our plan is the following right so we build a tree or the graph so here the graph actually is tree so we record the degrees of the noes and then we find van node uh with degree equals one then use it as source for see depths for the traversal will be sufficient for this problem because it's tree right so that's we found the one with degree one so we can regard that as the root of the tree or as the source of the graph anyway so the different wording then um actually the implementation of the coding is rather straightforward so for commus I changed the fun the Argent name to a so a is corresponding adjacent pairs right so first step we are going to do is build the graph or more precisely in this uh problem the tree so this Syle actually I'm going to use um the colle default dictionary right so it's a let's call tree right say collections default dictionary so uh I'm going to use a set as a neers and also I want to have a degree so degree I'm going to use collections default dictionary so I will put a function or just a int right then I'm going to Traverse this a so for u v in a right so I'm going to do tree um U so V is in the neighbor I'm going to add V so similarly Tre of V I'm going to add U so in both case so because there's an edge connecting u and v so we're going to do um degree of V is increment by one so similarly degree of um U is incremented by one right so then uh we have the tree so we can print out this tree uh treat or degree let's see both print um the degree let's do a test so we're going we're using this example right you can see two has a neighbor 13 and one has just neighb two and three has neighor two four right this four has neor three so you can see one has degree one that's here and two has degree two three has degree two and four has degree one right so once we're done here so basically you can find one node with degree one right so this actually very simple right so we just need to use a traversal right so here uh what we want to do is let's see uh the sauce I'm going to use this the sauce so let's say negative one right because uh here I guess um anyway I don't care so the num length is M so let's change it to none right so for um say node and degree in degree items right so once I found a degree that is um one I just break right if degree equals 1 so I'm going to set Source equals this degree uh equal this node and then just the break right so this is the that's we find we just a stop so you can print out the source if you like so for this Example The Source can be one or four right here we print out one so then let's do the traversal I'm not going to write hyper function because it's so simple this problem so do and depth first based traversal here actually you can also do um uh bread first based s so here I'm going to use a Visage as a set to monitor or to avoid um repetition the reason is that we are dealing with a undirected graph so then the stack I'm going to uh to initialize is this right the source and then it's a basic Loop where s so we're going to have the note is going to be S pop left uh pop just a pop from the TA and then um let me also initialize a result right so this is the result array right so we have this if node not in visited so I can do this visit it because we are going to visit this node let's first do this so visited add this note right meanwhile I'm going to append this node to the list to return right after this we are going to check the neighbor of this node this is very simple for neighbor in tree um Noe then I just want to check if neighbor not inv visited so I'm going to append this neighbor to the stack um neighbor right so after WS we just need to return the state of this result variable so notice that here I CH I do a check here and also I do a check here there are some redundency but if you write like this way it will make your code very safe so this is one solution format to this problem so we can do a test yeah it passes um one example now let's look at generic case yeah it passes all the generic cases so I guess that's basically about it for this uh this video so here uh we explained a concept called degree for undirected graph right then we solve this problem by building the graph and tree and record the degrees of the nodes and then we found one node with degree one and then we do a traversal to get the original uh array or list so that's about it for this video so actually we have a uh Channel and we have a large number of playlist within that channel it contains different types of problems um using different techniques so you're welcome to follow up if you want to support this channel so you can uh just give us thumb up or share with your friends so with that said thank you
|
Restore the Array From Adjacent Pairs
|
count-substrings-that-differ-by-one-character
|
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`.
You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` are adjacent in `nums`.
It is guaranteed that every adjacent pair of elements `nums[i]` and `nums[i+1]` will exist in `adjacentPairs`, either as `[nums[i], nums[i+1]]` or `[nums[i+1], nums[i]]`. The pairs can appear **in any order**.
Return _the original array_ `nums`_. If there are multiple solutions, return **any of them**_.
**Example 1:**
**Input:** adjacentPairs = \[\[2,1\],\[3,4\],\[3,2\]\]
**Output:** \[1,2,3,4\]
**Explanation:** This array has all its adjacent pairs in adjacentPairs.
Notice that adjacentPairs\[i\] may not be in left-to-right order.
**Example 2:**
**Input:** adjacentPairs = \[\[4,-2\],\[1,4\],\[-3,1\]\]
**Output:** \[-2,4,1,-3\]
**Explanation:** There can be negative numbers.
Another solution is \[-3,1,4,-2\], which would also be accepted.
**Example 3:**
**Input:** adjacentPairs = \[\[100000,-100000\]\]
**Output:** \[100000,-100000\]
**Constraints:**
* `nums.length == n`
* `adjacentPairs.length == n - 1`
* `adjacentPairs[i].length == 2`
* `2 <= n <= 105`
* `-105 <= nums[i], ui, vi <= 105`
* There exists some `nums` that has `adjacentPairs` as its pairs.
|
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
|
Hash Table,String,Dynamic Programming
|
Medium
|
2256
|
253 |
hi everyone today's question is meeting rooms 2. this is a very popular question amongst companies like amazon bloomberg facebook google apple microsoft and so on right now so the question says given an area of meeting time intervals consisting of start and end times i'll find the minimum number of conference rooms required that means that we are given a particular set of intervals for which is to start in the end time of each meeting and we have to find out that if all of these meetings were to happen how many conference rooms which is the minimum will be required to conduct these meetings it means that if there are two meetings which are occurring at the same time we need two meeting rooms at that particular point in time for them to happen so we have to find the minimum number of conference rooms that's required for all the intervals okay so for example here 0 30 5 comma 10 and 15 comma 20 as we can see that 5 comma 10 and 15 comma 20 are pretty much non-intersecting that is they can be non-intersecting that is they can be non-intersecting that is they can be held in the same meeting room but zero comma 30 is a meeting that is going uh basically having an overlap with in this case both of these meetings so this will need an entirely separate meeting room for it to occur so that's why we need total two meeting rooms here and the second example has two intervals which are completely non-overlapping and that's why we need non-overlapping and that's why we need non-overlapping and that's why we need just one meeting room for them to happen okay i hope the question is clear so as mentioned in my previous video about um meeting rooms we do have one thing to keep in mind whenever there is a question about intervals that is the input sorted if not you can either sort it on start time or the end time some questions work well with both of them some questions need a specific start or the end time approach to be able to solve them so always consider all these options whenever looking at any interval problem the next thing to remember here for example in this case is that even after for example you sorted on the start time you would always need to know which meeting ended the very first so if there are five meetings that have already happened till now which meeting ended the very first because there is a probability for example in this case uh the earliest meeting that's starting is at zero but it ends at 30 whereas we have another meeting that starts at five which is later than 0 but ends earlier which is 10. so when we are considering 15 comma 20 and trying to find out if this needs a new meeting room or not we should not compare it with the end time of 0 comma 30 rather we should be able to compare it with the end time of 5 comma 10 and that will tell us that there is one meeting room that is occupied but it will be freed by the time this one starts so i do not want to add a new meeting room to my answer right okay so uh in order to be able to do that we also need to keep the processed intervals sorted in the order of the ending time of the interval okay so first of all we will sort this entire input on the start time of the intervals and then in order to have these uh processed elements sorted on their end time we will use a priority queue because that's what is uh the best use case for a priority queue that is a heap to keep whatever elements it has at hand sorted in a specific order that is specified so we can use priority queue there and then whenever we are bringing in a new interval we compare it with the meeting that is ending the first if there is no intersection we can just reuse that room otherwise we'll need a new meeting room and we just add that interval to the priority queue so it's going to be very simple once the implementation is done i hope you understand the approach so let's get started some base conditions first okay so if the intervals equals requires to null or intervals dot length equals to zero we need no meeting rules so we return zero okay the next is to quickly have this sorted intervals sorted on okay so let's have a new comparator that will take integer area objects yeah and we will say sorry compared okay b and just sort this on the starting time so just return a of zero minus b of zero makes sense okay now we also need a priority queue yeah uh and in this we would again need to override the comparator which is obviously of the same type okay now we have public end and b yeah and here we want to return uh basically the priority queue should have at the top the meeting room that's ending the very first uh sorry the meeting that's ending the very first so we make use of the end time to keep this sorted okay fine so we have the priority queue and we have the intervals sorted to priority queue we just add the very first one that is intervals of zero okay and now we start from i equals to one yeah so now let's get the current which is intervals of i okay and this is an array sorry yeah and the previous one we can just pull so previous represents the meeting room that ends the very uh the meeting that ends the earliest right so yeah okay now if the current starting time is less than right is less than previous end time then we know that there is an intersection so if the current meeting is starting um yeah is starting at a time earlier than the time at which the previous meeting ended okay then there is an intersection and we can just uh add both of them to the priority queue because we cannot create an intersection yeah because we would need like two meeting rooms for both of them so we just add otherwise yeah so now otherwise i can't reuse the meeting room which is being used by the meeting previous okay so what i need to do is that i just need to say that previous's end time should be equal to current send time because now that meeting room would be occupied for this current meeting till it ends so we just update that and we again just push this one into the priority queue yeah okay so for example for 5 comma 10 and 15 comma 20 we would see that 15 is less than is greater than 10 right so we will just update this intervals n time to 20 and be done with that all right and we just have to at the end return the size of the priority queue which represents the number of meeting rooms required to conduct all these meetings okay let's see if that works that does work um the time complexity for the solution uh if just considering the priority q part would be different but since we anyways have to sort the entire intervals array this will become n log n and because we're using a priority q to store all the intervals the space complexity also becomes o of n so i hope you like this solution and you find this helpful if you do please like share and subscribe keep going and take care guys
|
Meeting Rooms II
|
meeting-rooms-ii
|
Given an array of meeting time intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of conference rooms required_.
**Example 1:**
**Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\]
**Output:** 2
**Example 2:**
**Input:** intervals = \[\[7,10\],\[2,4\]\]
**Output:** 1
**Constraints:**
* `1 <= intervals.length <= 104`
* `0 <= starti < endi <= 106`
|
Think about how we would approach this problem in a very simplistic way. We will allocate rooms to meetings that occur earlier in the day v/s the ones that occur later on, right? If you've figured out that we have to sort the meetings by their start time, the next thing to think about is how do we do the allocation? There are two scenarios possible here for any meeting. Either there is no meeting room available and a new one has to be allocated, or a meeting room has freed up and this meeting can take place there. An important thing to note is that we don't really care which room gets freed up while allocating a room for the current meeting. As long as a room is free, our job is done. We already know the rooms we have allocated till now and we also know when are they due to get free because of the end times of the meetings going on in those rooms. We can simply check the room which is due to get vacated the earliest amongst all the allocated rooms. Following up on the previous hint, we can make use of a min-heap to store the end times of the meetings in various rooms. So, every time we want to check if any room is free or not, simply check the topmost element of the min heap as that would be the room that would get free the earliest out of all the other rooms currently occupied.
If the room we extracted from the top of the min heap isn't free, then no other room is. So, we can save time here and simply allocate a new room.
|
Array,Two Pointers,Greedy,Sorting,Heap (Priority Queue)
|
Medium
|
56,252,452,1184
|
1,356 |
Hello everyone today trusting gift pistachio problem is short bike twitter account in that we were given a challenge and this gooseberry has to be shifted in that it has to be started because whatever number is there in it whose mind is video Most of all, you have to keep that first, you have to talk to the younger brothers in advance and if the admit card of any two number check is issued to both of them, then think about these things and see that first of all, you have to keep this thing first, so in this case, take 1427 first is now four but see how many of these are tweets cent means who is his nephew how many marks got in the project then if how to see his final result then this compound like how many times is there one in it Papa used to take SIM mercury compound like two in Bar in the early to bed scene, first of all we have to keep the one who has tweeted more than half, hence the schedule time of both of them goes according to this tradition. Okay, so he is on the first number. Now we have reversed it, the one who is first is second. And in the past, who is the first to have such problems in physics, you have kept the famous one, which one has come first in 151, who has come first, full flower, ex-serviceman, this is our request, flower, ex-serviceman, this is our request, flower, ex-serviceman, this is our request, Sir, it is okay, the question was asked that from time to time constipation can happen. Add Login and Development Ko aap man dila, this is some express news, we perform the same element, it is okay to add, this is time wise, let's start bike saving account, it is okay, this is a non- start bike saving account, it is okay, this is a non- start bike saving account, it is okay, this is a non- option, which is exam clear, is it okay here and what is it here? We are turning all of them on and while adding a little, it is okay to set us up with the Gurjars, we have to source it, here we have a computer, Home Ministry, Custom Duty, if it is okay for that, then we will give new information, the chances are limited, okay, we are doing this. A year ago, on whose message did I feel scared in the room, where people look carefully, comment on this may be a little long, it is of the computer, but I will request them maturely that after every time, Vishal will write the previous one and at a slightly longer level. - There will never be any confusion and also the level. - There will never be any confusion and also the level. - There will never be any confusion and also the computer of the account is a little small but like that, call me tomorrow as part of the committee, how can we do something like this, we can add to it, okay, if you invest in this way, only then you will get the money. The problem ca n't be there, swearing, okay, so here first of all cast and class, this traditional anything cover, improvement, less pressure, you can just use it so fast, complete your mission, but it is so much and it is so thick, so much and just what do you need that it is so much You have to write the function, you have to crush the comeback, what you have to do is to side it, okay, so what is the first object here, this inch, so here we have to type what means ₹ 1 appreciation shot that the ₹ 1 appreciation shot that the ₹ 1 appreciation shot that the statement will come okay which What do we have to take towards the run, this is the welcome of Tuesday, you are here, this is the investment in the function at work, captain, we two * say investment in the function at work, captain, we two * say investment in the function at work, captain, we two * say that it is tighter than these, so find it from the data, meaning, we will give two numbers, okay, this is you money. By drowning which we have two numbers and this has to be placed first, it is clear that looking at this, the quadratic will ask the chain to remain at number two and you clear your position. For the state account, it is okay, so this one, we have Bill account is amazing that without impure, our life difference increases, where will we grate, how many beats is beta testing, so like in English, we will add fennel, here it has been done, by being here, it is okay for the company, this is fine between us both, friend, now you this See, if you write in the descending order, on this letter too, rate minus one, this little black, here Java code will extract it and what to do is, now apart from Sara, make any wall - and what to do is, now apart from Sara, make any wall - and what to do is, now apart from Sara, make any wall - 140 character and cry. Okay, you can do this workshop on this. Let's say that if it is too much, submit - mark it was too small, submit - mark it was too small, submit - mark it was too small, return it, Tamil Nadu, keep in mind that whenever you have to do due to south, you are here - man and pick up the phone to this person, you are here - man and pick up the phone to this person, you are here - man and pick up the phone to this person, if you are looking for any Indian team. Send me all the best thing, now you don't have to do anything to shoot the CNG model, you just have to call me here and here - call me here and here - call me here and here - is it or are there knives, now this can also happen, sometimes we see our How can anyone say like this, first of all, its special, it is felt, so in this orbit, its and in the court, in this matter, we do not have any data structure, happy birthday, the thing that is pesticide, the winning team is the match winner and nutrition and first of all You calm down, okay, on which ascending order, the smallest of the fun came first and why mother used to get that from Dhow, still ₹ 300, by the way, used to get that from Dhow, still ₹ 300, by the way, used to get that from Dhow, still ₹ 300, by the way, send a message, if you feel like this, then you do not have to do anything else, you are like this. Tell me this, so keep this letter in the settings, then you can next it here so that while cutting it like this, it returns because Hanuman ji is equal to you, now again you take this front piece of yours here again, this is now for this. Just before this I had written that now when the record was completely standing, basically write like A, then you have to compare further, then it came to me that one has to do better, then one Samsung like here, which gives us this, you and there. Will you take this for me, now if you find the world difficult, tell me this video has been made from dry food, you will get subsidy, I had to do shopping in it, this is all I have, the amendment was not coming, Saif is penetrating into the mind, sitting and doing nothing, I got to complete it. Will keep it all right, all this will cost you so much, comment below, I will get it clear to you, do share the submit button on any name, thank you sir.
|
Sort Integers by The Number of 1 Bits
|
minimum-number-of-moves-to-make-palindrome
|
You are given an integer array `arr`. Sort the integers in the array in ascending order by the number of `1`'s in their binary representation and in case of two or more integers have the same number of `1`'s you have to sort them in ascending order.
Return _the array after sorting it_.
**Example 1:**
**Input:** arr = \[0,1,2,3,4,5,6,7,8\]
**Output:** \[0,1,2,4,8,3,5,6,7\]
**Explantion:** \[0\] is the only integer with 0 bits.
\[1,2,4,8\] all have 1 bit.
\[3,5,6\] have 2 bits.
\[7\] has 3 bits.
The sorted array by bits is \[0,1,2,4,8,3,5,6,7\]
**Example 2:**
**Input:** arr = \[1024,512,256,128,64,32,16,8,4,2,1\]
**Output:** \[1,2,4,8,16,32,64,128,256,512,1024\]
**Explantion:** All integers have 1 bit in the binary representation, you should just sort them in ascending order.
**Constraints:**
* `1 <= arr.length <= 500`
* `0 <= arr[i] <= 104`
|
Consider a greedy strategy. Let’s start by making the leftmost and rightmost characters match with some number of swaps. If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively.
|
Two Pointers,String,Greedy,Binary Indexed Tree
|
Hard
|
1437
|
529 |
hey everybody this is Larry I hit the like button hit the subscribe button let me know how you're doing this farm I'm gonna stop alive right about now Boyd's okay cool 5:29 minesweeper let's Boyd's okay cool 5:29 minesweeper let's Boyd's okay cool 5:29 minesweeper let's play the minesweeper game and it is a big computer link you're given the 2d charm matrix representing the Gameboy M represent an unrevealed mind ye represent an unrevealed empty square and be rewritten reviewed blank squared that has no adjacent minds Richard 1 to 8 represents how many minds are Jason - represents how many minds are Jason - represents how many minds are Jason - this will be R square and finally X representative revealed mine now given the next quick position amongst all unregular square we turn the board after we've earned this position according to the following rules if a mine M is revealed then the game is over change to X if an empty square years is with no adjacent mine is revealed then change it to reveal blank and always adjacent unreviewed square should be reviewed recursively I'm an empty square with at least one adjacent - we would then change it to adjacent - we would then change it to adjacent - we would then change it to the digit 1 to 8 and that's it we turn the board but no more squares okay so I feel like I actually played a lot of wide sweeper maybe not anymore but when I was younger because it came free with Microsoft Windows right so I think I get the rule so we would double check ok so where are we clicking it's a birthday okay so input will tell you where to click and then these are all empty and in the beginning you click on here and then it to do and then we real - X but then it to do and then we real - X but then it to do and then we real - X but you don't maybe or that one ok so basically the idea behind this one will be either deaf or search or breadth first search but just processing them one at a time you for exam you don't need to reveal all and we do my up yeah the game is over we don't have to remove it ok fine input do we have to be real that the game is over I don't think so ok it's 50 goddamn probably a stage when the game is over some mites have been reviewed okay well let's just do it I mean I think we and I understand how Mine Sweeper works but of course that's one of the tricky part about an interview sometimes is that they give you a problem that relates to something that people know about but it is different in some weird way and then everyone is trying to wrap around you know they focus on a point that is weird about it so then I would just sell what I believe is to minesweeper problem and okay so you begin with years and Rubio beers reviewed okay so basic you only reviewed a mine if you click on it so I think that part is straight for it so that's just to if okay let's also just change to or C is equal to quick all right how many clicks do we get it's just one way because if we have a list of int okay I guess that's fine I just wasn't sure okay if the board of RC and actually that's set this up gross is equal to length of the board columns is equal to length of port of 0 theta okay so they do force that is between 1 to 50 so I don't have to do any bound checking if they have warm and down will help you a little bit sad but yeah but if this is you go to the mine then we can and we can just return to port after we shift that to know you are sad and it's a list of a string okay so I can do this that's what I'm trying to do and it's still a test case where this is true let's set up the test cases a little bit so we could have a little bit of a resemblance of TTT okay so the first one is wrong which we knew because we didn't write any code but a second one is right so at least we understand the prom little bit better as well okay so that's the base case or an edge case maybe you have an empty so the only other thing is give this yeah if so we do this recursively but if it is not a blank square we just change it to the number of adjacent squares okay let's do this that's just right and you could do this recursively or with a platform for social preferences you century similar to flood fill out type algorithms with or island finding or someone like died whether you knew basically if you get a square with no minds no adjacent minds then just keep on recursively looking at his neighbor so that's basically what we're gonna do here and before that just to look at and adjacent I just want to make sure that the directions out of four directions or eight directions and in this case that's fine give me a second and then this to tag oh yeah it's diagnosed I usually write this in a different way so I think I'm just a little bit bad about it yeah so now we can do the recursion that should do it I got that first search and then we just have a row and just call it a row in a column that is not this one but we'll record this one but yeah if board of our C okay so now that's just to account for each one so what is he again other years just an empty square but then we want to change it from okay so we only want to yeah so we only want to process this if disease at you so okay we turn but let's say that it is a Yi then we just go for all the directions to look at it let's say TR t see the new our new see and now we just have to make sure that it is within bounds and they say we count the number of if port RC is equal to mine we in comment if it is not then what notation this is kind of me a bit did I click something I think I clicked on did I click on one or submit I don't know but it seems like I may have kind of wrong answer some kind of hotkey thing okay I went the T pocket maybe I don't need can't get rid of this okay this is it covered up to thinking but oh yeah so now you look at the count if count is greater than zero then we're done right oh and C is equal to not the string of cow and we know that there's a single teacher so when we don't have to do any crazy math then we return otherwise we set it to zero or is it civil plank oops Frank and then we recursively look at the neighbors again so we do the same thing here yeah then we could just to your purse you know and see and every and this will only trigger if it is a nickel a nun in empty space and ye space so that should be good and then now we do it on our input and then we return port a wrong answer hmm maybe I didn't understand this one yeah but that is the first one okay this is really hard to read actually because I it's still a way to make this bigger can't drag and make this longer but okay so my output is that there's a lot of use and one B hmm so I'm just not be cursing quite right that's okay and in the second case I know the second case is still okay it's just the first case basically expects us to click on all these other ones but I do not click on all the other ones I'm just checking double-checking the typos right okay double-checking the typos right okay double-checking the typos right okay let's just do a quick debugging I'm a little bit confused for that let's take a look okay so it definitely doesn't seem like it did the recursion so the distaff really tries to do it but it doesn't go through here all right I'm just being an idiot that is not this it should be rows and it should be columns okay silly mistakes okay still the wrong answer but hopefully slightly better what is the doubter oh did I muck this up oh yeah I checked the wrong thing so that's fine a lot of typos on this farm for me but yeah okay that looks good so let's submit it cool oh yeah so that's just basic depth of search even though I had numerous implementation typos but that's where yeah that's why we're practicing and when you practice you kind of you yeah you kind of I don't know just get a little bit less yeah more familiar with your coding and then figure it out so this is just step for search and you can show that you so what is the one time complexity right so the first time complex is that you look at each cell once and for each input for this to this input you do at most of all of one amount of work there's there is a phone up here but it always does at most a dish up you know operations or a dish time some constants if you want to point it that way and also all of a dash here so oh so it's gonna be linear time because we look at each cell and most once for a given click so yeah and in terms of space we depend on how you want to put it we actually just used to input bullet and then updating it so we don't use any extra space but if you want to be strict we do then your space and that linear being by the way is those x columns because linear is doing the size of the input and the input is n times M or rows times columns not just you know so it's not quadratic in that sense but um yeah but that's what I have for this problem that seems crazy straight for it except for that I implementations always tricky that's why ya always have to keep a job always keep on getting it ready I think this I actually think this is a relatively common maybe not common but I know people always want to ask this as an interview question for whatever reason so definitely practice this and for interviews and even if you might not get to sit directly these kind of flood-fill to sit directly these kind of flood-fill to sit directly these kind of flood-fill algorithms or I'll be cursive type things with def first search will they come up all the time on interviews so if not this one is something similar especially like I didn't finding or something like that or a flood fell yeah for competitive deaf research it happens all the time so you can't you just got to know it but yeah but that's all I have for this problem so
|
Minesweeper
|
minesweeper
|
Let's play the minesweeper game ([Wikipedia](https://en.wikipedia.org/wiki/Minesweeper_(video_game)), [online game](http://minesweeperonline.com))!
You are given an `m x n` char matrix `board` representing the game board where:
* `'M'` represents an unrevealed mine,
* `'E'` represents an unrevealed empty square,
* `'B'` represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),
* digit (`'1'` to `'8'`) represents how many mines are adjacent to this revealed square, and
* `'X'` represents a revealed mine.
You are also given an integer array `click` where `click = [clickr, clickc]` represents the next click position among all the unrevealed squares (`'M'` or `'E'`).
Return _the board after revealing this position according to the following rules_:
1. If a mine `'M'` is revealed, then the game is over. You should change it to `'X'`.
2. If an empty square `'E'` with no adjacent mines is revealed, then change it to a revealed blank `'B'` and all of its adjacent unrevealed squares should be revealed recursively.
3. If an empty square `'E'` with at least one adjacent mine is revealed, then change it to a digit (`'1'` to `'8'`) representing the number of adjacent mines.
4. Return the board when no more squares will be revealed.
**Example 1:**
**Input:** board = \[\[ "E ", "E ", "E ", "E ", "E "\],\[ "E ", "E ", "M ", "E ", "E "\],\[ "E ", "E ", "E ", "E ", "E "\],\[ "E ", "E ", "E ", "E ", "E "\]\], click = \[3,0\]
**Output:** \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "M ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\]
**Example 2:**
**Input:** board = \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "M ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\], click = \[1,2\]
**Output:** \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "X ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 50`
* `board[i][j]` is either `'M'`, `'E'`, `'B'`, or a digit from `'1'` to `'8'`.
* `click.length == 2`
* `0 <= clickr < m`
* `0 <= clickc < n`
* `board[clickr][clickc]` is either `'M'` or `'E'`.
| null |
Array,Depth-First Search,Breadth-First Search,Matrix
|
Medium
|
2206
|
939 |
hey what's up guys chung here again so this time i want to talk about this lead called the problem number 939 minimum area rectangle you know this is one of those like uh you can call it either math or g geography problem you know since we haven't really talked about this kind of problem before and i feel like a it's a good time to discuss to show you guys what's what are some common approach for this kind of uh geometry problem so you know with those kind of geometry problem is you already give you're usually given like a set of points with that with the coordinates x and y and then it asks you to determine like some areas or like how the numbers of the rectangles you this these points can conform right and in this case it asks you to find the minimum area of the rectangle formed from this point okay so you know in order to form like oh by the way so this side is parallel to the x and the y axis which means you can only form like a rectangle uh parallel with x and y axis something like this okay right something like this those four points and there is also like a minimum area rectangle two problem in that problem you know it's the same question but so that one's like it's not only uh parallel so you can have like a rotated triangle not triangle the rectangle yeah not triangle you can have a rotated like rectangle in that problem and i think i will be i'll be uploading that videos maybe that w maybe tomorrow but today uh let's only let's focus on this one here and i think in my opinion this one is a bit me here a bit easier than the other one because this one is only it's limited so the constraint says you can only have a vertical or horizontal line here okay so first things first in order to form to find the minimum area of rectangle of the rectangle we have to find all the rectangles that can be formed with all the points that's the first step okay um so i think there are like a few ways where you can do it but today i think i'm gonna uh show you guys two ways of doing that um i think the first way is like it's kind of a brutal force you know basically let's see um the first way is like let's say for example you have two points let's say you have two points here okay and you have two points and uh with these two points you have a let's say this is x one and y one okay and this one is like x two y two okay so you have two points here and since it's all the edges right all the side of the rectangle are they're all like parallel to they're either vertical or horizontal so with those two points you we can already assuming the other two points here it's easy to find it so find that right basically this point will be a x one y 2 right and this at this point it will be x 2 y 1 right so the first ways we just loop through the entire we just fix two nodes first okay we fix two nodes first and then we will be looking for the other two nodes the other two points if we have find those two points right then we know okay we have already confirmed we can form like a rectangle and then we just calculate the area of the rectangle and then we just keep updating our answer okay pretty straightforward right and yeah but there is a little bit trick here to find how can we fix those two points right i mean a very naive ways we just loop through each uh each point right basically we find all the combinations and then we'll try to find the uh the other two points right in uh if the other two points exist in the uh in the current uh in odd in all the inputs but that will come a little bit slower especially when i try to use that approach with python it gives me a tle i don't know why is that because the length of this point is like only 500 so because that the time complexity for that is it's going to be a uh basically it's going to be a 250 000 i'm not sure why it's uh it's tle so i mean so a basic because every time we're like basically looping through uh looking through everything right in uh for to the point to find the other two one the other two uh the other two points and one of the improvements we can make here is we uh you know we keep like a scene set here okay so and every time uh we also loop through the notes here every time when we have a when we finish looping through the this points here we add that to the scene node here and every time when we calculate the area we're when we're looking for the other two points we only look for the scene sets okay we're not looking for the entire points here the entire point the entire array here so it's this one so uh we are actually cutting the uh the loop the inner loop like to uh to a like to a smaller set right okay so okay let me try to code these things here i'm not sure if you guys uh understand my approach basically we're trying to uh to fix two points first and then we use those two points to look for the other two points okay so i'm gonna have a scene set here and uh of course we need the answer right since we are we since we are looking for the minimum value i'm going to define this as a maximum value and then so we're going to have a p1 right the p1 and x1 y1 okay in the points okay and then for the second point right for the second points we for the second point we're only getting the second point from the scene set right it's y x2 in scene so and then with those two points right we can look for the three the third and fourth one which is the uh the so the third one is x y and y two in scene and uh x two y one okay it's also in scene if that's that how if that's the case we know okay we have already find the area here right it's going to be a find the rectangle so it's going to be the x1 minus x2 we need the absolute value right because the area is always like positive right y1 minus y y2 and then we just update the answer here minimum answer dot area okay and then we just add this we just add the uh the current node current point to the same stat here in the end we simply return the answer here we return the answer if the answer is smaller than the system because it's possible we couldn't even find no single uh one just one rectangle in that case we need to return zero okay i think let's try to run this one first submeat yeah cool so this one it's so it passed and i think uh maybe some of you may have a question like the uh what if the uh you know since we're like fixing two uh we are actually we are assuming those two points the fixed two points are like the point one and point three basically right because we're using those two what if the uh what if those two points are horizontal aligned horizontally or vertically what's gonna happen let's say what if the p1 sorry if the p1 is let me draw these things here what if py is this here and the p2 is it's here what if the p1 and p2 there are on the same line here right um i mean if that's the case right so this is the x one and y1 this is x2 and y2 right so in this case the uh so in this case the x1 minus y2 i mean will be the same as x1 uh y1 right so in this case the this thing this x1 y2 will not be it's not it will be it's going to be false okay because we uh we use this scene to verify that you know otherwise we'll be ha we will need to uh check if the area is greater than zero right then we uh then we update but in our case i mean since we have this check here because when the p1 and the p2 are on the same line right and uh the x1 and y2 they will be the same it will be the same value so and the which in this case has not been added to the scene that's why this thing is it's optional here okay this will just also work i mean okay so basically that's the first approach by uh by fixing two points and then with those two points we can start looking for the other two points okay yeah and this thing only works in the uh only works when the when all the other side are parallel to either x or y why is that because let's say we have these two nodes here okay sorry the two points here and let's say the um the rectangle can be rotated right so in this case with those two points fixed we cannot fix the other two points because the other two points can be anywhere as long as they have the same center let's say this is a point one and point three okay and this is the center point here i mean if the uh the if the uh i mean if the uh the if the rectangle can be rotated so we're going to have like a like infinite possible rectangles i mean as long as the uh basically these things can be rotated the let's say we have another one here the this is the first one right basically this is going to be the p2 and p4 right as long as the other two points can conform like a diagonal line that has the same centers i mean these things can either uh can basically can move right this can move here and right so this is also like a valid rectangle okay this is also a valid rectangle basically we will have indefinite possible rectangles if the rectangles can be rotated and actually that's how that's exactly how we are going to solve the solutions uh in the minimum area rectangle 2. but in this case since there's only with those two fixed points there are there's only one possible rectangles okay which is this one right that's why we only need to fix two points and then we will we can make we can be sure uh what the what's what are the other two points we're looking for and once we find those two points we know then we can calculate the answer the area and then update the answer okay cool so that's the first approach okay and okay another approach is this let's say we have a we have different dots here let's see dots here okay come on too big here i'm drawing some dots randomly here okay here right so i'm just drawing some dots randomly as you guys can see here you know another way of doing this you know and since the uh they are like uh all aligned with x either x or y axis no so to be able to form like uh a rectangle so the rectangle is like this right basically the uh so with what we need to know what we are looking for another way of looking for a rectangle is we just need to find a pair of the vertical line here okay same here right we need to find a pair of the vertical line that has the same start and end point okay so in this case that's uh so these two lines right so these two vertical lines they have the same start y one and white and y two right they have the same start and end point as long as we have those two pairs then we know the two vertical pairs and then we know okay those two pairs can form like a vertic a rectangle okay so and we'll be using that to find the rectangles by uh by saving all the other vertical lines basically all the vertical lines into a hash table and then we'll scan basically we'll scan the uh the lines the vertical lines from the from left to right okay so in order to do that we need to pre-process right basically we're going to have like a hash table the key is the x coordinates here and the value is going to be the list a list of the y coordinates basically we're going to store for each x how many what are the y coordinates on that on this x in this case we have two here and here's an another two and here right so that's how we are we're going to store all those y1 and y2 pair and we will be scanning those from left to right and every time when we have like uh when we're at this current uh the current uh y one and y two pair right and we'll be looking for if the previously one have any uh have has any us has any uh the same the previously lines have any if they have the same pairs and e and if they do and then we know okay we find that i find a rectangle and then we will be calculating the rectangle the area of the rectangle and keep scanning and another thing is that not only we need the hash table to store the uh other the y coordinates uh for each x we also need a second hash table to store the uh to store the last x axis for each of the uh for each of the white pairs so what why is that because for example here right let's say this is a one two three right and this is one two three four okay three one two four okay this is also two four and five this is also one and the three okay because let's say we start from this the first line here right and we have a y we have a vertical a line uh is one and the three okay and then when we are at the uh the vertical line 2 here right x2 here we have a 2 and the 4 and then we'll be looking for okay is this 2 and 4 exist in the previously uh in the pre previous like a hash table no it's not there so we just keep doing it okay and now we have this one we have one and three here okay so once we have one three we check okay so is have we seen uh have we ever seen a one and three before yes it's here and the value is one here and then with the current x3 we can calculate the area right and once we finish calculating this line here you know since the uh then we will be will need to update we'll need to update the uh the last x for the line 1 3 to the current x here so that when we meet the line a one uh meet the line one three again we know the last one is three here because there's no point to use this one anymore because since we are like sorting where because we sorted the uh those hash table by the uh by x but x axis so and x is always increasing right so there's no point for us to calculate the uh yes true that you know this will also be a bigger rectangle right but there's no point for us to calculate this area because we know we have a smaller one here right that's why we only keep the uh the latest x for the one and the three and we just keep scanning it okay yeah actually there's another like a problem you know if you guys are interested i think it asks you to find the same description but it asks you to find the numbers of the uh of the rectangles all uh that all these points can form okay so then can you if you guys want to solve that problem you know similar idea here basically you also need to store the uh basically store the uh the vertical lines here okay and every time when you see a different a new vertical line you know you uh i think probably you also need to sort that the vertical lines and every time when you see a and the vertical line with the same numbers basically you just add two numbers you just add the uh you keep adding the count of the existing count of the same vertical lines here so for example here you when you see this one right so at the beginning this one this thing is one so when you see this like a vertical line with the same one three you have a number one okay and then the second time you see the number uh you see a another one here right you need to add two here okay right basically one two and three if you see a third one here okay there's if there's another one three here you need to add three here okay that's how you count the number of the rectangles cool okay so enough talk okay let's try to code this these things here okay and all right okay i'm gonna come out this thing here uh so like i said oops uh first we're gonna need to pre-calculate the pre-calculate the pre-calculate the all the other y-coordinates on each x all the other y-coordinates on each x all the other y-coordinates on each x and how i'm gonna call it columns uh maybe column is not good name okay whatever columns you know default right dictionary list okay and then for x and y in points okay uh columns actually should be y coordinates yeah i think this name is more prop up more proper name x dot append y right that's how we initialize these things here and uh what's next uh yeah and then we need to sort these things from to from smallest to the biggest okay when you sort by the x that's why we're going to do a x uh in uh sorted right we inserted the uh the y core or d nates okay and so now we have a list of the we have a y we have y list okay in the y dot co or d nate dot x okay and we also want to sort uh this white list because um i mean we don't have to sort it just stats you know when we try to find that uh the list the lines right the vertical lines here we need a two we need to start end right i mean if we don't sort it we could end up having like y2 dot y1 right instead of the y y1 and y and y2 that's why we want to sort this uh this list okay so from the lowest to the highest so that we will make sure we're sure that the next second one is always the bigger one right second y is always the bigger y so um now we have the uh i and y one okay one in enumerate uh y list okay we find we have the first y here right now let's find the second y uh for j in range uh in range i okay so yeah and here the y2 is the uh so y list of j okay so now the y one is greater it's greater than y two okay so now we can see this uh basically if the oh yeah since we need to check if this is the same y one y two exists we also need that like another uh another hash table to stores to store the uh the vertical lines that we have seen so far okay it's going to be the what do you call line okay vertical lines how about this okay basically if the we can use either y1 or y2 as long as we follow the same sequence it's fine basically i'm using y1 y2 as a key so if this thing is in the vertical scene lines okay in the same lines here okay then actually here the key is the line value is the x coordinates or the next okay so uh if the if this one if this line has been seen before and then we can uh calculate the area here so here the area uh is gonna be the uh what's the area here so it's to be the current one so current x minus the uh the scene lines the previously lines area okay y1 y2 okay times what times uh y1 minus y2 we're not using the absolute value here because we know we're sure that now the y1 is greater than white than y2 okay and then we have this uh of course we need uh the answer here okay the answer is like system dot max size so here uh we have a answer equals to minimum okay alright answer dot area and okay yeah one last things every time when we find a lines here okay we'll be updating the lines because for the same lines we only need to record the latest x okay so here scene lines dots y one and y two equals to the current x okay yeah that should just work and here is the same return here i'm going to copy this from the previously result so this should just work okay submit cool yeah as you guys can see this one is it's a it's faster because even though you know this is like uh n squared solution but since there are like a lot of um since there are like a lot of like lines here right i mean the actually we are not looping through all other points here right because it's like a one uh 1.5 n square you know yeah but anyway i the idea is this right i mean uh i think that one thing you guys need to learn from one take away from this problem is that you know the first approach is kind of okay i think it's a you know it's not that hard to come up with i think it's the second one that you guys the second solution approach you guys really need to remember were try to understand it basically especially with this like parallel to x and y axis you know we to find uh rectangles all we need to do all we need to find is the uh a pair of the uh of the vertical lines okay as long as we have those the same pair of the vertical lines we know we have found a rectangle okay and that's exactly what we're doing here basically we are uh maintaining like a x uh the y coordinates for each x and then we sort okay we sort by the x and then for on each of the x axis uh we loop through all the possible vertical lines on the on this x and then we're for each of the line the vertical lines we have we're trying to see okay if we have a same pair seen before if there is then we know we find another vertical uh sorry we find another a rectangle we can just then calculate the area and then here uh we're always updating the this what the x coordinates for the first y1 and y and y2 because we are looking for the minimum one right so there's no point to store the previously x for this current for this x uh y1 and y2 yeah and in the end simply return uh cool i think that's pretty much i want to talk about for this problem yeah and i hope you guys enjoyed watching the videos and stay tuned same thing here and see you guys bye
|
Minimum Area Rectangle
|
valid-permutations-for-di-sequence
|
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`.
**Example 1:**
**Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[2,2\]\]
**Output:** 4
**Example 2:**
**Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[4,1\],\[4,3\]\]
**Output:** 2
**Constraints:**
* `1 <= points.length <= 500`
* `points[i].length == 2`
* `0 <= xi, yi <= 4 * 104`
* All the given points are **unique**.
| null |
Dynamic Programming
|
Hard
| null |
68 |
so today we are actually going to solve very disliked and yet very popular lead code problem that has been asked at tons of different companies so let's get started with the question so the lead code problem we are going to solve is called text justification now you can see that this is a lead code hard problem and also very controversial problem because it has more dislikes compared to likes but the thing is the only reason I'm solving this problem is because this has been asked at tons of different companies so let's try to understand the problem statement basically we are given an array of string called words and we are also given a number called Max width now we need to format the text such that each line exactly has the max width character and is fully Justified from left to right now there are some conditions that we need to follow in order to complete this exercise so we should pack our words in the greedy approach that is pack as many words as you can in each line and every single word or between two words we need to have at least one extra space when there is necessary also we need to make sure that every single line exactly has the max width characters now we are also being told that whenever we are dealing with extra space between the words they should be distributed as evenly as possible but in case we realize that the number of spaces on a line does not divide evenly in that case we need to divide it between the words and if there are empty slots on the left we are going to be assigning more space on the characters on the left hand side and the last condition is that for the last line of text it should be left Justified and there should not be any extra space inserted in between the words and that's it now there are bunch of different conditions so let's try to understand this with some of the actual examples for this problem now we are given a string or string of words such as like this where it says that this is an example of text justification and we are being told that the maximum width in every single line we can have is 16 characters including the spaces nothing more than that so let's try to see that how does the solution for this problem should look like now the thing is first let's see that how many characters this needs this has four characters then this has two characters and then this also has two characters and this example has seven characters so let's try to sum up and we are trying to root for or find the greedy of approach and trying to find as many words as possible within the boundary of 16 characters plus we will have to consider at least one space between any single two words which means what I'm suggesting is that instead of treating this as like four 3 and two by its character size we are actually going to add one more value to it so let's assume that this is five then this is three this is also three and this is eight okay so now let's try to do the sum and see how many characters can we fit in so for this one we maximum is 16 now if we do some of these three characters then it we get the value as 11 and then 11 + 8 if we try to do it 11 and then 11 + 8 if we try to do it 11 and then 11 + 8 if we try to do it goes 19 so 19 actually exceeds the value we are trying to find which means we cannot include this character example okay so after realizing that we are only going to be working with these first three words so we have this first word that is this second word is and third word is n okay and we need to put this in one line such that the first word starts with t inside this given line the last word has to be n because we don't want to have extra space after the last character for this particular line okay so this has to be first word this has to be last word and we need to have in total 16 characters now the thing is originally we saw that we were considering five and then three in terms of characters but now let's not consider these spaces let's only consider the values of the characters which means this is currently four characters long this is 2 characters long and this is also two characters long which means in total we are working with 4 + 2 + 2 so total are working with 4 + 2 + 2 so total are working with 4 + 2 + 2 so total eight characters we already have which means we will have to add eight spaces inside this first line that we are trying to create which means we can put four spaces over here and we can put four spaces over here because remember there should not be any space after this character n so in this case we are going to build a string like this so first is going to be this then there are going to be four empty strings then there is going to be character is and then once again there are going to be four empty strings and then we are going to have the character n and this is going to be the first part of the answer where we have created a string that contains exactly 16 characters and we will still have to iterate over these remaining files so let's try to do repeat the same process once again so let me just write down this answers at some place now let's try to find the second line and let me also clean this up a bit now let's repeat the same process for the remaining characters so how many number of characters this example has it has seven but we also need to consider space so there are going to be eight characters this off is going to have three characters this text is going to have five characters and this justification is going to have 14 characters and since this is the last character we are not adding an extra space and remember there is also a DOT or the full stop behind this line that this is also considered as an extra character so now let's try to do the sum so if we do 8 + 3 we get 11 + 5 we so if we do 8 + 3 we get 11 + 5 we so if we do 8 + 3 we get 11 + 5 we already get 16 which means we are by defa default add the 16 character Mark which means we cannot add this justification so now let's try to deal with just these three words and once again we are dealing with example and then off and then text but now we are not going to include spaces for now because we will have to do that calculation so now this is seven characters this is two characters and this is four characters so if we do the sum we get the value 13 which means in total maximum width we need 16 which means we still have three extra spaces that we have to distribute but the thing is now this is not an even number of spaces this is odd number of spaces so we will have to divide if we try to divide this by two we get like 1.5 but divide this by two we get like 1.5 but divide this by two we get like 1.5 but this is we can not divide 1.5 spaces so this is we can not divide 1.5 spaces so this is we can not divide 1.5 spaces so we are going to divide two spaces between here and then we are going to put one space here because remember there has to be at least one space and also if we divide 3 by two we get like two options 2 + 1 so this is how we are two options 2 + 1 so this is how we are two options 2 + 1 so this is how we are going to distribute the spaces so second answer is going to look like this where it's going to be example then we are going to have two spaces then we are going to have off then we are going to have one space and then we are going to have text so this is going to be the second line of the answer so let's Al also Mark this one as well okay and now in the end we are only dealing with just single uh word or in the last line and this word contains 14 characters so we are going to have it Justified completely on the left side of the portion so the answer is going to be quite simple that we are simply going to create an answer with justification and whatever is the remaining value or in order to make it 16 we are just going to add Extra Spaces and this is going to be the answer this is the total three strings that we will have to return and this is the whole explanation of the problem now how to solve this problem well actually I was also solving this problem along with explaining the problem because we don't have to use any extra specific data structures we don't have to use any extra characters nothing like that the simple logic is that we are simply going to run an algorithm the purpose of this algorithm is that let's assume that currently we are given the word string and this are given like X number of words okay and each of them are in the different length and let's assume that the width we are given is for some example 10 now the logic is first we are going to keep on iterating across every single word plus adding a space with each word until the point where we run out of the number 10 the moment we run out of the number 10 we will have to identify that what was the last character that would not be included or the last character that uh we can only include so let's assume that we can only include up to this point uh in just one line which means for the next line we can consider all the remaining items now amongst these lines we are going to forget about this one space for now we are only going to be concerned with the size of the characters and see that what is the size of the characters we get so let's assume that we get the size of the characters as six so if the size of the characters is six for each one of them which means we will have to deal with four extra spaces so now in this case if we are dealing with even number of extra spaces so we can simply put it between these two words or all the remaining portions between any number of words and then we once again mark it as the part of the answer so these three x are going to be part of the answer so X then two spaces once again X then two spaces and then x uh and then we are going to repeat the same process for this remaining item so this is the whole solution and in order to build the string we need to use string Builder class or some sort of that functionality every single language has the way in order to build the string and this problem seems hard but it is only hard because you will have to iterate over this logic and there are lot of different edge cases that we need to cover what is the importance of this problem well this is how actually the tools such as like word and Google doc they actually do the text indentation so that's why this problem is has practical implication there are no questions in that but this specific problem does not deal with data structure as much as it deals with iterating over different strings and trying to find the reasons and that's why this is such a highly unliked problem on lead code um but it is what it is I just explain you that how to solve this problem when we do see the coding solution things will make much more sense if we see time complexity it's pretty simple that the time complexity is going to be bigo of s where s is the total number of characters that are present inside uh this word string so sum of every single character so first of all we are going to initialize an array list called lines to store our answer then we are going to have an index value starting at zero and we are going to have the condition that while index is less than the total words that do length we are going to first of all do the count of all the words uh length of all the words and then we are also going to keep track that what was the last value of that we have been able to identified and we are going to put it as index + one then we are simply going as index + one then we are simply going as index + one then we are simply going to iterate over that while last is less than the current words. length we are simply going to keep on adding the value and keep on checking that if the next adding the next word exceeds the max width or not if it exceeds the max width we simply break if it does not exceed we increase our counter and we also increase the last pointer as well now once we are at this stage we are at a position where we have the values of the words that can be included in one single string or one single line for the answer so we are going to initialize a string build now for this string Builder we are going to append the words that are currently present at the index and then we are simply going to check that if we are on the last line of the line and it has only just one word we are going to do a left justify which means we are going to put all the words that are currently present and whatever the difference is we are simply going to upend that for the for our existing string Builder if that is not the case uh then we are going to calculate that how many spaces do we need to do so we are going to calculate the spaces based on the maximum width minus the count divided by the difference of the number of words and then we are going to check that what should be the Extra Spaces divided amongst each entity so for that we are actually using the module function by div and then we are simply going to run a couple of for Loops in order to generate the string that I just explained and then in the end we are going to add all the strings that we have been able to create inside our string Builder and return lines that we have create initi initiated originally the ARR list as the answer so let's try to run this code okay seems like our solution is working as expected let's submit this code our scode runs 100% faster than all code our scode runs 100% faster than all code our scode runs 100% faster than all the other Solutions which is pretty awesome and uh once again I will be posting the solution in the GitHub repository link is in the description thank you
|
Text Justification
|
text-justification
|
Given an array of strings `words` and a width `maxWidth`, format the text such that each line has exactly `maxWidth` characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that each line has exactly `maxWidth` characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left-justified, and no extra space is inserted between words.
**Note:**
* A word is defined as a character sequence consisting of non-space characters only.
* Each word's length is guaranteed to be greater than `0` and not exceed `maxWidth`.
* The input array `words` contains at least one word.
**Example 1:**
**Input:** words = \[ "This ", "is ", "an ", "example ", "of ", "text ", "justification. "\], maxWidth = 16
**Output:**
\[
"This is an ",
"example of text ",
"justification. "
\]
**Example 2:**
**Input:** words = \[ "What ", "must ", "be ", "acknowledgment ", "shall ", "be "\], maxWidth = 16
**Output:**
\[
"What must be ",
"acknowledgment ",
"shall be "
\]
**Explanation:** Note that the last line is "shall be " instead of "shall be ", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.
**Example 3:**
**Input:** words = \[ "Science ", "is ", "what ", "we ", "understand ", "well ", "enough ", "to ", "explain ", "to ", "a ", "computer. ", "Art ", "is ", "everything ", "else ", "we ", "do "\], maxWidth = 20
**Output:**
\[
"Science is what we ",
"understand well ",
"enough to explain to ",
"a computer. Art is ",
"everything else we ",
"do "
\]
**Constraints:**
* `1 <= words.length <= 300`
* `1 <= words[i].length <= 20`
* `words[i]` consists of only English letters and symbols.
* `1 <= maxWidth <= 100`
* `words[i].length <= maxWidth`
| null |
Array,String,Simulation
|
Hard
|
1714,2260
|
108 |
okay let's talk about converse sorted array to binary search tree so you are giving the array and you are changing the red to the binary search tree and there is a way to find out the root because the arrays are really shortest so basically you just need a middle index so the middle index is left plus right minus left divided by two and that will give you a middle index so the main function just has an array so i need to have the range so i have left and right so i pass in zero into num length minus one then i would say if left is greater than right i return no then the middle value is left plus right minus f divided by two and then if i have a middle value i just put into the root right now my root of left is the range between uh negative 10 to n minus one right so left comma and then n minus one and then for right is n plus one to the right and i just return root don't worry about the recursion stuff i mean that will handle it and it just rounded okay and let's run again all right it's pretty good so the timing spacer for the spacer i actually need a note right so it's all the one and then tying your video every single note once so it's all the fun as well so that would be all the run for both
|
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
|
410 |
Jhaal hey guys welcome back to my channel in this video we are going to solve split air cure assam 100 giver statement hair given and adams witch consist of native in tears and user name you can spread fear into a beneficial continue saver is right and allowing them To minimize the largest time, what is there in the mother's name survey research problem, there is an Adams giver and an interior end given, what we have to do is to divide this edit into m not it continues address, after that we have to find the smallest largest sum, okay So let's understand the problem is saying here carrier given her name to given not dominant we can divide this edit into two sub addresses okay so what is before the possibility and we see seven will be 11 elements can be taken Will be available with Android by 2025. Okay, then the maximum you can take is 1257 plus 0 maximum. Then we can make 7215 in 727, then add 510 and eight, so here how much will be 515, 5823 and 983, then the degree is that. We can say 725 with then 810 and one that guy okay that can do it so what will happen here is that team 80 2729 50 ultimate goes in taken okay then what we can do is invest 725 skin with Okay, so here if it is more than 129 500 600 800 then we will fix it, then here we reminded this maximum sum and who is the minimum in this, there is editing, so this is it, but what do we have to do, we have to return it, okay. So, how will we solve this problem? Here we will try to solve this problem by using binary search. Whenever in a problem statement, minimize is the largest and maximize is the smallest, then what can we do in that condition? You can try to use the truth, you can think that solving the problem is not white, you know that mostly they use it and do it in the dark, it is not so, now we can use binary search even in the dark. There is a WhatsApp, mind research on cancer, so using this concept, we will try to solve the problem here. Okay, so what we will do here is, we will put it, okay, what will be the voice mail, this will be the maximum element of mine, okay, the maximum element. And what will happen to the art 10 maximum element Miyan here, not the most minimum, absolutely minimum large sum, then the most minimum large sum, and there is a condition here that you can divide the sub add in two sums or divide it in any sum, then this What are the possibilities in the condition that the size is one in the morning and when can the maximum be pointed in it? When the maximum element is there, the tight element will be the gift here, what else will be there in the maximum, what will be the maximum sub addition here, what will be the maximum sub addition all. Why the audition of the element because here it is not negative then the maximum largest maximum sub addition what will be that Hisar element addition then here the addition will they see 729 50 3252 ok we will erase and clean Mantu here l r - Mantu here l r - Mantu here l r - l that al Plus and minus l that by two is okay so how much fun is this here 3210 will be controlled here okay so one is done then what will we do right now we will take all the addresses here in the morning we will take it and see which ones It is causing an accident, okay, how much account point will you add then A7 plus to 9500, what will happen here, tune it, this will give it infotainment channel, if it is causing an accident, then the account alarm will be Ravan, okay then we will add tenth plus here, 8-What? Ka or if it is here, 8-What? Ka or if it is here, 8-What? Ka or if it is not given a seat, then there will be one in the account, then the account is my one, hey, is this less than us, is it much less than us, so what will we do in this condition, what should we do, if we try to minimize it, what will we do to you? Will add to this then meet - If you what will we do to you? Will add to this then meet - If you what will we do to you? Will add to this then meet - If you get my voice then the medicine is one. 20 minutes minus one then minutes will be minus one. I say 121 - 124 aloe vera I say 121 - 124 aloe vera I say 121 - 124 aloe vera here the additive stand is fine then what will we do here. If we do the midfielder from this side then How much will I be effective here? Okay, Vipin will be there, then what will we do and we will fine here all the addresses which will be making an impact, then we will add from 1295 well. If I set this feedback of 2015, then how much will my account become ? It will be one, okay then we will set plus 80, ? It will be one, okay then we will set plus 80, ? It will be one, okay then we will set plus 80, what will be eight, we have to request account here Dr. Two, so what will we do in this condition, here we will try to minimize the album, we will try to maximize it, okay, we will maximize the potato. So this will become meet plus one so how much is my I will do my shifting plus one will come here it will be okay I plus one meet plus 12816 this will become six more tables and how much time 2828 then we will meet point from here beat how much My will be erased here, then my mail here is my sixteen and how much is this, it is more than 120, then what will we do in the account, we will see how much, which is developing 18, we will add 729 50 cents, we will add one seat, then in the account, I will become one, okay then we will add ten plus, this is equal to this vaccine is not working, so what is this account, this is my letter name here, so in this condition, what should we do and we are minimizing and how much will my tweet become? - It will be 1837 and l what will my tweet become? - It will be 1837 and l what will my tweet become? - It will be 1837 and l what will happen to me here 1616 or what should we do here in my mind what will happen next I will be sixteen ok next will be 6 then we will give the marksheet to the secretaries 729 50 thousand unreserved current This account of the villagers is doing an accident of fit and plus eight. How to do the account here? This is the account, this is equal to MK, so what we are doing here is that we will try to include in the circles. Like the albums and bell's or More than medical 178 that I am 17th here I will fold you mit here Bitcoin will be seventeen here will be 200 let's see 0 how much is fitting then 1779 500 to 1000 you will be contra here okay who becomes one then temples And current account will go to Dr two because debit has to be done on Sunday then we will do aloe vera here if we maximize then mill plus one will become 2018 and will become relative and I will be 80 this condition one till now we do when my selection will be equal to two and but What A is greater here then from here we will break what will we give from here will come out then what will we do return will do acting talent IT will return but I am the answer so how to code they see that this and intel this Hero is and 80 ML is my meeting maximum number and toe next key and norms oh ok what will we do here mail custom Or what will we do here? Mobile electronic waste to are you okay? So here I have taken it refined. We are internet, this is meat, what will be my e-mail e-mail e-mail plus and minus health mic two. Then what will we do here. Add total were done total time here let's take 10 account cont 0 ok took control then what will we do here and toe buy here salted then what will we do first we will check here that total sum plus i is ratan That there is Girdhar Mithai treatment, what will we do in that condition, total and total, contact 09818369381 plus, we will do it, okay, part plus, if that, what will we do here, I will add it to the total at this time. Ok ok, I have done one lesson and then we will see that the account which is mine if we will unite the market the name here. Come here scientifically when we come out we will check then this account of mine is Listen ML if my writing is and So what will we do? What will we do? Minimize and minimize Media - Media - Media - Vansh It's So now what we will do here is Aloe Vera Will maximize Will do My plus point is that we have done this Then what will we do here So finally we will add a return Okay We accept and submit the adjustments to the court. Thank you.
|
Split Array Largest Sum
|
split-array-largest-sum
|
Given an integer array `nums` and an integer `k`, split `nums` into `k` non-empty subarrays such that the largest sum of any subarray is **minimized**.
Return _the minimized largest sum of the split_.
A **subarray** is a contiguous part of the array.
**Example 1:**
**Input:** nums = \[7,2,5,10,8\], k = 2
**Output:** 18
**Explanation:** There are four ways to split nums into two subarrays.
The best way is to split it into \[7,2,5\] and \[10,8\], where the largest sum among the two subarrays is only 18.
**Example 2:**
**Input:** nums = \[1,2,3,4,5\], k = 2
**Output:** 9
**Explanation:** There are four ways to split nums into two subarrays.
The best way is to split it into \[1,2,3\] and \[4,5\], where the largest sum among the two subarrays is only 9.
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] <= 106`
* `1 <= k <= min(50, nums.length)`
| null |
Array,Binary Search,Dynamic Programming,Greedy
|
Hard
|
1056,1192,2242,2330
|
1,027 |
hello everyone welcome back series of announced and today we are revisiting the lead code problem longest arithmetic subsequence we receive great feedback on our previous video on this topic and some of you have suggested some optimization so in this video we are going to optimize our previous solution so let's get started in the original solution we use a dynamic programming approach with a two-dimensional list approach with a two-dimensional list approach with a two-dimensional list however as some viewers pointed out we could optimize this using a one-dimensional list of dictionary this one-dimensional list of dictionary this one-dimensional list of dictionary this way we only store the difference we have encountered making it more space efficient so let's try to implement it so what we do is n will be a length of nums so if length is less than or equal to then return the length itself so if n less than 2 return n otherwise longest two as we have at least two elements we start the longest sequence with two so DP with map and range and list of dictionaries to store the max length for each difference at each index so what we do Loop over each pair of elements in the ri and for I in range and for J in range to I calculate the difference between the current and previous number so beef will be num I minus num of J so difference between two elements and if the difference was already seen at index J get count and add one I'll start from 2 since half thin at least two elements with this difference so DP at I difference will be dpj and get difference one plus one and update the maximum length found so far so longest will be Max of longest and DPI and the difference so return longest array so let's run our code so as you can see it's uh space optimized this time so yes and looking at previous example we've mentioned before so I write of 9472 10 output is free this is because we have a increasing arithmetic sequence so 4 7 10. so difference between uh these three numbers for 710 is free so it create a sequence with difference of three so that's why we output a length of particular sequence so let's submit it for unsynthesis cases and see how it's working uh so yeah it's counting and yeah so this time this solution uh beat 68 with respect to run time and also 80 almost 81 with respect to memory and our previous solution uh bit only 16 with respect to run time and with respect to memory 58 so it's uh optimized and as you can see uh it took about 4 700 milliseconds and here uh three thousand so previous example was more than 50 percent slower so I hope you find this optimized solution helpful It's always important to remember that there can be many ways to solve a problem and sometimes there are small tweaks that can lead to a better or faster solution and I appreciate feedback and discussion on our previous video and keep it on coming don't forget to hit the like button if you learn something new And subscribe to stay updated on future coding Solutions challenges and tutorials and keep practicing stay motivated happy coding and see you next time
|
Longest Arithmetic Subsequence
|
sum-of-even-numbers-after-queries
|
Given an array `nums` of integers, return _the length of the longest arithmetic subsequence in_ `nums`.
**Note** that:
* A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
* A sequence `seq` is arithmetic if `seq[i + 1] - seq[i]` are all the same value (for `0 <= i < seq.length - 1`).
**Example 1:**
**Input:** nums = \[3,6,9,12\]
**Output:** 4
**Explanation: ** The whole array is an arithmetic sequence with steps of length = 3.
**Example 2:**
**Input:** nums = \[9,4,7,2,10\]
**Output:** 3
**Explanation: ** The longest arithmetic subsequence is \[4,7,10\].
**Example 3:**
**Input:** nums = \[20,1,15,3,10,5,8\]
**Output:** 4
**Explanation: ** The longest arithmetic subsequence is \[20,15,10,5\].
**Constraints:**
* `2 <= nums.length <= 1000`
* `0 <= nums[i] <= 500`
| null |
Array,Simulation
|
Medium
| null |
46 |
hello everyone my name is sakshi and in this video we are going to solve problem number 46 on lead code which is given an array numbers of distinct integers we have to return all the possible permutations of the delay we will follow these three simple steps to solve this problem firstly we will look at the recursion tree for this problem after that we will implement the algorithm and then we will discuss the time and space complexity of our algorithm let us first look at the recursion tree i have drawn the tree for a specific example of 1 comma 2 comma 3. how do we find permutations of an array let's name this array a so if we start from index 0 then for every index i greater than equal to 0 we will swap a of i with a of 0 and then we will apply this permutations function recursively for the second element and then for the third element and so on so here let's look at this we are starting from index 0 we are swapping a of 0 with a of 0 so we get 1 comma 2 comma 3 a of 0 with a of 1 we get 2 comma 1 comma 3 then swap a of 0 with a of 2 we get 3 comma 2 comma 1 now for this layer we are done and we are done with index 0. now going on to index 1 we will swap a of 1 with a of 1 we get 1 comma 2 comma 3 and then swap a of 1 with a of 2 we get 1 comma 3 comma 2 now similarly 2 comma 1 comma 3 and here we are swapping 1 and 3 we get 2 comma 3 comma 1 3 comma 2 comma 1 and swap 1 and 2 we get 3 comma 1 comma 2. and these are the six permutations of the array which we need in our solution we are done with the recursion tree now let's look at the implementation i am going to write a recurse function look at the inputs this is the given array size of the given array current index and the final output vector in which we will be storing our permutations now according to our logic we will move from index to n and we will swap numbers of index with nums of i then we recurse for index plus one and after that we have to swap again to get the original array look at this when we are at one comma two comma three we swapped two and three we get one comma three comma two now we have to swap back because we want to reach two comma one comma three as well so we swap back we reach one comma two comma three and then we swap back um because here we asked we swapped one with one so we swap back we get one comma two comma three again and then we go in this tree in this subtree so that is why we need to swap back now when will we store nums into ret when we reach the last element that means then index is n minus 1 then we push nums into rdt and get it off to call this function i am getting the size of the array defining a vector output vector alrighty now i'll call recurs n will start from index 0 and i'll just return rdt let's run this code it works fine we are good to go we are done with part one and part two of our process now let's jump to the part three which is discussing the time and space complexity of this algorithm let's first discuss the space complexity uh so we are not using any extra space here ret is just the output vector but we are using the space for uh storing the recursive calls which is the space used by the recursive stack which is order n by this tree so the depth of this tree is n which is the size of the array so the space complexity of this problem is order m now let's discuss the time complexity uh which is the number of recursive calls into the time complexity of one recursive call so um what is the time complexity of one recursive call here time complexity of this line is order n because the size of num's array is n and the time complexity of this for loop is also order and in worst case so the total time complexity of one recursive call is order m now uh we have to find the number of recursive calls for that look at this there are three calls on the first level three into two calls for the second level which can be generalized as n calls for the first level and into n minus 1 for the second and into n minus 1 into n minus 2 for the third and so on it goes till the last number is 2 because here the last number is 2 so it goes till n into n minus 1 into n minus 2 and so on up to 2 which is n factorial so the total number of calls is the sum of all these numbers clearly the last term is n factorial all the other terms are less than n factorial and the total number of terms are n minus 1 since we want to calculate the big o of the number of recursive calls we can say that the number of recursive calls are big o of n minus 1 into n factorial which can be further called o of n into n factorial so the total number of recursive calls are n into n factorial and time complexity of one recursive call is order of n so we can say that the total time complexity of the recurse function this recurs function is order n square into n factorial and we are calling this recurse function here so we can say that the total time complexity of permute function is also order n square into n factorial if you face any difficulty in understanding any segment of this video uh i would suggest to have a look at my previous videos on subsets also i have added the link to this code in the description below if you like this video please like share and subscribe if you have any doubts or comments please leave them in the comment section below that's it for today see you in the next video bye
|
Permutations
|
permutations
|
Given an array `nums` of distinct integers, return _all the possible permutations_. You can return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\]
**Example 2:**
**Input:** nums = \[0,1\]
**Output:** \[\[0,1\],\[1,0\]\]
**Example 3:**
**Input:** nums = \[1\]
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= nums.length <= 6`
* `-10 <= nums[i] <= 10`
* All the integers of `nums` are **unique**.
| null |
Array,Backtracking
|
Medium
|
31,47,60,77
|
257 |
hi friends welcome back today we are going to solve lead code problem 257 binary tree paths given the root of a binary tree written all root to leave parts in any order a leaf is a node with no children so they have given us a binary tree here and as you can see one two five is one path here and one two three 1 2 3 is another path so i actually took a little bigger example here so i can explain little better and so we are given a binary tree and we have to capture all the paths starting from a root node going to the leaf node so all the leaves you know so we are going to use a backtracking for this purpose and we are going to actually like uh start with the root note 2 and we are going to kind of maintain a list you know like of nodes that we keep visiting uh on the way so let's add two and we will go on the left side first and then we will go on the right side so we are going on the left side we are going to visit root like node 7 so we are going to add say 1 into the list and again we are going to the left and we're adding 2 into the list so as soon as we reach this node 2 which is a leaf node we are going to capture the list that we have so we have 2 7 2 so we are going to add this 272 into our path and then we will actually backtrack so now we are already at the leaf node so we are going to backtrack to the previous node that we visited which is 7 and we are going to remove the two from the list and now we are going to go to the right side right subtree of 7 which is 6 right so we are going to go visit 6 and we will add a 6 into our list here and then we will go on to the left side and we are visiting 5 so we will add 5 into our list here so this is our list and once we reach 5 we are again at leaf node and we are actually want to capture the path that we have uh visited so far so now the path is as you can see 2765 so we have this path 2765 we are going to add this into our paths list and then we will now again backtrack from 5 to the previously visited node 6 and we will go on to the right side and at the same time we will you know remove the 5 because the 5 we already have seen now so now we are going to 11 and we are going to add 11 into our list here so now again we are at a leaf node and we have a list now of a path like a 2 7 6 11 so as you can see here 2 6 2 7 6 11 we will add into our output paths list and we will now again backtrack from 11 so we will go from 11 to 6 and 6 to 7 and 7 to 2 right so now 11 we will remove 6 we will remove and then 7 we will remove so now we only end up with a 2 in our list right so let me just write it down here so now again our list becomes just with one element 2 because other elements we have removed because of the backtracking so now we are going to visit the right side nodes now so we will visit a 5 and we will add 5 into our list then we will visit next node 9 we will add 9 into our list and we have 4 on the left side that we will visit and we will add 4 into our list so as soon as we visit 4 we are visiting a leaf node so we are going to capture this path into our output list which is 2594 so this is a 2594 added into our list so this is how we will use a backtracking analyst uh so here is the implementation that same approach that i showed you let's just discuss little more details here so um so the output we want to uh return is a list of string so i took a list of string which is a result uh then i have implemented this traverse which is a recursive function here and we will pass the root first here and then list of string as a list here and this is the output list that we are using only to capture the output paths that we receive from root to leave so it is list of strings here right so the main purpose of this output is only to get uh the paths out of this function right because the function is returning voids that's why we are passing a list of string here so um you know first thing we will check is if it root is equal to null then we will just return we don't have to do anything if we reach a node which is a leaf node then we are going to add the value of the uh leaf node into the list and then we will just create a new list from the list this is required because you know otherwise uh the list is on the heap so it will keep appending on to the original list that's why we have to create the new error list here and that new arrow is which is uh actually this new list contains the path from root to leaf we will add into our output list that this output list here we will add and then we will remove the last node that we added this is required because we are actually backtracking right so the last node that we have added we want to remove it and then return it so the same thing as i explained here so for example from 2 once we are going back from 2 to say 1 in the back track then we want to remove that 2 from the list right that's what we are doing here so you know if we are visiting any intermediate node for example we visited two then we are visiting seven right say one is an intermediate node it's not a uh leaf node so in that case we will just add the value of that intermediate node into our list here and then we will recursively go on the left side of the root and we will go on the right side of the root and then at the end we will take out the last value that we added into our list here right so this value that we added into our list we want to remove this is for the backtracking purpose right when we are we want to go back in the back tracking then we want to remove the lastly added value so that's what we are doing here so once we get actually once we return from the traverse function we have this list populated list is a list of strings and it's it has all the paths so we are going to you know iterate through the all the paths and we are going to use a string builder and we are going to append this kind of arrow actually because this is what they want us to return right one arrow to arrow five so this is what it is doing we are using a string builder for that purpose and then we are finally once we are done for every path then we are going to add that path into our result which is a list of strings right and here what we are doing is we have that extra arrow at the end that we added here though we are just taking it out here you know because that extra arrow that we added we are just removing it here so at the end of the function we will just return list and that list will contain all these paths like this so i took a example which is this example that given to us so let's quickly run through the code so as you can see the code is working fine we are getting the correct output and we are going to submit this solution now okay so the solution is getting accepted uh so this is how you know we are going to get like all binary tree paths which are starting from the root and going all the you know all the leaves of that tree you know so this is how we can use a backtracking and linked list or list actually for the implementation so i hope you like this video if you like this solution please hit the subscribe button and click on the like button uh also click on the bell icon so you will not get like missed on any future videos that i keep posting thanks for watching the video
|
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
|
466 |
hello everyone so today we'll be solving a little heart problem and it is called county reputations and it the problem is as follows that uh we can define a string in for s comma n and this string it basically represents the as a string concatenated n times and there is one more concept in this problem that a string s1 can be obtained from string s2 if we can delete some characters of s2 to get the s1 so what we need to do we have pin give one two strings that's one and s2 and str1 and str2 can be formed by concatenating s1 n1 times and h2 and we need to return the maximum these are f such that str2 comma m can be obtained from str1 so let us take a look to the constraints so the length of s1 and s2 both are less than equal to and the length of s n1 and n2 is less than equal to 24 6 so basically these str1 and str2 are of the order 10 to the power so the these two things are listening for it so if we would be doing something like this like suppose there is a string made of infinite concatenation of s s2 and there is a string that is made of n1 concatenations of s2 so basically this represents the str1 and this the upper string this part represents the infinite concatenation of sdr2 so basically we will be measuring how much part of this string can be obtained from this string and after obtaining the length of this we can divide the length of str2 to get the m so the standard algorithm says to take two pointers so basically there will be a pointer two for this string and pointer one for this string so whenever we will get uh this corresponding character is equal into these two strings we will be increasing both the pointer and when whenever we want the we will be getting that the two characters are not equal we will increase this pointer and after uh when this pointer pdr one will reach to the end of this string we can find the matched length using the pointer two but this approach will give us really because uh the length of the ptr one is of the order to power it so we need to optimize this so the one optimization that we can do is that at the start of each uh each iteration over s1 this pdr2 will be present at some index of s and after end of each iteration it will be present at some index of s so suppose like if at the first it will start from index 0 of s2 then it may be possible that after end of first s1 it have moved to x4 and aft after the end of another s1 it may present it may possible that this 4 will move to 2 index 2 of s2 so what we need to do we can recompute all these uh all this like movement of indexes from index for every index i for like we can compute that uh at which position the speed pointer two will move if we will start from i equal to zero at i equal to one and i equal to two and up to length of the this length of this s2 so for implementing this first let us store the length of the two strings now what we need to do we can use an unordered map for storing the indices and let us call increase so basically it will tell us the increase in the pointer to whenever it will start from a certain index of s2 and after the end of the each iteration of s1 so we can use a for loop that will go from r0 to length of 2 length 2 minus we can now use two pointers so one pointer is vtr another pointer is pdf equal to i so basically we are trying to store the increase in length for each so this has two the pointer pointing to s2 will start from i and the pointer pointing to s1 will start from zero so we will do this for each length of this one so dpr will do until ptr1 is not less than not equal to length of length number so if s2 if s1 ptr1 is equal to s2 dtr2 mod length we need to do this because the ptr may exceed the length this length to start from the beginning so just in case this will happen we will increase the two pointers and just in case this was not the case we will just increase so after this loop will be executed we can store increase in the pointer of pointing to s2 by subtracting it separating the eye okay so after this free computation so this precomputation will take uh how much time length two into length one so the complexity of this precomputation is length two into length now we need to do the main thing so what we'll do we will start we will again take up pointer one and we need to we can call it we simply ptr because we there are two pointers this time and we can take a variable total match length so what we will do now we will iterate over this whole string and find how much length of this string has been matched in this history so initially this pointer will be at zero and we since this point this string is made up made by concatenating s1 and one times so we can run this loop for n1 times now this total match length will increase by increase of vpr after each iteration and this pdr will also increase by this same quantity but we need to take model of pdr with length of keep it within limits and after end of this loop we will get this total match so this uh now we have got this total matchstick now we need to find how much str 2 is present in this total match so we can divide the length of each str2 to get the answer let us try down here so some error has everything is okay here let's check here yeah sorry it should be i plus yeah so we got success so the total complexity say the complexity of this part is the other computation part is order of length 2 into length 1 and the complexity of this part is order of n1 so the overall complexity is length and since this n1 is within limits with less than 246 it got accepted so thank you guys
|
Count The Repetitions
|
count-the-repetitions
|
We define `str = [s, n]` as the string `str` which consists of the string `s` concatenated `n` times.
* For example, `str == [ "abc ", 3] == "abcabcabc "`.
We define that string `s1` can be obtained from string `s2` if we can remove some characters from `s2` such that it becomes `s1`.
* For example, `s1 = "abc "` can be obtained from `s2 = "ab**dbe**c "` based on our definition by removing the bolded underlined characters.
You are given two strings `s1` and `s2` and two integers `n1` and `n2`. You have the two strings `str1 = [s1, n1]` and `str2 = [s2, n2]`.
Return _the maximum integer_ `m` _such that_ `str = [str2, m]` _can be obtained from_ `str1`.
**Example 1:**
**Input:** s1 = "acb", n1 = 4, s2 = "ab", n2 = 2
**Output:** 2
**Example 2:**
**Input:** s1 = "acb", n1 = 1, s2 = "acb", n2 = 1
**Output:** 1
**Constraints:**
* `1 <= s1.length, s2.length <= 100`
* `s1` and `s2` consist of lowercase English letters.
* `1 <= n1, n2 <= 106`
| null |
String,Dynamic Programming
|
Hard
| null |
205 |
some problems will try to confuse you by using a new terminology and you will often find these kind of problems in the beginning rounds of all of these tech companies and hidden beneath it is a very simple string problem one such problem is isomorphic strings on lead code let's see what we can do about it Hello friends welcome back to my Channel first I will explain the problem statement and we'll look at some sample test cases going forward we will try to solve this problem using a Brute Force approach and see its limitations that we are going to optimize it and add solution dry run of the code so that you can understand how all of this is actually working in action without further Ado let's get started going over the problem statement you are given two strings and you have to determine if they are isomorphic so what is isomorphic even mean strings first with some other character and you can form the second string so let us try to understand it even better using some sample test cases for example look at the test case number one in this example you can start with the letter e and replace it with a so my string becomes AGG correct and now you move on to the second character that is g and you replace G with d once you do that your string becomes a d so we were able to achieve the string right so for the first test case you return true as your answer because these two strings are isomorphic in our second test case also you proceed with the first character that is f so you replace F with B so you get b o now you look at the second character that is O so you replace o with a and now your string becomes b a now look at it the third character is O again but you have already replaced o with a and hence you cannot replace o with r now so there is no way that you can achieve this string bar with the first string Foo right so for this particular definition false will be your answer similarly look at the third test case real quick you start with the first letter P and you are going to replace it with t next you will replace a moving ahead you will replace e with L and R with E and ultimately you will get your string title correct so for this test case also your answer will be true because these strings are also isomorphic now there is one kind of test case where you have to be careful with look at this fourth test case my string is badc correct so you may say that okay I will start with the same process you replace B with K so now you get moving on to the next character you replace a with I and now look again the third character is D and you may say that okay I can replace D with K and then move ahead but this is wrong you see that you have already replaced B with K so K is already taken care of you cannot replace any other character with the character K because think about it if these strings were in reverse order right so then you are replacing K with B then I with a and then once again you are replacing K with d so that invalidates these two strings to be isomorphic correct so this third substitution is not allowed and hence these strings are not isomorphic so you have to return false as your answer now if you feel that you have understood the problem statement even better feel free to try it out on your own otherwise let us dive into the solution a good developer will always try to come up with a brute for solution first because that can guarantee you if a solution to a problem even exists so given this example test case you have to determine if these strings are isomorphic so how do you proceed well you can proceed in the same way the way we are verifying our test cases what did we do we took our first character that is p and this for what do we have to replace it with the character t once you do that you get a new string and that is t a t e r right now moving on you move to the next character and that is a and what do you replace it with I so a is gonna get replaced with I now replace the occurrences of a in this string with I and what do you get your new string t i t e r similarly you proceed with the next character p and that is already taken care of move to the next character e and that has to be replaced with l once we replace it the new string becomes t i t l r correct move ahead now with the last character R and replace it with e once that is done you get your final string that is t i t l e you see that you were able to go from one string to the other string that's perfect right but if you remember from our last test case you also have to verify if you can go to the first string from the second string as well so you are gonna follow the same approach but this time you will try to replace one character at a time from your second string you start with the first character T correct and you are gonna replace t with p once you do that you get your new string piple just keep moving ahead now replace I with a once you do that you get a new string t a p l e keep moving ahead one by one and then you will arrive at your final string and that is paper so you see that we were able to go from paper to title and we were able to go from title to paper both the directions right so these two strings are isomorphic and yes this solution works you are able to verify and this will give you a correct answer also but do you approach in this approach you are making so many Replacements right and this will lead to forming so many strings this will waste a lot of time and you're gonna compare a lot of strings so definitely this is not desired we need to come up with an efficient solution so try to think what can we do about it okay so let us take up this sample test case and try to determine if these two strings are isomorphic or not so how did we proceed in The Brute Force approach we looked at the first character that is L and found out okay what do you have to replace it with you have to replace L with a p correct now notice that you do not have to form your string again and again what do you have to check you just have to check if you have already encountered this character before and there is there a very efficient way to determine if you have already encountered a character yes that is a hash map because a hash Map works in an order of one time complexity to check if character exists in some sample set so I will take the help of a hash map and try to map all the characters and their replacement what do I have to do over here I have to replace L with p so I'm just gonna make these two entries over here in my hash map right you do not have to actually form the new string the next character is I and I have to replace it with r you see how I'm populating my hash map simply keep moving ahead the next character is B and that has to be replaced with I moving on my next character is r and it gets replaced with v look at the next character that is a you do not have to replace it with any other character and that is fine so you can simply just add it to your map look at the next character now the next character is r and it has to be replaced with c now look at your hash map when you look at the hash map you see that R already exists over here right and it maps to V so definitely you cannot change the value of R once again and that is where you stop you will say that hey these two strings are not isomorphic because you have already replaced the value of R once you cannot replace it twice and hence these two strings are not isomorphic this way you can easily determine without wasting a lot of time now notice that there is a edge case that you have to be careful about for example you have these two strings b a d c and k i k p once again you create your hash map and then you proceed corrected by character you see B and you replace it with k you see a and then you replace it with d you see a d again and then you replace it with K you see a c again and then you replace it with p you may say that wow these strings are also isomorphic but here is the catch once you are checking in your hash map you not only have to check the keys you also have to check in the values column as well because think about it when I encounter the character D it has to be replaced with the character K right you may check that okay D is not prevent so I can add it but check what are you replacing it with you are replacing this value with k but K has already been taken care of right so you cannot add this entry over here because think about it when these two strings are reversed now as soon as you replace this key your string will become b i b p correct and now when you move ahead you see a k again this K has already been replaced with B you cannot replace it again with d so that is the only thing that you have to be careful about and once you iterate through the entire string if no controversies were found then these two strings are isomorphic and you can simply return a true now let us quickly do a dry run of the code and see how it works in action on the left side of your screen you have the actual code to implement the solution and on the right I have these two strings which are passed in as an input parameter to the function if isomorphic oh and by the way this complete code and its test cases are also available on my GitHub profile you can find the link in the description below moving on with the dry run what is the first thing that we do first of all we do some sanity checks that if the length of these two strings are different then definitely they can never be isomorphic right because you cannot add or reduce characters so if the lamps are not same simply return a false and you're done moving on what do we do next thing is we create a hash map that will map your character to the mapped character so you will have the original character in The First Column and the replacement in the second column correct so I get my hash map and once I have my hash map I will start a for Loop to iterate over each character in my first string right so I will start with the string B and check what do I have to replace it with so my original string is B and the replacement string is K say this if condition very carefully now I check if in my map I already have the original character that is B right now my map is completely empty right so I'm just gonna add this mapping to my map so I'm gonna say that okay replace B with the character k now you move on to the next character that is a so this time the original character changes to a and the replacement changes to I once again you are gonna check if your map has the original key that is a is not private in the map so what do you will simply add this to your map right so a gets added over here now move ahead and check the interesting part you take up the character D and you have to replace it with K correct you come inside your if block and you check if you already have D you do not have a d over here right but do you add it no what do you also check if your map contains the replacement value and what is the replacement value right now that is K you see that hey K is already present so if the replacement value is already present you know that these two strings cannot be isomorphic and you will simply return a false in any other case also if you find a character let's say a and that maps to X you check if you can find a A in the map if a has already been mapped to I that means you cannot map it to X now right in that case also you are gonna return a false so this Loop will run and try to find if there are any controversies that can say that hey weave to strings are not isomorphic if you are able to iterate through this entire Loop without any errors what does that mean this simply means that both of these strings are isomorphic and you simply return true as your answer the time complexity of this solution is order of n because you iterate through the original string and the space complexity of the solution is order of one because you need a constant space in your hash map to determine if the characters have been mapped correctly since the characters are asci characters the maximum size of hash map is 256 and that is constant space I hope I was able to simplify the problem and its solution for you as per my final thoughts I just want to say that whenever you come across such new terms just take some time and research upon them because think about it when you're practicing you have some time in your hands to look up and then come up with a solution but think about it if you are in a coding interview if you are in an online round where the time is limited let's face 60 Minutes for three questions then you cannot afford to waste some time just learning about the topic problem beneath it is so simple right so just keep that in mind whenever you are practicing just refresh upon them a little bit so while going throughout this video did you face any problems or have you found any other such problems which are using a very technical term which is new to you so tell me everything in the comment section below and it will be helpful for anyone who is watching this video as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where I can simplify programming for you also let me know what problems do you want me to follow next until then see ya
|
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
|
326 |
welcome to joey's tech my friends in this video we'll solve a lead code problem which is power of three it's a good problem to solve and is one of the popular interview questions that is asked from lead code so let's quickly take a look at its problem statement you are given an integer in the ask is that your program should return true if n is a power of 3 else it should return false so if you take a look at the equation over here then you can say that n is a power of 3 if there exists an integer i repeat integer which is x i will be telling you two methods to solve this problem of power of three one will use recursion and the other will use the logarithmic function available in java.lang.mathclass in java.lang.mathclass in java.lang.mathclass but before that if you are new to my channel then hit the subscribe button and the bell icon as that way you won't miss out on these coding tutorial videos i create for you i am in my intellij ide now in which i have created this class power of 3 in which i am going to write this java program so we will create the main function now so for that we are going to simply write psvm and there you go main function created in the intellij ide we will first declare an integer variable n and initialize it to let's say 81 so for that we are going to write into n after the equals to sign we will write 81 okay the first technique to solve this problem is to find out this x and check if x is an integer for that we'll use this math rule of logarithms to find x and this expression log n to the base 3 can be rewritten as log n to the base 10 divided by log 3 to the base 10. the value of the numerator and the denominator can be easily calculated using the log 10 function from the java.lang.math class java.lang.math class java.lang.math class so let's declare a double variable first and let's call it x so let's write double x now we will have to import the java. class first to make use of java. class first to make use of java. class first to make use of the log10 function so we are going to write import java.lang write import java.lang write import java.lang dot math okay now let's make use of the log10 function so for that we are going to write x equals to math dot log 10 and within its brackets we are going to pass n divided by math dot log 10 and within its brackets we are going to pass 3 okay that's it now if n is not a power of 3 then this x over here is going to contain a decimal value else if n is a power of 3 x is going to contain an integer and this can be simply checked by type casting the value of x to integer and comparing it again with x if they both are same then n is a power of 3 else it's not and we are going to make that check in system.out.println in system.out.println in system.out.println only so that directly the boolean value gets printed so it will be system dot out dot println and within its brackets we are going to write within brackets inc okay after that we'll write x so here we are type casting the value of x to an integer and we are going to compare it using the comparison operator against x only okay so if they both are same then true will be returned else this expression over here is going to return false so the program is complete let's run it and check the output and there you go the program says true which means that 81 is a power of 3 and yes it is 3 to the power 4 is 81. now let's change this 81 to 80 and rerun the program and let's see if it prints false this time or not and there you go the program says false let me change this 80 to 27 which is again a power of three the program should print a true and it has printed true that means this method that we have coded over here is working fine now this was method number one let's look into the second method which is going to solve this problem using recursion for that we'll create one function we are going to call it f underscore power of three this is going to accept one argument which will be n this n so let's create that function over here it will be public static and it is going to return a boolean value so the return type will be boolean we are going to call it f underscore power of 3 and it's going to accept an integer argument which will be n okay the idea is to keep dividing the number n by 3 until it becomes 1 and then return true so first we'll write the code to check if n is equal to 1 or not if it is then we are going to return true okay in the else part we'll write return and make a recursive function call so for that we are going to write f underscore power of 3 but this time as its parameter will pass n divided by 3 okay so let's say if 27 is passed as the value of n then in the successive recursive function call 9 will be passed as the parameter and in the next recursive function call 3 will be passed as the parameter and in the final recursive function call 1 will be passed as the parameter you see every time the value is getting divided by 3. so when n becomes 1 true will be returned all the way to the first function call and then finally to the main function okay but wait a minute we will have to take care of that value of n which is not divisible by 3. so before this else we are going to write an elsif okay and as its condition we are going to check if n is not divisible by 3 if it is not divisible by 3 then the program should return false okay so if 33 is passed as the value of n let's say 33 is divisible by 3 hence false won't be returned but a successive recursive function call will be made and 11 will be passed as its parameter now in the next function call this check is going to determine that 11 is not divisible by 3 hence false will be returned from the second recursive function call to the first function call and finally false will be returned to the main function okay and now we are going to make the function call from here from the main function and we are going to do that from system dot out dot print so within its brackets we are going to call f underscore power of 3 and as its parameter we are going to pass in okay so our program is complete let's run it and check the output and there you go the program returns true when n is 27 let's pass 28 it should return false and it does let's pass 9 this time all right it returns true let's pass 243 which is 3 raised to the power of 5 and again it returns true so this method has also passed a lot of test cases i have already submitted both the methods on lead code the recursion method is faster than the first method that we coded over here and with this we have come to the end of this video if you have enjoyed learning this problem from joey's tech then do let me know in the comment section i'll see you in the next video goodbye and take very good care of yourself
|
Power of Three
|
power-of-three
|
Given an integer `n`, return _`true` if it is a power of three. Otherwise, return `false`_.
An integer `n` is a power of three, if there exists an integer `x` such that `n == 3x`.
**Example 1:**
**Input:** n = 27
**Output:** true
**Explanation:** 27 = 33
**Example 2:**
**Input:** n = 0
**Output:** false
**Explanation:** There is no x where 3x = 0.
**Example 3:**
**Input:** n = -1
**Output:** false
**Explanation:** There is no x where 3x = (-1).
**Constraints:**
* `-231 <= n <= 231 - 1`
**Follow up:** Could you solve it without loops/recursion?
| null |
Math,Recursion
|
Easy
|
231,342,1889
|
211 |
hello guys i'm raj and welcome back to the new episode of competitive programming with python series guys if you are a new viewer to this channel please subscribe it and uh click the bell icon if you have any doubts please comment it on the comment section so today's uh problem that we are going to try for is this lead code problem so here this uh you know this kind of problems are very unique to lead code platform i have hardly seen this type of problem in some other platforms i'm sorry if i don't know about other platforms that there where these kinds of problems are available so i will solve this problem so we have to design and search we have to design our data structure such that we can add words and search word in a very efficient way so the problem statement states that we need to make a word dictionary class so we will have we have the three basic functions that are already defined uh which is init which will initialize the data structure and then we'll have the add word method which will uh add a new word to the data structure and finally we have the search word function which will search uh for a particular word in the present in the text researcher or not so what uh this problem statements says is that we will have a set of words that we are going to you know in uh embedded into the register and then we want to search those uh search any word based on uh like in an efficient way so what uh there is a click there is a small uh you know change or a tweak in this problem is uh this uh that we have will be having a dot uh character as well in whenever we are searching for a word so we will have we will store the words in the register and whenever we are searching for it we will uh apart from the letters a to z in lowercase or uppercase uh we will be having a dot character as well so dot character can be replaced by another character for the subsequent position so let's say i have you can see on the screen as well let's say i have a word bad and i am searching for a word that is dot a and d so here this the first dot can be replaced by a b or any word in the possib uh in the like present in the data structure so for this kind of query so bad uh so that pattern is present in the data structure so we'll return a true or if or false if that pattern is not present in the data section so giving an example uh they have given an example here as well so that first up they are adding bad then dad and then mad then we'll search they are searching for pad so your pad is not present because there are only three words in the register so it will return false then if you search for dot a and d so for dot a and d we have ada of like in most all three words but we can replace this dot by b d or m any uh like any character so here uh this pattern exists in the data structure so we'll return true else uh if it was it wasn't the case that we will we would have written false so making this kind of a data structure is somewhat tricky because uh for every uh like this pattern or a word you have to search for all the words that are present in the data system so the first thing that comes into our mind is hashing right but hashing would be a very good uh way to tackle this but uh here we have dot uh we are going to expect a dot in the query as well so we if we are going to expect the dot then we have to manipulate with the keys so whenever you are using hashing we will be using this awards as key right but if you want to if you have to use the manipulation in the key then that cannot be possible in hashing because in python dictionaries we cannot manipulate or the values of present in the key so we have to think of something else so here uh this problem is very related to the triad data structure so try data structure is essentially something like this so uh try is an extension of tree uh so it stores the words in forms of nodes so here each node carries a character so we'll have the first root node then uh like in the child of this root node we will have different words starting with the first letter so let's i have this four words as an example starting with g and we have geeks gear and g's so we will start off i will take the common uh like the prefix or the first character so like this all four words have the same character uh starting letter s g so we'll only have a single node with g as the root or the child of the root element so we'll have g and then the those are those characters which are common to all words that will where that will take only a single node and whenever there is there are you know different characters possible available at the same position of the words then that will be you know placed in the that will be taken as a different nodes or as the style nodes of the parent or the like the last character so here we have g and double e as like two common or three common nodes and then for k r and z we'll have three child nodes of like the last e or the second e and then for geeks t and gigs uh we have another two channel node of k which is snt so that's how this you know whole structure is made so let's say apart from these four words geeks uh like all the geeks version i have let's say another word name is raj so here r is an altogether new uh like new first character right so we'll be having a new separate uh child of the root which is which will start from r so we'll have a different uh node here with starting with r then we'll have a as the sub child of r or the child of r and then we'll have j as a child of a so that's how we can add new like words in the like in on the fly so they the using this kind of a necessary is one approach to solve this problem but i will have a different approach that i like found out when i was debugging my own code i found this method very useful and very fast as well so we'll have a dictionary as usual so we'll have uh we'll use the root as the name of the dictionary so i will be using uh the default dictionary which is a feature or a library present in the collections library in by it's an inbuilt library of python so i'll be using default and i will take every like every value of the key to be a list so essentially will be i will be storing uh like keys and values as list so that the key will be uh so whenever we are adding a new item to the to this dictionary or this data register i will be storing that word by using the length of that word so you know to make like the such thing uh easy because like we are not we are like we will be we'll be searching for word based on the length of the word right so if you have 1000 words with different number of lengths so then there is no point for checking of other lengths if the length of the search word is 4 and we are try we are comparing it with a length of 5 6 10 and so there is no use right so we are in order to reduce the searching uh area or the searching corpus i will store it i will store the word in a list using the length so what i will do is i will whenever i uh get to know i will whenever i encounter new word to knew what to be added i'll just use the length of that word and i will append the word to that respective t value pair so i will append the word so that's how you can add a new word so here i'm using cells so you don't have to return anything right so now comes the interesting part so now we have to search about right so since we are going to expect dot here in the search word as well so first i have to check if dot is present or not so we have to write separate codes for if the dot is present in the word or else or if it is not present so if dot is not present then i can easily check for uh the words using the like the words length uh like we can get the list of words which are of same length using the length of the word and then i can simply just you know check if the word is present or not so i will check if dot is present in word so i am using the python properties of in operator so if bot is if is dot is not present in the word so i will first take out uh like i will check if the word is fully present or not so if dot is not present then i can simply uh check you can simply return if word in self dot root then i will check for length of word so i will be fetching the list of the words that are having the same length of the search word then i will uh so here i will be getting a list so now as soon as if the word is present in this list and then it will return true or else it will return false so that's what we want a boolean answer if it is present or not so now comes the interesting part where we are having we will be dealing with dots so let's i defined as a set dots which will store the indexes of where the dot is present in the word so i will draw it on the code or i will just go through the each character of the search word so i will write length of word if i will check if the word of i is equal to dot or not so if the character is dot then i will append or i will add the index to the dots dot set so now that i have i know what are the indexes or what are the positions where dots are present so my approach is going to be like if you are like if you uh so make if you can have multiple possibilities or multiple characters present uh can be present like for any dot we can have an alternative of 26 alphabets right so in like if you check for each dot uh for multiple like you make 26 other companies that would be very hectic uh in order to you know try out the combinations and check if that combination is available or not so rather than doing that i prefer to use this method so in which i will uh whatever the length of that searched word uh the words are present i will transform each word to uh into the search word and if the transformation is possible then that is the pattern that we are searching for right so let's say uh you can appear you can see on the screen as well let's say i have a bad word which is stored in the dictionary and i have i'm searching for dot 80 right so now i will try to con convert that bad word into this pattern dot ad so i can add like i have the indexes of dot so i will take the index of i which is 0 and i will take the word bad and then i will try to convert the first character into dot so i will convert the bad into dot ad so which is then now i will compare dot a d and dot a d so dot a dot add mesh so i will return true because we i have found the search pattern or search to work right that's how i will go and i'm going to tackle this problem so now i have the dots uh indexes available so i will loop through all the words that i have in the root directory or the root dictionary with the same length as upward this will essentially will be a small number of strings that are available in uh as compared to the whole uh whole number of strings that are available in the dictionary so now that i have i will save it to a small uh temporary variable so in order to you know not hamper the original value of the string now for each of uh this thing uh for each value for each index in the dot set i will try to transform the string like i will keep the like i if i have an index i will keep the uh the characters behind that index and after that index same and i will transform that particular character or that particular index will i will replace it with the dot so that's how i can i will do so i'll keep this uh like the previous characters as it is i will append a dot in place of that curtain i will keep the rest of the characters as it is so now i will transform each of this uh each of the words like this and that if i will check and then at the end i will check if that is equals to word or not so if this is true then i will return that return to else i will be just like always continuing for all the uh words present in the list and i just i don't found any uh any word with this following our pattern then it will i will by default and false so that's how it is done so let's try this code if this is working or not syntax error don't forget to mention in yes it is working for the test case let's submit this code yes this code is working fine which is 92 percent uh in time and 93 percent in space so this is a very uh handy solution that you can use or you can try to emulate so that's it in this video thank you guys for watching this out if you haven't subscribed please subscribe it uh till then this is dodge signing out
|
Design Add and Search Words Data Structure
|
design-add-and-search-words-data-structure
|
Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the `WordDictionary` class:
* `WordDictionary()` Initializes the object.
* `void addWord(word)` Adds `word` to the data structure, it can be matched later.
* `bool search(word)` Returns `true` if there is any string in the data structure that matches `word` or `false` otherwise. `word` may contain dots `'.'` where dots can be matched with any letter.
**Example:**
**Input**
\[ "WordDictionary ", "addWord ", "addWord ", "addWord ", "search ", "search ", "search ", "search "\]
\[\[\],\[ "bad "\],\[ "dad "\],\[ "mad "\],\[ "pad "\],\[ "bad "\],\[ ".ad "\],\[ "b.. "\]\]
**Output**
\[null,null,null,null,false,true,true,true\]
**Explanation**
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord( "bad ");
wordDictionary.addWord( "dad ");
wordDictionary.addWord( "mad ");
wordDictionary.search( "pad "); // return False
wordDictionary.search( "bad "); // return True
wordDictionary.search( ".ad "); // return True
wordDictionary.search( "b.. "); // return True
**Constraints:**
* `1 <= word.length <= 25`
* `word` in `addWord` consists of lowercase English letters.
* `word` in `search` consist of `'.'` or lowercase English letters.
* There will be at most `2` dots in `word` for `search` queries.
* At most `104` calls will be made to `addWord` and `search`.
|
You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.
|
String,Depth-First Search,Design,Trie
|
Medium
|
208,746
|
1,793 |
Welcome to the runtime error today in this video we will see lead code problem of the day that is maximum score of good so this is basically a hard level question but I don't think so that this is a hard level question because when I solved this question Then I came to know that this is a very easy question, if you have already solved the container with most water question then you will not have any problem in solving this question because we are going to use the same concept of it so Without wasting time let's check what the question says So what does the question say that we have given an integer j are called as numbers which is basically start from zero indexing means its indexing is going to start from row as is usually like our array Along with that, we have been given an integer which we can call k and what we have to do is to find a sub array. Here is our sub array, that is, a minimum number out of that sub array and the product of the length of that sub array. It should give a maximum product right I hope so you got me and whatever integer is given to us k the element at that position must be in my sub array This is what this condition says that i should be less than equal t k and k should be less than equal to j What does this mean is my kth position element must be included in my sub array Right this sub array must contain my kth position element and whatever is my sub array sa is the minimum element in it and my Length of my sub, the product of these two should be maximum. So I hope you understand the meaning of the question. Now let us see the sample input output. Suppose this is our input and the value of k is given. Three, what does this mean? Also my sub array is the element of third index in that sub array must be in my sub array so for example I am taking a sub array as seven ok seven what does it mean I have included seven in my sub array now suppose I am Going as three, I took four, then I took one, then suppose this has become a sub array of mine, okay, what is its length, the length is four, okay now, which is the minimum number from this sub array, which is my minimum number? Is one and what is the length of my saber four So what is the answer Four has come but what is given in the question I want a maximum possible score What does it mean Whatever is my minimum value It should be a maximum one I know this is a little confusing to hear but one thing I can make sure is that if I want a greater product whatever the length I'm multiplying with any of the numbers this number has to be greater right meaning whatever is my minimum number That should be my greater now suppose I am taking a sub array as 4 3 7 4 and 5 now what is the length of this sub array 1 2 3 4 right so what is the length of this sub array is five right and which is the minimum number in this whole sub array Which is the minimum number out of which three is right so I can say if I do 3 * 5 = 15 so I am getting maximum number when I am choose this as my only 3 * 5 = 15 so I am getting maximum number when I am choose this as my only 3 * 5 = 15 so I am getting maximum number when I am choose this as my only right if I include one then will my minimum number will come as One and if I multiply any number with one I am going to get that number only but what is said in the question that I want maximum sum product then to get maximum product I should take care that whatever my minimum number comes It should be a maximum one right end at the end and simply if I multiply it with my length of saber it should give me a maximum answer so I hope so you understood the sample input output as well now let's try to check how we can Derive the solution for this question Now let's check how we can derive the solution for this question In our question two things are given, an er is given and a value of k is given. The meaning of this is that whatever my Saber is element present add index three must be present in my sub array what does it mean element presented index th is seven whatever I am taking sub array must be seven in that sub array from this can I say That whatever I will start my sub array, I will start from seven only because one thing is sure, I have to take seven in my sub array. There four what I will do is I will try to start my sub array from seven and I will try. To go either to the right or to the left Right say for example this is my left and this is my right Now the point is on what basis will I decide whether I go to the left or whether I go to the right there should be Some condition should I move to the right and should I move to the left because anyway I can't move ok go left if I move left then I will get one and one will be the minimum element in my subray then that I multiplied the length of sub by the minimum element, so anyway my answer will be minimum but what is said in the question, I want maximum answer, if I went right, suppose in place of f, if I had one, then here also I would get one. Then this problem will be on what basis we should decide whether we should move to the left and we should move to the right. First of all what we will do is before moving to the right and before moving to the left we will check that the left of the seven is And which is the largest number to the right of seven, three is bigger or four is bigger because what is the problem, I have already told you that what ever is the minimum number is it should be a maximum one right due to which we can get the product maximum if If I choose three then my minimum number will be three. If I choose four then my minimum will be four. Because anyway seven is greater right then I am getting four minimum. Here three is the minimum. Which is the greater one four? So of course I will choose four because at the end I want maximum product right so what will I do for this I am taking two variables from for example my is minimum and from for example answer where am I starting from I am starting from Because of the question, a pre-requisite of the question is that the question, a pre-requisite of the question is that the question, a pre-requisite of the question is that the element of kth index must be there in my sub. Initially there is only one element in my sub. Right this is my length of my sub. What does it mean, I have only one element in my sub. Four is my minimum number, which is the same number which is present in my sub bar, then for minimum number is seven, maximum product is what is the minimum number which is my seven and length of my saber is which is one of mine, then my maximum answer also comes along. I went there four, I also started the answer with that now I will check should I move to the right and should I move to the left so first of all I will check this, if seven to the left is three, seven to the right is four. If I go to three of three then my minimum will be three and if I go to four then my minimum will be four and which one is greater three or four of course four is greater and at the end I want the maximum answer there is four what will I do I will move right since right value of seven is greater than left value of seven there four I will come at four now I will check which is the minimum value in this sub array four which was first seven there Four has come here Four now what is the length What has become my length What has become Two There four Length of sabre is two Right now again I will check the answer What is the minimum value of four What is the length of my sabre two Answer What has come eight is my 8 greater than sen yes then the answer has come eight right now again I will check should I move to the left of seven and should I move to the right of four I will check left of seven is three And right of four then five which one is greater again fa is greater because if I move to left then my minimum value is three then again if I try to multiply with length my answer will be reduced anyhow there for I will choose five And there four I will move to the right so I came here now my length kya ho gayi sub array ki length kitni ho gayi three there four again ma length is updated to three now again from this sub array which is the minimum Value is four my minimum value is already also four now what will be my answer my minimum value is four and my length is three so my answer comes 12 now is my 12 greater than that of course yes there for I will update that then 12 Now One Thing Is Sure I Ended Up Over Here Which Means I Ca n't Go Beyond It Because There Is No Element Here Now The Question Comes One thing is that my right is over but my left is not over So I will try to go to the left but the problem is if I keep going left I will get at the end one and again my product will be reduced there for I will take care of that as I go left What is my minimum element should not change right should not change means what should not be very less okay I will go to three now what will be the minimum value three will be right let me change this so I will go to three left Value so minimum value how much has it become I am three because of this entire sub array which is the minimum value in this whole sub array only three Na Yes now I am length of sub array how much has it become 1 2 3 4 Right How much was it earlier then it was three so now Char ho gayi now what is my answer minimum value is 3a ma length is four so mara answer aa gaya 12 is my 12 greater than 12 no late for i will not update it now again i will check is my four greater right because anyway i can Not go to the right so I'll come at four Then I'll come at four now What's the minimum value What is the minimum value From this hole all are at once again Ma's is a minimum value So three My minimum value is done now What is the length my length becomes five right my length becomes five now my minimum value is thi and my length is five then what will be my answer 15 now I will check is my 15 greater than 12 of course yes there for I will simply update Two to 15 Now again I'll come over here I'll go to the lap pick one Now I've taken one What's the minimum number in all this What's the minimum number What's the one Okay so then the minimum has come One Length increased by one more then length becomes six Right now minimum number is one and length is six answer becomes six Now I will check is my six greater than 15 No there for I will not updated so at the end I will simply return 15 Which is my answer right because 15 is the maximum answer we get from this particular ride so I hope so you understood the meaning behind solving this question, it is a very easy question, I have taught it very easily, now we will see the pseudo code meaning of this code. We will try to write pseudo code for all the things, whatever concepts we have discussed here, so first of all what I will do is I will take a function named f and we will pass in it an array named a n that is my length of My are and k what is this p which is given to us here and what is the most important thing whenever we were discussing this intuition then we discussed one thing that I all are always start from seven because already said in the question Whatever is the value of my k, the element of that particular index must be in my sub array. There four I am starting from seven there for what I did is I took a variable called mean value right because I have to track the minimum value. so that it is not too short delay for my minimum value what will be a of k because I am starting my sub are from this position and again what is my initial answer will also be the same because till now my sub is the same length So if I have only one element then how much will my answer be because minimum value 7 into the length of my subre one so my answer will be sen there for answer also I will link it to the same a from k se now what I will Do is I took two variables like we checked here this is my left this is my right there four again I will take two variables that is left so left is again inila to k and my right also where is inila hai k ko inila hai Meaning, my left is here and my right is also here. Now I will start hydrating, so what we will do is start hydrating while my left is greater than 0 and my right is less n minus 1 n - right is less n minus 1 n - right is less n minus 1 n - what we are doing. Before going to the left we are checking if i ma for is greater and th is greater right meaning what we are checking if er of r is greater than er of r + checking if er of r is greater than er of r + checking if er of r is greater than er of r + 1 right ts region y what I did is take n -1 right ts region y what I did is take n -1 right ts region y what I did is take n -1 So again what will I do here first of all what will I calculate is the left value so this is my left value what will I see in the left value if first of all I will see that my left greater then should be 0 if my greater then is 0 then what should I Want array of left - 1 right which means I'm studying it here I want this value because I want to - 1 right which means I'm studying it here I want this value because I want to - 1 right which means I'm studying it here I want this value because I want to compare this three with this four so that I can decide whether I go to four or go to three right so for that I have this What do I do if ma left is greater than 0 which means I am at the particular range of my array if it is then give me this previous element if not then what do I do should I give zero only because why did I do n because we saw here That first of all my r was finished but see my l is still in the range of that particular a, then we cannot say that my r is finished then finish my a also No there are certain elements at This particular range to there four, we should consider that also, this is the reason why we have put the condition on else here and if in this case even one element is going out of my array then I do not want the element but give zero similarly. I will calculate for write 2 that is write value m write which is it should be less than n - 1 if it is then what n - 1 if it is then what n - 1 if it is then what should I do write + 1 if not then give should I do write + 1 if not then give should I do write + 1 if not then give it cry similarly see here my write is exhausted This means there is no further element here, so then I just return the row because I have to compare this row with the left value, right with the left value, so the same thing I did over here, then we will see if right if my Left value is greater than right value what does it mean I am initially present here then I left value is greater than right value there for I will move left because at the end what we have discussed my minimum value should be maximum there For the side where the bigger element is, we will try to move to that side. For there we will move to the left right. What will we do in that left minus because I came to the left and will update again in the mean value. Mean value is equal to minimum of. Mean value and left because already I have done this minus there for I don't need left -1 else if this for I don't need left -1 else if this for I don't need left -1 else if this condition get false then what I need to do is I should go to the right so again what I will do is I will simply Do right plus and again I will update my mean value t mean value is equal to minimum of mean value comma a of right and at then what have I said we will look at the answer that is minimum value from my sub are into my length of sub Hey then I got eight and every time I will check with this answer is it greater than 12 yes update now comes 12 is my 12 greater than 8 yes update 15 comes is my 15 greater than 12 yes update so Every time we will update if I am getting the answer greater than the previous answer right so here I will write what I will write is the answer is equal to maximum answer because we need a maximum one so maximum of which means is the minimum value right this Is my minimum value into what I need to do is length of my sub are and what will be my length of sub are that is right minus left pw right and finally at and what I will return I will simply return answer so this is the simplest Code I have written I hope so you understand this first what we did is what we did initially is the value of k is the minimum value because I have to start from here so my left is also on here, right is also on here. So the same thing I did over here, my answer is also the same, the minimum value is also the same, this is a very important stage because we know that at the end, whether my left will finish first or my right will finish first, then due to this, if one of them If any one is finished then I don't want an element, I want zero, that's why we have written both these conditions and at the same time I have simply said whether to go to the left or to the right. On what basis will we decide whether to go to the left? Or where on the right is the maximum value, we will move to that side. So I hope you understood this pseudo code and intuition for this code. Now let's try to check what will be the c+ p and the java code for this. This the c+ p and the java code for this. This the c+ p and the java code for this. This is the CPP code. And this is the Java code, you can see the language in which k is table, so first of all what we did was take the length of the array, so first of all I took two variables that is left and right and what we said that k is Whatever value is given, we have to start from there, so the same thing we did over here right, so I started the left and right from K and what is the most important thing, I am starting from the particular index where my k is there for me, what is the length of all r, it is the same and what is my minimum value, that is my minimum value, where is the minimum value into length, how much is one, my answer is kitna aa gaya, that is aa gayana na there for me, I have given the answer. Also, my minimum number is initialized with the same number, so at this point, what I checked is that the left is greater than 0 and the right is less than - 1, so here 0 and the right is less than - 1, so here 0 and the right is less than - 1, so here also I put that condition. So again I have written two important conditions here that is left value and right value that is if my left is greater than which means I am in the range of the array then give me its previous element if the range of my array is to the left side. It's over so don't give me the element because we are going out of index. What I need is just give me zero instead because at the end I have to compare the maximum value. Late for zero won't make any difference to me. Similarly for right if my right What does it mean here, if I am not going out of bounds, I am still here, that means there is an element for, give me five returns and if I am standing at the position of five, there is no element next to it, then Give me zero return because there is no element ahead of it so same thing we did for left value and right value then we checked left value is bigger right value is bigger so we try to move to the side where my value is bigger So that whatever is the minimum value we can get the maximum so same thing we did here if my left value is lesser than the right value then we have to go to the right and at the same time I updated the mean value similarly if I have to move towards left, the value of left is bigger than the value of right, I have to come towards left and I have updated the mean value and at the end, I am updating the answer for every position, if it is maximum then my answer is into minimum value of. My Sabre, now whatever is my Sab Arre, what is the minimum value out of which we are multiplying it by what is the length of my Sab Arre and whatever is my updated answer, I will store it in my answer and then I will finally return the answer. This Was The Most Simplest Question Just Hard Bola Hai Lit Code Ne But I Don't Think So That This Is A Hard Solution For This So I Hope So You And Understand This Question Really Well If You Are New To Our Channel Hit That Subscribe Button So That You can get a daily updates on placement interviews and lead code solutions till then i 'm
|
Maximum Score of a Good Subarray
|
minimum-moves-to-make-array-complementary
|
You are given an array of integers `nums` **(0-indexed)** and an integer `k`.
The **score** of a subarray `(i, j)` is defined as `min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1)`. A **good** subarray is a subarray where `i <= k <= j`.
Return _the maximum possible **score** of a **good** subarray._
**Example 1:**
**Input:** nums = \[1,4,3,7,4,5\], k = 3
**Output:** 15
**Explanation:** The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) \* (5-1+1) = 3 \* 5 = 15.
**Example 2:**
**Input:** nums = \[5,5,4,5,4,1,1,1\], k = 0
**Output:** 20
**Explanation:** The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) \* (4-0+1) = 4 \* 5 = 20.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 2 * 104`
* `0 <= k < nums.length`
|
Given a target sum x, each pair of nums[i] and nums[n-1-i] would either need 0, 1, or 2 modifications. Can you find the optimal target sum x value such that the sum of modifications is minimized? Create a difference array to efficiently sum all the modifications.
|
Array,Hash Table,Prefix Sum
|
Medium
| null |
218 |
today we're gonna be working on lead quote question number 218 the skyline problem a city skyline is the outer contour of the silhouette formed by all the buildings in that city uh when viewed from a distance uh given the solution given the locations and heights of all the buildings i returned the skyline formed by these buildings collectively so every building is going to have a left a right and the height the left of i is the x coordinate of the left edge of the ice building right of eye is the x-coordinate right of eye is the x-coordinate right of eye is the x-coordinate of the right edge of the ice building height is the height of the ice building now you may assume all buildings are perfect rectangles grounded on an absolute flat surface at height zero the skyline should be represented as a list of key points sorted by their x coordinate in the form x1 y1 x2 y2 each key point is the left endpoint of some horizon horizontal uh segment in the skyline except the last point in the list which always has a y coordinate zero and is used to mark the skyline's termination where the rightmost building ends basically what he is saying is like when we're going to be returning our skyline basically x and y is x is going to be our height right there okay this is the height and this is the x is the hydrogen when we're returning here no x is the x coordinate y is basically the height of that building yes uh so in the end we're going to be returning 24 0 basically meaning that the last one the height is gonna be equal to zero and the distance or the x-coordinate is the distance or the x-coordinate is the distance or the x-coordinate is gonna be uh pointing to the end of the skyline that's what he is talking about okay uh mark the skyline termination where the right most building ends any ground between the left most and the right most building i should be part of the skyline's contour and there must be no consecutive horizon horizontal lines okay of equal height in the uh in the output skyline for instance two three four five seven five eleven five yeah basically they all have the heights 5 12 7 should be merged together so we should actually have mentioned 4 5 where the height changed from 3 to 5 and then after that we shouldn't mention all these points until we are here 12 7 where the height again change it's not acceptable the three lines of height five should be merged into one of the final one in the final output so basically in this example if the buildings are 2 9 10 starting at 2 9 is where it is ending and 10 is the height so left starting point right ending point and the height that's how the buildings are given and the output is going to be 210 which is this one then the 315 and then 712 then yeah 12-0 yeah 12-0 yeah 12-0 so that's how we're gonna do it in doing it so we're gonna be making using a use of like some of the uh the libraries uh in python which is basically he push and he pop so that we can get the largest element inside the heap so for that we're going to be doing the from heap q import heap push and heap pop these are two uh functions we need what we're gonna be doing is like basically we're going to be creating the events every building is going to get converted into events uh so our events are going to be equal to basically three things right uh one is the left right where the building starts one is the negative of height and one is the right where the building ends the negative of height is taken because this function heap pop returns you the minimum element but we are not interested in getting the minimum element or minimum item we are interested in getting the maximum height so we're going to be putting all the events using negative height so that when we are using the heap pop on the height we can get the building with the maximum height okay and this is uh sorry for l r and h inside the buildings so for if we go through if we iterate through the buildings this is for every single time we're gonna be getting three things left right and height we are putting them as events where every event is left the middle one is the height and the right one is the you know the right of the building where the building ends once we are done with that we need to have we need to include the event where the building ends all the contour like the contour ends for that one we need to add an event where we're gonna say that it's a list of uh it's a list of the right zero and then the zero so what we are doing is like we are taking the last element right so four one two four yes for uh we are not we don't want to take we don't want to worry about the left for the last event we don't want to worry about this and the last uh the starting of the building we just wanted to know where the building is ending and we don't worry about the height either because this is the event where our height is gonna be zero in buildings so this is where we will be able to successfully add the last event where we know that okay the buildings ends here okay and then we're gonna be sorted and the way it's gonna be sorting it is on the base on the first element which is the where it is starting so it is start it is going to be sorting and from left to right this should be events okay the second thing we want to do is uh our result is going to be equal to the x coordinate which is the x and the height right so the result we're going to initialize uh we're going to initialize it as zero the zero and then we have every single time we're gonna have a live building which we're gonna be working on so the live building we're gonna initialize as 0 which is again the negative of the height so the height for every single time it's a what is the height of it and what is the ending position so we're going to initialize our ending position at the beginning to infinity so that would be infinity again uh again the result is basically equal to like the x and the height right and the life is basically equal to the negative of height and uh the ending position okay so once we have initialized it all we have to do is like we have to iterate through all the events for and what we're going to be calling them in the uh when while iterating is the event has a left point yes uh so it is going to have a left point okay and it is gonna have the negative of the height and it is gonna have uh and the right point uh where it is ending so we're gonna ignore the right point because uh we are actually documenting the left here so that's going to be our position so the left is going to be our position we're going to document negative h and the r uh which is gonna be the right like that where the uh where the event ends but we are more uh because we are actually documenting or we're gonna be uh making it uh keeping the record of where the building starts so we're just gonna call it r right but mainly we are uh more concerned about the position where the left which is the left of the building and where the building starts so for every single time in this we're taking these three things from an event we're doing basically first of all we are trying to get the highest uh building right so for that one what we're gonna say is like uh while the live we're gonna check is now so the live again is the negative of the height and the uh the like the end position of that so we're gonna take the first the live building and uh we're gonna take the second like the second element of that which is the position uh the end position where it ends right if that is less than equal to the position or while that is less than equal to the position you're gonna keep uh getting the keep removing and get and making that one heap pop live we're gonna keep removing the element and keep getting the shortest uh one with based on the height uh which is the negative height which is eventually gonna give us the tallest building so we're gonna keep doing that until that condition is there the second one is uh if we have the if the negative h exists in that case we're gonna keep pushing uh the building into our uh like the live uh heap so for that we're gonna say live and what we're going to be pushing it is a building which is the negative h and r so every we are actually making pushing that one into the heap and uh because while we are gonna be getting it every single time we're gonna we are at adding that element to the heap whether or not that's gonna be in the front or not depends on the height because that is basically depending on when we are doing the heap pop uh so based on the height we're gonna be uh making sure that which one is gonna be the live uh building and in the end we're gonna say that uh like basically we're gonna compare our result uh like the results the last result we added to the result uh a result list and the current the live one so for that if the result of the last like the last element and the one basically the result one is the height if that is not equal to negative uh negative life of because basically we are trying to get the height here and we have to do the negative because we already saved the negative height of zero if these two things are not equal that means we need to put uh the new build like the new point in the result so when we are putting it here we have to use position and the height is the new height of that one and in the end we're gonna be returning the result uh but we're not gonna be taking the first element uh because that's going to be 0 so we are returning result with 1 onwards event does not exist looking good so far yep and it did pass all the test cases
|
The Skyline Problem
|
the-skyline-problem
|
A city's **skyline** is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return _the **skyline** formed by these buildings collectively_.
The geometric information of each building is given in the array `buildings` where `buildings[i] = [lefti, righti, heighti]`:
* `lefti` is the x coordinate of the left edge of the `ith` building.
* `righti` is the x coordinate of the right edge of the `ith` building.
* `heighti` is the height of the `ith` building.
You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height `0`.
The **skyline** should be represented as a list of "key points " **sorted by their x-coordinate** in the form `[[x1,y1],[x2,y2],...]`. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate `0` and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour.
**Note:** There must be no consecutive horizontal lines of equal height in the output skyline. For instance, `[...,[2 3],[4 5],[7 5],[11 5],[12 7],...]` is not acceptable; the three lines of height 5 should be merged into one in the final output as such: `[...,[2 3],[4 5],[12 7],...]`
**Example 1:**
**Input:** buildings = \[\[2,9,10\],\[3,7,15\],\[5,12,12\],\[15,20,10\],\[19,24,8\]\]
**Output:** \[\[2,10\],\[3,15\],\[7,12\],\[12,0\],\[15,10\],\[20,8\],\[24,0\]\]
**Explanation:**
Figure A shows the buildings of the input.
Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list.
**Example 2:**
**Input:** buildings = \[\[0,2,3\],\[2,5,3\]\]
**Output:** \[\[0,3\],\[5,0\]\]
**Constraints:**
* `1 <= buildings.length <= 104`
* `0 <= lefti < righti <= 231 - 1`
* `1 <= heighti <= 231 - 1`
* `buildings` is sorted by `lefti` in non-decreasing order.
| null |
Array,Divide and Conquer,Binary Indexed Tree,Segment Tree,Line Sweep,Heap (Priority Queue),Ordered Set
|
Hard
|
699
|
244 |
let's go through liquid 244 shortest word distances distance okay and two right distance to um but this question is give us the word dictionary which is a string array and also what I want and a word too and let's find the shortest distance um we can take a look at the example the word dictionary like a practice make perfect Kodi mix and now let's see the coding um we have indexed 0 1 2 3 4 coding index is straight and practice the index is true so the distance this one is the one and the Max and coding um make uh appears at index one for and coding appears that street so here the distance is true here the distance is one right so we know for every query the world one may appears multiple times um in the world dictionary you know uh what was it to have the same behavior to me appearance multiple times so what we're thinking about is that for every word in the word prediction we create a list um to stop its indexes for example we have for the coding uh or let's like make sure make uh it will have one in fortnite so uh we're going to create a map the key will be this word and the value a list of indexes and uh when we compose this map what I would have been to do is that we use this word one word to get a uh each list for example at least one might be the world ones indexes and at least two probably the word tools indexes for example if we have one so one three five and the word two which appears at 2 7. 8 right so we can use the two point her so one is this one pointer I another is so allergic pointer and uh index and uh also we have the while loop in the inner layer apology and we have if distance while distance I and J is greater than distance i j plus 1 will have to keep it moving right when doing um this is the following four I something little while loop right when uh moving out of the while loop We compare get a minimum distance between an ing for one specifically and globally we have a minimal distance and I try to get the minimal value Global value that will be this result okay so let's begin to write code for this and uh because every word there are distinct so this there is no duplicates we don't need to care about whether this greater or greater equal to right so we just arrived greater will be fine so let's begin to record for this we're going to create a map and we have the word and the screen as a key and the list of the integer uh index that's a value we use two pointers because when we compose this map uh the list is already sorted uh so we don't use them as it's already sorted um we use two pointers that will be o uh N1 and uh into uh maximum and one into right if we have a sorting to the binary search um if we do spanner search even we don't need to sort by research that will be for each one will be a logger for example we search where to be logger into so that's what M1 and one multiple button into the 10 complexity will not be better than the two planets um so the question is very similar to the hitters question uh so let's begin to write a call for this map personal hash yeah um and uh we are going to how data Index right well in my equals addiction right after last five plus the words dictionary I mean and uh well how not computer for absence um or a close to new array list and um having this IRA so um what we're going to do is in your chair is what was the map it where the one it is 2 equals map but forget to order two nine uh we have shots is about it right let's have that I see that outside um smaller than list one dot size uh plus Nosa wow there's a j Loop JS summer and list two little stars and um abstract um these the two data Theta ji um minus this one beta uh I as long as this one is greater than greater than the next one right so we'll move the J pointer as long as this one is put again next one well you know um so uh let's see we have two plus one so we should have this one to be smarter than GMS one right two plus and we just have a greater sign here should be fine and we have a result equals the next mean result uh we moving out to this one that means but this I will get the shot is the distance and then we can't result now
|
Shortest Word Distance II
|
shortest-word-distance-ii
|
Design a data structure that will be initialized with a string array, and then it should answer queries of the shortest distance between two different strings from the array.
Implement the `WordDistance` class:
* `WordDistance(String[] wordsDict)` initializes the object with the strings array `wordsDict`.
* `int shortest(String word1, String word2)` returns the shortest distance between `word1` and `word2` in the array `wordsDict`.
**Example 1:**
**Input**
\[ "WordDistance ", "shortest ", "shortest "\]
\[\[\[ "practice ", "makes ", "perfect ", "coding ", "makes "\]\], \[ "coding ", "practice "\], \[ "makes ", "coding "\]\]
**Output**
\[null, 3, 1\]
**Explanation**
WordDistance wordDistance = new WordDistance(\[ "practice ", "makes ", "perfect ", "coding ", "makes "\]);
wordDistance.shortest( "coding ", "practice "); // return 3
wordDistance.shortest( "makes ", "coding "); // return 1
**Constraints:**
* `1 <= wordsDict.length <= 3 * 104`
* `1 <= wordsDict[i].length <= 10`
* `wordsDict[i]` consists of lowercase English letters.
* `word1` and `word2` are in `wordsDict`.
* `word1 != word2`
* At most `5000` calls will be made to `shortest`.
| null |
Array,Hash Table,Two Pointers,String,Design
|
Medium
|
21,243,245
|
33 |
Hello friends today Arvind subscribe number three and click the subscribe button and subscribe my channel subscribe it subscribe hai ki want to spend side by side arrest 3242 subscribe script writing note subscribe and subscribe our Channel subscribe and subscribe the Channel Shampoo Per Cent In 90s Quite From The Difference Between The Elements Subscribe And Subscribe For Number In Hindi YouTube Scan Not True Or Not Hidden Cam What Is The English Of Five Is Forces 1234 500 600 Simple Problem Subscribe You Will Cost You See Weather Your Middle Element subscribe The Video then subscribe to the Page if you liked The Video then A Nizam - One Is The Middle Element Is Not A Nizam - One Is The Middle Element Is Not A Nizam - One Is The Middle Element Is Not The Great Number 80 Right Side Of The Middle Element It Is Between And His Middle Element Is Equal To Do subscribe function are skilled in the target subscribe and subscirbe not specified language English language start from the best in the land of - subscribe left best in the land of - subscribe left best in the land of - subscribe left a plus right - left divided by too poor raw two a plus right - left divided by too poor raw two a plus right - left divided by too poor raw two in whichever plus are the advantage of subscirbe boys pet saaf Can Result In To-Do List Subscribe Now To Two To-Do List Subscribe Now To Two To-Do List Subscribe Now To Two To Your Left This Loot Subscribe Topic Subscribe Now To The Number You Later This Is The Great 123 Your And Number This Inside Left Side She Writing This Page So You Will Find THE VALUE OF ARE YOU JUST NEED TO SEARCH IN THIS POINT 1 - Click Subscribe button on right side from subscribe number initially pomegranate vain target ki saini style ireland 70 etc white weakness lums embroidery 499 500 600 subscribe and subscribe the Channel subscribe Text A Target Screen You Can Start With Loot 6 To Three Lamb Skin Three Do You Will Need To 200 Comes To Click Subscribe Button On The Right Side That Exit Point In Chief Air Tight Dresses And Easy To The Number On The Left Side Is This Is Not Possible for a greater noida subscribe is greater than age samuel there right side cutting this is that point collect so they have to modify this fiction and half basirwas subscribe school that we make it one in your target is vansh varchanam subscribe element subscribe started bhi to Fikr Hai 135 Dhund Arvind subscribe The Video then subscribe to The Amazing and Element subscribe
|
Search in Rotated Sorted Array
|
search-in-rotated-sorted-array
|
There is an integer array `nums` sorted in ascending order (with **distinct** values).
Prior to being passed to your function, `nums` is **possibly rotated** at an unknown pivot index `k` (`1 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,5,6,7]` might be rotated at pivot index `3` and become `[4,5,6,7,0,1,2]`.
Given the array `nums` **after** the possible rotation and an integer `target`, return _the index of_ `target` _if it is in_ `nums`_, or_ `-1` _if it is not in_ `nums`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[4,5,6,7,0,1,2\], target = 0
**Output:** 4
**Example 2:**
**Input:** nums = \[4,5,6,7,0,1,2\], target = 3
**Output:** -1
**Example 3:**
**Input:** nums = \[1\], target = 0
**Output:** -1
**Constraints:**
* `1 <= nums.length <= 5000`
* `-104 <= nums[i] <= 104`
* All values of `nums` are **unique**.
* `nums` is an ascending array that is possibly rotated.
* `-104 <= target <= 104`
| null |
Array,Binary Search
|
Medium
|
81,153,2273
|
479 |
hey what's up guys yeah just for fun yeah so that song is a little 479 largest perimeter product okay so this problem is very bad and very many people don't do not like it so given array end return the largest parent or integer that can be represented as a product to an integers in the written module one three seven okay so on n equals to one is nine uh this problem uh is uh for example not equal to 978 basically you can find 99 times 91 which is nine zero nine right so this guy's a pairing drum and uh 987 right so basically you need to find a two so basically the problem is that you need to find a let's say a1 up to a n which is on digits and a b1 of bn which is undigits and other products is a pattern draw okay it's a parent okay and you can see the answer uh n equals one from eight right so that means this problem is so difficult that you almost need to use the uh some careful force to solve it right otherwise that the problem if there is some trick before it is then it should not be so small okay so the first two uh i think was one and nine and you go to 987 that we i we can just record right because we only need to find the rest okay so uh one what idea is that use proof force right you can uh use the peripheral solution let me just see for that you guys see the peripheral solution and we can talk about the other one right so this is proof of solution right so for uh oh sorry this is not reversed i think it's uh yeah okay yeah let me just introduce the solution okay so uh the solution looks like this but basically ready so this must be two n right so the idea is that uh you know the what is the possible answer what was the possible idea uh what's the upper bound for answer upper bound must be 10 to the power eight okay the reason is that uh sorry at least upper bound means that uh the 99 right so you start from 99 and your lower bound is a 10 right so this operating door means that the all the possible the bounds for the possible uh number that you can use okay and you need to start from upper and the lower and minus once basically you start from upper right you start from 99 and then you ask you know let's say your t to be straight i and uh reverse so this will give you a playing draw also maybe it is a very hard to understand let me just introduce so for example uh so i start from 99 right and this is my first check and i add 99 to this right 99 so i need to add square i can find two integers x and y such that uh x is two i digits why it's two digits right i can check where this issue if this is not true then i go 99 and i go 98 right and then i need to microphone 89 right and where is it if not true like 97 79 if it is it's not okay i go 96 69 right and then this is the and once you keep going then you will find the answer will be nine zero now okay all right this is a step that i that's very simple right so the idea is that i start from so these t is what we want to do right and then we i change it into the string and i start from upper and check that whether this guy leaves j square greater than t okay the reason is that uh if j squared is less than t that means i don't need to check right then i need to check that where t is modulo j is zero right so basically for example from 9999 i need to check that whether these guys divisible by 99 okay maybe something if this is not true like check for 999 is divisible by 98 something right if it is not true then i keep going until that i find something which is divisible right so for example if i find 99999 up to maybe something time something if this is true then i get it right so this is somewhat careful proof but almost reverse right so this j squared greater than t something that you need to check if j squared is less than t that means you don't need to check right so if t modulus is zero then you return t module one three one otherwise j minus one the minus one it means that your check queries 98 97 so this is just careful real fast it's not there's no shape for it right so you just do this and the list is uh almost can solve so almost and solve this problem but probably uh i think this is the best that uh that you can do right i mean for a complexity right i mean if you for this check that this is small yeah okay so see you guys next video
|
Largest Palindrome Product
|
largest-palindrome-product
|
Given an integer n, return _the **largest palindromic integer** that can be represented as the product of two `n`\-digits integers_. Since the answer can be very large, return it **modulo** `1337`.
**Example 1:**
**Input:** n = 2
**Output:** 987
Explanation: 99 x 91 = 9009, 9009 % 1337 = 987
**Example 2:**
**Input:** n = 1
**Output:** 9
**Constraints:**
* `1 <= n <= 8`
| null |
Math
|
Hard
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.