id
int64 1
2k
| content
stringlengths 272
88.9k
| title
stringlengths 3
77
| title_slug
stringlengths 3
79
| question_content
stringlengths 230
5k
| question_hints
stringclasses 695
values | tag
stringclasses 618
values | level
stringclasses 3
values | similar_question_ids
stringclasses 822
values |
---|---|---|---|---|---|---|---|---|
1,672 |
Hello Everyone Welcome and Welcome Back to My Channel Suggestion or Going to Discuss the Problem 15.25 Lite Video Please Like Problem 15.25 Lite Video Please Like Problem 15.25 Lite Video Please Like and Subscribe My Channel Thank You Get Notified When Most Innovative Swift Dedicated Problem is Research Customer Wealth Very Simple Problem Lecture and Crops and Interior Grade Account The Account Of Eyes Where Is The Amount Of Money Obligation Customer Is Jain Spiritual Returns Dave Dadar Is Customer Hath Twitter The Wealth Turtle This Amount Of Money Chauhan Vinod And Bank Account Is It Is Customer Argument Maximum With Person Turn On The Maximum With Latest Updated What is given to assistant this value desire zdi and sez fixing 021 account that i j what is this recent this representatives responsibility customer is customer that fans accounts of i j value test match in the bank account id value indore izzat bank account It's the British over here growth customer emphasis customer health 151 d0 bank account it's a super rich customer what do you tell me to point customer back to count how much is the total wealth dart customer help 10.30 am customer how total wealth dart customer help 10.30 am customer how total wealth dart customer help 10.30 am customer how much wealth jio customer is relax bank Account It The Bank Account 2012 Bisaria Bank Account And How Much The Total Events Total 20 One Plus Two Plus 303 Six Similarly This Post Customer How Many How Much Wealth Three Plus Two Plus One 6 Total Wealth Maximum Will Take Only Will Return 7766 Ko Hain Pisi For This Taken Take Care Over A Year They Have Written 0123 Customer Number Of Rose Water Customers And Kollam Is The Bank Account Dr To Bank Customer On Right Side Customer Oneplus 6 Customer Maximum Do 10th That You Pimple Question Were Just Going To Zero where going and finding possibly columns and they are updating the maximum wealth to what we will do it is what we will do e will take available discretion available maths wealth in hence civilized 202 will go to ISRO will calculate the sum of the calling seekers Senior Research Is This Is Greater Than Maxwell's Updated Express Delhi To Connect With Letter Samudra Column 600 Is Grade Film Actress Gas Updated On Ki Devi Godhan Extra Vidhi What Is The Song Of The Calling 7 Plus Path Bread Or No Pages To Return To Top That to after registration will get the maximum will take is this is open today approach and the electric in a soon shivering simple science what were taking rating initially available max health 10th winding road and columns and danger of creating or friends this for this wealth visible for Each Person After Each Customer And Calculating Asadhya Columns Practice All The Best Customer Is By Which Bank Accounts Of Wealth Creators And They Will Update The App Will Return Full Time Tour And Travels And Tours Slum Sorrow In Love With 14 And Kulwinder Biscuit Interview Questions Soen But They do and please subscribe my channel thank you
|
Richest Customer Wealth
|
find-the-index-of-the-large-integer
|
You are given an `m x n` integer grid `accounts` where `accounts[i][j]` is the amount of money the `ith` customer has in the `jth` bank. Return _the **wealth** that the richest customer has._
A customer's **wealth** is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum **wealth**.
**Example 1:**
**Input:** accounts = \[\[1,2,3\],\[3,2,1\]\]
**Output:** 6
**Explanation****:**
`1st customer has wealth = 1 + 2 + 3 = 6`
`2nd customer has wealth = 3 + 2 + 1 = 6`
Both customers are considered the richest with a wealth of 6 each, so return 6.
**Example 2:**
**Input:** accounts = \[\[1,5\],\[7,3\],\[3,5\]\]
**Output:** 10
**Explanation**:
1st customer has wealth = 6
2nd customer has wealth = 10
3rd customer has wealth = 8
The 2nd customer is the richest with a wealth of 10.
**Example 3:**
**Input:** accounts = \[\[2,8,7\],\[7,1,3\],\[1,9,5\]\]
**Output:** 17
**Constraints:**
* `m == accounts.length`
* `n == accounts[i].length`
* `1 <= m, n <= 50`
* `1 <= accounts[i][j] <= 100`
|
Do a binary search over the array, exclude the half of the array that doesn't contain the largest number. Keep shrinking the search space till it reaches the size of 2 where you can easily determine which one has the largest integer.
|
Array,Binary Search,Interactive
|
Medium
|
786
|
107 |
Ko Camera Badi Today They Are Going To Discuss Level Model Transfer Suggestion Thursday That Anirudh Next Level Badji Soft Shiny E F Will Find Love Letter Will Be Amazed To See If Implemented On A [ __ ] Sports Special Guest Is The Freedom [ __ ] Sports Special Guest Is The Freedom [ __ ] Sports Special Guest Is The Freedom At Midnight Children Will Be Removed From Children Who Will Return Of The Day Travel In Which All The Animals For The Current Levels Will Get To Exit Point After Time I Know You Will Not Go To Wear Look And Removing Them Into Your Final Result To Give Up Perfect First Bottom To Top 100 Words Will Simply Dress Will Reverse Of Result India that
|
Binary Tree Level Order Traversal II
|
binary-tree-level-order-traversal-ii
|
Given the `root` of a binary tree, return _the bottom-up level order traversal of its nodes' values_. (i.e., from left to right, level by level from leaf to root).
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[15,7\],\[9,20\],\[3\]\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[\[1\]\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-1000 <= Node.val <= 1000`
| null |
Tree,Breadth-First Search,Binary Tree
|
Medium
|
102,637
|
1,024 |
hey what's up guys this is chung here again so today let's take a look at 1024 video stitching okay so you're giving like a series of video clips from a sporting event blah that lasted 2 seconds and these video clips can be overlapping with each other and have varied length and every video clips is interval okay and it has a starting time and an ending time and we can cut these clips into segments freely for example eclipse can be cut into a different any of the length and it asks you to return the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting events from 0 to t if the task is impossible return minus one i mean this part is like a little bit of con confusing you know basically as you guys can see if you just by simply looking at this like the other the examples here and this one is actually uh an interval problem so what it's really asking you to do is given like this kind of intervals and also a range from zero to this t here you need to find out this the minimum number of intervals you need to uh you will use so that you can make the range cover until this t number here yeah and that's basically it is and if it cannot cover to t simply return minus one for yeah just uh same as this example two here because this zero one and one two you can only cover from zero to two right i mean you cannot reach five that's why it's minus one yeah and the constraints is like they're always in the range of one of 100 okay so every time i mean when you guys see like interval problems you know sorting is always should be the first thing that comes to our mind right same thing for this problem i mean we sort right first thing first the thing first we sort by the start time okay all right so after sorting by the start time now we just need to find the uh we just need to find the smallest intervals we uh we can use so that we can reach the time t here right and so from here onward we have actually there are like two ways to solve this problem the first one is obviously the dp because it's getting asking to get the minimum right so dp is always one way and the other one is what is a greedy yeah actually so for this problem grid is also a solution all right so let's try to do it with dp okay how can we uh so the dp right so when i define the dp here you know i'll define like this dp the length uh i'll define it to like 100 uh 100 101 so the reason being is that you know even though we're only asked to check until this t here right but you know the clips range the total length is from 0 to 100 and when we are later on when we uh looping uh traverse these clips here you know the index could be uh greater than the t here i mean we can also do a early stop right but i'm just gonna to uh initialize this thing since it's not that big so it doesn't really matter right if we do a 100 or 200 right so and since we're it's asking us to get the minimum values so i'll initialize everything with system max size here okay and of course the n is the length of clips right so this dp what does this one means it means that you know at this location right or at this time at ice time what's the minimum intervals right we need to use interval pretty straightforward right and in the end we simply do a dp t here right so this dpt will give us the values we need all right cool so in order to do that you know since we have already uh sort we have already sorted these clips here that's why we can simply start processing from the first one to the end so for each of the clips here it has a start time and end time okay and the base case is dp 0 equals to zero so what does this one mean it means that um to i mean to cover until the time zero time how many clips we need zero because there's no time right that's why the first thing is zero so and now we have a start and end for each of the clips right so what should we do here i mean we have a start and end and uh for i in the range of start of starts to end plus one so it means that you know at the current eye here because this means that the current clips can cover from s to e plus one this is a ring it can cover okay sorry this one is um in here and for each of the range the current clips can cover we can simply check we can simply do a dpi here right to do what equals the minimum of the dp i plus what plus the dp s plus one the dp i or the dp has plus one so what does this one means it means that you know to get to the current state right to get to the current state you know since we are having right i here so the dps means that's the starting point of the current range right and if we know that you know basically this one set is saying that from the last step to get to the current step right and what because from the dps means that to get to the starting point what's the minimum steps what's the minimum clips we need to get to that to the starting point of this of the current clips and then since uh plus one means that we are adding the current clips okay and so and for each of the clips we're doing the same thing here right and then in the end we can simply return what the dpt right and we also need to check the if i know this is a minus one case so when will this minus one happen it means that let's say if we cannot we can never uh reach the t here it means that you know the d the value for the in the dp t will be what will be this one will be uh will be the number even greater than this one because we're doing this kind of like d s uh ds plus one if we cannot can never reach that you know uh the value will be i'm sorry it's not greater it will be still the same as the dp the maximum value here so we can simply do this right so we only return if the dp t is smaller than the system max size right else minus one yeah so let's run the code here okay so the test case passed submit all right cool so i mean i think we can't have like a sim early terminations here like d i know if s is greater equal greater i think s e co were greater than the t i believe we can save safely break here because we know we don't need that because those clips we will not be using those clips for stitching and tlt here right i think this should also work yeah it doesn't really matter but as you guys can see here that's why i defined this 100 because you know for the case of the uh of let's say the clips is pretty long but the t is like small right that's why i need to is there like a t here yeah for example this one right in example four here if we use t to define dp here and when we are traversing from two to eight you know this dpi will be uh out of the index right because the 8 is greater than t that's why i define this 101 yeah so that so this one that's it right so and the time complexity for this one is the uh so we have a range right so let's say the range is for clips we have clips that's n right n times what n times the uh this is the uh the range of the clips and it's also like uh 100 so it's going to be a n times in right and for the space complexes it's all of n right that's a space and that's the time yeah so that's the basic dp solutions basically you know we just uh we stored the chips we start we store the clips and then since it's the clip is sorted we can start processing it from the first one and every time when we're at the i mean these current clips the previously started clips have already been prop have already been processed that's why we can just update the current dpi with the previously with the starting point right then the plus one cool so that's a dp right and now how about the greedy right so the greedy is also kind of like uh easy to understand you know let's say we have a few uh intervals here let's say we have this one and we have this one okay and then we have a bunch of others like the uh let's say we have this one something like that right as you guys can see so the first one we have they're all starting from zero right so if they start starting from zero let's say we're at this location right we're in the middle of here so the greedy way is that you know within the range of the current basically if from the current range that we can reach okay we're trying to extend our father our furthest place we can reach as much as possible and so from so for the first one we will pick from between zero one and two here we pick number two here because the number two is the furthest one we can reach that's why for the first one we have one the first uh clip is one and then for the second one right and for the second eclipse we'll start processing again but keep in mind here we don't need to uh process zero one and two here because we are we have already sorted the clips and we'll once we have processed that clips we can just ignore them we can just leave them behind so from here after this after processing zero one two our maximum end is right here that's the end and now for the second eclipse for the second clip we're starting from this three and number three clips and the number three clips is within the range of the current end which means we can pick that okay and number three we can keep and then we have also have a number four basically you know for as long as that the clips is in the range of this current end we can use them and then at the second round we also try to extend our ending the end as long as much as possible so at the uh at the second round right so we will be basically we'll we're picking this number four here because the number four gave us the longest end here so this is the first stitching the first eclipse and this is the second eclipse and we do it until we reach the uh until we have reached the uh until the n is greater than the t right and then we know okay we have find the uh the solution and with that and by then the answer will be the minimum we need because we are using a greedy approach here we're trying to reach the uh defaulted i mean the farthest place uh we can by using the current uh the current available uh clips and then we will try to switch to a next set of clips we can use and then we try to extend the farthest place we can reach and how about this minus one case right so the minus one case happens uh when the uh when during uh when there's and when we cannot extend this uh this end anymore then it means that we cannot reach the t and that's when we return the minus one okay yeah and that's basic that's the basic idea for the greedy solutions so let me try to implement the grady solutions real quick here so same thing here we have n length of the uh the clips right we sort and then we have the answer right the answer is zero and then like we have a current end we have a current n equal to zero and since we'll also be uh tracking the uh how many clips we have pro processed before i'm going to also define like a clip index equals to zero so and next one is like the if the current end it's smaller than t we'll keep doing it otherwise we'll simply return the answer so why is that because by the time current and is equal uh either equal or greater than t then we know okay we have reached the we have covered to the to this t time and then we can simply return the answer okay while we're still trying to reach t here every time when we are at this current end here we will increase the answer by 1 first which means that every time when we are at this while loop here we know we need another clip okay but which clips we are we're looking for here right and we're basically trying to use the clips that can give us can take us as close to t as possible which means that we're going to have like a while clip index right it's smaller than n because we're using this clip index to help us track the uh the processed clips and while this thing is smaller than n and the clips dot clip index uh it's equal or smaller than the current end right and then we uh we do what we uh so this one means that okay so this clip is within the current end which means we can pick this clip as our next clip right so that's why we're gonna maintain this the current end with the uh with clips dot clip dot index one sorry so here should be zero because that's the uh zero is the starting point right and one is the ending point and we're using basically we're trying all the candidate the candidates so uh and we pick the ones that can take us the i mean the furthest okay and if oh so here you know since we need to uh compare the uh since we need to handle this minus one case here so which means we will need uh we need to uh also mark the uh the old end and the new end because the uh since we are using the current end right e first uh using the same variables here you know basically where we're losing the previously end so that we can compare here so what i mean is like this so if the current end is the same as the old end means be before processing this current while loop here if they are the same it means that we cannot move our cursor further which means we are basically we are we're stuck here and that's when we need to return the minus one so to do that right and we need to uh what we need to just define the temp temporary uh variables inside the while loop and we use that to record the previously uh end here okay and so that will also be using this one here yeah actually even without the even without that even without this uh this minus one handling here we still need to uh create this local variables because here right if we're using the current end here and every time when we are extending this current end we are like basically keep moving forward until we have reached the end that is wrong right because our range is the end in the previously stat uh in the previously state that's why we need to create this like a temporary variables to cut to give us like a threshold for the current while loop and we use this one to stop the outer while loop here right and as when we re when the current end is equal it has reached the t here we can simply stop and we also check the minus one case cool so let me run the code here oops clips i think a few typos here sorry about that hmm i know sorry so clip index plus like i said you know once we have uh once we have finished processing the current clips since they are they have been sorted we can just move this clip forward because we have already record the end for that clip that's what that's why we can always moving forward and run the code here all right accept it submit all right so it's also passed and yeah as you guys can see so for this one right i mean we have an n log n here and how about here we have an n here that's the while loop here and it seems like we have another while loop here but as you guys can see here so this clip index is always moving forward always moving to the right so which means that so the clips will also be processed in total n times so that's why we have an n plus n here and that's why for the greedy solutions the uh the time complexity is bounded with it's unlock n okay yeah and space complexity i think for the space complexity since we're doing the sorting here you know it's also unlocked and oh sorry it's not unlocked and it's the uh it's a it's often right okay yeah i think that's it for this problem yeah and i think it's a great uh good practice for both the uh the dp and the greedy uh thank you so much for you guys to watch this video stay tuned uh see you guys soon bye
|
Video Stitching
|
triples-with-bitwise-and-equal-to-zero
|
You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`.
We can cut these clips into segments freely.
* For example, a clip `[0, 7]` can be cut into segments `[0, 1] + [1, 3] + [3, 7]`.
Return _the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event_ `[0, time]`. If the task is impossible, return `-1`.
**Example 1:**
**Input:** clips = \[\[0,2\],\[4,6\],\[8,10\],\[1,9\],\[1,5\],\[5,9\]\], time = 10
**Output:** 3
**Explanation:** We take the clips \[0,2\], \[8,10\], \[1,9\]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut \[1,9\] into segments \[1,2\] + \[2,8\] + \[8,9\].
Now we have segments \[0,2\] + \[2,8\] + \[8,10\] which cover the sporting event \[0, 10\].
**Example 2:**
**Input:** clips = \[\[0,1\],\[1,2\]\], time = 5
**Output:** -1
**Explanation:** We cannot cover \[0,5\] with only \[0,1\] and \[1,2\].
**Example 3:**
**Input:** clips = \[\[0,1\],\[6,8\],\[0,2\],\[5,6\],\[0,4\],\[0,3\],\[6,7\],\[1,3\],\[4,7\],\[1,4\],\[2,5\],\[2,6\],\[3,4\],\[4,5\],\[5,7\],\[6,9\]\], time = 9
**Output:** 3
**Explanation:** We can take clips \[0,4\], \[4,7\], and \[6,9\].
**Constraints:**
* `1 <= clips.length <= 100`
* `0 <= starti <= endi <= 100`
* `1 <= time <= 100`
0 <= i < j < k < nums.length, and nums\[i\] & nums\[j\] & nums\[k\] != 0. (\`&\` represents the bitwise AND operation.)
| null |
Array,Hash Table,Bit Manipulation
|
Hard
| null |
132 |
Hello Everyone Welcome to Day 725 Original Some 4 Injured S Questions Silent Room A Partitioning Two Then Already Sold Tonic Partition in December 2004 Don't See the Video Age Electronics Questions in This Question Give Winners Rings End Partition Tab Screen Office Partition Before Rule Me To The Number Of From Obscurity Subscribe Acid 10 2012 Subscribe To That Blast Mazdoor Let's Look At Presentation Kind Create Display Let's Get Started That Calling Room Partition * Liquid 132 That Calling Room Partition * Liquid 132 That Calling Room Partition * Liquid 132 Season-2 Liquid Problem Item Provident Season-2 Liquid Problem Item Provident Season-2 Liquid Problem Item Provident Combination Subscribe Equation In Two 251 I am in office today A problem is identified below list of all the states rings in poland aa tinder different example triple bco and of david difficult questions of mind in all possible subscribe and subscribe the Video then subscribe to the Page if you liked The Video String Starting From i plus vansh uptil gel minus one this year android dual plus one april - 151 - video dual plus one april - 151 - video dual plus one april - 151 - video subscribe love you all the that we jus writing watershed dpo of your plus one aa j - vansh provided with director se aa j - vansh provided with director se aa j - vansh provided with director se z according to build sustainable will be using This Information To Computer Answer Is This Vansh That You Correction Bill DBW-17 This Vansh That You Correction Bill DBW-17 This Vansh That You Correction Bill DBW-17 The Amazing Partition Will Submit It Will Find Out The Solution To Point From 0.5 Inch Width subscribe Point From 0.5 Inch Width subscribe Point From 0.5 Inch Width subscribe Video Subscribe To Hai And To All Possibilities To Rebuild Trying To Find Out The Results Minimum Grip to Make the Partition Spiderman and Electronic Subscribe Information for Stadium Vihar Phase Dad Total Something Required for Every Indian Has Been Taken Into Consideration for Example Total Subscribe Total Cutoff in Subscribe Total Records - One Who Completes Length a Improve Process Only Good Quality computers solution for and total cuts of three up till date and new create in stones at 40 point to disposition of what do you will cry and bring that every possible thing from 10 equal ujjain starting here 12302 list series page 6 and sunao sir ji hum Bhi Orat Is Particular Index Is Equals To Meet At This Position And Who Will Check Weather Tomorrow Subscribe To This Point The Total - 121 Subscribe To This Point The Total - 121 Subscribe To This Point The Total - 121 And Anshu Meeting In New Cut Hai Plus One Will Find Out The Minimum Possible User Cross All The Index Of Might A Balance In Due Course Strengthen BPFI Below This Sacred Ground Wear Maybe Below This Particular String In This Calendar And You Already Know The Answer For This Particular Richest Man - 110 Total Richest Man - 110 Total Richest Man - 110 Total Cost Secure Subscribe To I Anil Minimize Positive Values for Five Minutes of Question A Possible Patience i10 and i20 subscribe The Video then subscribe to the Page if you Just AN's Reporting No Difficult Axis - Reporting No Difficult Axis - Reporting No Difficult Axis - 300 Others Back to the Total and Variable and Created A Pia Ray of Science and Clothes and That Will Help to Do a Romance State of Every Possible Suffering of Which Points Rings and Will Talk About This Friend Digital Bird It's Straight Forward I Think You're Already Aware of Laptop Keyboard Notifications More and White the Significance Off But Minimum Every Possible And Start Getting From Subscribe Maximum Number Off Do 128 Dena Is Designer Look For Equal To Zero Amazon Ek Duje Check In It Only Under This Tree Not Compare The Cut Will Be Computed Total Votes - One Plus One Class Ninth Subscribe The Amazing spider-man subscribe 0 ki aisa in total cuts off side zoom minimum volume tenth able to get out of total records - 110 subscribe hai akshar and if you want two days session immediately don't forget to like share and subscribe channel thanks For giving its followers tune in for more updates on coding decoding the questions.
|
Palindrome Partitioning II
|
palindrome-partitioning-ii
|
Given a string `s`, partition `s` such that every substring of the partition is a palindrome.
Return _the **minimum** cuts needed for a palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab "
**Output:** 1
**Explanation:** The palindrome partitioning \[ "aa ", "b "\] could be produced using 1 cut.
**Example 2:**
**Input:** s = "a "
**Output:** 0
**Example 3:**
**Input:** s = "ab "
**Output:** 1
**Constraints:**
* `1 <= s.length <= 2000`
* `s` consists of lowercase English letters only.
| null |
String,Dynamic Programming
|
Hard
|
131,1871
|
962 |
Hey gas ho are you all you are doing good welcome tu de lord so today c will solve de van more question in our ise level in our stack cities and if you have not have access de stack analysis it so we are in our medium level so In this we are given that we have a name in which give us I less which will be and the value of Namsai can be that means take the example that if we have the example then here our which is I is like small. It should be first of all and Journals of I is that lesson so if you see here then our this is 540 0 <= 5 or correct. <= 5 or correct. <= 5 or correct. Now take another example so our example is like this is this with so what is this. D index of a date is you what is D index of six date is zero and it will give you zero but it was giving A4 So you have you take date index un date I am K date will give D maximum index of J Give it always less and equals tu van ho will solve this okay if it is greater than zero then you can solve it in this example we will friend that one which is 330 so what we will do here you will get 2s1 okay so now you will go here and here But if you apply it, you will get it here also, then you will find its max, so by doing this, you will have to do it again and again in this time, okay this much will be clear, there was no big deal in it, okay I have value here and I have so find a value. Every I have to find a value every which is less than the array of For which the smallest elementary which will have the smallest value, when it is understood after taking it, then we will tell why take this one, why do it like this, we have taken five. Okay, so if here we take the smallest value as the smallest sec. If we are keeping it in then it is sure that if the smallest value in this type is smaller than this type, now that value start of -1 of -1 of -1 < insert zero 5 - 4 like we will get What are we doing? We don't have any element man take 36 okay 10 okay sorry you took us okay so what we want is it doesn't matter to us if we have the smallest value. That this element which we are taking in the last will be smaller than the smaller value in the whole strike, so now whatever value we will do, it will be smaller than the present one. What have we done in it, we learn 540 elements. We took six, zero six is correct ok Give greater and equal you will five, four minus are watching, if you get then it is good, if you don't get then you will be left behind I hope you will be a little clear as to how to do ok if Take this man here we have 20 and over here we have anything over here your [ your [ your we will see six is not less than zero six and is not greater than 10 so this time we will come 13 But 13 will see 13 is greater so what will happen here 4 - 3 So two things here look at what is in 6-5 what does So two things here look at what is in 6-5 what does So two things here look at what is in 6-5 what does this mean 4 - 1 It will also this mean 4 - 1 It will also this mean 4 - 1 It will also give you this is index this is valid and the second What is possible? 13 - 10 and the second What is possible? 13 - 10 and the second What is possible? 13 - 10 - 0 Date is three Okay, that means our 'I' and ' Okay, that means our 'I' and ' Okay, that means our 'I' and ' Are of' are also laser because Are of' are also laser because Are of' are also laser because we have inserted it in this type and are taking this value from our name, how else? Inverter hum kya kar raha hai namsaab aayi se thibhi kar do ok Dos not infinity hai aur return kya hai result hai hain kya kar raha hai and what is the result us previous year solution then we do the last element We are taking, we said if that if the value is there, think every time, let's check once, are we giving it to you, this is the list of which is ours, that is our out of index, if open this type of value Have ranged and ironed this sex Taking it as if we will reach no matter what, even here we see what is the intention of this every year So here we had written equals, now if we will write equals, proper sweet husband UNLOCK AND YOU DO NOT HAVE TO TAKE OTHER EXERCISES UNLOCK
|
Maximum Width Ramp
|
flip-string-to-monotone-increasing
|
A **ramp** in an integer array `nums` is a pair `(i, j)` for which `i < j` and `nums[i] <= nums[j]`. The **width** of such a ramp is `j - i`.
Given an integer array `nums`, return _the maximum width of a **ramp** in_ `nums`. If there is no **ramp** in `nums`, return `0`.
**Example 1:**
**Input:** nums = \[6,0,8,2,1,5\]
**Output:** 4
**Explanation:** The maximum width ramp is achieved at (i, j) = (1, 5): nums\[1\] = 0 and nums\[5\] = 5.
**Example 2:**
**Input:** nums = \[9,8,1,0,1,9,4,0,4,1\]
**Output:** 7
**Explanation:** The maximum width ramp is achieved at (i, j) = (2, 9): nums\[2\] = 1 and nums\[9\] = 1.
**Constraints:**
* `2 <= nums.length <= 5 * 104`
* `0 <= nums[i] <= 5 * 104`
| null |
String,Dynamic Programming
|
Medium
| null |
438 |
hi guys welcome to beginner check is in this video I am going to discuss about uh find all anagrams problem right as I'm discussing about a sliding window approach this is the fifth problem on sliding window approach I have already published the separate video on anagram if you don't have understanding of anagram I would recommend you to go through that video first I will share link in the description box so let us go through the problem statement so this is the lead code problem number 438 find all anagrams in a string right so uh like let us understand how can we apply sliding window approach on this problem so first we will identify whether this problem is applicable for sliding window or not okay so let me um go through the problem statement first here thing is and B written an array of all the start indices are p is anagram in s so we have P and S we have to return all the anagram of p is in s indices actually not the substring so you may return the answer in any order so order doesn't matter okay so here we have given this uh input s is equal to CBA EBA bacd and P is equal to ABC so we have to we can get num right so we have to find the anagrams of P into s okay so in ABC let me draw this example okay let me draw this example on right sorry s is equal to c b a t b a b s e d e b a d a c d and P is equal to ABC we have to find out the anagrams of P okay so here if we see CBA is anagram of P right because all the characters are same and we have to and the length of substring will always be equal to P's length so here CBA is anagram the first so we will keep our size window size as 3 only because this p is 3. the length of p is 3 so that is y right now we got this CBA okay now let's see Bae ba is because e is not present in P right so we can ignore that a e b is also not anagram because it is not present in now EBA next substring so EBA is also notice anagram because it is not present in b a b bab is also not an anagram because here B is repeated but here B is only appear one once time now a b a same for a b as well because a is repeated here but here a is a single character now BAC so again we got b a c another anagram of P into s right now a c d so ACD is not anagram because D is not present in P so these two substring are considered as anagram right so CBA appear at zeroth index and this one is appear at six index 0 1 2 3 4 5 6. seven eight nine right so this is the final output in this test case in this inputs 08 and so the final output should be 0 6 right so let us first understand whether this problem is uh like can we apply sanding window approach or not let me go through the problem statement again right so for sliding window okay let's so given to string s and be written an array of all the start indices are p is anagram in s okay so in this problem statement okay so what is the rule of sliding window the first rule is in the problem statement either we are talking about a string or array so we are talking about history second so are we talking about service ring subsequences yes we are talking about service frame because each anagram will be treated as substring in this string s right so do we have any window size so if window size is not they are not there in the problem statement then we can simply um like in the sliding window approach we have to type of fixed and variable right as we discussed earlier in the previous videos right so if out of 3 those conditions are satisfied then we are good to go with sliding window approach sliding window since I am discussing about sliding window technique so I'm uh that is why this problem can be solved with another approaches as well but my uh like uh but I just wanted to solve this problem is sliding window so that is why I have picked 10 problems to just like get a handy of sliding window because this is a very simple in the previous videos I have already discussed about some like sliding window template and all right so we can simply put those template and get the result that's all so let us understand uh the approaches like how can we solve this problem okay so we have this uh right yes same input c b a e b a c d and P is equal to ABC we have to find the anagram of P okay so here we have to make this window as 3 kind of right so for that easily for every sliding window problem I am just using one map right so in the previous videos the previous problem I have uh so it's the same way I will solve this problem as well okay so we will keep to variable I is equal to zero J will be increment like I can say J is a next pointer okay I is a previous point right okay so if I is equal to 0 J is equal to 1 I'm just maintaining one Mark to keep the frequency of each word like each character right so here the map size is um right so I'm just choosing the window size as we have this equal to this piece T dot length is equal to middle size I'm considering okay right so uh right I is equal to 0 J is equal to 2 we have d one I is equal to 0 sorry J is equal to 2 we have what CBA 1. rate so since we have this string okay so for anagram the rule is I already discussed this thing in the previous video so for anagram the rule is the first rule what size up string should be same second is what so character of each character should be same each care should be same right each car should be same each cash should be set okay irrespective of their orders order doesn't matter whatever the character appear in the first string the same character irrespective of their orders the same character should be appear in a string 2 okay so this is the rule of anagram so here we got this C B A J is equal to 2 okay so CVA and we will maintain one map for this p man and we will keep all the occurrences of characters a b c sorry one okay this is pmap and this is s map okay so we will compare this s map dot equals P map if these two maps are equal then we can simply say like we can simply say this the p is uh like s is anagram of P okay substring CBA is anagram of T we can simply store the index of CBA the initial index of CDA okay so in this case we can write we can maintain one list other name whatever so we will store there the index of anagram string okay right so if this is not uh equal then we can simply write let me uh put I is equal to 0 J is equal to 3 so in this case if we see we have C B A and what e right one so here in this case um the map side is 4. and window size is J minus I plus 1 is it greater than P dot length we will compare this one because our uh um our windows I should not be exceeded with p dot length okay this is the uh we have to find the anagram of T that's why so J minus I plus 1 so J is 3 this is 0 this is 1. so 4 right and the length of p is 3 so 4 greater than three so in this case we will remove this character right so if J minus I plus 1 greater than what P dot length okay so in this case remove Pi it there that's all this is the business logic we have to build right okay so let us uh build this uh Solution on the lead code itself okay here they have this split group okay so let us uh create this map so pmap okay new hashmap sorry okay let me enter I is equal to zero I less than what P dot length right I Plus 6. okay so T map dot put what P dot carat P map dot get or default right P dot correct I 0 plus 1 right so we will get uh appliances of each character in pmapp okay now we need to Define another map over here what is sorry right s map right we maintain two characters sorry two variables is equal to zero into J is equal to 0 right so as uh I already discussed about uh sliding window templates so I'm just going through the same thing let me start with J less than what um s dot length okay and what uh s map dot put what is dot Care at I let me copy this we can simply it okay so right here we should make it yes this should be is this should be S right and they should be this right so we can increment J plus if P map dot equals this map we can simply return the we can simply store the result here list because return type is written type is list right result is equal to new arraylist right result dot add all right okay this is the result if J minus I plus 1 greater than what P dot length so what should we do we should remove ith character right we should remove wire character so I ith character as in yeah so let me start in Loop here and this should be greater than what P dot length so the this will execute until unless J minus I plus 1 greater than P dot length so here right um from s map dot put so let me okay yes dots carrot I base dot carrot I and S sorry s map dot get is that carrot I minus 1 okay right okay so if okay so here um okay s map dot get here at I equal to 0 we can simply remove this map Dot we move what a start I okay and here we'll increase pi plus so after this Loop right will here we will return result okay so let's see let's run this what happened okay J plus okay this is not required but let me best practices I'm testing okay so here uh we should have this s map dot contains what key test Dot Care at I okay so this should be only okay still there okay something we are missing here okay oh sorry okay fine here it should be J right sorry I just copied them okay right I think this should be run now okay so this is accepted let me submit this solution right so this solution is accepted and the run time is 81 Ms okay right so finally like we are able to uh solve this uh this problem with the help of sliding window approach in the next video I will discuss some more uh problems based on sliding window approach so see you in the next video thank you bye
|
Find All Anagrams in a String
|
find-all-anagrams-in-a-string
|
Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** s = "cbaebabacd ", p = "abc "
**Output:** \[0,6\]
**Explanation:**
The substring with start index = 0 is "cba ", which is an anagram of "abc ".
The substring with start index = 6 is "bac ", which is an anagram of "abc ".
**Example 2:**
**Input:** s = "abab ", p = "ab "
**Output:** \[0,1,2\]
**Explanation:**
The substring with start index = 0 is "ab ", which is an anagram of "ab ".
The substring with start index = 1 is "ba ", which is an anagram of "ab ".
The substring with start index = 2 is "ab ", which is an anagram of "ab ".
**Constraints:**
* `1 <= s.length, p.length <= 3 * 104`
* `s` and `p` consist of lowercase English letters.
| null |
Hash Table,String,Sliding Window
|
Medium
|
242,567
|
215 |
hi guys hope you are doing great our today's problem is Keith's largest element in an array it's a medium difficulty level question on lead code and one of the most top liked questions as well so the question States finally KF largest element in an unsorted array note that it is the key eighth largest element in the sorted order not the kieth distinct element so for example in 3 2 1 5 6 4 if we were to find the second largest element the largest is the 6 and second largest is 5 and that's our answer similarly in 3 2 3 1 2 4 double 5 6 the fourth largest element would be 4 because 6 is the largest 5 second largest 5 third largest and 4 fourth largest so that shows us that we are not ignoring the duplicates right the question also says that we can assume that K is always valid which means that K will always be between 1 and the length of the array all right so let's take a look at the various approaches we can use to solve any unsorted array question I wish to pause take a look think and come back ok so I think we have a very clear winner here today it's top key elements because this approach is specific for questions around finding the top key small s largest frequent elements of the array so let's see how we implement that so typically in questions requiring us to find the top key largest or talki smallest or more frequent or the closest sorry we need to use a min heap or a max heap and it has been my observation that whenever you have to fire the largest element you can use a min heap and when you have to find the smallest you can use the max heap so this has been my observation I would request you guys to have look at similar such questions maybe four or five and understand and validate this approach so in Java the priority queue is an implementation for he okay the default implementation is that of a mini so many heap would always ensure that the smallest element is at the tip of the heap right in this question we would need to use min heap and that is why we don't need to play around with the comparator right there would be other questions where would we would need to and we will let look there how we can override the compare method so the approach for this would be that we just take a priority queue which is the min heap implementation and let's say we insert 3 into it since 3 is the only element there wouldn't be any HIPAA fication and we'll check that is the size of the priority queue more than key so we would always want the priority queue to go beyond K so k plus 1 and then do the HIPAA fication and then in those elements whatever is the smallest element we will eliminate that right so we insert 3 fine size is 1 not more than 2 we insert to HIPAA fication occurs 2 is at the top and then 3 still the size is not more than 2 we insert 1 HIPAA fication occurs it's 1 2 and 3 now and the size is 3 so now we eliminate the element at the tip of the heap which is 1 so we are left with 2 & 3 none and is 1 so we are left with 2 & 3 none and is 1 so we are left with 2 & 3 none and now we insert 5 so he vacation occurs two three-and files and vacation occurs two three-and files and vacation occurs two three-and files and again the size is more than two so two gets eliminated similarly when six comes in three will get eliminated and when four comes in four itself will get an eliminator so at the end when we need to return an answer all we have to do is just return the element at the top of the priority queue which is going to be five and that's going to be our answer so if you observe here at every step whenever we are adding a new element we have for that particular number of elements the KS largest so this could be used when you have to find the K largest element in a stream as well right so the only difference would be that every time you add a new element before eliminating you could just capture that and add it into an array or whatever is the desired output collection like okay so let's implement this now implementation for this is pretty quick we just take a priority queue of the type in Peter new mattress / vq q okay now let's just mattress / vq q okay now let's just mattress / vq q okay now let's just iterate through all elements of nums okay so we first add it okay to the priority queue we have added it now let's check if the size as I was discussing we want it to go to P k plus 1 right so that's why we add it after that we check is the size greater than key if yes we just do a bigger oh okay right so at the end we just have to return the element at the top and that's figured out okay let's just try to run the school oh yeah sorry you have to be done this let's submit it great so the time complexity right the time complexity for this would be O of n log key that's generate because log K is for the heap application that occurs internally of priority queue that's like a constant that you can that's a constant time complexity that you can always use in cases where using where you're using priority queue so lucky is that and we'll be doing it n number of times because we'll be doing that for each element so that gives us off n log K and the time complexity is this the space complexity would be of K because or K plus 1 because we will always be storing that many number of elements in the priority key not more than that so that would be our space complexity so that is if you've really liked this video please like share and subscribe keep coding and take care
|
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
|
18 |
hello and welcome in this video we are going to solve problem number 18 of let go that is for some problem okay so before starting the video I am going to tell you that please solve question number 15 that is threesome problem before attempting this problem so if you have not solved this problem please go and solve this and you can find a video for this in display list okay so now coming back to this problem so in this problem we have given an array of n integer and we have to return an area of all the unique quadruple quadruplets BCD should be between 0 and n and A B C D should be distinct and we can say unique okay num and we have also given a Target so our num say Plus numbers should be equal to Target so we have to return a quadruple which sum is going to be equal to Target and all the num indexes should be distinct and also our quadruplets will be also unique so let's get let's go to the example so moving towards test case one we have given an array 1 0 -1 0 to minus 2 so and Target equal to -1 0 to minus 2 so and Target equal to -1 0 to minus 2 so and Target equal to zero so we can see that there are total three quadruplets that can be made minus 2 minus 1 2 now after adding this target sum will be going to be equal to 0 and 1 quadruplet will be minus two zero two and another one will be minus one zero one so these are three quadruplets that can be made using this array okay so moving towards test case two we have given an array two so we can say that and Target equal to eight so we can see there can be two quarter plates with distinct indexes you can see that these two are same quadruplets so our quadruplets should be unique that has been mentioned here so we can return only one of these so our output will be only one that is 2 Okay so now how you can solve this problem so as usual the knife or root Force approach will be to use for Loops for time inside a one inside each other so this is going to be something like this will be running a for Loop from I equal to 0 to n minus 3 then inside this will be running another for Loop for i j equal to I plus 1 to n minus 2 and inside this I want another for Loop k equal to J plus 1 and minus 1 and inside this another for Loop okay so you can see that time complexity can for this one is going to be n to the power 4 we go of n to the power 4 inverse case so obviously this one is not recommended one so what is the approach that you are going to follow so if you have followed the vid com entire playlist then you must have seen or two pointer method for to some problem interesting problem so I am going to apply same method for this one first we will be running a for Loop for I equal to 0 to n minus 3 and we will be up we'll be updating our Target value equal to new Target will be Target minus I and then we will be doing threesome problem inside this and this will be going to give remaining three numbers okay so by doing this we will be able to find the quadruplets so this is the rough idea I am going to write the pseudo code for same in the next slide so let's go into let's slide okay now I'm going to write the pseudocode for same as I have already mentioned discussed all that parts for this threesome in our previous video so please go and watch that if you are not watched then coming back to this problem now we'll be doing a for Loop before that the what the requirement for this problem first we have to sort our array okay first sort the array nums and then we'll be running a for Loop for I equal to 0 to n minus 3. and inside this first we will check whether I nums of I is not equal to nums of I minus 1 just to avoid the duplicate items okay so we have to return unique element so we will be first checking that our current value is not equal to previous one so in this case we will be doing continue okay and before this we have to check whether current index is greater than I 0 or not so I'm not writing this here so you have to make sure of that okay inside this will be running another for Loop for J equal to I plus 1 to n minus 2 again we will be checking this same condition here and then after we will be doing two some problem inside this okay so now we have to update our new Target so this is going to be something like Target minus nums I Plus J and here we are doing some calculation which is going to decrease our time complexity by a huge margin so first we will find maximum what can be maximum using for next all the elements so as we have find out two elements already so we have to find out remaining two so maximum number of sum is going to be done last two indexes as we are array sorted so maximum is going to be equal to nums n minus 1 plus nums n minus 2 and similarly mean sum is going to equal to nums J plus 1 plus nums J Plus 2. and first we will check if Maxum is lesser than new Target then we don't have to do any calculation simply do continue here and again we will check if mean sum is greater than new Target then we are not going to get any result for this J so we'll be taking from here so we do break okay now this is going to increase our time com decrease our time complexity by a huge margin okay so don't forget these four lines okay then after we will be doing two pointer inside this just do two pointer do two point that we have already did into some nthism and check remaining two values of two pointer and if result fund are stored that in our result so first we have to declare a result variable this is going to be list of list our result and then after this we have to return our result at last okay so how we can do this two pointer for that we will be going to see this in code okay just go to the compiler and the and write the code for same so first declare our result list of list foreign we can check size of dot length as you have to check every time so we are checking it initially okay now first you will check we'll be checking if I greater than 0 and nums I equals to nums I minus 1 in this case we don't have to address it just continue from here okay and then we will be running a four Loop equal insert this that it's going to be I plus 1 and J should be lesser than n minus 2 J plus again we will be checking for duplicacy if J is greater than I plus 1 and nums J equals to nums J minus 1 in this case do continue now calculate new Target that you have to find okay so this is going to be Target minus nums I Plus nums J okay so we have to update our Target now time to find them mention and maximum mean sum is going to be equal to nums J plus 1 plus nums J Plus 2. and maximum is going to equal to nums n minus 1 and N minus 2. okay then we'll be checking if maximum is lesser than new Target we don't have to check we don't have to do any calculation for that just continue and go for go ahead and next day okay and after this we'll be checking if means something greater than new Target then we are not going to find any result for this J for this ISO will be doing break from here now initialize left that is going to be equal to J plus 1 and right that is going to be equal to n minus 1. so this is the search space in which we have to do two pointer now do two Pointer while left is lesser than right insert this find current sum that is going to be equal to nums left Plus nums right if current sum is equal to new Target then we'll be doing some calculation inside this and else if case may we will if we will find that currently lesser than new Target we have to shift or left by one index and L in else if do right shift by one index okay so as we are satisfied this condition so we have to store this inside our result so result dot add errors dot Edge list method we are using here so nums I nums J numbers left into numbers right these are four indexes that we have found okay now we have to check for duplicacy for that we will be doing then we will first we will be shifting our left by one and right by one then we will check for duplicacy if while left is lesser than right this is the condition that we have to satisfy and then we'll be checking if Norms of left is equal to nums of left plus one in this case more left by once and same for right or check left LS7 right and nums of right is equals to nums of right minus 1 in this case do right minus okay everything's okay yeah now at last we have to return our result I hope everything is okay now run this okay so this should be nums n minus 2. run this again yeah take another test question now submit this okay so we have got one wrong answer so let's go back and check whether we can do any okay so as we are adding two numbers this can be long also so just count this too long now check again submit this okay so our result is faster than 96 percent of the Java submission so I have told you that we are doing these three lines to just optimize our code so if we are commenting this and submitting this again you will be seeing we will going to see a huge margin okay so now you can see that our code is only faster than 59 percent now you can yeah so if you have learned something from this video you can like this video subscribe to the channel and don't forget to share this video among your friend thank you
|
4Sum
|
4sum
|
Given an array `nums` of `n` integers, return _an array of all the **unique** quadruplets_ `[nums[a], nums[b], nums[c], nums[d]]` such that:
* `0 <= a, b, c, d < n`
* `a`, `b`, `c`, and `d` are **distinct**.
* `nums[a] + nums[b] + nums[c] + nums[d] == target`
You may return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,0,-1,0,-2,2\], target = 0
**Output:** \[\[-2,-1,1,2\],\[-2,0,0,2\],\[-1,0,0,1\]\]
**Example 2:**
**Input:** nums = \[2,2,2,2,2\], target = 8
**Output:** \[\[2,2,2,2\]\]
**Constraints:**
* `1 <= nums.length <= 200`
* `-109 <= nums[i] <= 109`
* `-109 <= target <= 109`
| null |
Array,Two Pointers,Sorting
|
Medium
|
1,15,454,2122
|
35 |
hello everyone welcome to JavaScript problem solving playlist so today's problem is called search insert position so it says that given a sorted array of distinct integer and a Target value return the index if the integer is found if not then return the index where it would be if it were inserted in order so let's visualize it so given a sorted array of District integers and Target value so let's just say you are given a list you are given an array that contains five integers one two three four five and your target is let me insert it your target value is value let's just say 2. now return the index if the target is found if we can find the target then we are going to return the index what is the index of our Target 2 the index is 1. and if we can't find the target then return the index where it would be if it were inserted in the order now if I can't find the target to let's just say 2 is not here so if it were here as it is a series of numbers if there are not any numbers written here then what would be the index the indexes is still going to be the one so we need to figure that out so let's code it up and actually I have coded up before so that I can unders I can explain it better so we are going to use binary search method and to do that we need to take the median number of it now this is our array one two three four five and this is our Target and I have taken a function that is called search insert and two parameters nums and Target and console Log search item nums Target here and I am using an extension called coca.js extension called coca.js extension called coca.js and when you install it if you press uh shift Ctrl and P then run it here what it is going to allow us to run the function console right in the vs code so here the output tree it is all already given us given to us by coca.js already given us given to us by coca.js already given us given to us by coca.js so we have taken the nums and Target nums is the array and Target is the value that we are going to find so let's start is going to be 0 and end is going to be nums dot length minus 1 because our index is going to start from 0 that is why we are taking the index 0 here and we are taking the nums length minus 1 so we are going to get the index number proper index number from 0 to 4. and we are going to take the mid we are going to play a loop while start is less than or equal to end that is our start and end uh as long as they are not greater than stat is not greater than and the loop is going to uh happen so we are going to take the middle mat.4 start plus end divided by 2 that mat.4 start plus end divided by 2 that mat.4 start plus end divided by 2 that means right now our middle is going to be let's calculate it our index start is 0. so our end is 4. if I divide it by 2 so right now my middle is value is 2. now if nums made is equal to Target so what that means is that nums made that means in the nums array of 2 what is the number let's see if the num area of 2 the number right now is 3. in the nums array index to the number right now is 3. is equal to 3 if 3 is less than or if T is equal to Target that means our Target is our Target right now is 4. if it is equal to G is equal to 4 then return made as it is not equal to 4 then we are going to go to our else if statement if nums made is less than our Target is it less than is she less than 4 yes it is less than 4 so it is going to go to this code start is going to be now mid plus what so what is our meat right now our mid right now is 2 so our start is going to be 1 and I'm going to return the start so this is the solution of our problem now let's just say instead of Target if I give it 2. what happens constant meet right now our mid is still going to be 2 our Target is not going to uh it is going to be 2 and it is going to be 3 our Target is 2 is it is not T is not equal to 2 what it is less than our tree is 3 less than 2 no so in this case we are going to go to this code 3 is not less than 2 so 3 is greater than 2 so our end is going to be mid minus 1 so our mid right now was 2 so it is going to be mid minus 1 so right now our end is equal to 1. now the loop is not uh loop is going to happen again because our start is 0 and our end is one so the loop is going to happen again now it is going to come here and for the second iteration now my 0 and 1 what is going to be my mid now my mid is going to be 0 Plus 1. divided by 2. it is going to be 0. right now my mid is going to be 0 so nums 0 is equal to Target or not let's see num 0 is equal to 1 we are looking for 2 so no our code is not going to go here it is not equal to 2 1 is not equal to 2 so the code is not it is not going to return here it is going to go here and let's see if 1 is less than Target yes uh 1 is less than Target so our start is going to be right now mid 1 plus 1 is equal to 2. uh sorry uh then our start is going to be mid is equal to 0 right now so it is going to be one so here is the answer let's see if I put other values other errors if it gives us the desired result or not so let's just say number is going to be this what is wrong number is going to be this and the target is going to be 5. output should be 2. yes output is 2 let's see if my number is this and the target is 2 output is one target is 2 so output should be one yes output is one and if the number is this and the target is 7 output should be for yes outbreak is for so this is it this is the uh solution to this problem
|
Search Insert Position
|
search-insert-position
|
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[1,3,5,6\], target = 5
**Output:** 2
**Example 2:**
**Input:** nums = \[1,3,5,6\], target = 2
**Output:** 1
**Example 3:**
**Input:** nums = \[1,3,5,6\], target = 7
**Output:** 4
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `nums` contains **distinct** values sorted in **ascending** order.
* `-104 <= target <= 104`
| null |
Array,Binary Search
|
Easy
|
278
|
1,627 |
hey everybody this is larry this is me going with q4 of the recent weekly contest 211 for lead code uh where i finished 35 i guess but uh hit the like button hit the subscribe button join me on discord let me know what you think about this problem it is a tricky problem it's all math problem and i think to be honest a lot of how i solved this if you watched the video which is right afterwards um i spent a lot of time just like staring at the screen staring in the sky staring up my ceiling staring up uh pictures of people i don't know well i just kind of try to think about inspiration and um and how to solve this problem and you know sometimes i'm going to talk a little bit about the thought processes of just giving you the answer because you know like anyone can look at an answer be like oh yeah that makes sense but this is my thought process so my thought process was to be honest a lot of it was just thinking about similar problems and i was thinking about prime decomposition uh in a lot of ways and i was thinking about um now i was thinking about maybe pre-processing the queries or maybe pre-processing the queries or maybe pre-processing the queries or something like that uh kiwis craze um so but looking at that n is equal to ten thousand uh i was like uh okay so yeah and you know that building to full graph if you just do ten thousand square uh it's gonna be too much right um so i was thinking about different problems like that uh where like you know you have gcd um because another they've wrote it in a really funny way but basically the answer is that if the gcd between two numbers is greater than threshold uh strictly i don't know why they do it this way strictly greater than threshold then you know um uh the threshold then you know there's an edge between them so i was thinking about prime decomposition i was trying to think about like similar problems where without the threshold you could be like okay well like the threshold is one where like it's greater than one well you know you could do you know the prime factors of two numbers and then uh similar to that right so i think along those ways like for example if your ratio is one uh all the even numbers will be together and then order multiple threes would be together and so forth um and then you kind of uh merge them together in a way because if six is in the threshold then that means that um you know you merge the two and the three components there's a similar problem there um but that prime uh factorization of every number uh it's gonna be a little bit slow if we do it for every number right it's like n times square root of n or something which for ten fourth maybe is fast enough i don't know but i thought it'll be too slow during the contest uh so basically the key thing to notice is just to be honest there's no um uh because as soon as and if you watch the video you see me like do a trigger real quickly um and and the prerequisite for this problem is something called the prime cipher it was erito studies uh i'm just going to sift because i cannot you know pronounce this very well clearly um but uh i gotta every time i have to google how to say this one correctly but okay but now that we have this right what does that mean so the key thing to know from this if uh at least for me i don't know if this is in here but the key thing to know for this one for me which i actually did not know this for a while maybe i did know this for a while but um but uh but i wasn't sure in general right so um wow there's a lot of crazy stuff here but um but the key thing to note is that the complexity of this is n log n because basically your if you do it from every prime uh and you do it naively it's going to be o of n plus o of n over two plus o of n over three plus of n over four plus dot right um so it turns out that we sum this up um you know you get o and like log n or something like that or clear what it is but yeah uh because usually i do i write an optimized version which doesn't really make sense in this problem but once you kind of figure that out um yeah once you convince yourself this is i mean i think my form is a little bit off but uh this is n of log n so once you figure that out then and this becomes straightforward to do um because now what you want to do is just to start it from the threshold right so now how do you think about this in terms of graph right uh well two you know this is a connected connective and connect i can't english with this uh video connectivity problem and for connectivity problem uh you know there are a number of ways to do it you can do breakfast surgery do that for search union fine is the other one and the way that i do it is union fine because we're going to do a lot of these queries um you know they're up to ten to the fifth query so we're gonna do union fine right and basically we're literally looking at each divisor and going okay is this number um you know uh basically instead of asking okay it's given two numbers a and b what are the common divisors right so that's one way to do it the other way to look about it from the sif perspective is let's get all the let's say we have a divisor that is k uh let's get all the numbers that are multiples of k right so like we said earlier um here you know we get all the even numbers and then we merge them together into one set in union fine right uh we're gonna get all the multiples of three put them together get multiples of fours put them together get multiple multiples of five put them together and so forth uh and once you kind of put all that uh union fine does a little bit magic uh that's the prerequisite for this problem as well as union fine i'm not going to go into damage details for union fund because that's beyond the scope but you know that's also pre-work for this problem that's also pre-work for this problem that's also pre-work for this problem for me um but basically now as we said we put them all in the same one super node if you want to call it that you know if you if two nodes are connected that one super node that is connected right and translator probably holds here right if a is connected to b and b is connected to c then a is connected to c right um so from that's pretty much it uh it's just trusting that this is fast enough and i didn't always know this i only learned this much later on um so once you can't do this um well for this problem we have a threshold and what does that mean well instead of looking at it you know we just don't construct like now because we ignore devices of uh let's say the threshold is three and higher right um or like you only care about numbers that are three and higher well that means that all the even numbers are no longer connected right so basically from that idea we just start the threshold or we start x from the threshold and i'll plus one because it's strictly greater than and then for every x in this case in my code i connect every divisor together and you can kind of do it by you know like i said because of you know this is you know you have some like m square edges but because you know it's connected uh all we have to do is connect it to the first node which is x right because if we have like for example even numbers you could say you know you have 2 4 6 8 oops 10 and so forth and then you could say the edges are 2 to the 4 2 to the 6 2 to the 8 2 to the 10 uh and also 4 to the 6 4 to the eight and then dot right but we don't have to care about these because of the transitive property that we just talked about um because we know that four is connected to six because two is connected to front two is connected to six and that's how we just do the union straight up with the x and once you do that uh for each query just do a union fine query um you could talk about some math but because of path compression which i do uh it's going to be you know at worst not at worst but amortized over one eventually uh you could do some math to kind of uh do that but that means that for each query uh there's gonna be all one ish it's a little bit higher than that but that's all one ish you could look up inverse agreement function if you want uh but yeah uh so this is all one for each query which is obviously going to be faster than 10 to the fifth and this one the preprocessing is of n log n which for n is equal to 10 to the fourth will be fast enough uh anyway that's all i have for this problem uh to be honest as soon as i make that recognition i was able to code it up i mean this is only like 20 lines of code and not even you know like you if you have libraries for this you could have done this much quicker um let me know what you think let me know what you like uh and you know join me on discord uh i and oh yeah and you can watch me stop this live now i was trying to be too clever um trying to solve it solved a different problem uh with the prefix which is something that i do too much okay oh damn it that was dumb okay uh for don't the time i don't do it recursively too okay focus what is going on here one two and two x and y share condo so gcd is greater than some threshold okay and in direction and b sub i are connected huh oh what is yeah and i got two long answers that's maybe three i don't remember i was silly that's how much when i do bottoms up okay focus okay this graph i have some ideas but i spent too much time on the other one hmm this home strip the equator then okay that's why hmm one okay that would work i guess whoops to i guess so you i know it doesn't really matter okay hey uh thanks for watching uh this you know video uh let me know what you think hit the like button it's a subscriber and join me on discord and let me know what you think about this contest this problem and so forth uh and i will see y'all next fall bye-bye
|
Graph Connectivity With Threshold
|
last-moment-before-all-ants-fall-out-of-a-plank
|
We have `n` cities labeled from `1` to `n`. Two different cities with labels `x` and `y` are directly connected by a bidirectional road if and only if `x` and `y` share a common divisor **strictly greater** than some `threshold`. More formally, cities with labels `x` and `y` have a road between them if there exists an integer `z` such that all of the following are true:
* `x % z == 0`,
* `y % z == 0`, and
* `z > threshold`.
Given the two integers, `n` and `threshold`, and an array of `queries`, you must determine for each `queries[i] = [ai, bi]` if cities `ai` and `bi` are connected directly or indirectly. (i.e. there is some path between them).
Return _an array_ `answer`_, where_ `answer.length == queries.length` _and_ `answer[i]` _is_ `true` _if for the_ `ith` _query, there is a path between_ `ai` _and_ `bi`_, or_ `answer[i]` _is_ `false` _if there is no path._
**Example 1:**
**Input:** n = 6, threshold = 2, queries = \[\[1,4\],\[2,5\],\[3,6\]\]
**Output:** \[false,false,true\]
**Explanation:** The divisors for each number:
1: 1
2: 1, 2
3: 1, 3
4: 1, 2, 4
5: 1, 5
6: 1, 2, 3, 6
Using the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the
only ones directly connected. The result of each query:
\[1,4\] 1 is not connected to 4
\[2,5\] 2 is not connected to 5
\[3,6\] 3 is connected to 6 through path 3--6
**Example 2:**
**Input:** n = 6, threshold = 0, queries = \[\[4,5\],\[3,4\],\[3,2\],\[2,6\],\[1,3\]\]
**Output:** \[true,true,true,true,true\]
**Explanation:** The divisors for each number are the same as the previous example. However, since the threshold is 0,
all divisors can be used. Since all numbers share 1 as a divisor, all cities are connected.
**Example 3:**
**Input:** n = 5, threshold = 1, queries = \[\[4,5\],\[4,5\],\[3,2\],\[2,3\],\[3,4\]\]
**Output:** \[false,false,false,false,false\]
**Explanation:** Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected.
Please notice that there can be multiple queries for the same pair of nodes \[x, y\], and that the query \[x, y\] is equivalent to the query \[y, x\].
**Constraints:**
* `2 <= n <= 104`
* `0 <= threshold <= n`
* `1 <= queries.length <= 105`
* `queries[i].length == 2`
* `1 <= ai, bi <= cities`
* `ai != bi`
|
The ants change their way when they meet is equivalent to continue moving without changing their direction. Answer is the max distance for one ant to reach the end of the plank in the facing direction.
|
Array,Brainteaser,Simulation
|
Medium
|
2317
|
137 |
Hello guys welcome to present day disney today exactly 2012 problem single number two please write the video n you don't forget to subscribe to this channel university update ki jeevan hone matiyari open teachers every element 3D effects of one witch appears at least one find a single Word Limit Note Phone Number In Samples Example 130 Number World Championship Written And Example For 9 Years Which Can Solve Tuition Help Algorithms Practice Set For Word Village Map And For Every Value Nehru Report Elements Ki Number Office Jakar And Value Novel Aap And Jitendra Ki Use values one being violated isko Use values one being violated isko Use values one being violated isko gol-gol thumb in one after and video link to the gol-gol thumb in one after and video link to the gol-gol thumb in one after and video link to the video is on the top and also in description check out for dussehra the map look like this e agree can see in your value equal to one should be written and not Come Under 5 Minutes Question Tracking How They Can Solve At Any Time And Without Using Any Additional Space Network Fruit The Thing That Comes To Mind Can Avoid Using Only When The Answers You Can Not A Number Of All Elements And Simple To Work Only Three States Of elements in one to three states of elements which will designer corporation transfer rule is a supposed to be submitted best wishes element come two times and end allu best wishes element don't know of every element will update hi hello let's check the match schedules and Importance is not right to build to table with input has a noida output dedication elders but channel can never given at the same time because element got here once and aishwarya ka to is so important combination of welcome allocation not adjust no will see the cases where In Food No Taxes Has Not Been Put Is The Value Of To make sure converted into expression for boys will be used for operations and share and all nations or computer expression for the das with expression when combined with water similarly for expression for the values and greater noida express way as a nation of no anchor for a Day Meanwhile From Decoration Noble Saintly Father Arrest Figure Truth Table For Rest And Expression And Will Look Like This Is Not Followed For Special Pattern Values Of Land Lord For Special Pattern Values Of Land Lord For Special Pattern Values Of Land Lord SIM The Giver Otherwise Give Expression To Lack Of Knowledge And Used For Eggs In Computing Expression Belief And Simplified procedure subscribe to hai railgaadi tamil bhi sample now will just finished his two variables hi hello and update both s on the expression of divide and rule content element which akad once vighnesh last two years not regret over 18.0 nothing will change notice boys akad only 18.0 nothing will change notice boys akad only 18.0 nothing will change notice boys akad only one Subha Update 2018 2019 Change Ho That No One Comes The Times To Update Hi 200 Comes Once They Update Low Agriculture And Will Return Low Time Complexities After And Space Oven Exact Same Pattern Tomato And Shared A Link With Java Coding Description Clock Of Thank You For Watching My Video Flag Video Please Like Share And Subscribe Our Channel Platinum Infection What You Think About The Video
|
Single Number II
|
single-number-ii
|
Given an integer array `nums` where every element appears **three times** except for one, which appears **exactly once**. _Find the single element and return it_.
You must implement a solution with a linear runtime complexity and use only constant extra space.
**Example 1:**
**Input:** nums = \[2,2,3,2\]
**Output:** 3
**Example 2:**
**Input:** nums = \[0,1,0,1,0,1,99\]
**Output:** 99
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-231 <= nums[i] <= 231 - 1`
* Each element in `nums` appears exactly **three times** except for one element which appears **once**.
| null |
Array,Bit Manipulation
|
Medium
|
136,260
|
117 |
welcome guys so today we are going to solve the lead code daily challenge populating next try pointers in each one second we are given a binary tree we have to populate each next pointer to a point is next right now if there is no next right node the next pointer should be none so basically given a binary tree and if structure is like this well and left right and next point so we have to assign the next pointer of each node such that it points to directly right node in that present in that way excluding the implicit stack space so after reading the question the first thing that comes into mind is like level or the traversal in which we will traverse from each level and in each respective level we will assign from the first node to the last node directly next nodes to its next point of like in the first level so we will assign next pointer of two directly to three then four five seven and each layer in a single level then four next pointer will point to five next point and the point two seven and then last one so it's a brute force like we will do the follow-up position we will do the follow-up position we will do the follow-up position a little bit later now let's focus on the normal solution so what we will do is like we will do dfs which will store all my notes in vector form within with respective levels and are very able to denote current levels if is less than equal to level iv in the storage the level in which we are going to insert the current node is not present so we will just push we will in the storage of the current route and increase our level by one hope you tested this and maintained now vfs and now as we are done with the level order we have our notes is to just assign the next pointers and storage i j dot next is equal to so this line just assigns the next pointer of the current node to the next node present at that level faster than 99.7 so this is the brute force approach now we will move up to the follow-up now we will move up to the follow-up now we will move up to the follow-up you may only use the constant we are currently using a space of order of number of nodes present in the tree so we have to reduce this now after the brute force we have an idea that the thing is like in a given level we have to just assign next node of our node next pointer of a node to directly right node present in the screen so now instead of using a dfs traversal and our storage vector to do all this stuff we will use three pointers of type node and now i will tell you further that what these three pointers are doing so pointer one is that gummy pointer which will just help us to reach the leftmost node present at a certain level while we are traversing pointer to just help us to get back to the node of which the next pointer we have to assign to the directly right like if we got the pdr1s2 then the first store ptr2 and second then we will assign dot t and the next pointer of 2 to 3 and then we will move ahead to 3 and the pointer 3 of the current pdr3 i the node traversing in the binary tree has this left side or not if it is present then we will simply ptr 2 dot next is equal to so you might have some question that why we are assigning the ptr next to the left of the current node so the answer to this is like we are at number one node so the ptr3 will point to one it has some right left node so basically if we are at level zero we are assigning the next pointer of level the next level we are not like we are not you might have some question that why we are assigning ptr2 next is so the answer is that if we are at level 0 we are trying to fix the next pointer of the next pointers of the next level so the left side of one is two and we will just shift our pointer ptr two to two and then we are like uh continuing the process of assigning this pointer so if ptf3 right not equal to then ptr to connect and then like we are at first we forwarded the ptr2 to 2 and then we are checking that ptr1 dot right ie3 is present and we are assigning the next pointer of 2 to next and inside after this for loop we are doing like ptr3 is going to be it's working fine available in the description see you soon
|
Populating Next Right Pointers in Each Node II
|
populating-next-right-pointers-in-each-node-ii
|
Given a binary tree
struct Node {
int val;
Node \*left;
Node \*right;
Node \*next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`.
Initially, all next pointers are set to `NULL`.
**Example 1:**
**Input:** root = \[1,2,3,4,5,null,7\]
**Output:** \[1,#,2,3,#,4,5,7,#\]
**Explanation:** Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 6000]`.
* `-100 <= Node.val <= 100`
**Follow-up:**
* You may only use constant extra space.
* The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
| null |
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
116
|
1,034 |
Hey guys welcome back to my channel and today we will do the question number 10 of the code coloring or what did you give me in your given a cross a matrix grid the grid is okay this is a matrix right and three inger row column And color one row gave us one column, one color is ok f value in the grid represents the color of the grid square at that location ok which is the color given to us in the grid means whatever value is given to us represents the color Which color is given filled like this see here this one is written then here P one color is filled here also one and here two one is ok two square are called adjuncts if when are they adjuncts if If they are next to each other in any of the four directions, look at a matrix, okay, in a matrix there is any element, the element above it will be adjacent, the one on its side will be the one below it and the element on this side of it is the diagonal element. It won't be adjacent. Okay, so and the border of a connected component is all the squares in the connected component. The border of the yes okay look. The border of a connected component is all the squares in the connected component that is adjacent to atleast. A square knot not in the component and on the boundary of the grid. Look like there is a grid. Hama ha. Look like a grid. We have this grid. Let's take this one. This will make sense. Li Na Tutu and below that's okay. So look, now we have What are the rows and columns given in this? Jeev, now what we say is that this column will be ours, we will go to the first column in row zero, then we will get the element with 'y', okay, if we get the go to the first column in row zero, then we will get the element with 'y', okay, if we get the go to the first column in row zero, then we will get the element with 'y', okay, if we get the element with 'two', element with 'two', element with 'two', then we will do it in this, what is its value 'two'? then we will do it in this, what is its value 'two'? then we will do it in this, what is its value 'two'? We know what to do, we have to color all the adjacent toes, we have to color the border that they have, we have to color the one that has been given to us, we should not color that which is not their border, which color border? It will be either or it can be that which is on the boundary, it can be a border or the one whose boundary is touching any other color can be a border. Okay, so see how we will do it, we will see it right from the graph, top. I have also given it, we will do it with Deus, we have given it, we will do it with Deus too, let's see how we will do it, first of all, we will store our original color, what will be our regional color, we would have written the color, it is ok, whatever the color or grade is. We are given row and column and the element will be our regional color, after that we will run a function, the function will be what will fill it, what will we give it, okay and we will pass it, pass our row and pass the column and We will pass our new color which we have to fill and we will also pass it and we will need it and we will see the rest later, first we will create this function, we will create the fashion and we will make it code S. Let's copy all this, okay, copied it, paste it on it, okay, let's add one more thing to it, our original color, okay, O color, instead of column of row, let's do C, instead of row, let's do it, okay, now in this we Do we run it first? Look, it does n't seem like we had done a question earlier, similar to the flood fill question. Yes, it is a similar question, why in this also we have been given a row and a column at the beginning from where we have to fill. If you want to start yours then it is okay then look, first of all we will run flood fill in it, see what was there in the flood fill, first of all our row, ours should go out of bounds, right row and column, our row is always, if ever, our row is below zero. Either our column has gone back from zero or sometimes our row which is the size of the grid dot size is fine, it has become equal to the size of the grid or our column has become larger than the size of the grid. It is equal to the size of grade of zero or bigger than that. Okay, we will return it. Okay, but this much was there in the pallet fee, but in this we will put one more extra condition that whenever our adjacent color is different, then We will not go there if the adjacent color of ours will be different like look at this one has an adjacent two, this one also has an adjacent two, below this one is not of this one, look at this There is no forest, the adjacent one of this forest is two, okay and the one on its side is two, so two is adjacent to both of them, but we will not go to two, why won't we go, we have to stick to our forest, whenever we Look, our grid of rows, grade of r, if ever ours is not equal to our original color, okay, if ever our original color is not equal, we will still return, okay, let's return. If it is not done, it means that we will have to fill the color in the grid, okay, what color will we fill in the grid, what color will we fill in that cell, what will be our new color, okay, what is the new color, is it not our color, it is okay. Look after this we call this TFA like we called in flood fee, we called it four times, one for top, one for both sides, one for bottom, okay, so in the same way we call DFS, how? Let's copy this, okay, let's do it four times, okay, wait for this, leave this, sometimes it gets clicked, look at this, first we run it for whom, first we do it like this, first we run it, like the above, as if this is any one of ours. Near element is the element which is above it, what will it be r human and C okay for this we will run it then for whom we will run it Y will remain here then we will run it for the right side what should be the right side pv right after that After this, we will run it for the bottom, it will be 'P' and it will remain like this. Well, run it for the bottom, it will be 'P' and it will remain like this. Well, run it for the bottom, it will be 'P' and it will remain like this. Well, what will happen after that, we will run it for the column minus 's' and 'Y' will remain our ' run it for the column minus 's' and 'Y' will remain our ' run it for the column minus 's' and 'Y' will remain our ' Rohi'. See, we have done our D-fill See, we have done our D-fill See, we have done our D-fill work, okay, but in this we What we will do is we will check that at the end, we will check whether our element is only the border one or also the middle one, which will be the one in the middle, which will be the index of its row and column, that will be the one. We will store it in a vector so that later, what have we done, now we have colored all the elements, but who do we have to color, who is on the border of that color, like someone has given us two numbers of the two numbered color? Borders will be borders, but we have to color them, which is the color given to us, yes, okay, so now how will we check it, the way to check is that one, R is always our R, if R is always ours, it should be greater than zero, okay. It is not possible to have a border case. If we had taken the border case then ours should have been equal to two but that will not happen. Okay and our column should also be greater than zero. Okay and our row should be that lesson. Grid size should be minus from this. Okay. It should be at the bottom, it is okay and our column should also be at the bottom, what is it, zero data, it is okay, after this we have done this, the basic condition is okay, this is our row and the column should not go out, it is done, okay. We have checked for the boundary but for this also we have to check that whatever is our color is also similar to the color, it is our grid and also the color should not be equal. Only if the colors are equal then it will be the middle element. If its colors are different then it will be the boundary element. Okay, so we will also run this in our grid of rows. The element above it is fine. Let's see the element above that. First okay, the element above that will be row left and right, if it is ever, it should be equal in color, only then it is okay, Y should be equal in color, and how will we see the element on the right side of this, right side, this should also be equal. Okay, this should also be equal to color and what will be our bottom element? The bottom element will be A P. Okay, this element should also be equal to color and what will be our left element? Aa mine is ok ho color is ok color is il hai so what will we do see so we will make our vector outside vector g ler kar te vector of per because we have to push row also we have to push column also pu ok Let's take this here, we will push back in B and give Thi rope comma column Okay, come comma, we have give Thi rope comma column Okay, come comma, we have give Thi rope comma column Okay, come comma, we have asked, we are doing pair push, so we have to put curly spaces, okay, this is the syntax for pair push. We have pushed it, look, okay, maybe we can color it here, we can do it here also, but what will happen after that, we will not know, like we have colored one element, but when we check some other element. If we do this, then we have put this condition or else this condition will become false, okay, so we will have to store all the rows and column indices in the vector first, only then we will color it later, okay, now we have created our def. What will we do? First of all, we will do this, meaning we will color it which was its original color, okay, how will we iterate the vector, look at the vector, okay, let's take int r, we will read the first row, okay? And let us take these Run this and the compiler is coming, wait, big is ok, come minus y, see y size minus aga y, and this will not happen because look here, ra aa mine, this is because then the color answer or the run time should come. Now yes, it is accepted but if we submit it, then do a test case. If it doesn't work, then one T has arrived. Yes, okay, how will it work, see any time. It may happen that we have the original color and we have this color. Sometimes these two can also be the same, okay, whatever we have to color, okay, the original color and this color, if we look at it, we will do it in this, will we never do this, when we add color to it, we will put its negative, okay? Here too, let's put a negative while checking. Okay, here too, we will put a negative. And here too, okay, here we have put a negative check, after that we will make it positive below. E Lesson Dot Size and G. Cy P done and if we ever think green any time green any i j is less than zero, if it was native then what will we do with it, we will multiply it by minus, ok, we will multiply it by minus, now let's run it, done. Now we will submit it gets submitted, the run time is coming, why is it coming, we made some mistake, we see that the initial is yes, we put a condition on one Y also, if our original color is red, then its other color is simply written and the gad is still coming. Hey let's see if it is equal in one minute then we will return it ok hey [ hey [ hey This is also correct ok here we don't get equal to two see ok now let's submit and see it has been submitted now isn't there a mistake here We did it, okay, so see what we have done in this code, first we stored the original color, after that if our original color is the same as the second color, then we simply return it to the grid, after that, otherwise we will run our DFS. How to run DFS? Just run the algorithm with flood fill. Whatever we did in flood fill, we did the same but what extra work did we do? In flood fill, we had to color all the elements. There are only boundary elements in it, we have to color them, okay? Well, we had to color them, so look, we did that in this, so here we colored the entire element, okay, we colored all the elements, but here we stored the elements which are not boundary elements. Okay, we stored it in the vector. After that, here in our main function, we iterated over that vector, went to the index of each row and column and filled it with our original color. Okay, after that we A negative was taken here, the negative was taken here so that sometimes it may happen that our color is ours and his is our new color, like look, this is our original color and after doing the color next to the original, it is okay. This color and this color, the adjacent sides of this color, that is, those that are not included in our component, should also be of the same color. Okay, so we have chosen a color which is not there in it, that means, minus negative. Look at this. It is given in the description that look, whatever our color is, it will be less than 1000, okay, and our color will be bigger than one, okay, so that's why we did a minus, after that what did we do at the end? At the end, we made a loop. If whatever element is minus, we multiply it by minus and to make it positive, then we return the grid. Okay, this was all about the code and if you liked the video, then like, share and subscribe and see you in the next video with another amazing code. Till then take care thank you
|
Coloring A Border
|
subarrays-with-k-different-integers
|
You are given an `m x n` integer matrix `grid`, and three integers `row`, `col`, and `color`. Each value in the grid represents the color of the grid square at that location.
Two squares belong to the same **connected component** if they have the same color and are next to each other in any of the 4 directions.
The **border of a connected component** is all the squares in the connected component that are either **4-directionally** adjacent to a square not in the component, or on the boundary of the grid (the first or last row or column).
You should color the **border** of the **connected component** that contains the square `grid[row][col]` with `color`.
Return _the final grid_.
**Example 1:**
**Input:** grid = \[\[1,1\],\[1,2\]\], row = 0, col = 0, color = 3
**Output:** \[\[3,3\],\[3,2\]\]
**Example 2:**
**Input:** grid = \[\[1,2,2\],\[2,3,2\]\], row = 0, col = 1, color = 3
**Output:** \[\[1,3,3\],\[2,3,3\]\]
**Example 3:**
**Input:** grid = \[\[1,1,1\],\[1,1,1\],\[1,1,1\]\], row = 1, col = 1, color = 2
**Output:** \[\[2,2,2\],\[2,1,2\],\[2,2,2\]\]
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 50`
* `1 <= grid[i][j], color <= 1000`
* `0 <= row < m`
* `0 <= col < n`
| null |
Array,Hash Table,Sliding Window,Counting
|
Hard
|
3,159,340,2186,2247
|
243 |
hi today we're looking at question 243 shortest wall distance um basically the question is given a area of strength and two other words right after that you need to find the shortest distance between them so uh if you look at example one um coding and practice the distance between practice and coding is one two three so that's yeah that's the answer uh that's why we have to be and then make some coding um we could either have makes encoding here where the distance is two or we could have coding and makes here where the distance is one thereby you need to find the shortest distance and the approach that we'll be taking to the problem is that we will be having two indices uh that would be uh they'll keep track of both the words uh as we iterate through the array of words and then we'll keep uh updating the indices as uh as soon as we see one of them and then after uh every iteration what we do is we try to check the minimum distance so anytime we see something that's smaller than the one that we've seen previously it gets updated and that's how we keep a track uh the solution will become clear once uh i start writing the code but the time complexity of the entire solution is of n where n is number of uh strings in the string array and space complexity is of one because we'll just be using uh three variables to store the two indices of the word one and word two and uh the minimum value that we've seen so far so let's get started uh we have end let's say index one um let's just initialize that to minus one index two and initialize us to minus one as well then you have the minimum which is integer dot um max value cool okay and then you have a for loop and iterate over all the words start plus yeah so if words of i dot equals one then you just update the index one is equal to i and then you do the same for forward two x2 is equal to i and after these conditions have been checked you want to look at if other both the indices are not equal to and that means both of them have been updated um you want to update the minimum that's not equal to -1 and what you do is you have the men you compare that to my document to what we've seen so far already are the difference in the new values if one of these values have been updated in the new iteration you want to calculate that so i thought absolutely to get the difference between them so index um index one and index two um yeah that's good and then in the end you just wrote uh down let's quickly run this um oh great does it the difference between those two or not yeah i should fix it equals index 2 and x 1 is not equal to minus 1 and x 2 is not equal to y is expected is equal to three why is this a problem index one is equal to minus one index two is four minus one and if let's do equals one index two minus one f index i oh it's minus one ah right here okay so this is that was a quote that was a problem um okay perfect awesome uh yeah so there was a problem if you have any questions let me know it was there was a it was a pretty easy problem but um do let me know if you have any questions let me know if there any problem that you want to solve for the questions uh in the comments below and don't forget to subscribe thank you
|
Shortest Word Distance
|
shortest-word-distance
|
Given an array of strings `wordsDict` and two different strings that already exist in the array `word1` and `word2`, return _the shortest distance between these two words in the list_.
**Example 1:**
**Input:** wordsDict = \[ "practice ", "makes ", "perfect ", "coding ", "makes "\], word1 = "coding ", word2 = "practice "
**Output:** 3
**Example 2:**
**Input:** wordsDict = \[ "practice ", "makes ", "perfect ", "coding ", "makes "\], word1 = "makes ", word2 = "coding "
**Output:** 1
**Constraints:**
* `2 <= wordsDict.length <= 3 * 104`
* `1 <= wordsDict[i].length <= 10`
* `wordsDict[i]` consists of lowercase English letters.
* `word1` and `word2` are in `wordsDict`.
* `word1 != word2`
| null |
Array,String
|
Easy
|
244,245,2320
|
1,639 |
Hello everyone welcome to my channel with mike so today we are going to do video number 23 of our playlist of dynamic framing ok and liquid number is 1639 it is a hard level question but I am pretty sir I make it very easy it is a promise ok This will be quite easy because what we always do in the question of DP is that first of all we make it in the traditional way, then we make the bottom with your own hands, so a lot of things become clear from it, the caste is fine and there is nothing fancy in it, which is the normal family way. It happens that Recon Plus Memory will be made right in the beginning, after that we will go to the bottom up. The name of the question is Number of Waste, you form a Target String, Life and Dictionary, OK, Google and Amazon look at its input and output and understand that what is the question, then the problem statement is very It is long but I will explain it to you directly from here that it has given you your target string. Okay, what you have to do is to create the target and how to create it. It has given you a dictionary neither of words nor of words. So, what are the properties of this word, all the strings are of length, okay, all of them are single and you have to make all these words by making them the target, okay, and one thing, the most important thing is that this is the target. What is the first character of A, isn't the parameter A, so it could be, so look at this, which index is zero one, two, three, you are indexing the most, zero one, three, zero, one, three, so you know what if you have zero indexed it. If you have done this, then you will not be able to do zero index of any word and you will not be able to do it, mother, let's do this, a, this, You can do zero and either way, if I erase this one, what is the one more thing that if I take mother, I have done this, I have done it, okay, so this is gone, it is okay and all these will not be able to do that, not the third index of all. You will be able to do it plus one more problem, do you know what Rakhi is that no one else can do it on the left side, neither this nor this, you will always be able to do it from left to right, nor is it picked up from the third index either. In the next word, if I go here, I can pick only the one after the third, fourth, fifth, if it is there, then it is okay, it is not here, and if there are big words, it is okay, but the example is like this, let's show one more example. Let me give you an example, this input is my target, which is mine, it would be like this, if it was a DBA, then I have chosen 's'. Okay, so the index is 1, so I have chosen 's'. Okay, so the index is 1, so I have chosen 's'. Okay, so the index is 1, so here the index is one and the left side is completely finished. Its index left side is not completely finished. You can do that also, its zero and one are over, now after this the next word is healed from here, so you can choose from one only, okay, you can choose from one only, so these are all the restrictions, all these restrictions and you I have to tell how many words and how many ways are there by which I can make this my target. Okay, I can make the given target my target. How many such wedges are there. Okay, so I am not going to draw the entire waste, it is too much. Here are 10 ways. This will be made from I have modified the question a little so that you can understand it comfortably, so here are 10 bases that can be made because look here one is ahead and here one is in the middle and here only one choice can be made. I would have chosen this without even listening to this and if I had chosen this, I would have chosen this and this would have been the choice and many have been sent, there is one here too, so there are many options, okay So now let's see how to solve it. Okay, now see how I came to DP and why I thought that it can be made from DP. First of all, how did I see it? Most of all, I did not understand how to make it. Okay, so first of all, what did I do? Science, how many words do you have? Give me one, two, three words, then okay, it's 3 years, then okay, one more two, okay, 3 words, zero, one, you and the length of all the words. What is the meaning of this? What is the first word? What is the second word? What is the third word? Kaka, it's okay, so now you think for yourself, see what I thought, it is given in the question instead of mother, if you have zero indexed the first word i.e. you have zero indexed the first word i.e. you have zero indexed the first word i.e. you have made it this, then brother, all the words coming after this will be If they have zero then the pen cannot do it, that is fine from the story, so if this is done to him, after this I will have to go to the next pen, this I know, it is okay, I will have to go to the next pen from the first index. It will be necessary because the pen has already finished, I had done it for the first word, okay, and it is possible that I have done this and not that. It is okay, I may have done that, not that, but one more thing has to be paid attention to, not here. But how can you choose because there was an A here and here also I want an A. If I did not have an A here in this pen, then why should I choose this pen? So I should know, okay, zero. There should be A in the pen, so it is okay, zero is there in the pen, there is A in the pen, isn't it? There is A in the pen, here I have selected this one and then it got flooded in the next pen, okay then it will be seen in the next pen, see B. Yes, B has been selected, after that we can go to the next pen, isn't it an obvious thing in the next pen, we can do this, not that, so we are going to the next one, so what do I want in the next pen, I want A in this. So if it is not A, then after this we will give it here too, if you see this, then a method has been found, then here if you do not take this and take this, then another method will be found. Okay, then look here, so okay B. If you wanted B, there is only one here, took this one, look here, you are looking here, there was another way, then after this, these middles are formed, then after that they choose this, now A, then after that they also choose this, so many like this. Ways can be made, now pay attention to one thing, I have two options, sister, I have two options, look here, I took this A and did not take this one, I took this A, sorry and did not take this one either. So I have two options, one is the note taking option, it is visible that brother, I will not take it at all, from there I will not take anything from the pen, okay and or taken, I will either take it again and if I take it, then also be there. Shouldn't the frequency be there? There should be only one frequency. Okay, so I can see two options clearly. Okay, so from here I got a little hint that yes, DP can help here. Why DB, since I have seen it, I will only write the review. No, I will write the text then I will memorize it. Okay, then see how to write the text. Before that learn one more important thing. Okay, first I have to write the input here. Look, what is it? Aqua, I will not make the entire arrow diagram, it will become too big, but one thing. To understand the important thing, I am making a small trade diagram here. Kaka hai na kaka what is my target ab hai ab mine this is my target ok so look at me first of all if I have come here I am standing here me First of all, I need an A, okay, so I looked here, this is the first level, I got an A here, okay, I got an A, so it is an obvious thing, if I have done the A with zero TrendDX, then I have done it, not the zero thunder of the rest of the words. I will get it, okay, one thing, I got it from here, okay, now mother, let's take one answer from this thing, then I will get one answer, that is, one thing, I got it from here, okay, now look at one more thing, when I choose this. If I take it then what will be the next state, see what will be the next state, CCA will be left, its BBA will be left and its master will be left, isn't it the first index, first, okay and one thing, if we take mother, I am erasing it. I am fine, I have not chosen the 0 index of the first one, without listening to it, I have chosen the living one, its fine, anyway, then the rest of the words are also missing, then the zero index is missing, it would have been gay because zero thane someone ever do that. Zero index of all the others will also be eliminated. Okay, do you know this? It has been mentioned in the question, so if we take mother from this, one thing will come out. If we take only one thing, then from this too, look at the next state, it will be CCA BB. ACA because you can fly Zero Thunder from here or else I had taken it when Zero Thunder came in the same set and now I have taken it has been straight A since the very beginning, so look at this, so why are we all the states? Draw and see all the states. Why draw all the states? What will I do? I will see how many A's are there in the zero index. Okay, look, I am going to race this cleanly and tell you. I am seeing two A's in the zero index. How many A's are there in the 0 index? How much is one account, if there are two, okay then what will I do brother, I will do the same thing once tomorrow and multiply it by two. One more here is there a need to divide it, there is a need to do this, I have done this. This race has been done, right, just do it once tomorrow and then multiply it by you and this was very important to understand because if I put this A, okay, then the next state that would come would okay, then the next state that would come and all the other words would also have zeros. Thandex is no less now, isn't it, this is what is given in the question, or even if I am late for this A, my next set would have come only here and I could have taken all the rest with zeros, then it is the same, isn't it, all the statuses Why would you draw, just find out the frequency, not how many are there at the zero index of the same frequency. Okay, and multiply by this number, we will multiply by you, tomorrow we will multiply only once, the result that will come is only from that, if there is a state, then there is an answer. It will come, okay, then we will draw from the state, so we will explore in the branches, time limiting will become an obvious thing, okay, so what does this mean, you will have to store one extra information first, what is that brother, no in every index. How many characters are there A B K C K D K A K sara i.e. A Tu S K I K sara i.e. A Tu S K I K sara i.e. A Tu S K I will store it first then I will know the frequency before hand. Okay, I know the frequency before and so I have obviously used a method to find the frequency. And the method is to loop again and again, which is not there, now you take the index zero, you had chosen it, then all these zeros are finished, now one has come big, index one has come big, so now see if the index is right. In 'One' C has come once and B In 'One' C has come once and B In 'One' C has come once and B has come once, then you will drive again and again in the entire string, then you will index it on the list and then you will leave, then the next question will be tomorrow and the text will be for you, then if you travel again then it will be better Babar. Before traveling, it is better to store one frequency of yours named 2d in which what you will do is how many frequencies are there in each index, make noise of each character and then if you pay attention, your table will not look like this: your table will not look like this: your table will not look like this: Frequency It will look something like this, look, here it is C and till where dot will go, it will go till S. I want the frequency of each character on every index. Now okay, how much is the index. Look, here is the tax index, here also here is the tax index, here. But still the index is ok so I am drawing in the table hero one you are zero one you are ok so from zero to how many A's are there on the index let's see how many A's are there on the index from zero to one so one is seen here. One more A is seen here, there is no zero, what did I do, there is one frequency on zero index, that is two, okay, what is the frequency of B, let's see how much frequency of B is on zero index, it is zero index. But what is the frequency of 'C'? what is the frequency of 'C'? Look here, it is visible here. Okay, then on the second index, we can do this. The frequency of A is on the second index. The frequency of A is zero. On the third index, the frequency of A is visible as two. I am seeing zero here, two here, then file everything similarly. If you give it, then in the future I will know what is the frequency of any character on which index, what is the frequency of what character is required, whether a life is in the index, then it is very important, so this can be done by drawing tables. Okay, now let's see that the recjan we will write is not a story, how will we make the date in our family style, this recjan plus momo, so from the story I will tell now, you will understand yourself that you are recjan. You will write it, how will you write it, then do memorization yourself, dog, you have learned that many times, how to write butt recension, you should understand it, okay, so look, pay attention, this was my input, okay, so it is an obvious thing. I will be standing here saying that brother, I want A first, okay, I want this first and I will start from here, what does it mean that it is at i0 and what is this is the index of the target, which is the character I want so that to create this The target is the index and yes, what is mine, zero is the index of the dictionary. Now see what zero means, it is possible that I can take zero coolness of this word, either I can take zero coolness of this word, or I can take zero coolness of this word. We will be able to take zero index of any one word only, if we take mother, I have taken its 0 index, then it is obvious that I can take its zero index, sorry, I will have to make J = 1, I will have to make J = 1, I will have to make J = 1, I will have to go to the right side, I have taken zero. So if you have taken one, then you will have to do it like this, okay, and now I have the option, okay, I can either take this one, this is okay, or I won't take it, okay, or I am Jai to this one or So either I should not take it or I should accept it or I should not take it. Okay, so I have three options, right, I have all three options, that is, sorry, not three, I have two options, that is, I can either win, that is, whatever is the victory index. Either I take it or I don't take it's okay, then you see for yourself, I am going to reduce only two variables. Here, in the recognition function that is going to happen, I will just send I. What is I, brother? I is my index which iterates on the target. Will do, okay, till now it is clear and there is one which is the index of the dictionary. Okay, in the dictionary which we are traveling, I will remove it from here. This is clear to us, okay, now see, this is a very important thing. First of all, I have two options. What did I say that this note was taken? I did not take this Jeet index. Okay, if I did not take this jet in the dictionary, then what does it mean that I am K plus one? I will go to the side, okay, if it was zero, I am not taking it, then brother, I will not consider it, if I go to plus one, then what will I say, come on brother, no problem, you can solve it because I have come, India is not the only target. When I have not taken anything, then the target will not be formed, otherwise I will remain on I's side, but I will be flooded further because I have not taken this brother-in-law, so flooded further because I have not taken this brother-in-law, so flooded further because I have not taken this brother-in-law, so one option has become mine, this has become the other. What was the option? Do you remember that I took it for GS index? Okay, this is a very important thing. Pay attention to it. So, if I took it for Jeet index, it means mother, I took it for Jeet. So I saw two options. Here we are saying that either I will win this Hindi or I will take this, okay, you will look at all the words, where is yes, then you will solve it tomorrow, what had I taught earlier that do it only once tomorrow, but The number of frequencies were zero but multiply them by that. Okay, what is happening here is that I have taken the Jeet Index. Okay, that is, as many zeros as there are, let's see how far ahead we are on the zero index. One thing is visible. There is one here, it is visible here, okay, then I will find out the frequency, okay, I will find out the frequency, whose zero was it, which zero is ours, because I don't want one, so I am looking for the target, which is the target, what is its frequency? Okay, so if I am considering, then which letter will I be getting? If I am getting the letter 'A', which letter will I be getting? If I am getting the letter 'A', which letter will I be getting? If I am getting the letter 'A', then I will see how many times 'let zero' is appearing. Once here, there how many times 'let zero' is appearing. Once here, there how many times 'let zero' is appearing. Once here, there is an option. So, as many times as ' is an option. So, as many times as ' is an option. So, as many times as ' A' is seen here, the frequency should be known, A' is seen here, the frequency should be known, A' is seen here, the frequency should be known, not how many times 'A' is appearing in the Jet index, so I have stored here how many times 'A' is appearing in the Jet index, so I have stored here how many times 'A' is appearing in the Jet index, so I have stored here how many times 'A' is appearing in the 'Jeth' index, how many times 'A' is appearing in the 'Jeth' index, how many times 'A' is appearing in the 'Jeth' index, remember, this is why I made the table. Here was the frequency, here was the frequency of What is my character, this row is done, what is my character and frequency, this is not done, sorry, index, this is done, okay, this table was created, we will also populate this table, it is simple, okay, so we will multiply this many times and only once. We will solve it only once, we will do it tomorrow, okay this time I have taken I, so brother, we will do I + 1, okay, so now I can't do further zero because of cold, otherwise I will have to go to Plus One of Anywhere. Okay, I will comment till here, but it was very important, still after reminding, listen to each line again. Okay, it is very important, so let's see and got the take. Okay, and we need total base, otherwise what will I do brother? I will return the note, as many times as I could form the target in Take in Plastic, and as many times as I could form the target in Taken, I will add both and my total will be sent. If the form and the target sting are fine, then see how simple the solve function is. This question seemed to me that the name is big but the philosophy is small, the question is very big and the complex is going on but look how easy it is to solve it, isn't it right? If two variables are changing then you will take 2d DP and I will do voice and also read some corner cases to see otherwise you will understand the cases what will happen if I keep doing plus this has come or not if this is the end of it Reached target dot length means I = dot length means I = dot length means I = target dot length. Let's take the length of the target. M, right? If I have reached N, it means I have formed all the characters in it. The target has been formed, which means I must have achieved it in one lesson, so do one. Let's go to two, one method has been found ok and what could be the second condition that brother, I have not made the target yet and whatever is there is finished, to what extent has this equal of you reached that it has gone to three. Neither the length of each word is equal to the length of each word nor let's take it as K. Okay, so if we go till S = K, take it out. if we go till S = K, take it out. if we go till S = K, take it out. Okay, then now we will make the return zero because we are not doing forward form. What is J = 0? Brother, the length of every word What is J = 0? Brother, the length of every word What is J = 0? Brother, the length of every word is and the length of every word is right. And what is it saying that whatever is mine is done, right here it is three, so the maximum index is right. If this has gone till my tax then it is an obvious thing, now we cannot go further, if it has gone till the tax then it is ok, no more words can be made, hence we will return zero here, ok then this is my silk plus. Simple story, I understood what will happen, now we just have to code it, one more thing, remember, we had made a frequency table, it is not very easy to make a frequency table, what did I say that the table is something like this? Our second index will be okay, meaning it will be -1 index of the length of the meaning it will be -1 index of the length of the meaning it will be -1 index of the length of the word and the frequency of the character on each index A frequency B frequency C frequency D Okay so think for yourself on which it is going to loop. How simple will it be? Okay, the follow up will not be very simple, meaning it will be like this: meaning it will be like this: meaning it will be like this: Every pen has to be filed, no, we will file this pen first, okay, tomorrow this is equal to zero, how much is the pen, is it till 12345, right? Let's take the pen plus. Okay, after this, look, I am now moving to the first pen. I will need the first character of all the words. Dictionary Which character is 'K', 'Mines' will be found. Which character is 'K', 'Mines' will be found. Which character is 'K', 'Mines' will be found. And which index is going on? Kalam index is going on? How to write plus momo? We have understood it. Okay, if this is understood then the bottom will still be written smoothly but first let's write its code and submit it. Okay. So, first of all, let's make it like Momo in recognition. The question is quite good. It is good for the practice of DP. Recognition will be practiced very well. First of all, let's define some of our variables, where in M is what is the length of the target. It will be what is it, what is the in M is what is the length of the target. It will be what is it, what is the in M is what is the length of the target. It will be what is it, what is the length of each word, the dictionary has the length of all the words in the dictionary, so I am taking it as my mother, okay, now it is my own, what did I say, simple return solve this will do, okay in this I What you were sending was zero, starting from the index, isn't it the target, and now I have taken K as zero, okay, if we calculate the frequency, then we will have to send the frequency too, it is an obvious thing, right, and yes, send the target also. And now let's make the frequency. So, first of all let's plot M. What is my target dot length? Okay and what is my word of zero dot length? The length of is okay, now after what I said, let's make a frequency table. Okay, so remember the number of days, the number of characters possible in each index. Okay, so there will be 26 days because these and the columns in each index. How many will there be? It is correct that the length of the entire word is in the dictionary, so if we find out the frequency of which characters in each index, then there can be 26 characters. There can be 26 lowercase characters. It's okay for this English alphabets, let's populate it first. Okay, look at the forum and pen, make it equal, you zero pen, give it pen plus, so tomorrow everyone is going to write every pen. If you say pen, then which index is going on? Now it's okay, which word is it brother? Talking about the word of zero, then the frequency of K - A. On then the frequency of K - A. On then the frequency of K - A. On which index, in the pen function, I increased its frequency of this character in this pen, that is, how much frequency in this index. I have given this big, so I have made this frequency table, okay here, now I am going to write the return solve, this solve function, okay, in solved, what are you sending, brother eat, I am sending, enter G is sending and your frequency. The one who is sending the table is sending the frequency table and what else are he sending? I have seen the string and target character, it is okay and if I have not seen it and I am finished, then the obvious thing is that we will return it to zero. Okay, after this the most important thing is brother. Meaning, you have not done anything for the current character came in the target, poor guy, you have not taken anything for him, so what is the point of the current character and I discard my current G pen, you will go to G plus one. You have sent the frequency and target and if you take it, then what did I take it and if you take it, then what did I say that it is okay, first we will do the solve function tomorrow, if we took it then the current came and the character got it, then we will go to I Plus One and We will definitely go to plus one because now in the next column we can send the frequency and send the target but what did I say that instead of doing it multiple times tomorrow, it is better to multiply by the frequency, okay then by the frequency. What is the frequency brother? Whose frequency is the character I am searching for now? I am searching for the target of the eye. I have found an index and for which index I am searching for the brother-in-law. His frequency will be searching for the brother-in-law. His frequency will be searching for the brother-in-law. His frequency will be found from here and multiply. Will do in this, solve plus is taken, solve is given, maximum is okay, thousand is given, I am okay, let's set it to T - 1, okay, let's set it to T - 1, okay, let's set it to T - 1, size of T - 1 and what did we do every time by running it. But one more thing is what is given in the question that you have to divide the answer by the modal and look at what is given here, the return is okay, here also I am taking the mode and here also I am taking the mode is okay and here is what I am sending. Here also I take the mode and send it, okay all the runs should be done, there must be no mistake in the story, okay, what mistake did I make, what did I say here, which characters are visible here, from which index are they viewing, I made the word off zero. Every time here the word will be of pen and not the index. We are talking about the character of this index. Now let's color it and see. Let's submit it later. Let's see its time complexity. You must be watching yourself. That I have taken the maximum, but what will be the length, it will be of M cross only, right, you could have taken M + 1 + 1, you could have taken M + 1 + 1, you could have taken M + 1 + 1, this is the DP table, so the maximum we will take for each set. If you are traveling only once, i.e. visiting, traveling only once, i.e. visiting, traveling only once, i.e. visiting, then the time complexity will be as per the dimensions of M Cross, okay, so this is one video of my question, now after a little fear, I will release another next video. In which I have made the bottom up separately so that the video does not become too long, okay, generally recognition memorization, people see it first, after that you see the bottom, so first I have put this video, now after a little fear, you also see the video of the bottom. Will be uploaded ok able tu help any doubt hota hai please in d common session attractive and see next video 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 |
508 |
hey everybody this is Larry and apparently there's some issues with the daily plan uh hit the like button hit the Subscribe button join me on Discord um today doing an extra bonus day or a bonus whatever uh bonus for I'm doing an extra bar uh it is Friday the 13th here in New York and people are having issues with uh with um with the daily plan because it turned out to be a premium Farm even I had some issues if you watch that video and you're coming from there but let's do uh do a random medium problem and again when I do have premium they give me a bomb that is in premium but that's fine today's plan is 508 most frequent subtree some okay what does that mean come in the wood of a buying tree returned the most frequent sub tree sum if there's a tie returned Y is the highest frequency okay uh the subtree sum of a node is defined as a sum of one node Drive formed by the sub tree value what rooted that known okay and what are we supposed to return um just return oh I don't have to return all of them because this was returning wait what are we turn but most frequent oh man I think I've missed read this somehow because my English is bad I was thinking about the max I was like most frequent Max sub treesome for some reason and I was like what is what do you mean I don't get it um but yeah I mean all these three probably happened once and this one happened twice from the root and so forth okay I think this is pretty straightforward in concept um you just get us some of the sub trees and then put them in a collection table and then maybe do some sorting and that's pretty much it um I mean you know you can maybe make some minor adjustments uh we'll talk about that in a sec but and it's for 10 to the fourth it's not even worth doing because I'm being lazy but yeah so let's do that and then we uh we have sub trees some say array of x uh node in this case if node is none we return zero otherwise uh this is a binary tree it is a binary tree so yeah so left is to go to foreign cannot turn it off anyway um so this is you know regular uh regular subtree sum you know you kick it off I mean you don't return but you just kick it off and you'll probably do very happy right and then now we just have to kind of add a thing to keep track right so now we want to counter so maybe it's called counter because I'm not creative or maybe I'm really creative and then that's pretty much it right we will do it from boo and I think this should be good uh and now I think there's a counter dot most let me take a look I think collections that kind of actually has like a most frequent thing um but I think it just like some I actually don't know what complexity does not I think about it so it does have a most common but it doesn't do like any type record stuff so it doesn't really um you know it's not super useful but yeah so if you could do it in two ways like I said you could do in Sword but you can do something like max value is you go to calendar dot value and a Max of this right and then now you can just go for it again uh for uh all right all right let's go submit cool uh yeah I mean I would I don't worry about stop I get questions sometimes about like the beat percentage um because I know my complexity I don't really worry about and this is linear time linear space um and you really can do better than that's the lower bound or you could say oh space if you want to say that but there's no n here so linear time linear space um like I said that's probably close to lower bounds I'm not going to worry about it that much um yeah let me know what you think let me know if you have any struggle with this one um I mean we've been doing tree prompts all week so it's kind of uh just practice this week I suppose on trees uh even though this isn't part of the weekly tree things but yeah um that's it that's what I have so let me know what you think have a great weekend stay good stay healthy to good mental health I'll see you later and take care bye
|
Most Frequent Subtree Sum
|
most-frequent-subtree-sum
|
Given the `root` of a binary tree, return the most frequent **subtree sum**. If there is a tie, return all the values with the highest frequency in any order.
The **subtree sum** of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).
**Example 1:**
**Input:** root = \[5,2,-3\]
**Output:** \[2,-3,4\]
**Example 2:**
**Input:** root = \[5,2,-5\]
**Output:** \[2\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-105 <= Node.val <= 105`
| null |
Hash Table,Tree,Depth-First Search,Binary Tree
|
Medium
|
572,2126
|
1,684 |
okay this is 1684 count the number of consistent string we have all this string cost of distinct characters structures and their way over coded world first thing is consistently for character interesting appeals in their signal okay look at the number of consistency for example number one their announced character is just a b so the word one atp is narrow but in this case this number also third in this case we need to return the two and our second case abc is allowed so to a is okay b okay one two three four five this is okay all the cases are okay so we can call like this we need to prepare the return counter and every single word we need to convert these words into your set and master all the characters and if the length of this round character is more than zero then it's not the right case what's the third right system then it is there for long case you can code like this okay you passed all the questions
|
Count the Number of Consistent Strings
|
find-latest-group-of-size-m
|
You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`.
Return _the number of **consistent** strings in the array_ `words`.
**Example 1:**
**Input:** allowed = "ab ", words = \[ "ad ", "bd ", "aaab ", "baa ", "badab "\]
**Output:** 2
**Explanation:** Strings "aaab " and "baa " are consistent since they only contain characters 'a' and 'b'.
**Example 2:**
**Input:** allowed = "abc ", words = \[ "a ", "b ", "c ", "ab ", "ac ", "bc ", "abc "\]
**Output:** 7
**Explanation:** All strings are consistent.
**Example 3:**
**Input:** allowed = "cad ", words = \[ "cc ", "acd ", "b ", "ba ", "bac ", "bad ", "ac ", "d "\]
**Output:** 4
**Explanation:** Strings "cc ", "acd ", "ac ", and "d " are consistent.
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= allowed.length <= 26`
* `1 <= words[i].length <= 10`
* The characters in `allowed` are **distinct**.
* `words[i]` and `allowed` contain only lowercase English letters.
|
Since the problem asks for the latest step, can you start the searching from the end of arr? Use a map to store the current “1” groups. At each step (going backwards) you need to split one group and update the map.
|
Array,Binary Search,Simulation
|
Medium
| null |
451 |
hey everybody this is Larry this is me doing uh day three of the decemberly code day challenge oh excuse me hit the like button hit the Subscribe button join me on Discord let me know what you think about today's poem I'm probably gonna do an extra one just to warm up a little bit for the Advent of code that I've been doing um had a good day yesterday let's kind of keep it up uh I don't have I don't no wait aiming for anything high or anything but you know it would be nice to finish on the leaderboard um okay today's problem is 451 sort count is by frequency given as sudden the decreasing order based on the frequency of the characters okay and then one of the multiple answers we turn any of the mocha I mean I think a couple of ways to do it I'm going to try to do it as easy as possible um so we have frequency as you go to collections.counter of s and that will collections.counter of s and that will collections.counter of s and that will map the character to the account I mean you can do this in for loops and a dictionary um but you know it's just obviously a little bit more um takes more typing or work but this is fine I think so then now um we can do you know um we can I don't know that I have to convert it to list explicitly but now we can sort um sort this by um key is equal to Lambda for character we want to sort it by um the negative of frequency X this is so that it's decreasing order though you could also just sort it by regular order and then reverse it or something if you like um or like you know someone like this I suppose I think this is true this is very whatever and then we just return this but converting it back to string um cool I wonder if I could I wonder if you could do um walrus notation in some way to make it one liner but let's give it a submit oh stop oh did I mess this up too last time if I did um but basically I'm not doing the tie Breakers correctly I mean there are no tiebreakers but then I don't know I mean I think this is a valid interpretation but I don't know I feel like I said the same thing yesterday uh so I don't know what to say about it but I feel like that's a right interpretation in a precise 977 Day Street yay I'm precisely how they write it but hmm oh hmm I guess I just didn't read the I didn't read the examples uh because but why did they not put it Underwood okay fine I don't know what to say about it I mean it's fine I'm not good at that I make the same mistake three times as well or four times okay well that is kind of sad actually it looks like I'm yesterday I made the same mistake three times today I made the same mistake four times so I don't know maybe I do have a heuristic in my head and I am very consistent over the last uh three years or whatever it is I don't know what to say um but yeah this is going to be uh linear time then your space I know you're going to say something about your sorting but remember that there's only 26 characters right so um so that's gonna oh wait I lied about that one because I guess we're starting to end actually so that's n again technically um you can rewrite this with a linear sword or like an alphabet sword where you can even just reconstruct the string from the 26 things um and the counts and you know you could do it in your time so my code is actually I lied it's and again um linear space um but you can convert it to linear time linear space pretty quickly with uh using Alpha as in the size of the alphabet as a as an input um cool um that's what I have with this one for now let me know what you think I'm gonna do an extra problem it might be premium though but I don't know let me see uh but yeah stay good stay healthy took a mental health have a great weekend I'll see you later and take care bye
|
Sort Characters By Frequency
|
sort-characters-by-frequency
|
Given a string `s`, sort it in **decreasing order** based on the **frequency** of the characters. The **frequency** of a character is the number of times it appears in the string.
Return _the sorted string_. If there are multiple answers, return _any of them_.
**Example 1:**
**Input:** s = "tree "
**Output:** "eert "
**Explanation:** 'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr " is also a valid answer.
**Example 2:**
**Input:** s = "cccaaa "
**Output:** "aaaccc "
**Explanation:** Both 'c' and 'a' appear three times, so both "cccaaa " and "aaaccc " are valid answers.
Note that "cacaca " is incorrect, as the same characters must be together.
**Example 3:**
**Input:** s = "Aabb "
**Output:** "bbAa "
**Explanation:** "bbaA " is also a valid answer, but "Aabb " is incorrect.
Note that 'A' and 'a' are treated as two different characters.
**Constraints:**
* `1 <= s.length <= 5 * 105`
* `s` consists of uppercase and lowercase English letters and digits.
| null |
Hash Table,String,Sorting,Heap (Priority Queue),Bucket Sort,Counting
|
Medium
|
347,387,1741
|
1,877 |
hello everyone let's solve the today's LOD challenge which is minimize maximum pair sum in an array so in this problem we are given an array of integer numbers and what we have to do is we have to maximize the pair sum such that the maximum pair sum which we are getting is minimized in this array so let's have a look on the on example try with this example in this case we are not allowed to straight away use the pairs if we use the pairs three and five it would be eight and it would be five so in this case maximum value is eight but we are given that we have to minimize this maximum pair sum so for that how do we minimize the maximum pair some so in that case like the approach came in my mind is like why don't we just choose the minimum element and the maximum element together at every instant so in this case like we will choose the minimum element and the maximum element and after that the second minimum element second maximum element okay now the pair sum would be 7 and six so firstly these were the pair eight and five now 7 and six are the pair so that's why we uh we can choose in the way that we are choosing the minimum and the maximum element so if we have to choose the minimum and maximum at uh every step why don't we just sort this array straight away so if we sort this array it would be like this 2 3 5 and we can use two pointers one with the at the starting and one at the end and we'll uh keep on moving in this direction so and at every moment we'll just capture the maximum sum so here the sum is 7 and for this pair it is six so maximum sum so far is seven so we are going to return that okay it was quite simple like uh I don't find it a medium level problem it's quite easy we just have to sort the array and then doing the iteration using two pointers and check for all the pairs so the approach would be sorting the array and using two pointer one from starting and one from the end and checking all the pairs we are also given that uh the size of the given array would be even and we can only use one item for one pair only okay now let's start writing the code so first of all we are just going to sort this array arrays sort nums I'm just also capturing the length now we can take a variable to store our answer and in the answer I will just return this now we have to check for all the pairs 4 i = 0 I less than it should go to till 4 i = 0 I less than it should go to till 4 i = 0 I less than it should go to till n by 2 and I ++ math ++ math ++ math dot Max nums of I first largest from starting plus largest from n nums of nus1 - r I so for largest from n nums of nus1 - r I so for largest from n nums of nus1 - r I so for an array of size four the first element should be zero and the last element should be three which is length 4 - 1 - three which is length 4 - 1 - three which is length 4 - 1 - I let's try to run this Cod go to typo okay task cases are passed now let's try to submit it okay got submitted successfully okay thank you guys
|
Minimize Maximum Pair Sum in Array
|
find-followers-count
|
The **pair sum** of a pair `(a,b)` is equal to `a + b`. The **maximum pair sum** is the largest **pair sum** in a list of pairs.
* For example, if we have pairs `(1,5)`, `(2,3)`, and `(4,4)`, the **maximum pair sum** would be `max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8`.
Given an array `nums` of **even** length `n`, pair up the elements of `nums` into `n / 2` pairs such that:
* Each element of `nums` is in **exactly one** pair, and
* The **maximum pair sum** is **minimized**.
Return _the minimized **maximum pair sum** after optimally pairing up the elements_.
**Example 1:**
**Input:** nums = \[3,5,2,3\]
**Output:** 7
**Explanation:** The elements can be paired up into pairs (3,3) and (5,2).
The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7.
**Example 2:**
**Input:** nums = \[3,5,4,2,4,6\]
**Output:** 8
**Explanation:** The elements can be paired up into pairs (3,5), (4,4), and (6,2).
The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8.
**Constraints:**
* `n == nums.length`
* `2 <= n <= 105`
* `n` is **even**.
* `1 <= nums[i] <= 105`
| null |
Database
|
Easy
| null |
107 |
hello everybody welcome to my channel hope you are enjoying the coding and today is a very famous problem on tree which is a binary tree level order traversal part two so in this problem it is given as a binary tree and we have to print the label order traversal but not from the root to bottom but we have to print from the leaf nodes then followed up till the root nodes level and the nodes should be in order from left to right so here in this tree we have to print first fifteen seventy seven then nine twenty then three so these are the three levels we return we have to return in a list of lists so let's first understand how we will solve the ah let us say this is my node which is three ah three the given tree and then we have here nine twenty so nine and here is a twenty and then we have left child of twenty is fifteen and here we have seven so how we will do the basic binary like level order traversal of the tree so we have to go first level this is a level one let me mark like l one and this is our another level which is let us say call it l two and this is another level which is l three so we have to if for the simple level order traversal we can return like list of one like l one then l two then l three as a list of list so l one l two l three is also a list so it is this is r now in this problem we have to do a twist so we have to written in this format like l three first and then l two and the l one so one way of solving this problem just we will do the binary label order traversal and then use the collection dot reverse method and reverse this so this is using collections dot reverse method from the library classes of the so first how we will get the label order so for label order traversal we will you make use of a data structure which is very famous like q we will go q data structure here for the root so what we will do we will first add the root node here so which is three so let me take here instead of root i will take the data so we will take the three then we will fetch out this three and take a one size variable like current size so this size variable will give us a ah ident to create the labels so we will take the size so first initially once we start the process the size will be one so we will process the node three so first three will come here and we will add the three in the one of the new arraylist we will create a label one and we will add once we process this we will add the into the lets we will take another list of list which is called result here so we will add the l one in that so every iteration then we will check that does this node current node has the left child yes if it is yes then we will add less so in our tree it has 9 here we will add the 9 we remove this and we will check again now for right child does it has right child yes it has so we will add the 20 in the queue now we will again calculate the size of this current queue in the next iteration so it will be 2 so now we will process 9 and 20 and add into 9 and 20 in our l2 so l2 will have 9 first and then 20 and then for 9 we will check does this has left child no then we will not do anything if does this have right no we will not add it now for 20 yes it has left child 15 this all went out now we will add 15 and 17 in q so this way we will generate the level order traversal so the first approach for achieving the result of this problem we just use the reverse after the processing label order traversal using the collection dot reverse so let us implement first the basic label order traversal and using the collections we will solve this problem so first we need a list of integer which will be let us say called it result and we will initialize it and we need a queue to store our nodes so which is tree node we will call it as q and it is initialized with the implementation of linked list and here we will add first add the root node in the queue then we will process this while the queue is not empty while q is not empty we will process and then we need a size variable here in size which is the size of the current queue so we will take that and then we will create a list of which is an integer we have to get the for every level by level so let me call it level itself and initialize it from the array list and here this will be now we will use another loop and run until the size is there we will process the nodes of the which like all the nodes on the current level so here we will get the node first in the root variable itself say so this is from the queue we will fetch all the node q dot poll once we got this we will add the this into our label variable label add the root dot val so we have to take the value only and then we will check here if root dot left is not null in that case we will add the root dot left in our queue similarly we will do check for root dot write if not equal to null and add this also in the queue so this is what basic level order done once we process the current level and the first level we will append add into the list so which is level so this is the simple binary level order traversal now for this problem we will use the collections dot reverse our result so this will reverse all the labels and in the end we will return result so this is the basic implementation so let us try to compile our code oh there is error expected here ok i need missed one angle bracket for closing this any other error no let us compile again so it is compiling and it is judging now and we are getting the correct answer so lets submit our solution ah oh there is also we need to careful the problem we need to check the empty check if there is no node in the root so we will do if root is equal to null we sh just return new array list okay so this should let's test the this test case here empty one so it is judging with the empty test case we are testing now so whenever you do this problem like always in the case of tree problem always try to add the root null check condition which is like safer to avoid the wrong submission so this is accepted so let us talk about the time complexity of this problem so time complexity like here if you see we are processing all the node which is o of n let us say we have n node and this collection dot reverse will take o of h time which is parallel sequential to the o of n so the overall time complexity so this is o of h this will take o of h where h is a number of levels number of labels so this is what so overall time complexity is still o often where v n is the number of nodes so this is a one approach another approach we can do so just we need to reverse the levels so what we can do so we can get l 1 l 2 l 3 here so what we can do instead of like in this code here itself we will append using the this method so result dot add using the add the every time on the index 0. so this will automatically append then like what next level so here so we have this tree let us say so these are the labels so we first we will get the first level we will add into the list here like this so this is like label one added here then we will get the second label so for second level we will append this push this to the right and then at so this will be l2 l1 which is we needed then similarly for l3 we will do l3 but this operation is bit costly because appending into the list is a o of h every time we are doing for every iteration of label in our tree so this solution will be costly so there is another third solution as you already know like we have to reverse the orders so we can use a stack here and add the labels when we are processing first in the stack like l1 l2 and then l3 and then create the result from the stack pop the l3 add into the list then l2 then l1 so this is another approach but this needs the extra space so the best approach which is we implemented using a collection dot reverse so this is the solution thank you if you like my solution please hit the like button and if you have any questions ask in the comment section and subscribe to my channel
|
Binary Tree Level Order Traversal II
|
binary-tree-level-order-traversal-ii
|
Given the `root` of a binary tree, return _the bottom-up level order traversal of its nodes' values_. (i.e., from left to right, level by level from leaf to root).
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[15,7\],\[9,20\],\[3\]\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[\[1\]\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-1000 <= Node.val <= 1000`
| null |
Tree,Breadth-First Search,Binary Tree
|
Medium
|
102,637
|
1,869 |
hey everybody this is larry just me go over q1 of the weekly contest 242 uh longer contiguous segments of one than zeros um i think this one is pretty straight forward to be honest um it's just you know there's a lot of different ways to do it implementation wise but as long as you kind of keep it uh you know even uh you don't even have to do it linear because it's you know length is a hundred um but yeah uh so yeah just do it however you like to do it i don't know i don't really have much to go over for this one but the way the idea is by using group by which kind of groups can uh contiguous uh things together and then i just set them you know the longest of the length one is greater than longest of length zero or of segments of zeros and ones and that's basically what the prime asks and that's pretty much it um yeah uh that's all i have for this one and this is linear time uh linear space but you know uh yeah because we kind of the group by is a little bit messy but you know you could do it in less than that it could be linear time constant space if you're really uh slick about it but yeah that's all i have for this one uh you could watch me sub it live next loading so hey uh yeah thanks for watching hit the like button hit the subscribe button join me in discord let me know how you did on this contest i did okay but uh yeah and also on this problem what do you feel about resolution um yeah uh you know stay good stay healthy to good mental health and i will see you later bye
|
Longer Contiguous Segments of Ones than Zeros
|
longer-contiguous-segments-of-ones-than-zeros
|
Given a binary string `s`, return `true` _if the **longest** contiguous segment of_ `1`'_s is **strictly longer** than the **longest** contiguous segment of_ `0`'_s in_ `s`, or return `false` _otherwise_.
* For example, in `s = "110100010 "` the longest continuous segment of `1`s has length `2`, and the longest continuous segment of `0`s has length `3`.
Note that if there are no `0`'s, then the longest continuous segment of `0`'s is considered to have a length `0`. The same applies if there is no `1`'s.
**Example 1:**
**Input:** s = "1101 "
**Output:** true
**Explanation:**
The longest contiguous segment of 1s has length 2: "1101 "
The longest contiguous segment of 0s has length 1: "1101 "
The segment of 1s is longer, so return true.
**Example 2:**
**Input:** s = "111000 "
**Output:** false
**Explanation:**
The longest contiguous segment of 1s has length 3: "111000 "
The longest contiguous segment of 0s has length 3: "111000 "
The segment of 1s is not longer, so return false.
**Example 3:**
**Input:** s = "110100010 "
**Output:** false
**Explanation:**
The longest contiguous segment of 1s has length 2: "110100010 "
The longest contiguous segment of 0s has length 3: "110100010 "
The segment of 1s is not longer, so return false.
**Constraints:**
* `1 <= s.length <= 100`
* `s[i]` is either `'0'` or `'1'`.
| null | null |
Easy
| null |
1,716 |
start today's daily question calculate money in the Lal bank and like um hery wants to save money for his first carard so he put like some money into the bank every day he started by putting $1 on every day he started by putting $1 on every day he started by putting $1 on Monday and the first day every day from like Tuesday to Sunday he put like $1 more than like a day before um like $1 more than like a day before um like $1 more than like a day before um like on every subsequent Monday he put like $1 more than the previous Monday like $1 more than the previous Monday like $1 more than the previous Monday and we want to return in and we want to return like the total money so for this question we can use math or um what we can do is we simulation is like a blue Force so here is 1+ 2 plus 3 like a blue Force so here is 1+ 2 plus 3 like a blue Force so here is 1+ 2 plus 3 + 4 okay and seven St it's 1 2 3 4 until + 4 okay and seven St it's 1 2 3 4 until + 4 okay and seven St it's 1 2 3 4 until 7 and the second is from 2 three four okay um like number of week now we um I think it's Zer it's one so 4 I range um like it should be it should have like tub of the top should be four okay but no worries f i more n i 7 to Z like answer is zero plus our e to number of week T is zero like current is zero and current is number of quick okay then we do current just return answer so if it's like Monday the first day what we need to do is we Plus or equal to like the number of the week and the current is the number of week I'll say like here should be yeah plus one and number of week plus equal to one and number otherwise plus one and the current week like increased by one so we return the answer great so we pass this question
|
Calculate Money in Leetcode Bank
|
maximum-non-negative-product-in-a-matrix
|
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**.
He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**.
Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._
**Example 1:**
**Input:** n = 4
**Output:** 10
**Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10.
**Example 2:**
**Input:** n = 10
**Output:** 37
**Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2.
**Example 3:**
**Input:** n = 20
**Output:** 96
**Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96.
**Constraints:**
* `1 <= n <= 1000`
|
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
|
Array,Dynamic Programming,Matrix
|
Medium
| null |
207 |
today we will solve a course scheduling problem here you are given a list of courses and you are also given their dependencies that is which course depends on which course so the course on which some other course is dependent is called the prerequisite course of that course so you are given a pair of a list of such pairs so pair a b denotes that a is dependent on b so we have to find given this list is it possible to complete all the courses or not so it fits into the category of directed graphs since there is a notion of direction here let us look at this small graph so here course zero is dependent on course one and course three and course zero is also dependent on course two and course two is dependent on course three so here there is no cycle if you consider a undirected graph then you think that 0 2 3 is a cycle but if you see the direction then from 0 you can come to 2 from 2 you can go to 3 but from 3 you cannot go back to zero so there is no cycle here so if there is no cycle there is no cyclic dependency that is one course is a is dependent on b is dependent on c so let us look at this so we have a course a which depends on b depends on c depends on d and d depends back on some other course maybe b or even a then there is a cyclic dependency it can never be completed since for a you need to complete b for b you need to complete c first for c you need to complete d first so and but for d you need to complete b first but b you can complete only after completing c and d you can itself not complete without completing b so whenever there is a cycle uh there is no a possibility of completing the course so here the task is that to detect whether a cycle exists or not so this problem is also same as detecting cycle in directed graph and let's see the input format here you will be given a list of pairs so you will be given 0 1 zero two zero three and two three so we have added all the edges so it's kind of edges are given of a graph there are different ways of representing a graph adjacency matrix adjacency list and this is what is called edge list you are given a list of edges so you have to detect cycle in it how we can do that we start dfs from any node and there is some notion of called back edge in graph theory so we will not see too much detail of that so but let's briefly give you an idea so let's say i start dfs from a node i visit some node there will be more neighbors of this so but i have not yet explored those i will take one of the neighbors and keep going and let's say it ends here and we come to come back here so we have not yet done with this node we are just exploring it there are other neighbors remaining so this is in process of uh visit and this is also in process let's say there is no neighbor of this node one two three four so there is no number of four and we return from four so now this is completely visited and we come back to three and we look at its other neighbors so three is not yet completely wasted but it has been explored but not completely wasted four is completely wasted since there is nothing to do here but three we can come back again we visit its other branch and then come back to 3 and look for other possibilities so that we will call in process of widget let's represent by v and all the completed one we will represent c and all the other nodes with no level we will leave it as it is so these vbv are still in process of visiting c has been completed and here we come to this so we mark it to v and if there is some node some edge going back to one of the nodes which is which has been explored but not completely wasted then we will call this as backage so if there is a package there is a cycle if there is no backage then there is no cycle let's say these all nodes are explored so what will be the state and let's say this no edge does not exist and these all we have wasted we have returned back and we have not returned from here this is v and we come here so if there is some edge like this from this to this kind of edge then we will check that uh the edge goes to a complete node so if it's completed then it's not a package but if it goes back to a node like this which is not yet completed but just twisted it's in the process of widget then there is a cycle let us look at this example where there is a cycle so here i have reversed the direction of 3 and 0. so there is a cycle here so let us start bfs from any node let us pick a random node let us pick 2. so we come here 2 we see its neighbors so 2 is currently being visited so we its never is just 1 3 so we come to 3 is also v then neighbor of 3 is 0 so we come to 0 and 0 is also v then we look at neighbors of zero so first neighbor is let us say one we can encounter in any order so let us make it as long as possible so first neighbor of zero is one so we come to 1 we mark it v then we look at neighbors of 1 there is no number neighbor of 1 since there is no outgoing edge incoming edge is not counted that is this node was adjacent to 0 but not 0 is not adjacent to 1 so now there is no neighbor of 0 or 1 so we mark it as completed so we are done with 1 now we come back to 0 and we look at its other neighbor it has one more neighbor 2 so we see that it's never is 2 so we will try to visit 2 so we will see that 2 is neither unvested nor completed but it's v that is it's still being explored so this edge will become back edge and this will be the cause of cycle if we remove this edge then there will not be any cycle so this edge from 0 to 2 is a package and let's start from any other d any other node dfs i'm just trying to make the point that no matter from which node we start the dfs we will ultimately discover uh that package and we will ultimately discover the cycle so let us start from one so if i start from 1 we look at its neighbor none there are no neighbors so we mark it complete then we look for any other unvested node so we see that 0 is invested so we come to 0. it's v now it's being explored it's never is one but one is already complete so we not we will not go there and since one is complete it's not a back edge so this edge is not a package so this complete we will not go there let's look at other neighbors 2 so we come to 2 then its neighbor is 3 then its never is 0. so we see that zero is being visited started wasting but not completed that is the package and we will mark it as package so in this case three zero serves as the package so if there is a cycle let's say there is a cycle then which of them is backage well that depends on from where you start the dfs if you start dfs from here you will come here in this direction and when you reach here you will see that next stage is this one which is not yet complete so this will be packaged if you start dfs from let's say here then you will move in this direction and when you reach here this node this edge will become packaged so any of the edges of this cycle can become packaged depending on from where you start the dfs but no matter from where you start you will discover the package there is a back edge if there is a cycle so this we have to find so uh at any moment there are three states of a node can be in three states this is a node n it can be unwisted it can be visited vista means being explored we have reached here and we are exploring its neighbors but we have not yet explored all the neighbors being wasted let's call it and this is unlisted not yet touched and final is completed explored node and all its neighbors and the corresponding branches also so there may be many branches so we come here mark it wasted from unvested so it goes from u to v so this will be the transition it comes from u to v when we come to any node we mark them as v and when we return back so when we have listed all of these all will become c and we will look at its other branch when we have explored all the branches all the nodes then we look for any other unvested node it may be coming like this then we will mark this as c we are done with this part and this will become v and we will start exploring the other so let's look at a case where there is no cycle so let's look at this case so let's start from zero its neighbor is come here there is no more neighbor its complete its next neighbor is 2 this is v this is also v its next neighbor is 3 it becomes v there is no neighbor of 3 so we mark it as c and then we go back to 2 look at its other neighbor there is no other neighbor so we mark it as c then we come back to 0 and look at its other neighbor is 3 but we see that 3 is completed it's not v so this is not a back edge so there is no more neighbor of 0 so we mark it complete so we have done the dfs now every node is visited so there is nothing to explore and we did not encounter any package and this we will call it as a forward edge and not package we are concerned mainly with package where edge goes from one node being wasted so both of them are in v state that is second u state v to c so both of the nodes are in v state then this is package so let's write the code for this time i will make a change i will first write it in java and then c plus and then python so just for example you are given the number of courses and the course number starts from 0 to n minus 1 so it completely aligns with our indices of vectors and lists so that's good thing and you are given a list of pairs where pair consists of two courses one is the prerequisite of other you need to follow the consistency that there is an arrow from one to zero so for all the pairs just maintain the consistency that is arrow goes from first to second you can take the opposite also but keep it consistent for all the pairs so first let's do it in java so we will create a agent's adjacency list which will denote the nodes which are adjacent to a given node so if let's look at one of the examples so adjacency list for this will be one head for each course or each node so this is one main vector and each of them is a vector in themselves which stores the adjacent nodes so what are the nodes adjacent to zero it's one and two so here we will store one and two next there is no outgoing s to one so it will be empty for 2 it's 3 for 3 it's 0. so this will be the adjacency list representation of this graph and it's very useful for representing any graph if you are not familiar with it make try to study about adjacency list it's a building block for solving any problem you encounter with graphs it's very important so let's build this adjacency list first so this pre denotes the pair uh from this prerequisites areas so p will take the value of this next it will take the value of this and so on all the pairs and the first one we will assume an arrow from first to second so in the adjacency list of first we will push the second one now this adjacency list is built we will keep an array listed and here initial state will be 0 which will denote u state and then when it uh when it's being listed we will mark it as one and when it's completely vista we will mark it as two so there are in total three states so if it's unlisted so this is basically uh starting a new dfs so from a given node you can only visit all the nodes which are reachable from there may be some other nodes which are not reachable so we will call dfs so first let us define the dfs here so this one denotes let me write here zero means unwisted one means being wasted two means completely wasted so this is the condition where there is a package we will only fire dfs on adjacent nodes of a neighbor but if we see that its adjacent node is still being listed that is we just came back from there only and we are again going back to there so there is a package otherwise visited v equal to 1. so look at its neighbors so if for its neighbor also it returns false we return false that is if it's there is a package in any of its branches then return false else we will return true and now we are ready to do this and let's try okay this is a two dimensional we are looking at the neighbors of just this node v now our answer is wrong false true okay so we have not done the main thing here so when we are done with this node we store the wasted v equal to 2 so it will never get the value of 2 and it will keep returning false even for non-back edges returning false even for non-back edges returning false even for non-back edges and here also we need to return true here if it did not encounter any such case for any of the dfs it did not return false then finally it will return true so these are the two mistake hopefully that should fix it and now we are getting the correct result now let's take this negative case so it gives true false as expected so let's submit and the solution is accepted in java and let's look at some details for 46 test cases it takes around 3 millisecond so it's right here in the top around more than at least 90 percent for sure so let's now write down this same thing in c plus you now we have constructed this adjacency list and initialized vista to 0 that is unvested states and then this looks fine and c plus solution is also accepted so we will now do it in python 3. and the solution is accepted in python as well
|
Course Schedule
|
course-schedule
|
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`.
* For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`.
Return `true` if you can finish all courses. Otherwise, return `false`.
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\]
**Output:** true
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
**Example 2:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\],\[0,1\]\]
**Output:** false
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
**Constraints:**
* `1 <= numCourses <= 2000`
* `0 <= prerequisites.length <= 5000`
* `prerequisites[i].length == 2`
* `0 <= ai, bi < numCourses`
* All the pairs prerequisites\[i\] are **unique**.
|
This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
210,261,310,630
|
1,632 |
welcome to august 8th sleep code challenge rank transform of a matrix given m by n matrix return a new matrix answer where answer at row and column is the rank of the matrix row column the rank is an integer that represents how large an element is compared to other elements it is calculated using the following rules the rank of an integer starting from one if two elements p and q are the same row or column then if p is less than q then the rank of p is less than the rank of q if p is equal to q the rank of p is equal to the rank of q if p is greater than q then the rank of p is greater than the rank of q the rank should be small as possible which is guaranteed that the answer is unique under the given rules okay so we have a matrix here one two three four and our output is gonna be one two three so basically at matrix at uh let's say uh zero which is number one it is the smallest integer in its row and column so therefore we return the rank of one let's see the rank of the matrix at in a position zero one is uh zero one is two here and we know that um the answer is 2 because the matrix at position 0 1 is greater than 0 and 0 is at rank 1 so therefore the one the rank is one higher than the one likewise going below as well number three is larger than uh zero and also is greater than rank one so therefore the rank is must be two likewise uh following that same pattern we have uh the rank of position one the numbers four because number four is larger than two or four larger than three and recall that the rank of two and three are sort of two so therefore the rank has to be three which is higher than two so that's kind of the uh method solve it and the rank of the matrix has all the same uh integer in each of the uh columns and rows and all the cells just to say that all rank is equal to each other and uh this one's a bit tough here but if you go through the same scenario here then you know that the rank and of all this will be the final output will be that you just kind of work your way going across and here's another example here so let's see the length of the matrix m length the columns are n m is greater or equal to m and then n is less than or equal to 500. um let's see some of the hints sort by the cell processing by increasing order that makes sense rank of cells rank the maximum rank of rows complex one yep handle the equal cells treating them with the uniform union find the strata structure all right so this is a hard question here so the first thing uh i guess following the hint here you can find data structure i'm going to use be using a disjoint um this joint set union uh solution and i'm gonna use the uh i'm gonna define it as basically a fine function for it as well first let's set up our matrix and kind of analyze that right set up so first we're going to find the rows and columns of it so we're going to find n by n and that's going to be the length of the matrix and then the row is going to be the length of the matrix at index i or index zero i should say zero all right now that we have our length and with our n m by n next we need to find a matrix called answer which is the new which is the output basically answer and that's going to be the list we're gonna make it uh basically a matrix out of it using list comprehension everything initialized to zero first so has zero on there star n for cell and matrix so we make a new matrix everything populated with zero and we're gonna have to find um the we're gonna make some rows and columns as well to populate so rows columns and that's going to be zero times m and then zero times n all right that's our initial setup so now we have our answer we have our n by n matrix and we have rows and we have columns let's see i'm going to be using um this joint set union at a solution so i'm going to first define the find function for it so i'm going to basically develop that so um i'm going to define if we're first going to initialize um a default dick called parent and it's going to take and dirt and i've just you can just set this joint set union function find function is going to be defined as definition of find and it's got taken a value and x let's see if x is not equal to the parent value dot set default to be x so that's the case what we're going to do is reassign the parent value at x to be um it's got a recursive call to itself so i'll find the value at the parent value nx all right that should and then we want to return the parent value at x all right now that we have to find our disjoint set union find function this is what it does it's a recursive function that basically is fine we're looking for the uh or finding the parent value at x and next thing we want to do is uh define the disjoint set union process i should say process for it so how that works is um if you're not familiar with the disjoint set union type function uh data structure neither am i mean you i just know well enough to define it for i j and the product of the range of m and range and yep so basically we're cycling through the product of the range times the range of n times nm and we're gonna do is uh update the value so value is gonna be matrix at i j which is the cell j and then we want to basically find the parent at the value at find vowel at x no i should say and square product and assign that to the fine value of vowel geez all right next thing you want to do is group together if the values are similar on the same connected group of coordinates so we want to define something called elements default dict i would use a lambda value function here default predict set and then we're going to do four is for i and j and the product of range m n range n what we want to do is we want to update the vowel to be the matrix at i j position so it's very similar to the first i uh set of code in the front and above it and then we want to reassign elements at the value location to be find a vowel at i dot add writing the tuple i j to it all right okay now is we're assigned the rank so for the value v in sorted elements for group and the element at v which is the value dot find the values we want to find the n rank which is the max of the max between row i and columns j oh let's see max again max yes oh it's uh let's see for i j in group plus one right for i j in group rows i will be assigned to n rank columns j will be assigned to n rank and our answer at i and then of all this i want to return our answer hopefully this works let's submit it okay accepted so this obviously is a very tough question uh so we did use most of the hints actually so sort the cells right which we did here sort uh recall that their salva rank medium rank row and column is plus one which is right here and then we did use the equal cells by treating them as union fine data structure we did use a data structure you defined for these two uh then we initialized it so it's pretty much all the hints and everything and even all the beginning uh type of clues are given in the beginning it's just very tough to land this one together it's also very bulky and very messy as well but um there you go space com time complexity is uh basically big o of um let's see big o of n times m log of n times n so uh big o of log m n and then uh space complexity will take uh it's oh geez so the find function is uh let's see yeah it's the space complexity is basically storing it in the answer but we also have this uh this joint union set return value here which also stores a value so it's um it might be it's i think has to rely on maybe the inverse ackermann functions but uh because the disjoint set union takes time complexity is uh it's very uh very hard to understand very complicated beyond the scope but yeah i'm not going to try eyeball it either otherwise yeah have a great day guys
|
Rank Transform of a Matrix
|
number-of-good-ways-to-split-a-string
|
Given an `m x n` `matrix`, return _a new matrix_ `answer` _where_ `answer[row][col]` _is the_ _**rank** of_ `matrix[row][col]`.
The **rank** is an **integer** that represents how large an element is compared to other elements. It is calculated using the following rules:
* The rank is an integer starting from `1`.
* If two elements `p` and `q` are in the **same row or column**, then:
* If `p < q` then `rank(p) < rank(q)`
* If `p == q` then `rank(p) == rank(q)`
* If `p > q` then `rank(p) > rank(q)`
* The **rank** should be as **small** as possible.
The test cases are generated so that `answer` is unique under the given rules.
**Example 1:**
**Input:** matrix = \[\[1,2\],\[3,4\]\]
**Output:** \[\[1,2\],\[2,3\]\]
**Explanation:**
The rank of matrix\[0\]\[0\] is 1 because it is the smallest integer in its row and column.
The rank of matrix\[0\]\[1\] is 2 because matrix\[0\]\[1\] > matrix\[0\]\[0\] and matrix\[0\]\[0\] is rank 1.
The rank of matrix\[1\]\[0\] is 2 because matrix\[1\]\[0\] > matrix\[0\]\[0\] and matrix\[0\]\[0\] is rank 1.
The rank of matrix\[1\]\[1\] is 3 because matrix\[1\]\[1\] > matrix\[0\]\[1\], matrix\[1\]\[1\] > matrix\[1\]\[0\], and both matrix\[0\]\[1\] and matrix\[1\]\[0\] are rank 2.
**Example 2:**
**Input:** matrix = \[\[7,7\],\[7,7\]\]
**Output:** \[\[1,1\],\[1,1\]\]
**Example 3:**
**Input:** matrix = \[\[20,-21,14\],\[-19,4,19\],\[22,-47,24\],\[-19,4,19\]\]
**Output:** \[\[4,2,3\],\[1,3,4\],\[5,1,6\],\[1,3,4\]\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 500`
* `-109 <= matrix[row][col] <= 109`
|
Use two HashMap to store the counts of distinct letters in the left and right substring divided by the current index.
|
String,Dynamic Programming,Bit Manipulation
|
Medium
| null |
1,883 |
hey everybody this is larry this is me going with q4 of the leeco weekly contest 243 uh minimum skips to arrive at meeting on time so not many people got this one during the contest i actually i have some complaints about this one uh i spiritual um i have a moral victory which is the only victory i have today uh of solving this during the contest but two things kind of fooled me uh that kind of led it to be incorrect one is just uh the precision area right i think in the on a normal day um or like a regular day where i was feeling a little bit better um you know it would be obvious to kind of remove the speed because you know all these fraction if i remove the fraction um and use only integers um i would have gotten this ac during the contest because it actually also makes it faster to do a lot of these calculations but i was just a little bit slow um there's no way around it uh i was just off i was trying to feel i think i spent too much time on q3 so i was trying to be a little bit um i don't know just a little bit lazy and try to see if i could get away with uh floats um and the answer was no i could not have uh if i didn't have done that uh i mean i know that i see some solutions of using epsilon spin if i had just not used floats um i would have gotten ac with the code that i have um sometimes demo the bricks but like at least i have more victory in having to recur uh the recurrence correctly um anyway we'll get to that now i'm just giving you the quick read retro so you know to lend that a little support hit the like button subscribe if you haven't join me on discord and give me some love uh you know and yeah but i like i said i haven't already doing that i did get to get the recurrence and the concept right but the position is a little off and it was it also became a little bit slow because of that um which there was another way to fix but anyway let's go over the solution so the solution is dynamic programming given that n is equal to thousand you know that the skip is um a thousand um and a naive way of implementing dynamic programming it's gonna be n cube if you just um for each state you try to see how many things you can skip and then you know group them together um but the other way of doing it is kind of noticing that um before we get into the code uh try not to you know um i don't know did i oh what the yeah this is leaving a print statement yeah oops um but yeah so the idea here is that okay let's say you have some array and i don't know just and some speed is equal to 10. just keep it easy right um what do you mean what does it mean to skip what it means to skip is that you know and the way that i was thinking about it is going backwards is uh is that if i'm skipping it means that i get okay let's actually define the states a little bit better um you know let's say we you know there's a pit stop which i denote by highlighting the comma what does it mean by having a comma right that means that if this is a rest stop and we have two choices we could either skip it or not skip it if we skip it then uh then you use the contribution of uh the um the previous number right and what i mean by that is that you know for example this is speed 10 then you know you use um 12 uh divided by 10 plus 8 divided by 10 and if you don't so if you skip this or so if you don't skip it then this is what happens to the last number right um if you don't skip it you have this number instead so you have just 12 over 10. now of course this is all divided by 10 um at least in our case so then the answer becomes a dynamic programming problem of okay let's say i have here i could choose to skip or not skip uh if i skip then i choose it to take the best answer that is arriving at this point um and then round it up oh sorry wait what did i say if i skip this rest stop did i just take the best answer uh at this point if i do not skip it meaning that i do take the break then that means that um i round up from everything um the best answer that's going on at that point right um that's basically the idea um i uh that explanation i'm not super happy with but see if you can kind of figure you know try to understand that logic a little bit um and i'll probably get you a little bit um thinking i think the problem one thing that i struggled with during the contest with this problem is that i was not defining the index correctly um what i had the what i did during the contest was that i defined the index as the index of the distance but it should have actually been the index of the commerce the space between and once you look at it that way then it becomes a little clearer of okay this is the rest stop that i have if i skip it then you know i could take all the fractional pieces of whatever the best answer was before if not then i take the best answer of um the whole number part where you round it up because that means that whatever it was before round up you know and yeah and that assumes some up uh optimal sub problems of course so in that sense you have to kind of just have that leap of faith but yeah but another thing to know about this problem is that because every number is divided by speed you can actually um you can actually multiply everything by speed um to get the right answer um and that is just means that you uh multiply by hours before by speed and then in your math you do the round up by having the speed um it will um you know then you can keep everything in integers and you don't have to store any throats and it makes things a lot faster as a result so then here because now we look at for each index of the rest stops uh an index can go from you know zero to n minus one i suppose um and skips left can go from zero to index i guess strictly speaking but you know all of n is fine right so this means that this is n squared um for the complexity and the idea here is okay we have two choices one is do not use a skip and here is use the skip and if we don't use a skip then we take the answer that we had by the previous rest stop we don't skip it means that we take that answer and then we round it up and this is the way that i do the math roundup after multiplying by everything by speed so this looks a little bit awkward that's what rounding up means uh keeping it by integers um if you have to work it on paper work it out yourself uh i'm not going to explain this part just because this is something that you can you know look at patterns for small numbers and figure it out and if you do use a skip then you can take all the fractional parts and then just add it to distance one additional thing i would say is that if you have a fraction class you can actually just use fraction and cache that um and that would make your math a lot easier as well um but yeah and then after this is after you calculate or this is the recursion um this is the recursion memorization dynamic programming uh as you can see this is of two time because they're of two possible states and of n square space um and then what's left to do is to answer the actual question and which is that you know if you can go from the last stop back to this so stop uh using a skip number uh that's you know this is saying if so okay so this function tells you how what is the minimum time to um to get to the end using skips left skips uh starting from uh ending at index right so then you ask yourself okay what if we use zero skip what if you use one skip or if you use two skip etcetera right and because this is cached or memorized this is going to be o of one so you know this is an additional for loop this is an o of one operation and you check it or one time every time and because all the thing is that everything interacts together and because you're filling out this table um the total time is still going to be n squared time because you only you know because we yeah everything is already calculated and this is an o of one call um so yeah and if you used up all the skips and it's still you don't have an answer then you know return negative one which is what the problem asks i actually did this plus five because i was just i wasn't sure if about like using n or n minus one skip or something like that in that case uh but you also know that if it was over uh you know it doesn't change the answer so that's why i just did it this way um i don't know this is contest e thing uh i think you know uh this is technically i think n is probably good enough uh if you want to be precise but yeah um that's all i have for this problem uh i struggled this one the test but i actually did get the answer to this one i added a couple of things to it but it still actually gives the same answer i just have the same problem which is the precision problem uh if i had fixed the position problem um everything would have been right uh it was also just a little bit hard to debug because the answer like i got the wrong answer and the wrong answer that they gave me was off by like 130 or something like that or whatever it was so i didn't think it was position because i thought that it was position there it would be off by you know one or two or something like that right but because we're doing this rounding thing thousands of times um it ends up that it accumulates a lot of error as a result and that's what bit me um i would have gotten this during the contest if it weren't for that position error um so again i guess i'm more victory it is better than nothing um yeah but hopefully next week will be better so you know give me some love give me some like buttons and i will see you next time hope this explanation was good if not leave some questions in the comments you know how i get to them i answer all the questions whatever uh and i'll see you later bye uh watch me it live during the contest and then struggle with it and then you can kind of see how i debug it and learn from it and so forth i actually you know went over time even during the contest or after the contest so you know so you could see the grind you could see the struggle you could see me you know taking a really long time to just realize it was position error um it's kind of weird because i think uh just learning you know years of competitive experience uh i would avoid not you know i would avoid using doubles and force as many as i can but i think i was a little bit on tilt from another problem from q3 of this contest and i was just a little bit slow and i didn't think it get through how to uh get rid of the speed and i was hoping that you know division is okay and i could get away with it then just no i couldn't get away with it i had to change everything to uh but i had to change everything to ends uh but yeah you could see that struggle and meet that regular uh realization and learning later um yeah uh see you later okay just silly i just misunderstood it okay how many people have gotten this so far behind and so many penalties uh one thousand uh just one of those days um okay you know you still gotta grind it out 27 have forgotten this so it's going to be hard um because they have a lot of leeway or time on me um okay wow that was a rough cute first doing today q3 is my being okay let's read minimum skips required and this is just like that q2 that from a few weeks ago except for it's more annoying you do dp let's see so now dp can you do tp thank you hmm but the thing is you have to figure out how to do how skips in a well that's going to be too slow can i unload a loop no i don't use a skip how device do the math easy if i use a skip well i don't use a skip you bubble up the number of times okay maybe i don't know if this is right let's see kind of eyes if we don't use a scoop it's just this plus press this if we don't use a skip this happens and what's up guys we do the ceiling otherwise we do use a skip and it's something like this okay maybe that's fine don't forget to cash hmm that's not right oh if this is hmm that's probably still not right 1.5 is probably not right 1.5 is probably not right 1.5 is probably not right how did that happen for 0 oh this is skips minus one and also if skip's left is greater than zero so two point five i always forget okay the last one is a little bit weird i forget um because we never returned we've never skipped the last stop anyway so that's my phone no this is probably actually two three one so skipping silver is doing that's not true right oh now that should be right already why is it giving me to a oh because this is seal so yeah i guess if i was before in the truth it doesn't really matter i skipped i put i get 10.5 i just got two because i put i get 10.5 i just got two because i put i get 10.5 i just got two because i skipped it first it's silly hmm let's get one how to get 2.25 speed is four so if i skip the first one the second time i think i'm doing it backwards maybe that's why if i do it backwards maybe that'll work hmm let's put this on the thingy do i guess i'm just pointing it still wrong though 2.5 at least that's still wrong though 2.5 at least that's still wrong though 2.5 at least that's more right but skipping one should not be 2.25 because we skipped the first pit's top ten this should be one this should be point five doing it backwards a little bit awkward because i think the 0.5 because i think the 0.5 because i think the 0.5 is messing up the thing because then we try to skip this one it actually just skips to three and two instead of the one into three and it adds things in a weird way something like this but i'm like well i'm clearly i'm wrong but no because this is also i think i'm just doing the math a little bit weird of course okay if we skip i'm using the skip this map is right but not using the skip oh sorry yeah not using to skip the map is right but using the skip it is a little bit well i mean it does the ceiling but i think i'm doing this in a little bit awkward because i'm trying to not do n cube then coupon is obvious but basically i don't know if i'm going to get this in half an hour this would a disaster but are you good contribution is this i think this house before is an end so it doesn't matter so this should be fine with uh with rounding up and then now this becomes if i don't skip oh that's not true because you may skip the one before and then that adds that up because basically at this point i think i'm returning two different things that's why we skipped it so if it was skipped if the last number is skipped what happens if it's skipped we can either keep going if the last thing was clipped then we actually want to return the fraction of number so then we don't do this silver then we want to return okay so then if that's the case when we turn this plus just no matter what uh whether we use the skip or not if we don't use the skip okay and then if the last number wasn't skipped and here we did use the script so it's true here it is false and the last number isn't skipped and we return this thing this roundup thing i'm not tired i'm just gonna use seal instead of using my other thing is that more right okay it's not more right still three why how many one so skip is going to be false all the way so it goes bam this is for skipping the next step so after it did this thing you could use a skip can we do this but it's a little awkward because if we do use a skip we actually okay this is wrong this should be the seal of this thing not so that we can continue to streak that is that better i mean this gives me the right answer and i don't know any better so i'm gonna go for it i guess and maybe just one more for time purposes actually i guess i'll just change is it fast enough time limit exceeded really they should only have two million elements maybe why is that time to be exceeded that's actually surprising damn oh your cash not fast enough oh it's time to exceed it because i've run it multiple times so it's still not a good sign even if we want it once and it's still too slow three seconds so it's gonna be a little bit slow this is that faster i won't do that many operations it's crazy that this is too slow i mean i don't know and i don't even know this is the right answer to switch languages whatever anyway so let's give it a submit and then if it's wrong answer then i don't have to think about it if it's time limited then use another language maybe okay that's actually good to know i guess because then i don't have to spend time on it i get negative one but expect seven so when it returns eight but it expects it to be seven to drive did the fraction thing finally come into play if this wasn't skipped this was not skipped this is a little bit long maybe this was not skipped and why would i take the seal still the wrong answer but um yeah why did i return to c on this one however if the previous was skipped no i needed this to be zero because the previous was skipped so then it's just this going forward yep okay and don't skip you don't skip then you return okay i think this is right but um as white as it gets hmm not white enough though but hmm i spent too much time on q3 otherwise maybe have a shot this is why this is right um this should be i don't know i'm spending a lot of time but okay i got the right idea but maybe my form is a little bit off i feel like we skip but then we stop the scope this is true we didn't skip then well technically i guess we need a nice seal around here but for symmetry's sake but so just this time what is the sum of this i was gonna put our calculator but let's just point out the sum so 42 divided six is seven right that means you have to skip every number how many numbers are one two three six seven eight nine ten if you skip all the numbers you should get the sum of all the numbers so maybe i'm messing up too because maybe i have to do this i mean i know that this isn't going to fix the answer but at least it should give me a validation test and this doesn't seem like that's doing that correctly because what it should do is it should do this move all the time that's the optimal move but it's not for some reason yeah that should not be eight because if you skip all the numbers then you should go to all the fractions that miss it well now speed is six so one sixth of all the sum should be right so what am i doing wrong hmm my skip order things and it's still wrong why there should be no ceiling in any of it so why is it getting eight okay because the is this the reason that we should consider the first one as having it skipped i mean it still gives me the wrong answer but is it a better wrong answer i mean it's off by one instead of four by two or instead of an impossible which is better but still a little bit weird because we start from here like 10 minutes left what a disaster was my ranking i don't even know anymore there's going to be a blood bath because cute 3 i'm just silly on but why is this off by one you do right answer seven even if i'm a little bit correct i'll be at eight even though okay there's some position errors which is still not good but also if you have a fraction class that'll be good but that's not given the point inside of that if it's not dp then it's probably some sort of sorting heap type answer but i don't know why this is not giving me the right answer though like why is it just not this entire time just give me the sum of water things well at eight it gets me the sum of the things okay so actually no okay so i think we're right but now there's something wrong with the logic so that's fine i guess actually okay not gonna get in 10 minutes am i so you don't skip hmm i mean i don't know maybe i just don't know how to solve this one maybe this is the wrong approach the zero answer isn't even right if we skip no answers then we're just wrong so i think we're just off by a little bit so there's probably something more weird about it because i think yeah the last one should not be then we return the ceiling of all these things which is fine hmm yeah i have no idea maybe i just know how to do this one i think i'm close in concept but maybe i'm missing one observation and this might as i said maybe even time limit so i don't even know if this is going to be right even if i fix whatever it is using the same logic um i feel like this is i feel good about this but sometimes no you know the results don't match up with how you feel huh i don't even know which step six or seven stops to skip or whatever i guess the answer is seven so seven stops to skip and there's no way i'm going to look at this tp array and a matrix and be able to figure it out so i'm just staring at using my same logic so unfortunate i guess i don't really need this because that should already return it for me it doesn't really change the answer though uh well i mean it gives me the right response now for some of them yeah giving by the right response for the first whatever well maybe not this one but a slightly better response we didn't skip i guess technically i guess we need to do this yeah i don't know i don't get it because you want to propagate maybe i'm doing it the wrong direction still i'm going to propagate this up uh down why not you'll know it yo though try it huh well i mean it gives the right input but now it might timeout i mean it might give wrong answer for other inputs but you know i don't have time to fix this yeah okay i mean i think this is it but uh i just did it the wrong way but i don't have time to finish this um i mean yeah this is probably the way to do it but let's see if i could do it and i just can't do another language fast enough i mean if i had another 10 minutes i could do it but um but that it is what it is i don't even know how to do it anymore but ugh that's really sad though um yeah i mean i'm uh poop like i said if i have about five more minutes i would have gotten this but i uh i mean i don't have time left but i am gonna try to well we'll see if this thing would have worked um so yeah all my times on cute we kind of came back to haunt me something up this guy looks a bit of weird no maybe this is for oh no i have meth dots here on both oops um yeah so i'm not looking at the answers or other people's solutions yet but uh because i do have time is that the code that i have uh i don't know if i want this to be accepted or not because that would just be sad can i find some more speed whoops also i don't hmm okay and now that cash double 1204 so i would have counted four minutes up to the contest maybe indexed negative one outbound that's probably true for which one bin skips because i skip time okay so i got in the wrong answer with java i mean i don't know if it's a translation or not but at least we know that this is going to give me the wrong answer let's actually take a look at python 3 for my solution because i already had that solution oops see if that would have gotten it right or so i don't know if it's translation or the code if it's the code and that's fine okay so i think i'm just wrong then um okay let's do some code reviews uh and yeah let's see i feel like i'm roughly close but maybe not let's take a look okay um there's a top down but i think this is pretty much how i did it so is that true all right let's take a look at another one because maybe that one is just and i think i did the same thing i just i don't know maybe just some weirdness uh on different things uh how much time did it might take anyway two seconds so that so it timed out uh on a bigger case but it's i mean it also is possible that there's some precision error um because yeah i mean just maybe press no but in java was okay so i mean they even they did some minus epsilon thing i don't know uh hmm i mean i have to right idea but yeah i don't know i mean people did it like bottoms up so it's a little bit different than the way i would have done it anyway but the idea is the same maybe let's see if i can find one that i could understand and i think that i have the right idea but maybe top down is a little bit trickier to do because the states are the same of you i mean we all have the same states so all right this is a python one maybe i'll know it there's a prefix thumbnail i'm using seal here i don't know why the syntax hiding is so weird but syntax okay yeah this is prefix um so this is oh that's just the pre-calculated so if you're using no skip it's just that okay that makes sense otherwise if it uses i then it is just the size of i what does that mean this oh this is just a sum okay that makes sense for example j that's what i did so i don't know i mean that's basically what i did but maybe top down was much harder um and also all this skip stuff because i was trying to tap down and maybe i don't know if there's anyone who did it top down i should have did it but i should have done it bottoms up i think that was maybe more intuitive yeah maybe top down i mean bottoms up was the way to think about it maybe this one was a little bit too tricky but i was going the wrong direction i think um and i think that was the issue as well um a couple and that took too long but i was trying to do the same ish idea of can i do this bottoms up i mean i do this top down let's see i mean i think um yeah i don't know i mean i feel like i was very close but maybe there's some really weird nuance that i'm missing but yeah i mean yeah i don't know i don't get why my um i mean other than this epsilon thing i mean well i have the same logic but maybe because i'm going backwards it's because it's the min of this is when we literally have the same ish code except i have this thing about skipped maybe i only skipped maybe that confused me i definitely tried this did i have seal in the wrong place is that right well that's just wrong so now why is that returning example though i actually won this what is going on what i'm very confused i mean i have basically the right thing so i don't know why is going on here why is this returning this nonsense if we have zero skips this is two times a lot i don't know why i have what's 665 1385 hmm yeah i don't get why my code is well because so this is the original recurrence that i had roughly i mean i had some variations of this and going in different directions but the react but it is the same recurrence pretty much so why am i like now i'm like definitely cheating a little bit but i just want to know why this is wrong like we literally ha like i'm looking back and forth and you can see me do it literally the same code almost like i'm cheating except they're going forward no that should be okay yeah i don't care i'm why i'm wrong hmm do i get the example as well let's see now the examples were right then why did i get this one wrong is it position there's no way that's precision errors by off by like that much those it's not like it's off by one or two 665 is this number and which and we're trying to get it to like off by 50 is a lot and that's like copying and pasting no i mean they tell you the same thing right 8 28 so now i'm still learning a little bit but yeah hmm i'm trying to understand why this like what is even different about my code like if i were cheating you know like i'm literally like i look at this code now and i'm like okay this is exactly the same right like i'm like i didn't intended it but i don't know why this is so different from me i don't know okay well i mean there's only one way to uh i mean okay now you're watching me kind of try to learn hopefully this is helpful if you're still watching i don't know if not that's okay well if not then you wouldn't be here to tell you that it's okay but yeah okay i mean obviously this is right because otherwise someone show up but why how what does that look like oops whoops what's 10 is this number what's my 10 um look the same so far so where do we diverge at 236. so we still have the same thing so far so what happened 500 baby so we still have the same answer at 500 so why does it start messing up after that just subtract i'm so confused okay starting at 600 it diverges but why because i have like some funky things where with these two repeats of 592. even 592 were away but 593 were wrong or well i'm wrong but why how many what is n here anyway n is like something big so it's not even it's just doing the math wrong it's not even like you know i'm off by a little bit that's just a sum to early terminate i probably should have done this by the way so that i could get some speed benefits um i wasn't thinking about it because i was thinking about getting it right but hmm this is the same logic d sub zero i mean i had something like this before but i don't think that if that changes the answer that'll be hilarious because i did it the other way and it wasn't right yeah so it's still the same i am so confused how these two codes are different now so this is apparently unnecessary but hmm i mean this is the only thing that's different but i can't imagine that anyway right nope yeah i don't think that would have changed anything i don't get that because this is i and this is j so why is this i literally have to write the same i don't know about the right answer but the same answer and i can't figure out why hmm the gallery currents is exactly the same foreign did i mess up is it this no i don't think so that would just be our problem with it yeah also then it would just be wrong for some numbers but hmm so sorry i'm just typing on discord trying to figure it out but uh but what you're watching is just me trying to learn and figure out why my fingers uh is off by so much and after 500 skips you start combining two in a row maybe my two in a row stuff is what off because of this i don't know hmm literally looking at the same code all right let's see yeah maybe let's see i was a little bit weird now this is just seal with an epsilon so which is exactly what i do okay and also i think one minor thing that i would say is that yeah we're kind of skips backwards so that's probably why it works but i don't get it oh why is why am i mean and this also is the case when i switch to java so it's not a python thing well i mean i think that's how i got this to begin with and both these um i mean i know that i simplified it a little bit but it still should be the same ish thing well at least according to them but so i'm having the same wrong answer but which is i guess good in this consistency but looking at this right answer i don't know what i'm doing differently like i literally have the same recurrence does the ordering matter no i don't think so right like why would the order matter no i mean or rather um i mean the order obviously matters but doing it top down which is bottoms up it shouldn't matter like my code is exactly the same except for i'm top down i'm too stubborn to figure out okay maybe not that stubborn let's play around with it let's say i have something like um so oh yeah i don't know unless i'm off i went somewhere really badly right let's see what did i do uh whoops what did i do okay i mixed up my eyes and j's and indexes oh that's unfortunate where did i go oh whoops should we zoom so i don't know if that should change might set off by how much did i add some so for each number oh oops okay so yeah so i have to say i mean at least this is consistent so what is my what is the difference between my top down and his top bottoms up and his bottoms up or hers like now this is exactly the same but um so at least i know that we're consistent well i guess not exactly the same but close hmm yeah okay i mean i didn't think that would change the answer but it is what their code is so what is the difference here like this is like now i'm just trying to cheat real badly but you can see why maybe am i missing something really obvious like i'm literally and this should be really weird i mean would that make a difference if that is the difference then i would just be really sad for a while no okay but then now why unless this seal is correct that would also be a little bit sad if someone like that is big enough to make a difference no okay well i don't know what was the answer against 6 8 that is enough to make a huge difference actually wow is that the answer is that what i messed up by hmm i didn't think it was position because the answer was off by 170 but uh maybe it is maybe i am wrong because this is okay wow so if i had just did this okay let me just remove this now i don't think i need it anymore then i would have been good wow i am let's give it a submit it may time out actually i forgot to change it to java i shipped it in java um oh accept it oh my i didn't well i don't know what to say other than i mean i had the right idea um i should have gotten it how many people ultimately got at this contest uh let's see uh yeah so i would have been top 200 if i had gotten it given in the worst case but it was only because of precision error maybe i should have tried that a little bit more i don't know that is wow i did not expect that to be honest um because basically so this is the java code that i had because the other thing times out but that's because i made it a little bit complicated but um but if i had just do this minus 1 u negative 8. this have been right yes i would have been right oh my i don't know what to say oh geez wow well i mean on the flip side i am happy that i um i'm happy that i would have gotten the right i mean i had the right answer right so i'm not that sad about it but you know i don't think this is within my whatever and there's no way for me to have guessed that it's off by like 140 so uh yeah so this was a rough contest and day for me so yeah uh hit the like button and hit the subscribe and show me some love uh and hopefully it will bounce back uh as i explain more problems but i hope you all have a good night have a good long weekend and i will see y'all later bye
|
Minimum Skips to Arrive at Meeting On Time
|
find-distance-in-a-binary-tree
|
You are given an integer `hoursBefore`, the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through `n` roads. The road lengths are given as an integer array `dist` of length `n`, where `dist[i]` describes the length of the `ith` road in **kilometers**. In addition, you are given an integer `speed`, which is the speed (in **km/h**) you will travel at.
After you travel road `i`, you must rest and wait for the **next integer hour** before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting.
* For example, if traveling a road takes `1.4` hours, you must wait until the `2` hour mark before traveling the next road. If traveling a road takes exactly `2` hours, you do not need to wait.
However, you are allowed to **skip** some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks.
* For example, suppose traveling the first road takes `1.4` hours and traveling the second road takes `0.6` hours. Skipping the rest after the first road will mean you finish traveling the second road right at the `2` hour mark, letting you start traveling the third road immediately.
Return _the **minimum number of skips required** to arrive at the meeting on time, or_ `-1` _if it is **impossible**_.
**Example 1:**
**Input:** dist = \[1,3,2\], speed = 4, hoursBefore = 2
**Output:** 1
**Explanation:**
Without skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours.
You can skip the first rest to arrive in ((1/4 + 0) + (3/4 + 0)) + (2/4) = 1.5 hours.
Note that the second rest is shortened because you finish traveling the second road at an integer hour due to skipping the first rest.
**Example 2:**
**Input:** dist = \[7,3,5,5\], speed = 2, hoursBefore = 10
**Output:** 2
**Explanation:**
Without skipping any rests, you will arrive in (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 hours.
You can skip the first and third rest to arrive in ((7/2 + 0) + (3/2 + 0)) + ((5/2 + 0) + (5/2)) = 10 hours.
**Example 3:**
**Input:** dist = \[7,3,5,5\], speed = 1, hoursBefore = 10
**Output:** -1
**Explanation:** It is impossible to arrive at the meeting on time even if you skip all the rests.
**Constraints:**
* `n == dist.length`
* `1 <= n <= 1000`
* `1 <= dist[i] <= 105`
* `1 <= speed <= 106`
* `1 <= hoursBefore <= 107`
|
Get the LCA of p and q. The answer is the sum of distances between p-LCA and q-LCA
|
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
2217
|
88 |
hi guys welcome to algorithms made easy today we will see the question merge sorted array given two sorted integer arrays nums one and nums two merged nums two into nums one as one sorted array the numbers of element initialized in nums one and nums two are m and n respectively you may assume that nums one has enough space that is space is equal to m plus n to hold additional elements from nums to if we see the example one we have three elements in nums one and these are the three spaces which is actually equal to the size of nums two and the output after merging these two arrays in a sorted way gives us this output similarly for example 2. now let's see what are the approaches we can solve this question the basic approach or the first approach would be copying all the elements from the second array into the first array and then doing arrays dot sort but the time complexity over here would become o of k log k where k is m plus n and the space complexity would be 1 as we are storing it in the original array so how do we reduce this time complexity the time complexity could be reduced by using a two pointer approach by using this two pointer approach the time complexity would reduce to o of k and the space complexity would remain over fun the main logic behind this approach is to start filling from the largest element at the back of the area that is given to us so let's take this example and here we can see that these are the empty spaces and this is the nums2 array and the nums1 array filled up till position 2. so we take two pointers that mark the end of these two arrays and a pointer i that would be the index at which we are going to write with this we'll compare the values at both p1 and p2 and write the value that is larger at our index i after writing we decrement the respective indexes initially p1 and p2 will start from m minus 1 and n minus 1 and i would be the end element or m plus n minus 1 so here as 6 is larger than 3 6 goes into the ith position and with this i and p 2 gets decremented again if you compare the value at p 2 is larger than the value at p1 and so we write the value at p2 at our index i and decrement both these indexes now if you come here p1 becomes greater than p2 so the value at p1 is written at index i and the indexes are decremented as we move ahead over here the values at p1 and p2 are both equal and so we can write any one of that in our index i so we choose to write p2 and here you see that after decrementing p2 it becomes -1 p2 it becomes -1 p2 it becomes -1 and thus we can break our loop as this values are already sorted in nums1 so now this becomes our sorted array now let's take another example of an edge case over here we can see that nums 1 is blank the number of elements in nums 1 is 0 and that in nums 2 is 1. so here initially our p1 would become -1 would become -1 would become -1 and p2 would be at 0 but can we compare the value at index minus 1 with the index at 0 no because index minus 1 is out of bounds so we need to take care that p1 is always greater than or equal to 0 while we are comparing now that we know all the conditions let's go ahead and code this problem so initially we will take 3 indexes p1 p2 and i with this will start our while loop while p2 is greater than equal to 0 in here we'll see the condition whether our p1 is in range that is p1 is greater than 0 and if nums 1 of p1 is greater than nums 2 of p2 in this case we write num1 of p1 at i because that is the larger one and we do a minus in both the indexes otherwise nums 1 of i becomes nums 2 of p2 and with this we need to decrement both the indexes so that's all let's try to run this code and it is giving a perfect result let's try to submit this and it got submitted the time complexity as we discussed is of k and the space complexity over here is o of 1. so that's it for today guys thanks for watching the video see you in the next one
|
Merge Sorted Array
|
merge-sorted-array
|
You are given two integer arrays `nums1` and `nums2`, sorted in **non-decreasing order**, and two integers `m` and `n`, representing the number of elements in `nums1` and `nums2` respectively.
**Merge** `nums1` and `nums2` into a single array sorted in **non-decreasing order**.
The final sorted array should not be returned by the function, but instead be _stored inside the array_ `nums1`. To accommodate this, `nums1` has a length of `m + n`, where the first `m` elements denote the elements that should be merged, and the last `n` elements are set to `0` and should be ignored. `nums2` has a length of `n`.
**Example 1:**
**Input:** nums1 = \[1,2,3,0,0,0\], m = 3, nums2 = \[2,5,6\], n = 3
**Output:** \[1,2,2,3,5,6\]
**Explanation:** The arrays we are merging are \[1,2,3\] and \[2,5,6\].
The result of the merge is \[1,2,2,3,5,6\] with the underlined elements coming from nums1.
**Example 2:**
**Input:** nums1 = \[1\], m = 1, nums2 = \[\], n = 0
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[1\] and \[\].
The result of the merge is \[1\].
**Example 3:**
**Input:** nums1 = \[0\], m = 0, nums2 = \[1\], n = 1
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[\] and \[1\].
The result of the merge is \[1\].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
**Constraints:**
* `nums1.length == m + n`
* `nums2.length == n`
* `0 <= m, n <= 200`
* `1 <= m + n <= 200`
* `-109 <= nums1[i], nums2[j] <= 109`
**Follow up:** Can you come up with an algorithm that runs in `O(m + n)` time?
|
You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution? If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution.
|
Array,Two Pointers,Sorting
|
Easy
|
21,1019,1028
|
131 |
Hello friends today I'm going to solve it could problem number 131 palindrome partitioning so in this problem we are given a string s and we need to partition this string such that every substring is partitioned into a palindrome and we are going to return all the palindrome partitioning off as so what's a palindrome it's a string that reads same forward and backward so let's see an example here so if this is a string then it is a palindrome because a red forward it's a b a and if we read it backward it's still a b a right so this is a palindrome also a single string a string with only single character is only is also a palindrome so now that we know what the palindrome is let's see how we could uh find the substrings such that they are all palindrome and we need to find every substring in the partition so now here in this example what are we going to do is we are going to use backtracking algorithm so we are going we will be using backtracking algorithm starting from the first index and then moving on to the next index so the first index itself is a single character right so this is our starting position and the end position as well so what we do is the first index is this single character and we know Single Character is always a palindrome so what we do is um we create we have an empty area so far and we also have like a result array so this is our result array and this is an array of current uh this is our current list of palindrome so what we do is since this Single Character is a palindrome we insert we push that character to our current list and then now um what do we have is we have a b we still have this string but now we move to the next um next index because we are partitioning the string right so since these characters uh this whole these substring is a palindrome we need to check now is the remaining substring palindrome um so we start from the first character and we check that it's again a single string so since it is a palindrome we push it to our current array so we have a we have another string a now this is our current array so far and Now we move to the next index which is p and this becomes our start and the end index and since B is also a single character so what we have is now in our current array is a b and then our string is a b and now since our pointer has moved to the uh beyond the end of the string so that is when we know that we have found the substring for up we have found all the Palin drums for this substring um all the partitions of palindrome so we push these to our result array so we push this to our result array so far so we have a comma B in our result area all right so this is what we have now we uh track backtrack from this position so since we were at this position uh this was both our start and end index now we try to move the end index but we know moving the end index to the next pointer would again mean that it's beyond the string so we just back keep on backtracking again and we knew here that the start and end was the same point now we move the end pointer to the next index now since start is this and there's this we will evaluate if a b is a parindrome in itself or not and since we know that a b is not a palindrome so we backtrack to our original um string which is at index 0 with the start and an index so now our end index moves back to the next index which is at index one and the substring that we are evaluating is now a and since a is a palindrome so what we get in our new um least because now we have backtracked and while we are backtracking we are popping up we are removing the elements from this list so we have the empty element at least and in the empty list since a is a palindrome so we push a into our list and then our string is a b and so far it was at index one right now we look at index two so our substring is this and is this a pattern drum uh this whole string is not a palindrome right this was our start Index this was our end index and since this is an auto palindrome so what we do is um our new start becomes the end so since we already have a now this becomes our um start so since this is a start and this will also be the end itself starting from zero index so since it is only one character so we push B to this array and what we get is AAP so to pushed these to our result area and then finally we backtrack and well basically this will be our final answer so now that we know how to um the logic the approach behind the solution let's start coding so let in equals to the length of the string and then let us create our DP so we are going to use dynamic programming approach that the space complex the time complexity is minimized given that we are compromising over the space so why are we using DP let me just tell you give you a short example suppose that we have uh an array a string like this and we know that this is a palindrome because we have uh evaluated these palindrome because how do we proceed with start Index this one and end index as this value next our start and end index is this value next our start and end is this then we move on to this and then finally our starting in a is both these right and then while we backtrack uh our end keeps on increasing right so this is our start now this becomes our end since previously it's start and end where the same position at same index now end is increased by one and then we evaluate this value and then we backtrack again and for this is start position it has the end value at this position but now our end value is increased by one and then again uh in the next iteration it's increased by one more so similarly in this case also our start and end basically if you look at just look generally start and end is the same and the next step next iteration end is increased by one in the next step again it is increased by one and then finally end is increased by one again now since we have already evaluated this string starting from the start and ending at this post end position we know that we will know that this is a palindrome so we will store the vat true value for this start and N index and then next for while we will be evaluating uh the palindrome with this start index and this end index we know that this value is a palindrome and all we need to check is these two character equal if these two characters are equal and this value is a palindrome then we know that this whole substring is a palindrome in itself right so that is why we are using this that the dynamic program now let us Define our TFS function so we'll need our start index and we will need the current the least to store our current um partitions and we are going to check our base case if the value of uh start is equals to n which means that we have reached the very end of the string that is when we will push our result so we are just pushing the copy of our result and then find what we do is we iterate for the end values and is the start because we know they start and the end initially is the same point and later on we keep on increasing the value of end and should be less than n so we keep iterating over this end value as well and we are gonna check if the start and end substring is palindon so for that what are we going to do we check um is the start character and end character the same and also start so what we checked is start and end characters will be the same and this substring should be a palindrome right so the substring between as okay DP so start plus one and end minus one should be a palindrome right this is start and this index is Star Plus 1 and since this is n then this index is n minus 1 that should be a palindrome and what if in the case where we only have we have not yet evaluated any of such characters for example if we have these only these characters and this is a start and this isn't so start plus one would be the N value and N minus 1 would be the start at that point we actually do not have the DP uh have found the value if have actually evaluated if this is a palindrum string or not so and also in the case where we only have three characters we know that these three characters will definitely be uh palindrome right so in those two cases uh we are going to check if or um starts so the difference between start and end index it should be less than equals to 2 either if either of these two conditions are valid and this is valid that is when it's a palindrome and we are going to push it to our current list push our substring and we are going to perform our DFS function call so the next start would be our next end value cursor and we pop the values from our current list before we move on to the next iteration and then finally we are going to call our DFS function from here and then return our result let's try to run our crew cool let's submit it now awesome
|
Palindrome Partitioning
|
palindrome-partitioning
|
Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1 <= s.length <= 16`
* `s` contains only lowercase English letters.
| null |
String,Dynamic Programming,Backtracking
|
Medium
|
132,1871
|
1,993 |
hello uh let's do this question i just did it took me way too long so i don't want to edit that you're given a tree but you can lock and unlock a node if you lock a node given a user only that user can unlock the node and no other user can it can only lock a node if it's already unlocked and there's also another function called upgrade where in order to upgrade a node you have to check that all the ancestors of that node are unlocked and at least one descendant of that node is locked and that the given node is unlocked i don't really understand semantics of this but there are rules so we'll just go with it how do we do this for upgrade we're checking the ancestors and the children so you could potentially be going through the whole tree and how many calls to upgrade would they be so the most 2000 calls in total to all lock unlock upgrade so let's say we have 2000 calls upgrade and then upgrade takes over and time then we have since n is at most 2000 then we have n squared which is fine what about lock and unlock that can be done constant time to check that all the parents are unlocked you just have to do they'll take login time and you can do that recursively and same for the sentence but we're given a vector p representing for a particular node at some index whose parent is that node we're given that the first node in this vector is the root which shouldn't have apparent so that's why it's minus one how do we do this we need a way to go through all the children of this tree and we're going to give an apparent vector so we need to keep track of the parents of each node and we could do that using some kind of adjacency list so vector of vector call it children let's also keep track of the parents in here we also need to know whether a given node is locked or unlocked so we could say int blocked can be a boolean and also a user vector which user lock this node if the node is unlocked it doesn't really matter what the user value is okay so let's go through and set parent is equal to p could you just make a copy of that make children equal to a vector of vectors of ins and what's the size of this probably p dot size what else we have logs make that equal to a vector of booleans size p dot size and use a executable vector of hence of p dot size for the children adjacency list we can go through each of the parents now we know that p of i is the parent of note i so the children of this node here should have i as a child so we just push that back cool now what about lock return true if it is possible to lock this node given the user well if it's already locked if this node n is already locked then return false because it can't i can't lock it otherwise it can lock it so let's set the block to be of n to be equal to true and the user for this node should be equal to u and then return true what about unlocking so returns true if it's possible to unlock this node if it's already unlocked so if it's not locked then return false because i can't unlock an unlocked lock so now we're guaranteed that it is locked at this point let's make sure that the user that wants to unlock it is the same user who locked it so we can say check that the user of n is equal to u if they're not the same then return false otherwise we can return true and update the lot value of this node to be equal to false and the user doesn't really matter here actually all we have to know is that it's unlocked what about upgrade so with upgrade we need to check all the parents are unlocked and all the descendants uh have at least one blocked node and that the current node is unlocked to be able to upgrade so let's just check the first case are all parents unlocked or bull are our ancestors unlocked and we can check the current node is unlocked so if so let's actually return that the first the current node is unlocked and our ancestors unlocked of the parent node of n but we need a base case because at some point if you keep going up the tree we'll get that n is equal to -1 so if n we'll get that n is equal to -1 so if n we'll get that n is equal to -1 so if n is equal to -1 is equal to -1 is equal to -1 then return true just pretend that's unlocked let's have another function to check all the descendants so at least one descendant so i have to go through all the children nodes let's just assume that so let's uh have the boolean result equal to whether the current node is locked and then go through its children and bitwise all that results of the children's with this result so we can go through for ins child in children of n and your result or equals to at least one ascendant locked and then return the result so now we can check that at least one descendant is locked let's do the upgrade function first we can check that all the descendants are unlocked so if uh ancestors unlocked n if not all the ancestors are unlocked then return false and that's including the current node because i want the current node to be unlocked and then i just need one node and then the sentence to be blocked so at least one descendant locked then so if there is not at least one node then return false so now that we've checked that we can actually upgrade this node let's actually go through all the descendants of this node and unlock all of them so we can say void unlock or descendants of int n let's also unlock the current node here so let's do locked of n is equal to false then go through all the children for into child and children of n to unlock for the sentence of the child so here we can say unlock all descendants the chart but we actually want to lock the current node so locks a given node for a given user so let's say logs of n is equal to true and the user who locked it is equal to u then return true that's pretty much it let's uh see if there's any bugs i'll error child so this bit should be n oh since um the first node is the root node whose parent is minus one i'm doing children of minus one which would cause an error so that should be one oh it should be i less than that how'd that happen okay let's give that a run all right so that's that thanks for watching like and subscribe keep using the code and i'll see you in the next video
|
Operations on Tree
|
sum-of-all-subset-xor-totals
|
You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the `ith` node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree.
The data structure should support the following functions:
* **Lock:** **Locks** the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlocked.
* **Unlock: Unlocks** the given node for the given user. You may only unlock a node using this function if it is currently locked by the same user.
* **Upgrade****: Locks** the given node for the given user and **unlocks** all of its descendants **regardless** of who locked it. You may only upgrade a node if **all** 3 conditions are true:
* The node is unlocked,
* It has at least one locked descendant (by **any** user), and
* It does not have any locked ancestors.
Implement the `LockingTree` class:
* `LockingTree(int[] parent)` initializes the data structure with the parent array.
* `lock(int num, int user)` returns `true` if it is possible for the user with id `user` to lock the node `num`, or `false` otherwise. If it is possible, the node `num` will become **locked** by the user with id `user`.
* `unlock(int num, int user)` returns `true` if it is possible for the user with id `user` to unlock the node `num`, or `false` otherwise. If it is possible, the node `num` will become **unlocked**.
* `upgrade(int num, int user)` returns `true` if it is possible for the user with id `user` to upgrade the node `num`, or `false` otherwise. If it is possible, the node `num` will be **upgraded**.
**Example 1:**
**Input**
\[ "LockingTree ", "lock ", "unlock ", "unlock ", "lock ", "upgrade ", "lock "\]
\[\[\[-1, 0, 0, 1, 1, 2, 2\]\], \[2, 2\], \[2, 3\], \[2, 2\], \[4, 5\], \[0, 1\], \[0, 1\]\]
**Output**
\[null, true, false, true, true, true, false\]
**Explanation**
LockingTree lockingTree = new LockingTree(\[-1, 0, 0, 1, 1, 2, 2\]);
lockingTree.lock(2, 2); // return true because node 2 is unlocked.
// Node 2 will now be locked by user 2.
lockingTree.unlock(2, 3); // return false because user 3 cannot unlock a node locked by user 2.
lockingTree.unlock(2, 2); // return true because node 2 was previously locked by user 2.
// Node 2 will now be unlocked.
lockingTree.lock(4, 5); // return true because node 4 is unlocked.
// Node 4 will now be locked by user 5.
lockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4).
// Node 0 will now be locked by user 1 and node 4 will now be unlocked.
lockingTree.lock(0, 1); // return false because node 0 is already locked.
**Constraints:**
* `n == parent.length`
* `2 <= n <= 2000`
* `0 <= parent[i] <= n - 1` for `i != 0`
* `parent[0] == -1`
* `0 <= num <= n - 1`
* `1 <= user <= 104`
* `parent` represents a valid tree.
* At most `2000` calls **in total** will be made to `lock`, `unlock`, and `upgrade`.
|
Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets?
|
Array,Math,Backtracking,Bit Manipulation,Combinatorics
|
Easy
| null |
335 |
uh today we're gonna working on lead code question number 335 self crossing uh you have been given an array of integers called distance okay uh so you start at point zero and on an x5 plane and you move the first element in the distance array me uh that's gonna be we're gonna moving that much uh to the north then to the west then to the south and then to the east in other words each after each move your direction changes counterclockwise return true if the path crosses itself and falls if it is if it does not so in this case we went north and then west and then south and then east and we cross across our cell this path just crossed itself and then in this case we went north we went into a counterclockwise direction but we never crossed the path again in this case it did so that's why it is returning to okay so first thing we can keep the uh keep the record of how many elements we have been given because they can be there it doesn't have to be exactly four we can have multiple other values so we can have like but all of them are gonna be so the first one is gonna be uh north west south east and then north south east so all of them are going to be in a counterclockwise direction so first thing is a keeping record of how many movements are there so once we have that but what we're going to be doing is if but one um sanity check would be if the l is less than 4 right or actually less than equal to three not four if it is less than equal to three or less than four right uh we're going to be returning uh false because that means that like provided we are going to be in a counter clockwise every single step uh we cannot just cross the path okay now we're gonna start uh with our i equals to the third one so and i equals to three we're gonna start from the three and up to the uh up to the l i plus right now there are four different ways we can actually touch that uh actually three different ways where we can actually cross that path again one is that the fourth line crosses with the first line so for that case what we are saying is like if the distance uh that third one right for example like if i is pointing to the third one is greater than equal to the distance of the second one the distance of second and the distance of the first one right is less than equal to distance of i minus three so what we are saying is like if you are sitting on the third one right third is basically the index is third we are on the fourth line right yeah because distance of i three being meaning the fourth line right so we're sitting on the fourth line if that distance is greater than the second distance and at the same time basically uh basically we have crossing means even if it is equal crossing mean when we are going back to the uh to the east side uh is greater than more distance we move to the uh to the west side and distance we moved in the south side is yes south i we're sitting on the last one so the second is south side is basically less than the distance uh less than or equal to distance we did on the north side if that is the case we're gonna say uh we're gonna say return true okay that is the first scenario right the other scenario is what if we have more than like the what if the fifth line meets the first line right in that case we're gonna say that the distance of i minus one right before even before that we wanna make sure that we are we're gonna end up in this one only when i is greater than equal to four yes so basically we have more than uh four entries inside the uh inside the in the inside the steps uh represented by the distance array so that is one thing okay so in that case we're gonna again make sure that the fifth line is meeting the first line for that we're gonna say distance of i minus one uh is equal to distance of i minus 3 right and distance of i plus the distance of i minus 4 is greater than equal to the distance of i minus 2. in that case we're going to be returning true and where and similar to that if the i is this is the last step where the last scenario uh where i is greater than or equal to five so we want to check if the sixth line uh meets the uh 6 9 meets the first line right so in that case we're going to say that if the distance of i minus 2 minus distance of i minus 4 is greater than equal to zero that's the one condition the other condition would be that uh yeah we need to have like four conditions for this one let me write it down so distance of i is greater than equal to distance of i minus 2 minus distance of i minus four okay the third would be that the distance now is uh of i minus one is greater than equal to distance i minus 30 and i minus 3 minus distance of i minus five and the last one is where the distance of i minus one is less than equal to distance of i minus 30. if all these conditions meet it roughly translates to that the sixth line is crossing the first line uh so that's why we are returning true so one more time distance of five minus two minus distance of this one uh so again you are sitting on the fifth uh one basically uh fifth index which is the sixth line uh so uh two entries before that like uh that would be we wanna make sure that thing is like it should be it shouldn't be greater than zero the difference of that like uh going in that direction so that shouldn't be greater than uh zero because if it is greater than zero then the six is not gonna it's gonna become a spiral so distance okay and again it becomes going in the same sequence the eighth one which is the sixth line is basically greater than uh whatever was the difference was uh there uh between the sec uh i minus two and i minus 4 that should be the current distance should be greater than equal to that difference and a similar thing we're going to do for the other directions for the east-west east-west east-west directions okay and once we come out of that and we haven't sent the true back we're gonna be sending false back for oh so for this one uh we're gonna start oops we're gonna this should be like if right over yep looking good and it works
|
Self Crossing
|
self-crossing
|
You are given an array of integers `distance`.
You start at the point `(0, 0)` on an **X-Y plane,** and you move `distance[0]` meters to the north, then `distance[1]` meters to the west, `distance[2]` meters to the south, `distance[3]` meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise.
Return `true` _if your path crosses itself or_ `false` _if it does not_.
**Example 1:**
**Input:** distance = \[2,1,1,2\]
**Output:** true
**Explanation:** The path crosses itself at the point (0, 1).
**Example 2:**
**Input:** distance = \[1,2,3,4\]
**Output:** false
**Explanation:** The path does not cross itself at any point.
**Example 3:**
**Input:** distance = \[1,1,1,2,1\]
**Output:** true
**Explanation:** The path crosses itself at the point (0, 0).
**Constraints:**
* `1 <= distance.length <= 105`
* `1 <= distance[i] <= 105`
| null |
Array,Math,Geometry
|
Hard
| null |
122 |
all right so let's take a look at this problem this one is called best time to buy and sell stock two it's another array problem and again what as i said in my previous video if you're thinking about a raise you're probably going to be thinking do i need to sort the array should i use an alternate index should i also maybe use any other additional data structures we'll get to that so let's go ahead and read through this problem you're given an integer array prices where prices of i is the price of a given stock on the eighth day on each day you may decide to buy and or sell the stock you can only hold at most one share of the stock anytime however you can buy it and then immediately sell it on the same day find and return the maximum profit you can achieve so it's pretty important the parts they bolted here uh you don't think about can i buy a bunch of shares where i'm trying to figure out uh you know i want to buy a bunch because today it's one and tomorrow it's 10 and that's the biggest gap you don't think about that they just said uh you can only buy one so that eliminates that and the fact that you can buy and immediately sell the same day means you also don't have to time the market either you can immediately get out so there's nothing about this that actually is tricky in the sense compared to the real stock market so whenever you're approaching problems like this uh just keep in mind that the problem the way it's worded might sound intimidating if you overthink it and try not to actually look at that way so here in this example you'll understand even further what i'm saying they're saying that our max profit is seven the reason being is that if you buy on day two which is where the price is one and then if you sell on day three where the price is five minus one is four and then you buy on day four where the price is three and you sell on day five where it is six then it is six minus three equals three so now you have that four and the three and you get seven so also keep in mind that if you bought here on one and then let's say this increased to three and you sold there you'd have a profit of two and then five was here and you bought insult you could buy again and sell here so you could have one three five and it would be the same as just going one to five and then not buying between five and three and that's because you don't have to time the market that's why i'm saying don't overthink this problem just think about it from one day to the next and so if i'm looking at this all i'm realizing that all i have to do is just say is the current day i'm looking at is it less than the next day and if it is then i just need to take that difference consider that i've just timed it perfectly take that difference and add it to my profit and it's as simple as that so here's your other additional information you always want to keep in mind they are telling you that no matter what you will at least have an array of index or an array where the size is at least once you'll have at least index 0 being valid now the other thing that you need to know is that your prices are bound you're not going to have negative prices that wouldn't make any sense but you also don't have to check for it when you're solving this problem in a real world scenario you might check for it in your code just to prevent invalid input but right now these are our constraints so now how are we going to actually track uh what our profit is so you know our profit will say that the profit is stored as a value we'll start at zero and then what we're going to do is we're going to iterate through our array so we'll say and i equals zero while i is less than prices dot length and then i plus now let's think about this if i iterate here um this will actually get me to the very end of the array but then i can't compare to the value at the end because i will fall off the array so i'm actually going to want to say -1 here actually going to want to say -1 here actually going to want to say -1 here reason being let's say there's only two elements in our array so we're looking at the first element here and then we want to compare it to the second element and say is the second element bigger well then if it is we'll go ahead and add that to our profit but then when we get to the second element we don't want to end up trying to compare it to another element that doesn't exist because we've fallen off the end of the array at that point so that's why we're gonna stop when we're at one element from the end and then additionally uh when you know that your array is at least going to have one value in it then i will end up being zero and prices will have a length of one so it'll be one minus one so if i is less than zero which is not so it'll automatically not go into this for loop and you don't have to worry about that condition either so now we'll go ahead and say that we're going to return our profit at the end so now we need to actually calculate our profit and like i said earlier you don't have to really consider whether or not you're trying to time it because you're not buying so many shares you don't need to know uh ahead of time if it seems like the right time to get in when you're iterating through this problem you get to know what the price is of the price is tomorrow and just know that you can just buy it and have a profit so all you're going to do is just say that if the price of today is less than the price of tomorrow then our profit will equal our profit plus the price of the tomorrow value minus price of today's value and to make this a little bit more readable we can actually change this so we'll just call it int value equals that so this is that value we're going to add and we can even do a plus equals operator and so that basically what that will do is they'll say profit equals profit plus and then our value so again just iterating what this does we're going through if we have at least two elements we're gonna hit coming here with the first element we're going to say is our first element less than our second element if it is then we want to store this value temporarily we don't have to do this but just for readability for us while we're trying to walk through this problem it makes a little bit more sense our profit that we've gotten in this one day to the next is just the value of the next day minus the current day and then we add that to our total profit and then at the end we return our profit and we're done so i'll go ahead and submit this accept it and for this your big o the complexity will just be n because you're going just through this array one time you're not iterating through it multiple times you're not doing anything else like sorting or anything crazy like that and the other thing is that your space will be constant it's constant because you're not storing anything else extra other than this profit value which is your constant extra space which is really not that much so you know it's constant because it's not in if you were storing uh you know profit for all of the prices from one day to the next you know you could end up storing uh big o of n as your space but you're not you're literally just storing only your profit and then returning at the end so like i said your constant space complexity here and the time complexity is just big o of n if you have any questions let me know in the comments below and let me know if there's any other problems you'd like to see in our future videos you
|
Best Time to Buy and Sell Stock II
|
best-time-to-buy-and-sell-stock-ii
|
You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
On each day, you may decide to buy and/or sell the stock. You can only hold **at most one** share of the stock at any time. However, you can buy it then immediately sell it on the **same day**.
Find and return _the **maximum** profit you can achieve_.
**Example 1:**
**Input:** prices = \[7,1,5,3,6,4\]
**Output:** 7
**Explanation:** Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.
**Example 2:**
**Input:** prices = \[1,2,3,4,5\]
**Output:** 4
**Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Total profit is 4.
**Example 3:**
**Input:** prices = \[7,6,4,3,1\]
**Output:** 0
**Explanation:** There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.
**Constraints:**
* `1 <= prices.length <= 3 * 104`
* `0 <= prices[i] <= 104`
| null |
Array,Dynamic Programming,Greedy
|
Medium
|
121,123,188,309,714
|
1,424 |
I hope that you guys are doing good let's see this problem diagonal Traverse 2 it has been asked by Facebook in this last 6 months three times that's a big number and last one year VMware and Google let's quickly see what this says is just that I'll show you two techniques to solve it and the better optimization to solve it because in interview you can be asked a followup question on that and also we'll see one extra part one bit extra part so as to see and solve a modification of this problem cool let's see uh so firstly the problem just very simple straightforward just says that we are having a 2d integer are called as nums we have to return all the element of nums in diagonal order and it's not important that all the elements would be present it is just that we can also be skipping many of these elements but we have to still return in the diagonal order that is the question itself for us now uh one way which you could have initially thought when you have seen this was that okay I'll just simply Traverse on my X I'll simply Traverse on my Y and then I'll just keep on pushing my elements like I'll just say okay just push this and then when the next time I'll just be traveling I'll push this and then I'll push this but you see I see that it is not important that if I am actually at the second element I could would like let's say if I'm at the third element like it is not important that I would be having a Fifth Element like this element five but I still might be having an element number seven so that diagonal traversal in The Matrix itself is possible when we actually have all the element which means it's a square or a rectangle Matrix but this technique right here would not work for us the technique which we discussed was just that we Traverse and then we Traverse on all the first row and on all the elements and from that element just go on the diagonal just go on the dagal just go here so it is one thing which will not work for us because we can have empty places also so it might give a n poter exception cool so that was one thing and again RN uh what if I just have a if condition where I'll just check if that I are actually in the bounds or not I'll say that's a good condition but still it is not a good technique why maybe I'll just ask you what if my Matrix looks something like this I have one row having let's say uh 1,000 elements then I have only one 1,000 elements then I have only one 1,000 elements then I have only one element then again I have 1,000 have 1,000 have 1,000 elements so by your Technique it what it will actually plan to do was it will actually and again here are let's say 1,000 1,000 1,000 elements so by your Technique it will actually go and try for this entire Matrix which is actually 1,000 into Matrix which is actually 1,000 into Matrix which is actually 1,000 into 1,000 but in reality I only have 1,000 1,000 but in reality I only have 1,000 1,000 but in reality I only have 1,000 plus 1,000 plus 1,000 I only have 3,000 plus 1,000 plus 1,000 I only have 3,000 plus 1,000 plus 1,000 I only have 3,000 elements but your Technique would actually go and do a 1 E6 which is way lot so for sure this technique would not work which is traveling diagonally by just modifying the indexes right so now what is a better next technique now if you just look at the pattern now what we are concerned of is these numbers so are they following any pattern or if you had known that the diagonal numbers follow a pattern so what is that pattern itself so if you can actually see that the sum of the coordinates as in I and G indexes are exactly as what is same if you will see the sum of their coordinates INX indexes are same one here for here it is two for here it is three and so on and so forth so this is and see it is not nothing big new uh it is a kind of thing uh which you can just by drawing the entire matter we can get to know that their sum is actually same so what we can instead do is we can keep a track let's say I'll keep a hash map and in that hash map I know that this is a key and these are the values so what I will do is I know that okay for the key4 I have these elements it's just that I have to make sure that I am processing in the reverse order which means firstly I just process this then this as you see in the output I have answer as if you just go and see I have my answer as 1 4 2 1 and then four and then two so basically first down and then process up so it is just that uh while processing just make sure that if you are processing elements you're processing elements firstly from down and then up that we can make sure by just iterating from the very bottom itself so that is not a big case for us but yeah you just saw a technique that the sum of these coordinates of the D elements are actually same which will infer I can just keep a hash map and with that hash map I can just store all the elements in the vector so again that was if I had these diagonal elements again an extra part on this is that if I just ask you considering like right now I'm just doing this diagonal what if I talk you about is diagonal what is the similarity in this just let me know so you will see that the difference here the difference is zero 0 the difference is same here if I ask you it's -1 -1 - one here the difference is it's -1 -1 - one here the difference is it's -1 -1 - one here the difference is same here I ask you it's 1 difference is same here ask you it's two difference is same so for this diagonal the difference is same for this diagonal the sum is same so interviewer can might also ask you a modification which is just give me this pattern rather than the pattern right here as you can see the pattern here is this like this he can ask you the opposite pattern also like this so please make sure that you remember this fact that the sum of the forward diagonal is same and the difference of the backward diagonal is same now that's a matter of fact that we'll just go on and simply use a hashmap to keep the track of a sum it's just that we have to make sure that we are actually traversing in the reverse order so we'll actually go on from the very bottom so as to Traverse okay in the reverse order itself all the elements we will be traversing and keeping in the reverse order as we go in from the bottom so I'll keep the first five in my Vector of that specific hashmap five and then when I will be going back and then going from here then I'll keep and push this particular five because of this key as five and then when I go back I'll just firstly I would have been pushed this four because of the his key for then I would have pushed four because of key4 then I would have pushed the four right here because of T key4 so it says that make sure to travel backwards like from the very bottom so has just push it and now the time like we'll write the code but the entire time is will be number of elements in this Matrix itself right because we are actually traversing on all the input that's it and making a hash map of its indexes so it will be nothing but o of n where n i Am saying that is the number of elements in this entire Matrix or Grid or nums and space will also be o ofn because for sure I am using an unordered map again we will opt we can optimize this and that can be a followup in your interview itself let's firstly quickly Cote this up that how we can code this as we saw that we need to actually as you saw here itself that um we need to firstly keep track of what could be the maximum key also as you saw that in this example um you need to keep track what is the maximum key here you will see that okay a key can be here key is this value which is I and J plus sum right so you should also be knowing the maximum key ultimately to actually go up to that point itself you can't just assume what could be a maximum key so I'll just also keep track of a maximum key parall while making my unordered map from key to all the elements itself right so what I will do is I know that the maximum key or I can also say the maximum sum because for sure um maximum sum is same as that of Maximum key which is I plus J and now I also wanted the answer final answer as you can see I have to return a vector so I just say that what happened yeah I just say that okay just push back in this Vector I also need an unordered map uh D map now in this unordered map what I need to keep track of is from a key to actually all the elements what happened to my typing today cool uh I just keep track of all the elements which means from Key which is the maximum which is the sum of the indexes to their actual uh entire uh elements Vector now I'll just say sum two elements now uh again I just I can just simply trade on The Matrix but it's just that I have to make sure I trade from the very end so I'll just say I equal to nums do size -1 I is great than equal nums do size -1 I is great than equal nums do size -1 I is great than equal to0 and IUS minus and again go in from the indexes you can go from the like end also as you can see here itself um if I just go back so if I just go in my indexes I can go from end also and I can move from front also because firstly it will get processed and then it will get processed so this is unique so both J equal to Z also will work and J from the end will also work if I actually go in so here I can just go in from anywhere let's take it uh G equal to Z again uh in for G I can go from anywhere right so I'll just do a nums of I do size again uh it's a j++ so now I have size again uh it's a j++ so now I have size again uh it's a j++ so now I have firstly I just update my maximum sum which is nothing but the maximum key now maximum sum is nothing but I + J maximum sum is nothing but I + J maximum sum is nothing but I + J and also I need to uh push in um for this sum two elements for this key which is actually I + J just push back uh the is actually I + J just push back uh the is actually I + J just push back uh the current element which is at this index which is nums of I and J now when this entire thing is pushed I know that I have my ready uh my map entire map ready of from some to elements then I can just iterate on all uh the possible Keys which is which the that's reason I just kept a maximum sum which is the maximum key so I can just go and iterate uh to all of my keys and I can test to i++ here I'll just make sure that I have i++ here I'll just make sure that I have i++ here I'll just make sure that I have toate my entire map which means I can just say that Su to elements map whatsoever element is there corresponding to this key I right here just push that element in my answer uh I'll do a push back and I just say that element itself and ultimately uh that is done and I can simply return my answer so with this you will see that we should be able to solve it if you don't have any typos so yeah uh so with this the complexity is actually o of N and space is also o of n can we optimize it yes we can how for sure we cannot optimize the time because we have to iterate on all of the elements we are using an extra space because of the unordered map can we optimize this yes uh we can not very much we can move this o of n space to actually o of root n which means uh we can just plan to do something like this that indirectly average space being used can be reduced to rout 10 again that is not a flagship reduction in any space or time it's just that a possible followup question for you to actually reduce a space or anything you can think of to reduce a space how we can do that if we just again visualize it we have an element we have other two elements now if I just go and ask you if I ask you to go like if you have an element zero if I ask you to go to reach to one you can go right you can go down if I ask you okay you are at one and you have to go to all the twos okay you can go right you can go down okay so you can see that to reach to the next layer I can just maybe simply do a BFS traversal now this BFS traversal I can just go right and down but you will see that if I go right and down again so I might be counting this element twice in my BFS so one way is I have to keep a visited that I have if I have visited this earli I should not visit it but that's a Overkill again you would be using a space which you don't want it at the first place itself so rather let's do one thing that for the elements who are at the index J like whose column J is actually zero go down for them and for rest of the elements again rest as in like for him also go right so you will see that for the element whose J index is at zero he will go down only and for the rest of the elements rest as in him also he will go right thus covering all the next Elements which are five so what I can do is and with this fact you will see that it's a BFS TR so these elements will be stored in a CU and at any point of time in average or basically in the first worst Cas itself let's say if I take you okay these are n elements right here and these are n elements right here in the worse to worst case still in the verse to worst case maximum element stored inside the Q will actually be root n which is nothing but root and elements will be stored so now um I would be okay one thing for sure that at maximum Point time I can have maximum root element show in my q and that is the space reduction from n to root n and nothing just start from just start off your BFS from the first element which is 0a 0 and then firstly make sure again you want to Traverse from diagonal like upwards right so make sure to actually go in down first if it is possible to go down and only when the J is zero again the condition is firstly go down only when the J is zero and it is possible to go down as in for him it's not it is not possible to even go down because J basically X plus one or basically I + 1 basically X plus one or basically I + 1 basically X plus one or basically I + 1 for him is not even there so make sure that okay it is possible to go down and also your J is zero then only you have to go down and for the other ones which is for these element for the other elements inside your Q just go right so again for this example one it will go down initially and then for the other elements it will go right okay go right it will just get these elements so you will have elements in this order while traversing in the BFS Travers so th you will see that for the first element just go down for the other elements just go right for him it's not requ to go right as you can see that it has no right again for right also just have a check that it is even possible to go to right or not for this the time will actually be o of n because you have to turn all the N elements but space will be just root and cool let's quickly see this up uh how the code would look like for us let's quickly reset the code and again it's just a simple um our BFS traversal and in a BFS traversal if you know that we used a q now we need uh indexes so we'll just use a pair of int in which is the in coordinates so I'll just push back the first coordinate which is 0a 0 I don't need any visitor stuff a simple Q traversal while my Q is not empty now what I will do is I'll just find the size which is Q do size now I'll just check okay considering this is the size right now just get me all the elements now firstly I should get the current in coordinates just from the front of the queue now when this part is done I should just remove this particular pair now again uh I have got this element just push this element in our answer so I just say nums of I and J just push this up now when this part is pushed my part is just to push his like firstly just go and check down I'll just go and have a check at down firstly I'll go and have a check if J is zero and also I + 1 is in the brange which is also I + 1 is in the brange which is also I + 1 is in the brange which is in the nums is actually less than the nums dot size so when this is a fact uh you will know that you can actually go down also so what you will do you can just simply push the down coordinate which is actually uh same x coordinate which is I but a down coordinate increased so but a sorry uh same in sorry increased x coordinate and the same y-coordinate which is simply same y-coordinate which is simply same y-coordinate which is simply representing going down and also I said that if we can go forward just go forward so I'll just say if J + 1 is forward so I'll just say if J + 1 is forward so I'll just say if J + 1 is less than uh nums of I do size uh which means you can go forward just simply go and go like you can simp just go forward with the same I and j+ one now with this with the same I and j+ one now with this with the same I and j+ one now with this the Q will actually make sure to actually return you the answer and that will be your answer being return cool let's quickly compile this bad boy up and yeah thank byebye
|
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 |
234 |
Hi welcome to question series and here we are going to attempt question number 234 which is the first question on 'Likeless', it is 234 which is the first question on 'Likeless', it is 234 which is the first question on 'Likeless', it is an easy level difficult question with very high courts and there are some minimal downloads here but the question is very interesting. We had done this type of question, we had done a question on checking palindrome here, if you come here, we had done this question here, but this question was based on an, okay, this one is a question without likes, this one is here. The question is that first indra on linklist, what we did here with pay here, we have to do the same from here, the same happens with links, which if you read from the beginning, read from the front, read from the back, the same happens only. Like, if you look here 1 2 1, if you read from the front, it is still 1221. If you wait from the back, it is also 1221, this is your nomric, palindrome, alphabet, palan, loans are also there, if you look here, race, end, read from front. Even if you read from the back, it is a race. If you read from the back, it is still a race. Here is your R, here is A, here is C and in the middle you have A. Meaning, this is your last word, this is your set starting word, this should match with your last word, the second word should match with your second last word, if your matching is happening here and all the words here are from you from now on. Matching from the front and the back, this word here is palladium. If I tell you, in the last two videos, I am covering the linked list questions here and we saw the first question here which Key was reversal lecturers where we reversed a link less second question we saw here detector cycle in English here we saw the cycle whether there is a cycle in it for a plane or not whether a loop is being formed in the clinic or not Right now the third question is being asked here, which will be asked, we are checking here whether there is a lakeless, there is a follower at all, which we have here, van, tu van or whatever is racing, okay, we have the proposal here. First of all, give us a link here, okay, I have four more punch elements here, see all the lyrics, if you consider this note as a box, then your note has two parts, okay. The first part is where the data is stored. In the data, you can assume the name here, okay. Next, which is your space here, it contains the address of your next note, as I explained to you in the last video, anything. If it is allocated then it should be on continuous memory allocation, which means that the memory allocation here itself is confused, what does it mean that if the first element has got the memory at 101, then the next element will get it here at 102. Next on 103, on this Next on 104 and 105 and 106 means continuous memory locations, okay, the memory locations of Oring are 101 something type, so you will see here, it is continuous memory locations, so whenever you allocate memory to Eric. And it has to be allocated 6 bits of memory. If it has to be allocated here, then you will have to first go to the memory and see where you can see 6 memory locations together. There, if somewhere you can see 6 memory locations together. /m location, locations together. /m location, locations together. /m location, you allocate memory to the error there, but this is not the case in linked list. In Likeless, if this one of yours is on zero van, then it can also happen that this one of yours is above 132, this one of yours is on support 161. This one should be your support 34 and that one should be your 42. Okay, so now I know here, I am sure, everyone would know that brother, if this is 101, then the next one will be 102 but I don't know in the linked list. Bro, if this one is 101 then where is the next note, then to create a link with the next mode, the address of the next note on the next mode is stored here, like if your next mode is on 132, then it is 132. Whatever is yours will be stored here so that this note knows at which memory address to point it where your next mode is, so in this way we create these notes here, okay like this here if this 132 is the address of the next one is 161, it will be here, there is data here and that is why it takes some express because it has to address the pointer here, so it is okay here, now this is what we have to check here. If you suppose this van, you and here on van, then here on mine, this on here, a little clear, if you are not able to see then the data I have stored here is this data 1221 here on mine, the same. Here I have to check the first element from the last element and then I have to check the second last element from the second element and the third element is common to both the elements so if it is like this then the scene here. It becomes that your first element is equal to the last element, second element is equal to your second last element, third element is common to you, so the list you have here is talent. If 1, 2, 3, 4 and 5 are suggested here then it is the first element. It is not equal to your last element. The second element you have is also not equal to your second list. Okay, but there is a difference here, if you have to check a pulse, then you will put a loop here. By putting the loop, you Here, people can traverse the whole in one go and what is the purpose of travels. Can you check its first position and its last question like if you are doing your towers, I am taking it here in support, then people can check here if your Here you are zero, it is dot length, which means it will be checked in a single loop, the whole type is given to you here, which is your rectangle question here, the value of i, if there is zero here, your zero here, then you are here. You can check and 11 length -1 because your zero has been done so that as the value of i decreases then from behind it will check the last element first but then minus zero on the last element is -1 on the second zero on the last element is -1 on the second zero on the last element is -1 on the second element so Here 11 i - 1 here will be the element so Here 11 i - 1 here will be the element so Here 11 i - 1 here will be the last element cos there are 6 elements so here you have 6 - 15 okay are 6 elements so here you have 6 - 15 okay are 6 elements so here you have 6 - 15 okay so the element at the zeroth index is the element that is at the index from your last. If it is equal, then it is absolutely fine, it will check your second time, I have explained this concept in great detail, okay, in this video, you have to watch this video here, okay, you will find the valid talent in the video description, in that I have explained this concept in detail here, but my motive to understand here is that what you can do with linklace, why can't we do it because what happens in a linked list, but linkless and you First position and last question have been compared with each other, okay, but here you do not know where your last node is, okay, here you will directly give dirt or zero and you will directly set indexing here. You can do eversing, if you want the suppose fifth element, then you will write AR fold here, it will give you the fifth element of no, but we cannot do this in linked list or you can write here as the first element and then the last element. We have to check its concept is a little different, okay, we have to understand the same concept here, what is that concept which has help, we can check it here, first understand them, if you know both those concepts already, then you will know that. There is no need to watch the video but if you don't know then please watch these two videos once, some of your concepts will become clear, like first of all, there is a video of Linked List Cycle, here Floyd has given us an algois. Which was the slow wonder of fast point and the concept was, you detect a cycle in an unlinked list, okay, then you watch this video, you understand the concept of fast pointer and slow pointer, okay, to understand what is the concept of slow contractor. It is important to watch this video and for that how can we reverse a link less, this video will come here because both the concepts will come here, okay the concept of passport will also come here and the concept of reverse links will also come here. I will show how it will come, but first please watch the video, after that it will come here, okay, I have this here, I have a link suggested here, punch elements, let's get punch elements, okay and first of all. I have to do it fast control here because now what do I have to do here, I will take it here in 2 pointer, one pointer will start from here in one point, it will start from here, okay and I will take it in one pointer here in the case. I will pay you some of my money after performing some of my things and at one point my money will have been paid here. After that, what I will do here is that I will compare the data of this note with the data of this note. I will compare the data of this note. From and then I will increment this here, then it will go here, I will increment this, it will go here, okay, then I will compare the data of this mode of this note, okay, after that, this increment will be this increment. It will happen that I will compare this note with the data of this note, it is okay, that is, if the data of this note is compared here, then it will come in equal almo size, okay, so in this way I am going to compare it here, but you tell me here. If I have a note here and I am implementing it here, the pointer is reversed here, so if I implement this note here, then this should be known further which is here in this case on tap. It must be pointing. Okay, so we should go further. This is where the concept of reverse links will come in. Where I have reversed this note till now, how will it come in here? Slow point and fast pointer concept is the same concept which helps in We can find out And I have to run a passport here. What is a slow pointer? It increments by one. If you have a loop here, your slow pointer will come here. But what does a fast pointer do? There are two sentiments, meaning he skips the notes one by one, so if your slow pointer has come here, then your fast pointer will come here in this case. Okay, again it will be incremented. Okay, your slope pointer in this case will come here. A must have been done and your fast point must have been skipped from here to here. Okay, so what is the scene now? Now you have a slope pointer here. Okay, in 1 second, erase some things here so that a little So, what is the scene right now? The fast point you have here has come here and the one who is your slow pointer has come here and it is here only that you will see this loop. Break has to be done if the next tap of your fast pointer is this fast co inter, let's come to that now but for now you understand here that if the next tap of your fast pointer here is your tap then you If you break the slot, then what will happen in this case is that your fast font will be here and your 100 will be here. Now what you have to do here is that you have to bring your fast pointer back to the head, then your fast pointer will be in this case. Okay, I am explaining to you the concept of how to check the palindrome link list. Okay, now what you have to do here is from your slow pointer to this pointer here to null. This is the second half, you have to reverse this list here, you can take these two points like this, it is okay till here, when you reverse here, what will happen in it is that you have to run these people till here. Unless your slow jo is equal to null, like you have slow null equal to here, then what would have happened in the case that sir, your jo here is this one is here, this one is reverse here. Okay, this one, which is your note, this one of yours, this one, which is pointing towards the tap here, must have come here, right, this note of yours must have ended here, okay, this is the concept we have used. I had understood that in the reversal link list, but what would happen in this case is that your slow one would have already arrived here, your slow one would also be pointing to it and the next one would also be pointing to it and the previous one would be pointing to it here. You must be doing okay, this bond of yours has expired here, this phone of yours has expired here, your previous one is pointing to it, this link list has been reversed here, so you have so much here. I hope you know the concept of reversal linklist, I am zooming in, you know the concept, if you know the concept of reversal links, then you are 100% here, there know the concept of reversal links, then you are 100% here, there know the concept of reversal links, then you are 100% here, there is no confusion here, no OK, your two are here. The previous one will be there for you, that's why I told you that please watch the video, the previous one is there for you, okay, now what do I have to do here, Sir, now I have to do what you have on the fast pointer. The fast pointer note, which is your note, and the slow pointer note, compare their data with each other. Okay, now you have to run a loop here. Okay, you have to run a loop here or follow it. Run the volume here. You will have to tap till your slow tap is not equal and you have to check here whether the data of your fast note is correct or the data of your nearby note. If it is yours, it is equal to yours, it is slow compared to the wireless which is your data, but now if you look, I have put a tap on slow here, so you will have to reduce one here, your entire link list will get reversed, that means half the links. If it happens in reverse, then you have to pick two and put it in the previous group. This will be understood a little more clearly. It's okay, so for now I am just giving you an overview, I will explain it to you again along with four and a little more. And if it becomes clear, then what has happened here is that your note which is slow has been paid here, after that you will get the fast pointer here and the slow pointer here, these notes have been reversed, so more fast. The note with the pointer is also absolutely straight here, so it will work perfectly. How will it work perfectly? Sir, if you check here then there is data of fast pointer and just close on date, if it is equal then it is absolutely fine, after that you can switch to slow here. Further badhaaoge means you will increment the slow here in the case and you will single increment the fast here in the case, then your fast will have reached here, slow will have reached here, after that your slow will be that of tap. If it is not equal then again it will compare the data of fast and slow, after that it will come here and then it will compare its date here, so in this way you can check your compliance here. I hope it is clear. It is done, if I am not able to understand, then if by chance you understand, then there is no problem, I will come here to the court, then you will get a little more clarity. Okay, let's go step by step. First of all, what do we have to do here? After that, if we go step by step, I will increase it a bit. First of all, what do you have to do here? First of all, what did we do here? Sir, if I have a link list here, I would have created a link place here for example. Okay, I have to take an example which will start from my place, so I need two pointers here, sir, one will be my slow pointer here, the other one will be my fast point here, okay and I have taken slow which will start from the first element here. Whatever I have here of the first element is fine in the head, my first one is pointing first, so I have given two here, I have made these notes here and I have made both of them pointed here, okay, now I have to run it till My fast one does not become null. Okay, the first case that will be yours will be that I have given the elements of yours here to make you understand and here the case of fast connect will be that and that case will be if your link is less. I had explained to you the elements and this in the link list cycle video, the fast one will come here, after getting implemented, then by incrementing this note, it will come directly here on the nail, so I have to check this here if till Fast is not null, there comes another case which is the OD case where you check the head and then the next one till it becomes null. Now if the elements that are supposed are those and the elements are not that, then there are more elements meaning which. The elements of OD number are suppose to take three elements here and this is your tap here. Ok fast. You will start from here by skipping one note and will come here. Now by skipping one note if according to this condition. Until you get a fast tap, you have to improve but after the tap nothing happens, so you will not be able to increment it here, you have to put a condition here and check if this is my fast and not the fast one. Unless there is a tap next, it will break here on the condition that it is your fast and the next of the fast is not your tap. In that case, sir, what do you have to do here, you have the slogan. You must have got it here, you must have got slow here and this you must have got fast here, Han, 1 second, I remove it all, I am okay, so what has happened here, your slow has become net here. Pay and your fast has come here, now I have to bring back the fast that is mine, okay, and the second half list of yours, I have to reverse it, okay, so what do I have to do here for that? Sir, I will have to put your fast here on mine, which means I will have to put the head back in your fast here, my head is pointing to it in the first cell here, so if I pick up the head and put it next to me. So my fast one will point to the first element, it is absolutely fine, after this now you have to reverse your list here, for that you will have to take plus note previous here, which will initially have null here because your The element which is there must be doing nalcopoint, I had explained it to you in the video and by the time your slow thing becomes nalini, that is, what should I try to do here, I will give the second half of the list here. This list from here till the end, I am reversing these notes, that is, I am reversing the link list here, so what you will have to do here, you will have to take a node next. No, you will have to put slow dot next, okay, absolutely correct, now the note that you have, this one which is your node, is complete, you have to reverse it, you have to put the previous here next to the slow, then verse. Next you will have to enter the previous here because the previous is equal to yours and it will break the note from the link less link list here and will point it to the null, absolutely fine now. You will have to increment this slow here. To reverse the next note, you will have to enter the slope in the previous one. Okay, so that your previous one gets implemented and now you have to increment your slow, so in slow you will have to enter here. Next will have to be entered, it is absolutely fine, what will happen with this, your no will be reversed here, but there will be one less than this, which I told you, this will happen that till the time your slow is equal to null, it will be equal to null. Till then this loop of yours will not break, meaning this loop of yours will break only when your slow one will become equal to your tap here, whenever your slow one will point to it, okay, this will be your Tantrik, fast, it will go into your head. It is okay and these notes have been reversed at your place and what will happen in this case, it will point to the tap at your place and these notes will have been reversed and the one that is slow will go to the tap at your place. Must have been done, okay, this will happen here, but don't make me do slow. Slow, you should do this element here, so you are previous here on this element, your previous here will be pointing to this in this case because you have done it earlier. Put the previous in the show and then increment the slow further, then first the floor previous is pointing to the same element, the butt, then what happened on this line, you incremented the slow and put it here in the null, so the previous is still the same. Pointing to the element which is your last element, then you have to pick up the slow, that is, pick up the previous one and put it in the slow here. Okay, now after that, we are here sir, we are going to do this here, now what will you do here that now Yours here, let me tell you in a second what actually happened here that yours here will not point to this, now yours here is slow, now yours here will point to this, okay Let's increase the dot a little for a second. Okay, so I hope it is clear that now where are you pointing your slow. Okay, now what you have to do here is that as long as your slow is equal to the tap. Till then it was not done, you have to compare the data given in the fast toss law here, okay, so here we will do the same, you will have to run a loop here, sir, if you give a minute, then it is okay, here you You will have to run the route until your slow becomes equal to your tap, till now it is fine, if the value in your slow is correct as per the name of your pay bell then you have to check here then you have to click here You have to return false if both of these elements are not your call, that means your talent is not on the list, then you have to return it here. If it is not so, then it will not go inside this one statement. If it does not go, then it means This element is equal here, if the element is equal here then you have to increment it in the case and you also have to comment fast in it. If this loop gets completed and your list of D will not return then your function is not done. So in case you have to return it, True means your list is the entire first don, so I hope it will be clear, in this way you will give a list with a link, please like it, if you are new to the channel, then subscribe. You can check them all through Late Question, link of all is in description. Thanks so much for watching by.
|
Palindrome Linked List
|
palindrome-linked-list
|
Given the `head` of a singly linked list, return `true` _if it is a_ _palindrome_ _or_ `false` _otherwise_.
**Example 1:**
**Input:** head = \[1,2,2,1\]
**Output:** true
**Example 2:**
**Input:** head = \[1,2\]
**Output:** false
**Constraints:**
* The number of nodes in the list is in the range `[1, 105]`.
* `0 <= Node.val <= 9`
**Follow up:** Could you do it in `O(n)` time and `O(1)` space?
| null |
Linked List,Two Pointers,Stack,Recursion
|
Easy
|
9,125,206,2236
|
489 |
all right hey there everyone the problem today we are gonna be solving is called robot room cleaner it's a hard implementation business problem so let me just go through this problem once you are controlling a robot that is located somewhere in a room the room is modeled as an m cross m binary grid where zero represents a wall that is an obstacle and one represents an empty slot the robot starts at an unknown location in the room that is guaranteed to be empty and you do not have access to the grid so basically you will be given this apis where you can call the move method on the robot that will move the report to the next cell you can call the turn right or turn left method that is going to be moving the robot's orientation by 90 degree and the clean method is going to clean whatever the current cell is if it is not an obstacle now let's try to see how we can solve this problem well the goal behind this problem is to clean up all the cells and you don't have access to any of the coordinates let's try to see how we can solve this problem well uh we can assume that uh initially the robot is at 0 position and it's a reference for this position all the position of the cell that we are going to be computing is related relative to this position now the idea behind solving this problem is to use depth for search and backtracking now let's see how we will do that initially the robot if you see the robot initially the robot i is at this look uh this position so it's gonna be moving this if you call the move method right now it is going to be moving to this cell so ah but how do i calculate the coordinates for that well you see the robot can actually move to the four direction because we have four adjacent cells and we can either move to the left right so if you go here it is going to be well the x coordinate will be minus one and the y will remain same and this position if you instead of uh let's say that you move to write first then the robot will be turning up then you call the move method then it is going to be zero uh zero minus and if you move here that is going to be 1 and 0 because you are adding 1 to the x value x coordinate and this is going to be uh yeah this is going to be zero one yeah that's it so let's try to see how we can solve this problem using backtracking let's say that robot is moving here again robot orientation is here from here i can also call the move method the robot will be here again from here i can call the move method robot will be here right now if we call the move method here the robot won't be able to move that because there is an uh um dead end so we can either turn the robot to the left or right so i'm gonna be turning the robot to the right because that's going to be clockwise direction but you can also do left or anti-clockwise direction left or anti-clockwise direction left or anti-clockwise direction now if i turn the robot to the right it is not going to be immediately moving it will just change its orientation now i can call the movement move method and it is going to be here now here again you can see that there is an obstacle but we can solve this problem what we can do is like we can again move the robot to either left or right since i have chosen right i am going to be moving the robot to the right so if i call the move right method the robot's orientation will be at right then again i can call right again the robot can keep moving until here it finds an obstacle now at this position i can again call the right method the robot will be at here the robot can go here and move yeah keep moving here till it gets this now uh once it receives that i can either call right or left i can call right if i call the right the robot will be winding to here robot can keep moving and here you see here is a special case the case is that all the cells are visited and nothing we can do from here we cannot move to right we cannot move to left or we cannot move to the next cell so in this situation we will have to backtrack back backtrack to the previous uh cell but how we are going to be doing that let's try to see in broader picture let's assume that initially uh the robot was here it moved to the cell that cell where we cannot go anywhere and robot is pointing to this direction it must be coming from this direction only otherwise we won't be able to reach the next cell now how do i go to the previous cell in order to go to the previous cell first you will have to change the orientation of the robot uh to uh move that robot to 180 degrees so that it can look like this how do we do that well since i am choosing right always so i can do is like i can move right then again move right then i can call the move method i'm defining m as a move method so it will be a clear previous cell now again i will have to restore the cell how do i do that well i can simply move again move right two times if i move one times right then it will be at here and if i move uh right again it will be at here as simple as that so this is my idea to solve the problem let's try to see how we can code it up all right let's implement this problem so i have given a clean room method which is having a reference to the robot so first the first thing i'm going to be doing is i'm going to be keeping the reference these dot bar is equal to robot and i will also be storing the directions it is going to be 2d array let me just name it so what are the points that i'm going to be storing let's try to see so if we see this diagram initially it is at 0 location so as i have mentioned that i will always be moving uh turning to right so from here if i go here it will be minus one zero but what if i want to turn right what are the things that needs to be added to the coordinate of the current robot that is going to be 0 minus 1 from here again if i want to turn right that is going to be 1 0 i need to add 1 0 to the coordinates and again if i want to move right then i will have to add 0 1 and so on and so forth so if i store them minus 1 0 minus 1 then 1 0 and 0 1 but why am i doing this well i'll have to remember uh the orientation or the direction of the robot from where it is coming previously so that i can keep moving to the same direction as i have mentioned that i will always be moving to the same direction until unless i hit some sort of obstacles or a dead end so this array will help me remember uh what was the orientation i will be using another variable called d which will be starting from 0 and it will go towards 3 and it will be cycling again from 0 1 2 3 0 and each time i want to change the direction i can just simply increment d change d so and take uh directions at d8 location that's all now let me solve this problem so i will be doing a depth first search which will actually be which will actually try to clean so let me just define a depth first search dfs and initially it is at zero location and initially i will have to pass again the orientation that's why i have taken this direction array so initially the orientation is zero that is it is going to this direction only that is the left and once it is done yeah that's it now let me just define the depth of search method and it is going to be taking uh two indices row column and the d which is orientation now what i'm going to be doing is since it's a depth for search i will also have to take a hash set it is going to be of type string and let me call this as visited why i am taking why am i taking this set it is because i don't want to visit the same row and column again and again that's a search which is already been visited or clean so initially what i'm going to be doing is i'm going to be let's take key is equal to row plus some delimiter plus column and i'm going to be adding visited dot add key that's it and if it is at the current cell then obviously the cell is empty we will have to clean that cell so what i'm going to be doing is i'm going to be calling this okay this dot robot.claim it is going to robot.claim it is going to robot.claim it is going to okay it should be robot not roboto is a font that i love okay once it's been cleaned you have to turn on wi-fi and connect to a network on wi-fi and connect to a network on wi-fi and connect to a network sorry it's a google assistant oh again okay so what i'm gonna be doing is uh i'm gonna be uh iterating over all the directions and try to call this method recursively to clean that for that i'm gonna be iterating over i is equal to 0 i greater than 4 i plus and then what i'm going to be doing is i'm going to be calculating the index of the new row and column so let's call it x so x will be rho plus directions whatever is the current direction i am going so that will be defined by d and 0. so 0 is basically the offset which needs to be added to the x value of the coordinate and y is going to be column plus directions d and 1. one is the column offset and now the main part here the first thing i'm going to be checking if not visited dot this is visited yeah not visited dot contains uh what i'm gonna be thinking is x plus some delimiter plus y if the cell is already not visited and we can actually move so robot dot move it means that this next cell is not an obstacle then i'm gonna be calling that first search with the new coordinates and obviously the direction now once the visited uh once we are done visiting that direction it is possible that there are other cells in other or the three direction for that we will have to backtrack go back and restore the position uh reach to the orientation of the robot to the current cell so for that i'm going to be defining a method this is going to be public void backtrack and what it's going to be doing is it's going to be this dot actually i don't need this i can just simply save okay turn right i guess yeah turn right that we have discussed we can call turn right two times then we can call the robot dot move method and then turn right two times that's it is going to restore the position or backtrack we can simply call uh backtrack that's it now once it's been done exploring in one direction we will have to do that for all the other directions for that i will have to actually change robots direction turn right and since i'm turning knight i should also change the orientation the new orientation is going to be d plus 1 since that json is adjacent to this one is actually moving right and it should cycle that's why i'm doing a modular division by four so that's all let me just run this code to see if there is any error okay now let me just submit this code yeah it's done so let's try to calculate the time complexity of this approach you see we are doing depth for search only one and one time and we are visiting each and every cell only once so the time complexity should be order of n and the space complexity is order of n since uh we're taking extra hash set for keeping track of all the visited cells but in reality the time complexity will be n minus m is number of obstacles let's say that we have given a matrix which is having all the obstacles all the ones then our algorithm won't run the robot won't be able to move to any of the cell for that's why we uh that's why we will have to subtract the value order of n and this is again same for the space complexity so that's all
|
Robot Room Cleaner
|
kth-smallest-instructions
|
You are controlling a robot that is located somewhere in a room. The room is modeled as an `m x n` binary grid where `0` represents a wall and `1` represents an empty slot.
The robot starts at an unknown location in the room that is guaranteed to be empty, and you do not have access to the grid, but you can move the robot using the given API `Robot`.
You are tasked to use the robot to clean the entire room (i.e., clean every empty cell in the room). The robot with the four given APIs can move forward, turn left, or turn right. Each turn is `90` degrees.
When the robot tries to move into a wall cell, its bumper sensor detects the obstacle, and it stays on the current cell.
Design an algorithm to clean the entire room using the following APIs:
interface Robot {
// returns true if next cell is open and robot moves into the cell.
// returns false if next cell is obstacle and robot stays on the current cell.
boolean move();
// Robot will stay on the same cell after calling turnLeft/turnRight.
// Each turn will be 90 degrees.
void turnLeft();
void turnRight();
// Clean the current cell.
void clean();
}
**Note** that the initial direction of the robot will be facing up. You can assume all four edges of the grid are all surrounded by a wall.
**Custom testing:**
The input is only given to initialize the room and the robot's position internally. You must solve this problem "blindfolded ". In other words, you must control the robot using only the four mentioned APIs without knowing the room layout and the initial robot's position.
**Example 1:**
**Input:** room = \[\[1,1,1,1,1,0,1,1\],\[1,1,1,1,1,0,1,1\],\[1,0,1,1,1,1,1,1\],\[0,0,0,1,0,0,0,0\],\[1,1,1,1,1,1,1,1\]\], row = 1, col = 3
**Output:** Robot cleaned all rooms.
**Explanation:** All grids in the room are marked by either 0 or 1.
0 means the cell is blocked, while 1 means the cell is accessible.
The robot initially starts at the position of row=1, col=3.
From the top left corner, its position is one row below and three columns right.
**Example 2:**
**Input:** room = \[\[1\]\], row = 0, col = 0
**Output:** Robot cleaned all rooms.
**Constraints:**
* `m == room.length`
* `n == room[i].length`
* `1 <= m <= 100`
* `1 <= n <= 200`
* `room[i][j]` is either `0` or `1`.
* `0 <= row < m`
* `0 <= col < n`
* `room[row][col] == 1`
* All the empty cells can be visited from the starting position.
|
There are nCr(row + column, row) possible instructions to reach (row, column). Try building the instructions one step at a time. How many instructions start with "H", and how does this compare with k?
|
Array,Math,Dynamic Programming,Combinatorics
|
Hard
| null |
322 |
in this video we'll go over lead code question number 322 coin change now if you haven't seen my video on lead code question 70 climbing stairs I highly recommend you watch that first coin change is a very similar problem to climbing stairs but it's harder the link is in the description so please go watch that first okay so now let's look at the problem given an integer array coins representing coins of different denominations and an integer amount we need to return the fewest number of coins needed to make up that amount if it's impossible to make that amount then we'll need to return Nega -1 and we can we'll need to return Nega -1 and we can we'll need to return Nega -1 and we can also assume that we have an infinite number of each type of coin for example let's say the coins array consists of 1 5 10 and 25 and the amount we need to make is 68 the answer would then be seven because we could use two 25 coins a 10 coin a five coin and three one coins and it's impossible to do any better now the most intuitive way that most people would think of is to use a greedy approach in this case this means we would start by using the coin with the highest denomination and then work our way downwards for example using the same example as before let's start with a total of 68 and since 25 is less than 68 we can use a 25 coin and then another and now the remaining amount is 18 since 25 is greater than 18 let's move on to the next largest coin which is 10 the remaining amount is eight so we'll use a five coin next and then the last remaining three will be taking care of by three one coins and now we finally hit zero and as you can see we used a total of seven coins now this approach worked for this example but the problem is it doesn't always work let's look at another example where the coin denominations are 1 7 and 9 and the amount is 21 using the greedy approach we'd start by using the nine coin and 21 - 9 is 12 we can then use another nine - 9 is 12 we can then use another nine - 9 is 12 we can then use another nine coin and the remaining amount is three we can't use the nine coin or the seven coin so we'll fill the remaining three with three one coins so according to the greedy solution the fewest number of coins is five coins however the correct answer is actually three coins since we could have just used three sevens instead so this is an example where the greedy solution failed so how do we solve this problem well one way to solve this is to just use brute force and calculate every possible combination of coins using recursion here's the idea we'll start by using one of each coin and subract it from the total so for each coin we'll calculate the remaining amount if we use that coin which will be the total amount minus the value of that coin and we'll do this separately for each coin if the remaining amount is still greater than zero then that means we need to use more coins and we now need to figure out the fewest number of coins needed to make the remaining amount and so we'll do that by recursively calling the same function again but this time pass in the remaining amount and this will keep recursing until we hit zero so let's visualize this with a simple example let's say the only two coins we can use are one and three and the total amount is six we'd start by making two recursive calls here one of the calls we'll assume we started by using a one coin so we'll subtract one from the total and call the same function again but pass in five as the new amount so we're now trying to find the fewest number of coins needed to make a total of five on the other side we'll assume that we used a three coin to start so we will subtract three from the total and recursively call the function with an amount of three so here we're trying to find the fewest number of coins needed to make a total of three let's recurse down the left Branch first from a remaining amount of five let's subtract one and pass in four to the new function we'll also need to try subtracting three and pass in two to the new function and we keep going from the amount of four we'll try using a one coin then a three coin and from the amount of two again we'll use a one coin then a three coin but now notice something when we tried to use a three coin on an amount of two we ended up with -1 this means we ended up with -1 this means we ended up with -1 this means we overshot the total so now we know that using a one coin three coin and another three coin leads to a dead end so we can stop recursing on this Branch let's continue with the other branches from a total of three let's use a one coin then a three coin but now notice that the remaining amount has hit zero that means we finally found our first solution which is to use a one coin and then a three coin we still need to explore the other Solutions though so let's keep going from a total of one let's use a one coin and now we've hit another solution which is to use a one 3 and a one notice that this is actually the same answer as before but the coins are just in a different order next using a three coin leads to -2 so next using a three coin leads to -2 so next using a three coin leads to -2 so that's a dead end and here we see the exact same thing happening now let's finish the far left Branch two will lead to 1 and - 1 so that's a dead end lead to 1 and - 1 so that's a dead end lead to 1 and - 1 so that's a dead end and the last call will lead to 0 and -2 and the last call will lead to 0 and -2 and the last call will lead to 0 and -2 and now we found the fourth solution which is to just use six ones now let's finish the right Branch three will lead to two and zero and so our fifth solution is to use two 3es the remaining amount of two will lead to 1 and - 1 and amount of two will lead to 1 and - 1 and amount of two will lead to 1 and - 1 and 1 will lead to 0 and -2 and that is our 1 will lead to 0 and -2 and that is our 1 will lead to 0 and -2 and that is our sixth and Final Solution now that we've gone through the entire recursive tree we can see that the optimal solution is to use two coins a three coin and another three coin this works but the problem is if n is the number of coins and M is the amount in the worst case this tree will have a height of M and each node will have n children so this runs in O of n to the m power time so why is this so inefficient well let's take a closer look notice that we're calculating the fewest number of coins to make an amount of one four different times we're also calculating the fewest number of coins to make two three times and we're doing the same thing for an amount of three and notice that we go down the exact same recursive branch each time so this is where the redundancies are we're calculating the same thing over and over again and making a lot of unnecessary function calls we also go down this very inefficient path of using six one coins when really by the time we got to the third coin we should have just stopped here and realized that we could have used a single three coin instead so we're going to make this more efficient by using dynamic programming to calculate the fewest number of coins to make a certain amount only once and then reuse those values to build our solution as usual dynamic programming can be done either top down or bottom up but since the bottom up approach eliminates the recursion entirely that's what I'll be focusing on in this video so here's what it looks like using the same example as before we'll will first create an array that goes up until index 6 which is the amount that we are given in this array each element will contain the fewest coins needed to make an amount of that index for example the element at index 3 should contain the fewest number of coins to make an amount of three we start by putting a zero at index zero because you need zero coins to make an amount of zero then let's figure out how many coins we need to make an amount of one if we start by using a one coin then the remaining amount is 1 - 1 which the remaining amount is 1 - 1 which the remaining amount is 1 - 1 which equals 0 so the next question is how many coins do we need to make an amount of zero to figure that out we can look at the element at index zero and we see that we need zero coins so the total amount of coins is the one coin we used initially plus zero coins so the total number of coins needed comes out to one we can't use a three coin yet because the amount is too small so let's move on and figure out the number of coins needed for an amount of two if we start with a one coin then the remaining amount is 2 - 1 which equals 1 so now amount is 2 - 1 which equals 1 so now amount is 2 - 1 which equals 1 so now the question is how many coins do we need to make an amount of one and as you can see we already calculated that and the answer is one so by using a one coin initially then using another one coin to make up the remaining amount we'll need a total of two coins we still can't use a three coin yet so let's move on to index 3 again we'll start by using a one coin and the remaining amount is two so how many coins do we need to make an amount of two and again we already calculated that here so we'll need a one coin to start and then two more ones to make up the remainder that's a total of three coins but wait now that the index is finally three we can start using the three coin so what happens when we start by using a three coin instead well 3 - 3 by using a three coin instead well 3 - 3 by using a three coin instead well 3 - 3 is 0 so how many coins do we need to make the remaining amount of zero and the answer is zero so now we found a way to make the total by using less coins we can use a single three coin to start and then Zer more coins are needed so we only used a single coin since one is less than three we'll overwrite the value at index 3 with one which represents using a single three coin to make the total and it's the same idea for the rest of the array we subtract both coin denominations from the amount we're trying to make and we use our dynamic programming array to reuse the previous L calculated number of coins instead of recalculating them over and over again so for index 4 starting with a one coin the remaining amount is three as we just saw the fewest number of coins needed to make an amount of three is just one so we'll need a total of two coins here then we'll try using a three coin first the remaining amount is one and we need one coin to make an amount of one this is the same answer with just a different order of coins so we'll leave it at two next is index 5 - 1 is leave it at two next is index 5 - 1 is leave it at two next is index 5 - 1 is 4 and we'll need two more coins to make up the rest so the value at index 5 is 2 + 1 which equal 3 then we'll try 5 - 3 + 1 which equal 3 then we'll try 5 - 3 + 1 which equal 3 then we'll try 5 - 3 which is 2 and we still need two more coins so the value at index 5 stays at three we're finally at the last index 6 - 1 is 5 which corresponds to three - 1 is 5 which corresponds to three - 1 is 5 which corresponds to three coins so we could use four coins to make an amount of six but if we start by using a three coin first then the remaining amount is three and we see that we only need a single coin to make up the remaining three that's a total of only two coins so let's rewrite this value to be two and we're finally done all that's left to do is return the value at index 6 which is two and we have figured out that we only need two coins for this problem the difference here is we only had to Traverse an array of length m + 1 and for each one of length m + 1 and for each one of length m + 1 and for each one of those elements we had to Loop through the array of coins which has n elements so in total the dynamic programming approach runs in O of n * m time which approach runs in O of n * m time which approach runs in O of n * m time which is a major Improvement now let's look at the code and try an example using python let's say the coins are 1 2 and four and the amount to make is seven we'll start by creating our dynamic programming array which I'll call DP this array needs to go until index 7 so it needs eight elements and this right here is kind of a cool python way of doing it so we're first going to create a list with just zero as its only element and then concatenate that with a list of length seven and fill it with infinity so it looks like this if you're not familiar this is a cool way you can represent infinity in Python it's guaranteed to be greater than any number when used in comparisons and adding and subtracting any number from Infinity still results in Infinity you'll see in a second why having an infinite value is useful here next we're going to iterate through the array starting at index one using the variable I we also have an in Loop which is going to iterate over the coins array using the variable coin so for each index we're going to try subtracting each coin amount from that index but before we subtract the coin from the index we'll first check that the coin amount is less than or equal to the index otherwise we'll end up with a negative number and go out of bounds right now I equals 1 and coin also equals 1 so we can proceed now let's break down this line a bit more first let's look at the element at index IUS coin in other words this is the remaining amount after we use the current coin right now I and coin are both one so IUS coin is zero the element at the zeroth index of the array is zero so this value here is zero we're then going to add one because remember we just used the coin and subtracted it from I so the total number of coins needed to make an amount of one is 0 + 1 needed to make an amount of one is 0 + 1 needed to make an amount of one is 0 + 1 which equals 1 we're then going to compare that to the current element at index I which is initialized to Infinity we're then going to take the minimum of those two values and that's going to represent the fewest number of coins needed to make an amount of index I so that's why we initialized all those values to Infinity it guarantees that it'll always get replaced by the first solution found to get us started so since one is less than infinity the element at index one will be one now let's look at the next coin which has a value of two 2 is greater than one which means we can't use this coin so we'll just skip it the next coin has a value of four which is also greater than one so we're done trying all the possibilities for index one and we can move on to index two we'll start from the one coin again and one is less than two so let's find the element at index 2 - 1 which is 1 so you need one coin to - 1 which is 1 so you need one coin to - 1 which is 1 so you need one coin to make an amount of one if we include the coin we just use then 1 + 1 equals 2 and coin we just use then 1 + 1 equals 2 and coin we just use then 1 + 1 equals 2 and two is less than infinity so let's write a value of two at index 2 then let's try the next coin 2 is equal to two so we can use this coin now the element at index 2 - 2 is 0 and 0 + 1 element at index 2 - 2 is 0 and 0 + 1 element at index 2 - 2 is 0 and 0 + 1 equal 1 is less than two so we found a way to use a fewer number of coins which is to just use a single two coin so let's overwrite the element at index I to be 1 next four is greater than two so we'll skip that for now and move on to index 3 then we'll do the same thing 3 - index 3 then we'll do the same thing 3 - index 3 then we'll do the same thing 3 - 1 = 2 and the value at index 2 is 1 + 1 = 2 and the value at index 2 is 1 + 1 = 2 and the value at index 2 is 1 + 1 = 2 so let's write a value of 2 for 1 = 2 so let's write a value of 2 for 1 = 2 so let's write a value of 2 for the next coin 3 - 2 = 1 and the value at the next coin 3 - 2 = 1 and the value at the next coin 3 - 2 = 1 and the value at index one is also 1 so either way we have to use two coins so let's leave this at two the four coin is still too large so let's move on 4 - 1 is 3 and we large so let's move on 4 - 1 is 3 and we large so let's move on 4 - 1 is 3 and we need two coins to make that amount so we'll start off by writing a value of 2 + 1 which is 3 next 4 - 2 = 2 and the + 1 which is 3 next 4 - 2 = 2 and the + 1 which is 3 next 4 - 2 = 2 and the value at index 2 is 1 + 1 = 2 Which is value at index 2 is 1 + 1 = 2 Which is value at index 2 is 1 + 1 = 2 Which is less than 3 so let's overwrite this with two we can now finally use the four coin and 4 - 4 = 0 + 1al 1 Which is less and 4 - 4 = 0 + 1al 1 Which is less and 4 - 4 = 0 + 1al 1 Which is less than two so finally we overwrite this with one since we only need a single four coin to make a total of one next is 5 - 1 is 4 which corresponds to 1 and 5 - 1 is 4 which corresponds to 1 and 5 - 1 is 4 which corresponds to 1 and 1 + 1 = 2 next 5 - 2 is 3 and the 1 + 1 = 2 next 5 - 2 is 3 and the 1 + 1 = 2 next 5 - 2 is 3 and the corresponding value is 2 + 1 = 3 which corresponding value is 2 + 1 = 3 which corresponding value is 2 + 1 = 3 which is greater than 2 so the value at index I stays at 2 lastly 5 - 4 = 1 which I stays at 2 lastly 5 - 4 = 1 which I stays at 2 lastly 5 - 4 = 1 which corresponds to 1 + 1 is equal to 2 so corresponds to 1 + 1 is equal to 2 so corresponds to 1 + 1 is equal to 2 so the final value stays at two for index 6 first we'll check the value at index 5 which is two so let's start with 2 + 1 which is two so let's start with 2 + 1 which is two so let's start with 2 + 1 which equals 3 then we'll check the value at index 4 which is 1 and 1 + 1 value at index 4 which is 1 and 1 + 1 value at index 4 which is 1 and 1 + 1 equal 2 so let's update this to a value of two lastly the value at index 2 is also one so nothing changes we're now at the final element which is going to be our final answer if we start by using a one coin then we need two more coins to make up the rest so we start with a three if we use a two coin then we also need two more coins to make up the rest so that's not any better and lastly if we use a four coin we still need two coins for the rest so now we know that we can't do any better than three coins and we're finally done with the loop the only thing left to do is to return the value at the last index the problem also wants us to return negative -1 if there wants us to return negative -1 if there wants us to return negative -1 if there is no answer so we have to add a bit of extra logic at the end if the last element of the array is still Infinity then that means we weren't able to find any combination of coins to make that amount so in that case we'll just return1 and I'll do a quick example of this at the end but right now the last element of the array is not Infinity which means we have a valid solution and we can just return that value so the fewest number of coins needed to make an amount of seven using the coins provided is three coins so we return three and we're done now to wrap this up I'll do a quick example where there is no solution let's say the coins array is just two and four and the amount is five we'll start the same way as before by creating the DP array and begin iterating at index 1 the first coin is 2 and 1 - 2 is index 1 the first coin is 2 and 1 - 2 is index 1 the first coin is 2 and 1 - 2 is -1 so we can't use that 1 - 4 is -3 so -1 so we can't use that 1 - 4 is -3 so -1 so we can't use that 1 - 4 is -3 so we can't use either coin to make an amount of one because they're both too big so in that case we just move on to the next index and the value at index one stays at Infinity which means that it is impossible to make an amount of one for index 2 we could just use a single two coin and we would need zero more coins after that so let's put a one here four is still too big so let's move on for index 3 if we used a two coin then there would be an amount of one left over so how many coins are needed to make an amount of one as you can see the value there is infinity since it's impossible to make an amount of one so 1 plus infinity is still infinity and the element at index I is also Infinity the minimum of infinity and infinity is infinity so the element that index three stays at Infinity since we can't make an amount of three we still can't use the four coin so we move on four - 2 is 2 four coin so we move on four - 2 is 2 four coin so we move on four - 2 is 2 which corresponds to a value of 1 + 1 which corresponds to a value of 1 + 1 which corresponds to a value of 1 + 1 = 2 so let's write two next 4 - 4 = 0 = 2 so let's write two next 4 - 4 = 0 = 2 so let's write two next 4 - 4 = 0 and 0 + 1 = 1 so let's overwrite this and 0 + 1 = 1 so let's overwrite this and 0 + 1 = 1 so let's overwrite this with 1 now we're finally at index 5 if we start by using a two coin then we have an amount of three left over since there is no way to make an amount of three the value stays at Infinity what if we used a four coin first well 5 - 4 = 1 and there is no way to make an - 4 = 1 and there is no way to make an - 4 = 1 and there is no way to make an amount of one either so we can't get the value at index 5 to be any less than infinity and the loop just ends now when we get to this condition the value at the last index is infinity which means that a solution could not be found so we'll just return ne1 and we're done
|
Coin Change
|
coin-change
|
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`.
You may assume that you have an infinite number of each kind of coin.
**Example 1:**
**Input:** coins = \[1,2,5\], amount = 11
**Output:** 3
**Explanation:** 11 = 5 + 5 + 1
**Example 2:**
**Input:** coins = \[2\], amount = 3
**Output:** -1
**Example 3:**
**Input:** coins = \[1\], amount = 0
**Output:** 0
**Constraints:**
* `1 <= coins.length <= 12`
* `1 <= coins[i] <= 231 - 1`
* `0 <= amount <= 104`
| null |
Array,Dynamic Programming,Breadth-First Search
|
Medium
|
1025,1393,2345
|
1,013 |
all right so this question partition to three parts with equal sum so G the array we can choose if you can partition the array into three different part of the uh equal sum so what does this mean so imagine you know you cut into three piece and then you say AAL to Bal to C the S of the array are equal so the first condition you need to check what does the whole entire array sum can this divide by three so how do you do this if some divide by three and then which mean does not you know the M three does not equal to Z zero you return false I mean this is not possible right this not possible it happen if you want the partition three if some up like three does not equal to zero so once this condition satisfy in the sum three equal to zero then you can actually what say left sum I'm going to say left sum right sum uh just RS and then this will be L left some and right sum so we don't care about the middle sum we care about left sum and right sum if left sum equal to right sum also equal to suide three and we know that the other one m s has to be equal but you need to be careful the left s is IND this I right s is in this j i has less than to J this is because when you increment when you adding the value I into the left Su and decrement the J value into the right some like you need to I starting from zero J starting from the last you know last IND inside AR minus one so if there are you know there are still I to J it works I less and J does not work because uh imagine this happen just imagine this guy and this guy are the same and this guy is also the same as this guy but once you increment your I from here to here and you decrement your J from here to here you are at the same position and this guy can be alone which represent mid sum right and just have to rtion if you don't understand then draw on the paper all right so let's do it so sum so using the arrays string array do sum so this will give you the sum right and also you let's talk about average so average equal to S 3 right so if s by three that's notal to zero you return false in i = z j = z and also left in i = z j = z and also left in i = z j = z and also left s equal to what the array i++ right i++ right i++ right s equal to array. minus so I add in the first value for first value add in the first value for the left sum adding the first value for right sum and yeah so initial it should be Z 0 plus M Sky 0 Plus this guy will be this guy right so using a du uh just say this should be a r lus one so this should be a last index start traversing from last index all right so do well so I less than J and then you return to uh sorry you return false if you cannot find it so in the DU value I has to less than J this is because if Le some that's signal to average you want to keep adding left some plus equal to array i++ so you cannot use it less than which i++ so you cannot use it less than which i++ so you cannot use it less than which mean imagine a positive number a big positive number and next one you have you know another big positive negative value right so you cannot use using the L so using the exact same idea WR some and then that does not equal to average some plus equal to array J minus so we know we increment I right over here we decrement right over here so at some point that will me right if I to J and you know left some is equal to average and also right Su is equal to average then you return true so you only do when while I is less and J because when the a m right uh there's condition there's one condition I explained so imagine just imagine like this part and this part are equal so I will be here J will be here so this represent I less than J right and there's another condition just imagine you increment I to here you decrement J to here this will represent I less and J so this condition satisfy Le two scenario right I less than equal and then two value right I has less than J in order to Traverse right if you actually have this you know J right over here I over here like you're using the element right it's not good it's not all right so let's talk about time and space this is you know a time all of them Traverse every single one of them and add into the some this is olant right so the worst case olant for time space constant all right timeing space of straight forward so if you still a question a comma let do next time
|
Partition Array Into Three Parts With Equal Sum
|
fibonacci-number
|
Given an array of integers `arr`, return `true` if we can partition the array into three **non-empty** parts with equal sums.
Formally, we can partition the array if we can find indexes `i + 1 < j` with `(arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1])`
**Example 1:**
**Input:** arr = \[0,2,1,-6,6,-7,9,1,2,0,1\]
**Output:** true
**Explanation:** 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1
**Example 2:**
**Input:** arr = \[0,2,1,-6,6,7,9,-1,2,0,1\]
**Output:** false
**Example 3:**
**Input:** arr = \[3,3,6,5,-2,2,5,1,-9,4\]
**Output:** true
**Explanation:** 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4
**Constraints:**
* `3 <= arr.length <= 5 * 104`
* `-104 <= arr[i] <= 104`
| null |
Math,Dynamic Programming,Recursion,Memoization
|
Easy
|
70,872,905,1236
|
1,334 |
Hello Everyone Should Come Forward To Pandit Slept For Half An Hour And Some Number 123 Phone Adhisankhya Medium Difficult Problems And Stir Well - Festivals And Subscribe And Share Subscribe To That Soha Then Yagyavan The Number Of City St. George Subscribe And You Must And Distance Between Cities Subscribe Must Subscribe That Ve Bhaiya Given Address Shares Mein Entry 12121 Floor End 21Show Videsh Aapta Vidron Its History Will He Be In The Country And Subscribe To 220 Cricket This Particular Graph Mein 150th Urs Subscribe To That Pandem Rakshas Vansh Will Not get it is the yash lutb school and simran for 2nd year MICROSOFT ROAD and total five system disturbance golden woman n12 subscribe this world subscribe button 12345 and subscribe 280 subscribe to that city 1600 complete admit woman es intuitive who lay down there Activities Does Not Upon In The Forest 452 Subscribe Like And Subscribe Developed List Number Seervi Inside This Jo My Cigarette Please Multiple Sex Images For This My Neighboring Cities Seervi Subscribe To Or Se Abhinav Latke Locator Golden Steps Suggestion Convert If More Than Rahu Influential Hai 's Mukhiyas Video Film Producer Loot Chuki 's Mukhiyas Video Film Producer Loot Chuki 's Mukhiyas Video Film Producer Loot Chuki Thi White Diamond Pocket Books Channel Medium Subscribe This Wallpaper Hotspot On That In Small Stock Song New Rang Chal Gurjar Young Basically A Grade Five Days Left For Each End Every Partner Arrested That 10:30 Aged Minimum Part spat between edit That 10:30 Aged Minimum Part spat between edit That 10:30 Aged Minimum Part spat between edit to different but this chapter fuel subsidy representative appointed and justice a rock band that shubham situation is that thanks will be there for ban on this thank you slot machine you unrighteous time comes under witch you and a former senior officers to subscribe na Forget Shri Radhe Maa Wife Film Ek Bottle Indian Cricket In The Recent And Each And Every Value From Countries Which Met Ki Gaon Plus Ka Tractor Over All The Adventures Of Ek Button Dekh Agreed With Tau School Shabd That Both Of These Are Updated Message Soft Pendant Equal To That read full hd builder ko matrix from him henna be applied for the train ghrr soya chaap member this is the trick for update vision from jhalawar my tablet word 999 find 21 ki ko direct ganesh metroman 123 for vitamin c 1667 did morning ki election bihar Due to which list should be recited, this Sanskrit for watching temple facility should die, one take back from royal college, solid loot-loot matrix loot-loot matrix loot-loot matrix 's girl Nau for Rich's 's girl Nau for Rich's 's girl Nau for Rich's Ajay Singh Vinit and glad and number of times means its solid version which ribbon is such troubled both point two. The point is part 554 that they have to die, the length of the caves of Ismail Glad Solid is in C plus J that the sun of the martyr's areas is 500 and you from the gas unit point that their Vishwa Vijay Choudhary Ado point is half inch institute sirvi various Characters 102 की शेरों के में शावत की की शेरों के में शावत की की शेरों के में शावत की विदर्भ की Pimples 101 सार हुं है विदर्भ की Pimples 101 सार हुं है विदर्भ की Pimples 101 सार हुं है MB रेसिपी Meet us that point quickly Name of MB रेसिपी Meet us that point quickly Name of MB रेसिपी Meet us that point quickly Name of acting 5210 5500 102 की है 102 की है 102 की है रे के में रेक्स रे के में रेक्स रे के में रेक्स Recipe Gond ki Bus Drop Minimum 5 की 5 की 5 की पॉर्न setting department Direct पॉर्न setting department Direct पॉर्न setting department Direct Power Pack Plus and Indirect Bar Subscribe to that channel because thing must subscribe solid entry li phone we jhal once again this issue tree surfaced hua ko a true gumo sugar display more shop secretary permission dot milo matrix off karo ki jkca tahun fix of chinu five plus page160 sexual Key or basic thing setting close loop thing andra breadth is the middle high and hypocrisy and intermediate paper time is not available minute appointment meeting sugar is taken sugar is lakhan dooba kar vaya sugar positive energy is placid it should you basically a is this trilok recipe that When no end hospital admit proven problem and unit do it is the a matrix youtube that audio center latest last year wrinkles citizen path well organized point cup sugar has taken that muslim nature electronic machine som children can such a i tell it brother pintu want Sarmo sambse hai baingan ki aur mix of main achhe-achhe aaye in english hindi achhe-achhe aaye in english hindi achhe-achhe aaye in english hindi dictionary was written in pune at controller in the country there are specific short time chahiye january chalte ho woh bewafa distance picture suggestion loot lo ek bandar song so ganjde complete the second Lo my favorite song pimples which is please song half exam this account on loot that Sachin Singh Rao Inderjit Yadav in the state that Chauhan to front daily iodine started basically appointed dug the subscribe to then only back record day number track List Bring to Front Was Okay So Let's Make the Deposit Before Sexual Exploitation Day That Obscene Messages on Facebook Amitesh Saubhagya Subjective Mode of From Which You Can Be a Loot 14 Years Shuaib
|
Find the City With the Smallest Number of Neighbors at a Threshold Distance
|
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
|
There are `n` cities numbered from `0` to `n-1`. Given the array `edges` where `edges[i] = [fromi, toi, weighti]` represents a bidirectional and weighted edge between cities `fromi` and `toi`, and given the integer `distanceThreshold`.
Return the city with the smallest number of cities that are reachable through some path and whose distance is **at most** `distanceThreshold`, If there are multiple such cities, return the city with the greatest number.
Notice that the distance of a path connecting cities _**i**_ and _**j**_ is equal to the sum of the edges' weights along that path.
**Example 1:**
**Input:** n = 4, edges = \[\[0,1,3\],\[1,2,1\],\[1,3,4\],\[2,3,1\]\], distanceThreshold = 4
**Output:** 3
**Explanation:** The figure above describes the graph.
The neighboring cities at a distanceThreshold = 4 for each city are:
City 0 -> \[City 1, City 2\]
City 1 -> \[City 0, City 2, City 3\]
City 2 -> \[City 0, City 1, City 3\]
City 3 -> \[City 1, City 2\]
Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number.
**Example 2:**
**Input:** n = 5, edges = \[\[0,1,2\],\[0,4,8\],\[1,2,3\],\[1,4,2\],\[2,3,1\],\[3,4,1\]\], distanceThreshold = 2
**Output:** 0
**Explanation:** The figure above describes the graph.
The neighboring cities at a distanceThreshold = 2 for each city are:
City 0 -> \[City 1\]
City 1 -> \[City 0, City 4\]
City 2 -> \[City 3, City 4\]
City 3 -> \[City 2, City 4\]
City 4 -> \[City 1, City 2, City 3\]
The city 0 has 1 neighboring city at a distanceThreshold = 2.
**Constraints:**
* `2 <= n <= 100`
* `1 <= edges.length <= n * (n - 1) / 2`
* `edges[i].length == 3`
* `0 <= fromi < toi < n`
* `1 <= weighti, distanceThreshold <= 10^4`
* All pairs `(fromi, toi)` are distinct.
| null | null |
Medium
| null |
110 |
what's up guys in this video we're going to solve this problem balanced binary tree given a binary tree determine if it is height balanced what is a height balanced binary tree a binary tree is a balanced binary tree if the difference in height of left and right subtrees for every node no more than one now we understand what is a balanced binary tree now let's see some examples for example if we're given this binary tree our job is to return true if the binary tree is a balanced binary tree and we have to return false if the given binary tree is not a balanced binary tree we know that a tree is a balanced binary tree if the difference in height of left and right substrates for every node no more than one okay for this node the height of left subtree is one and for right subtree is two so here we see that for this node three the difference in height of left sub trees and right subtrees are no more than one okay so let's check for this node and here we have no node on the left and right and for this node we have left here we have the height of left subtree is one and here we have the height of right subtree is one and the different of height of left subtree and right subtree no more than one so for this given binary tree we have to return true because this is a balanced binary tree let's take another example if we're given this binary tree let's check if this tree is a balanced binary tree okay for this root node the height of left subtree is 3 and height of right subtree is 1 and we see that the different in height of left sub 3 and right subtree more than 1 so for this given binary tree we have to return false because this tree is not a balanced binary tree now how we can solve this problem all right now let me go through the intuition this is our algorithm to solve this problem first we have a variable result equals to true we initialize result to true because first we assume that the given binary tree is a balanced binary tree okay then we have this function is balanced it takes root of the given binary tree then we call this function validate with the root node and this function will change the value of this variable true to false if the given binary tree is not a balanced binary tree and at the end we return the results now let's see the validate function this is our validate function it takes the root node of a given binary tree then we check if the root node is null then we return 0 then we call with left and right then we're gonna check if that different of left subtree and right subtree is greater than one then we change the value of result variable to false okay and then we're returning one plus maxed up one plus max of left and right now let me go through this intuition using an example then it will make sense the suppose that we're given this binary tree to solve this problem we're using here depth first traversal okay or you could say depth first stars and we're traversing the given binary tree in dfs manner before processing this node we'll visit the left most node first so this is our leftmost node and then here we see the left node of this node is null so for null node will return zero and here we see also null node so for now load will return zero then we'll return to this node 9 1 plus max of left and right and 1 plus max of 0 and 0 is 0 so 1 plus 0 is 1 and this if condition is not 2 because 0 minus 0 is not greater than 1 then let's go to this node this is a right node then this is the left node and then we have here now so we'll return 0 and here as well then we'll return to this node max of 0 and 0 plus 1 that is 1 then let's go to this node and here we have null so we'll return 0 here we have null will return 0 max of 0 and 0 is 0 plus 1 is 1 okay then let's process this node for this node we see 1 minus 1 is 0 so 1 minus 1 is not greater than 1 so result variable still remaining the same then we're returning to this node 1 plus max of left and right and 1 plus max of 1 and 1 is 1 so for this node 20 will return 2 then finally we are processing this node 3 so let's process this node for this node 3 we have left equals 2 1 right equals to 2 so 2 minus 1 is not greater than 1 so we'll return 1 plus max of 1 and 2 and that is 2 so 1 plus 2 is 3 for this node we return 3 and we're done with this validate function and we have validated this binary tree and we saw that at the end we have result equals to true so we'll return to the function and this is how we can solve this problem the solution will takes bigger of n time complexity over n is the number of nodes we have in the given binary tree and it also takes figure of in space complexity for the recursion call stack for better understanding let's take another example all right now we're going to take this example for a better understanding first we have this node one before processing this node we're going to visit first the leftmost node then this node before processing this node let's go to left and again before processing this let's go to left all right and here we have this node 4 and left null right now so we'll return 0 for left and will return 0 for right so 0 minus 0 is not greater than one so we will not changed result from true to false then for this node we will return one plus zero that is one let's go to now this node right node and left is null so let's return 0 right is now let's return 0 for this node we'll return 1 as well and now let's process this node 3 so 1 minus 1 is not greater than 1 so we're not going to change the value of this variable result then here what will return will written 1 plus max of 1 and 1 that is 2. now let's go to the right node this is our right node and the left node we have 0 and the right node we have zero and for this node we'll return one plus max of zero and that is one now let's process this node for this node we have left equals to 2 and right equals to 1 so 2 minus 1 is 1 that is not greater than 1 still results variable remaining the same and to this node will return max of to and one plus one that is three now let's go to the right node this is our right node and for left you have now so let's return zero and for right as well okay for left zero and for right 0. and we say 0 minus 0 is not greater than 1 so for this node let's return 1 plus max of 0 and 0 that is 1. all right finally we're going to process this node 1. we have left equals to three right equals to one so three minus one is two and two is greater than one so in this case we're going to change this result variable to false then we're going to return to this node one plus max of three and one and that is four okay three plus one is four and we have validated this binary search t and we found that result equals to false so we'll return false for this given binary tree this means that this binary tree is not a balanced binary tree again for traversing the binary t we're using dfs traversal this solution will take speed off in time complexity to traverse the given binary tree where n is the number of nodes we have in the given binary tree the solution also takes figure of in space complexity for the recursion call stack we are calling this validate function recursively that's so it takes big off in space complexity all right guys this is my understanding to this problem if you have understood this problem please like this video share this video and subscribe to the channel all right guys stay tuned with cs ninja thanks for watching i'll see you in the next video
|
Balanced Binary Tree
|
balanced-binary-tree
|
Given a binary tree, determine if it is **height-balanced**.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** true
**Example 2:**
**Input:** root = \[1,2,2,3,3,null,null,4,4\]
**Output:** false
**Example 3:**
**Input:** root = \[\]
**Output:** true
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5000]`.
* `-104 <= Node.val <= 104`
| null |
Tree,Depth-First Search,Binary Tree
|
Easy
|
104
|
208 |
Hello friends today I'm going to solve liquid problem number 208 Implement try prefix tree so what is a try is a data structure used to efficiently store and retrieve keys in a data set of strings um and it has various applications including Auto completion and spell checker so basically what does try look like let's see here so we need to create a try and we are inserting this word in our Tri data structure so as we saw in this example in this definition here it is a tree data structure right which means it is in the form of tree that is we have a node and then we have multiple children of that node and so on so this is what try will look like so here in this example we are inserting the word apple right so now our track try would be like it starts from the first letter a and then the next character in this word is p right so it will Point to P the next character is again P so it will now again Point to P the next is L so it will point to L and the next one is e so it points to e and so on let's suppose we have another um like word that is um air so if we have another word and we need to insert this in our try then we would start from a and we look that we already have the node a so we append the character I in our node a because it doesn't have any character with any node with the value I write so we append that I and then R would be appended to I so we append R to I so this is how we create our try so now let's suppose we have another word example box so if we need to insert box where are we going to start from the node here is a right and for box we'll have a tree which starts from B and then it will continue with all and then X right so this is how it will be so these three are actually separated but it should be connected in one way so that is we are going to connect it using a root node or we will have a root node and the root node to build point to the first character of all the words so we will it points to the first character that is a for this word and B for this word and if we have a character starting from C then we'll have that over here suppose it's cat then we'll have C A and then t and so on so we'll have it so on so this is how our try will look like so what's actually happening here what's happening here is that for root we have a multiple nodes root is pointing to multiple nodes and the maximum number of nodes will be equals to 26 because we have 26 characters in um Latin right so it's set here um where is it said yellow lowercase English letters there are 26 lowercase English letters right so that is wipe the maximum length would be 26 now we cannot like if it was a binary tree what did we used to do we start from a root note and then we have two notes right so we Define those two notes pile to the left and the right node but now here since we have 26 of those nodes so how are we going to denote those notes uh and how is that be associated with the root node or the parent node that it's emerging from so we are actually going to do that in the form of a map because if you look what's happening root is basically root would be the mapping of all of the First characters to the second characters so let's take this example here and see what does it mean to have a mapping so what are we going to do is we are going to create a map so a root node we start from root node initially it doesn't have any values in this root map and now we insert we start inserting so we insert the first character in our map which is our root so this is our mapping function and we insert the first character a so now we have a first character a and what should the first character a point to according to this map it points to the second character right so we have our first character a and also a points to the second character of another word also so here it a points to P for Apple a points to I for air so that is why a will also be a map so what a map let's add one more um word here in this example that's air so a will point to the two characters um the second character right so it will have P which will also be a map and it will also have I which will also be a map and so on so it will be a nested map it will keep on going in those ways now what we need to do is we also need to look at these two things here so we can insert an apple and we can also like insert a word app so we need to check if um we have the word Apple we have the word app or not while we insert our word Apple we have app right but that is but we didn't insert our app our word app in this um tree so how do we uh like distinguish between Apple and app from this node so what are we going to do is we are also going to create another node which will be an ain't node and this will denote the end of the three so if this end is set to true if the value of this end is set to true that is that means that we have the word app in our word in our tree so every word we insert will have uh end node which will be equals to true so basically in all in our map we'll have an end and that value will be set to true if it is the last character else it will be set to false so now we know how we could solve this problem using Maps let's start to write our code so what do we first need is we need to create our try object right so we are going to do that by defining our root um of the three that will be an empty map and then to this tree we are now going to insert uh the word basically like to this map we will insert the First characters and so on so let our map be equal to this dot root okay and now do iterate over each of the character in our word and I will check if the map already has that character uh we just uh continue to the next character in our word else we need to add that character um create a new character with I mean create a new map for that character so what we'll do is if it doesn't have that character then we create a map for that character and then our map will be equals to the map the next one so what's what are we doing is in root we have our word apple right so we have a word Apple we are inserting it into our root map so what we do is we first take the first character a and then we created a map for our root right so now we take the first character a and V10 insert it into our root so now while we are inserting this a will also be a map a type map so now next character is p and we search into this map the nested map that is initially we were looking at the root map now we are looking at the nested map a and we don't see we don't have the character P right the map for p so we insert P inside our map a so basically it will be like this which will be inside our root map and we will keep on continuing so we will now check the p and then we'll insert the next character P to this and so on so that's what we are doing here and what we'll also do is we'll also check if the map has is and value um set to true so if the map already has a value set to true then we don't do anything else if it doesn't have that is and then we are going to set it to false because we have not yet reached the end and then what we do is finally at the end we are going to set our map um is and two okay so this will denote the end of our word in our tree now we need to search right so how we're going to search is we are also going to do the same start from the root and we'll check in our map if we have a character within that map or not so we start from the word first character and then if the map doesn't have that character then we return false else what we do is we move to the nested map that is a map of c and then we continue checking and then finally we also need to check that map is and is set to true so if it's sent to true we are going to return true else we return false and finally uh to check for um words that have like to check for the tree try which starts with this prefix we it's on it's like the same thing here so what we do is we'll just copy and paste it here okay and I replace this word here with the prefix and return true if we could find the prefix in our tree now let's try to run our code and look if it works fine okay so I have some problem here undefined okay so we actually need to set it to false here because we have not yet reached our end awesome let's try to submit this great um so let's check the time complexity and the space complexity so while we create our try function the object we are creating a new map right so every time it's uh gonna take maximum of 26 um spaces 26 new spaces so that would still be a constant value because 26 is like a constant number so that's a constant space and constant time so every time we are using a constant space while we create a new map but here while we are inserting the insertion will depend on the length of the word so let's see here if the word was of infinite length of length n let's suppose it will if it was of length M than our like map would have multiple nodes right it will keep on growing in notes so we'll create an N number of nodes so that is why if the length of the word is n then the time complexity will be of n because we are iterating over each of the character here right and the space complexity will also be 10 of n and now our search function here so the search for the search function uh the time complexity is of n also because we are iterating over each of the character and the space complexity is constant similar with this case so hope you liked it
|
Implement Trie (Prefix Tree)
|
implement-trie-prefix-tree
|
A [**trie**](https://en.wikipedia.org/wiki/Trie) (pronounced as "try ") or **prefix tree** is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
* `Trie()` Initializes the trie object.
* `void insert(String word)` Inserts the string `word` into the trie.
* `boolean search(String word)` Returns `true` if the string `word` is in the trie (i.e., was inserted before), and `false` otherwise.
* `boolean startsWith(String prefix)` Returns `true` if there is a previously inserted string `word` that has the prefix `prefix`, and `false` otherwise.
**Example 1:**
**Input**
\[ "Trie ", "insert ", "search ", "search ", "startsWith ", "insert ", "search "\]
\[\[\], \[ "apple "\], \[ "apple "\], \[ "app "\], \[ "app "\], \[ "app "\], \[ "app "\]\]
**Output**
\[null, null, true, false, true, null, true\]
**Explanation**
Trie trie = new Trie();
trie.insert( "apple ");
trie.search( "apple "); // return True
trie.search( "app "); // return False
trie.startsWith( "app "); // return True
trie.insert( "app ");
trie.search( "app "); // return True
**Constraints:**
* `1 <= word.length, prefix.length <= 2000`
* `word` and `prefix` consist only of lowercase English letters.
* At most `3 * 104` calls **in total** will be made to `insert`, `search`, and `startsWith`.
| null |
Hash Table,String,Design,Trie
|
Medium
|
211,642,648,676,1433,1949
|
1,629 |
Hello Hi Everyone Welcome Platform Programming In This Video Highlight Kaise Bataunga Last Ke Jin Fact That Of Clans Previous Under Different Level Vs So Let Me Clear Per Distraction Few Minutes Ago Ki Sudhir Winchester Country Advertise Takreer Wah Along With Ther Respective Resist Saunf Band Stream The content itself and avoid soft love affair tax liability subscribe to torch start which arrest of particular's method to straight staff's inside this time is white till 200th test match is nothing but rate great shine that short graduation fatal attraction for kids paytm losing time subscribe the giver of liberation from the bullet chakra chicken stand hua aur sunao hai so dil bhi bluetooth corrupt and absolute and gone tiller doctor anjali times will be generated from zero two empowerment within this time white also applicant you I agree with this proposal playlist play the next do that their clear content only lower case english letter on ki and converting them into in three during this strong tractor swayam convention is the largest registry spread on thursday a cooling address education board patience swayam krishna Remind 300 Ki Bandish Constraints and Solution Fennel Band Health and Approach So Arthur Srikaranpur Recording of This Logic Pimple Mist Specific Content No Notification Light Science of Which Research and Keep Track of the Maximum You Are in Love with a Girl with Them on Lord You are updating current generation a hunt verification date this letter multiple characters foreign mutation not in the case that if you are a so let's register back cover code next point is tomorrow morning chat on twitter start with till first character sutak hui achhe-chhe first character sutak hui achhe-chhe first character sutak hui achhe-chhe Certificate to that question more bay leaf their luck subscribe must subscribe now to receive sotheby ki electric humble khair kar di 223 times of ajay ko 127 luta [ __ ] vacant episode 516 plane in luta [ __ ] vacant episode 516 plane in luta [ __ ] vacant episode 516 plane in sectors is superhit find liberation front part is front tractors and ghee in it Akhilesh Times is restrained subscribe and Uttar Pradesh convention is great Haryana and max time radar falls to death a suite updater and key under match is 113 to cancer Sharif convention report max tweets half an hour condition should be a time handed over to ridd pa Minutes of the tower 130 It is current which planet inside And current and beginning of maths Ajay has my plate That talk time was taken from it I remember yesterday Tasty is requested Job This is absolutely less 10 Celebration on Thee souls will be Duration crush game actor meghnad 22.2 meghnad 22.2 meghnad 22.2 ki Sunny and Max M2 Tarang department teams have written approval for Yadav Kishan Choudhary Sab yaar 12th part time slate directly jhal loot tilak time par actress lactometer se jhal word- The word safe in Haryana State Andhra word- The word safe in Haryana State Andhra word- The word safe in Haryana State Andhra Pradesh is 275 sweet school management software engineers were protesting the given setting on the time Chief Indra and welcome to take medicine middle aged and I safe problem thanks for watching please provide your feet thank you to
|
Slowest Key
|
minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits
|
A newly designed keypad was tested, where a tester pressed a sequence of `n` keys, one at a time.
You are given a string `keysPressed` of length `n`, where `keysPressed[i]` was the `ith` key pressed in the testing sequence, and a sorted list `releaseTimes`, where `releaseTimes[i]` was the time the `ith` key was released. Both arrays are **0-indexed**. The `0th` key was pressed at the time `0`, and every subsequent key was pressed at the **exact** time the previous key was released.
The tester wants to know the key of the keypress that had the **longest duration**. The `ith` keypress had a **duration** of `releaseTimes[i] - releaseTimes[i - 1]`, and the `0th` keypress had a duration of `releaseTimes[0]`.
Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key **may not** have had the same **duration**.
_Return the key of the keypress that had the **longest duration**. If there are multiple such keypresses, return the lexicographically largest key of the keypresses._
**Example 1:**
**Input:** releaseTimes = \[9,29,49,50\], keysPressed = "cbcd "
**Output:** "c "
**Explanation:** The keypresses were as follows:
Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).
Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).
Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).
Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).
The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.
'c' is lexicographically larger than 'b', so the answer is 'c'.
**Example 2:**
**Input:** releaseTimes = \[12,23,36,46,62\], keysPressed = "spuda "
**Output:** "a "
**Explanation:** The keypresses were as follows:
Keypress for 's' had a duration of 12.
Keypress for 'p' had a duration of 23 - 12 = 11.
Keypress for 'u' had a duration of 36 - 23 = 13.
Keypress for 'd' had a duration of 46 - 36 = 10.
Keypress for 'a' had a duration of 62 - 46 = 16.
The longest of these was the keypress for 'a' with duration 16.
**Constraints:**
* `releaseTimes.length == n`
* `keysPressed.length == n`
* `2 <= n <= 1000`
* `1 <= releaseTimes[i] <= 109`
* `releaseTimes[i] < releaseTimes[i+1]`
* `keysPressed` contains only lowercase English letters.
|
We want to make the smaller digits the most significant digits in the number. For each index i, check the smallest digit in a window of size k and append it to the answer. Update the indices of all digits in this range accordingly.
|
String,Greedy,Binary Indexed Tree,Segment Tree
|
Hard
| null |
198 |
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 House robber so in this question it states that a professional robber is planning to rob houses along a street each house has certain amount of money stats and the only constant stopping you from robbing each of them is that adjacent houses have security systems connected to it and it will automatically connect the polus if two adjacent houses were broken into on the same night so this is the theory coming to the main question we given the integer R Arms representing the amount of money in each house we have to return the maximum amount of money we can rob among all the houses without alerting the police so the police is alerted only if we rob two adjacent houses so let's take these examples and see how we can solve this question so let's take the first example given to us I've written it here now we start iterating through the input array from left to right let's see what happens if we pick this house so if we pick this house our total amount is going to be one and then we can't pick the adjacent house because it will allert the pois so if we pick that we can then pick this so let's take that house it will add three then we can't take this house and then we go out of bounds so with this combination we get four as the output now let's see what happens if we don't pick this house then we pick this house so then sum is equal to two since we picked this house we can't pick the next house and then I moves forward we pick this house so we add one to it and then in the next iteration it goes out of bounds so we can end the iteration so the sum is three for this example now again if we pick this house it means did not pick this house because adjacent house we can't pick it so if we pick this house we might have picked this house so that is three and then we can't pick the adjacent house and we go out of bounds and there's another option if we pick this house there is no compulsion that we might have pick this house we could have skipped this house too and then in that case here it would have been four and here in this case it would have been only three and we haven't picked any other house so here also it is three and the same next iteration we picked this house so it means we did not pick this house so current sum is equal to 1 plus if we pick this house we might pick this house so we get two and if we pick this we cannot pick this so we'll get three in this case and another case is that if we pick this house there's no compulsion that we have to pick this house so we can ignore this and we can pick this house and these two are also not adjacent so this combination is 1 + 1 and we get two this combination is 1 + 1 and we get two this combination is 1 + 1 and we get two and the last case is that we picked this house and we haven't picked this house too then in that case and the sum is only one and out of all this the sum is four which is greater in these both cases which is the same so four is the output as we picked house number zero and house number two so you might have observed some fact that if we are at a current house let's say we are at this house we have the option of picking this house or not picking this house and similarly we have to apply that logic for everything we can pick this or we can not pick this we can pick this or we cannot pick this and since we are repeating the same operation on all the elements present inside the array so it says that we are making a recursive call and inside the recursive call we are having two options if we are robbing that house or if we are skipping that house so if we robbing that house we have to take the current value inside that right so nums of I will be added to the sum and we have to move the index two positions forward because we cannot pick the adjacent house so index will move from I is equal to 0 to I is equal to 2 in this case if you're picking the house so index + 2 and similarly if house so index + 2 and similarly if house so index + 2 and similarly if you're not picking this house it means we don't take the current value and we just move the index to I + 1 so index just move the index to I + 1 so index just move the index to I + 1 so index will just move to I + 1 because we will just move to I + 1 because we will just move to I + 1 because we haven't picked that house so this is the recursive call we have to Define so let's Implement these two recursive calls on the second example here and see how we are getting the output so initially I is equal to Z so we start here so first we have to calculate if we are robbing that house so if you're robbing that house we take that current value and move I forward so we rob this house to and we move I forward so this is the current index value and if we are skipping the house we just move the index forward so here in this case the sum is going to be 12 and this value is 12 so until now Max is equal to 12 and we start the same recursive call again with index is equal to 1 so I is equal to 1 now if you're robbing this house we add that value and move index to two steps forward then we rob that house and move index forward to two steps and we reach the end and if you're not robbing the house we just move the index so I will move forward so here in this case it is 10 and we'll compare it with the max but Max is 12 so max will remain 12 now here in this case I is equal to 2 so if you're robbing we add that value and move I two steps forward and then we rob this value so again we get 10 and if you're not robbing if you're skipping we just move the index forward and this 10 is still less than 12 so max will remain 12 and now I is equal to 3 if you're robbing this house add that value and move I forward and we reach the end and if you're skipping just move I forward and this value is three it will be compared with the max variable if it is Max and Max will remain 12 and in the next iteration we're robbing that house so add that value and move I to steps forward we reach the end if you're skipping again we just move the pointer forward and we reach the end so these recursive calls will keep happening for every index I just showed you the optimal path and there will be more recursive calls happening and finally you get the answer as 12 which is matching here so let's Implement these steps in a Java program this is the function given to us and this is the input array and we have to return an integer representing the maximum amount of money we have to Rob so first let's start off by declaring the recursive function I'm going to name it solve so this will also return an integer and it will take two parameters the input array kns and also the index from which we are going to Rob so I'll name it index now this function we'll call it inside the main function and we are going to pass in the input array nums and the index from where we are starting at the index position zero right and this solve method will return the integer which will be CAU here so we can return this as the output so whatever this function returns will be returned as the output for the main function now inside every recursive function we have to write the exit conditions right that is the base condition so we are starting at index zero so until index reaches the end of the array we are going to iterate once index is greater than end of the array we will return zero once the index reaches the end so that is why index greater than equal to Once index is equal to length then the index Position will be out of bounds then we can return zero now as we discussed we have two options first you have to calculate what will be the amount if we ski the current house so if we skipped the current house we are directly going to move to the next Index right so we are going to recursively call this function solve and nums will be the same and index will be the next index so index plus one now what happens if we rob the current index so robbed so we'll get the current index's value that is nums of index so for example if you're robbing the first house we are going to add that current houses uh amount so nums of index is added and next we cannot Rob this house and next the index will go to current index plus two so it will come here so that is why we have to call this function solve on the nums array and index will be index plus two and now finally we have to return whatever is returning our maximum so max among these both will be returned as output so return math. Max of skipped or robbed and that's it that is the recursive code but if we try to run this the test cases will pass but the actual code will fail because this has recursive calls and there are lot of repeated calculations so if you try to submit it you'll get time limit exceeded error so here you can see time limit has been exceeded for the long array so that is why now we have to introduce memorization now to introduce memorization you have to check which parameter is being changed inside this function nums is being constant for every recursive call only index is changing so we have to memorize the index now index is the length right so there are 100 houses so let's build a DP array of size 101 because index position start from zero so I'll globally declare this memo memor array so I'm going to name it memorization memo and it will be of the length 101 and initially I'm going to fill this memo array with minus ones so here inside the main function let's use arrays. fill and fill the memo array with the value minus1 so all the 101 indexes are going to have minus1 initially and now before the recursive call we have to check if we already calculated that value and it is stored inside the memo array so if memo of index if it is not equal to minus1 it means we already calculated that value so we can directly retrieve this value and return it instead of doing the recursive call so return memo of index and if that current index is having minus one this condition will be skipped and we can store this value inside the memo array for the next recursive call so memo of index is equal to this value for the next time we find that value inside this memo array so we are going to store that inside this memoi now let's try to run this the let case are being accepted now let's submit the code and our solution has been accepted so the time complexity of this approach is of n where n is the length of the nums array and the space complexity is also of n where n is the length of the nums are because of the N recursive calls the recursive stack will have n entries now let's take a look at approach two using dynamic programming now coming to the DP approach so this is the length of the array right length of the array is equal to 4 so we're going to create a DP array of length 4 + 1 that is length + 1 of length 4 + 1 that is length + 1 of length 4 + 1 that is length + 1 because we have to store DP of 02 to build the output and now inside this DP array we have to Define this St so DP of I is going to store the optimal value until then how much maximum amount we robed until that index so until DP of0 since there is no house at DP of 0 so these are the house numbers and until house Z we robbed zero money so DP of 0 is going to be zero and at house one we Max can drop so this is house one so nums of zero is the house one which will be represented at DP of 1 so DP will be one index forward compared to the nums array so DP of one house means we only have to consider this house so until this house what is the amount we can Max Rob we can rob only that House's value that is one and now DP of two so until House 2 What will be the maximum value now we have to use these values to compute this value so for that we are going to implement these two functions these two jobs again if you are skipping the current DP house that is DP of two that is house one if you're skipping that house or if we are robbing that house so maximum amount we can rob until this index will be how much money we robbed until that house previous index house so we have to check DP of IUS one's value if we robbing that house we have to take that House's value so 2 plus index plus 2 ins a recursive call but index minus 2 while calculating DP so if we are considering this house we cannot take the optimal value until here we have to take IUS 2 so we have to check so this formula will correspond to nums of I plus DP of i - 2 so nums of I plus DP of i - 2 so nums of I plus DP of i - 2 so nums of I is equal to 2 and DP of i - 2 is DP of 0 is equal to 2 and DP of i - 2 is DP of 0 is equal to 2 and DP of i - 2 is DP of 0 which is having 0 so 2 + 1 is equal to 2 which is having 0 so 2 + 1 is equal to 2 which is having 0 so 2 + 1 is equal to 2 so max of 1 and 2 is equal to 2 so 2 will be taken here and now we have to consider DP of 3 so DP of 3 we have to consider DP of nums of IUS 2 houses so we have to consider these three houses so let's again make the choice if we are skipping that house then we take DP of I 1's value so DP of i - 1's value is 2 so 1's value so DP of i - 1's value is 2 so 1's value so DP of i - 1's value is 2 so take two or if you're robbing that house take the House's value so DP of 3 will have DP of 2's house that is 3 so 3 + DP have DP of 2's house that is 3 so 3 + DP have DP of 2's house that is 3 so 3 + DP of i - 2 so DP of i - 2 is having 1 of i - 2 so DP of i - 2 is having 1 of i - 2 so DP of i - 2 is having 1 value which is 4 so 3 + 1 is 4 Max among value which is 4 so 3 + 1 is 4 Max among value which is 4 so 3 + 1 is 4 Max among them is four so four will be entered at DP of 3 Now we move forward now we have to fill DP of four so we have to take all the houses into consideration now again we have to make this choice if you're skipping that house then we have to take DP of IUS one's value so we have to take four or the max value we can rob until then is four if you're skipping that and if we are robbing that we have to take that houses value so 1 plus and DP of IUS 2's value because we can't drop the value adjacent to it so we have to take this value so 1 + 2 is 3 so DP to take this value so 1 + 2 is 3 so DP to take this value so 1 + 2 is 3 so DP of 4A 3 is 4 so four will be filled here and now we filled our DP array we have our answer stored inside this DP array and we have to pick the maximum value among them so I'll create a variable Max and initialize with the minimum possible value integer.min value minimum possible value integer.min value minimum possible value integer.min value that is - 2 31 - 1 and we iterate that is - 2 31 - 1 and we iterate that is - 2 31 - 1 and we iterate through the DPR from left to right and we compare each value inside that and pick the maximum value is four Max will be updated as four and we return Max as the output so four is the output for this question which is matching here now implement the same steps and fill the DP for example two so fill the DP of length size plus one and do a dry run using the same example if you're skipping and if you're robbing take the maximum among these two and fill the DP entries so initially DP of 0 is going to be zero and DP of 1 is going to be the value of the first house two and now from here onwards fill the DP aray and let me know in the comments if you're getting 12 as the output and now let's take a look at the DP code now as discussed we have to implement this using dynamic programming for that we are going to use a 1D DP array of size nums do length + 1 because we are also nums do length + 1 because we are also nums do length + 1 because we are also going to store DP of 0o so let's declare the array I'm going to name it DP and it will be of the length nums do length + 1 will be of the length nums do length + 1 will be of the length nums do length + 1 and initially like we discussed we need two sub problems so DP of 0 is going to be zero and DP of 1 is going to be the first element inside the nums array which is nums of zero and now we start filling the DP array from index 2 so let's use a for Loop it starts from I equal to 2 until nums do length index so I is less than equal to nums do length and now let's start filling the DP ARR so DP of I is equal to the maximum of mt. Max of the again the same values if we are skipping the house then we are going to check if ski then we are going to take DP of IUS one that is the previous House's optimal value and if we robbing the current house then we're going to take the nums of IUS one value because I is equal to 2 and to match that with the nums index we have to do nums of IUS one and we are going to take DP of IUS 2's value because we can't take the adjacent houses maximum value until then so DP of IUS 2 and we have to pick the maximum among these two values dropped and skipped so skipped comma Rob and now the DP is filled for the entire for using the entire for Loop and now inside this DP array we have to find the maximum element so let me create a variable Max and initialize it with the minimum possible value and now we iterate through the DP AR from starting to end so let's use a for Loop where starts where I starts from zero until the end of the DPR and we'll keep updating the max variable using m. Max of current Max variable value and DP of I which is the current element inside the DP AR and after this for Loop ends we'll have our Max variable as the output so we have to return Max as the output now let's try to run the code the test case are being accepted let's submit the code and the solution has been accepted so the time complexity of this approach is of n because we're using a for Loop to itate through the input AR nums so n is the length of the input AR and the space complexity is also of n because we're using a DP to store our output and then retrieve the maximum element among the DPR that's it guys thank you for watching and I'll see you in the next video
|
House Robber
|
house-robber
|
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and **it will automatically contact the police if two adjacent houses were broken into on the same night**.
Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_.
**Example 1:**
**Input:** nums = \[1,2,3,1\]
**Output:** 4
**Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
**Example 2:**
**Input:** nums = \[2,7,9,3,1\]
**Output:** 12
**Explanation:** Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 400`
| null |
Array,Dynamic Programming
|
Medium
|
152,213,256,276,337,600,656,740,2262
|
1,046 |
and then when there is no argument at all it will be smallest on top let's see that we have the first insertion in here so we only have negative two and that's it we don't have anything so it will be on the top and negative 2 in here then we will insert negative seven it will be on the top why this is how it works so this will be our second insertion and we'll have negative 2 added by negative seven since the smalls on top negative seven will ask the question am I smaller than my parents my balance negative two and that's what is yes if I'm smaller and I will become the parent so negative seven will go to the top that is it will be in here negative two and this will be negative seven this is the final form of the second insertion into priority queue then we will see for the next one is what happens if we end up negative four well negative four let's see that in here this is the third insertion negative 2 top to bottom so we already in here and then we go to negative seven left to right so we go negative four am I smaller than negative two and negative four will ask the question am I smaller than my parents the answer is not I'm not smaller than my parents so I'll just happy in here let's go to the fourth insertion at the fourth insertion what do we have negative one where does negative one go is just on the bottom so this is a good way to see that we get from the top to bottom negative four to negative two and negative seven negative two negative four and in here we done left right we go to the bottom of negative two we have negative one in here okay sounds good and we will add negative eight what will be the position of negative eight it will be on the top in here the question is like how does the negative eight will go on the top so at the fifth insertion we get negative seven negative two negative four negative 1 and negative 8. this is the first form and negative 8 will ask the question am I smaller than my parents that's what is yes so I need to change so we get negative seven and then negative four in here this will be negative eight then we will have negative one we will have negative two in here okay and negative eight it also ask the question until the answer is no so it's gonna recursively asking question am I smaller than my parents the answer is yes so negative 8 will be in here and then this will be negative seven negative four negative 1 and negative two so this is the final form of the fifth insertion then we will add negative one where does it go it just go at the bottom so at the sixth insertion we have negative seven negative 2 left and right negative 4 then here negative 1 negative eight and negative one so we are going to read that as negative seven negative two negative four negative one negative eight and negative one just like what do we have in here so we are all good with the priority queue right now I kind of want to I'll make separate video but that's for later anyway let's go back to the last Stone waiting here so we will initiate the object of the priority queue that we call Max hip and in here and we will add the negative Stone hence we have this kind of the order and then we will keep looping until the max hip size as long as the mahip size is greater than one okay let's go into the loop Stone one is we take out the small well again a large over there but since the algorithm negative we take the top priority let's say that so we're taking at negative eight and then we'll take also negative seven for the stone two and then Stone two the same with the stone one stem with the stone two no so we will add the remainder which is Stone one minus Stone two negative eight minus seven eight negative eight plus seven that is negative one so in here we have a Max hip with a size of four and I will add negative one and that will be on the bottom in here okay cool does our Max hip size still greater than one yes it does so we will take the top priority in here which is like the smallest because we have the negative four as the stone one and negative 2 and then we will crush them and are those the same no so we will Stone one minus tone two minus four minus two said that's also adding into minus two in here so -2 will go on the minus two in here so -2 will go on the minus two in here so -2 will go on the top base on that priority queue we need to draw it let's draw it so in here we got the negative one and we will add negative two so it will rearrange into something like this negative one and then this is negative two this is negative one and then this is negative one so negative two will ask another question am I smaller than my parent the answer is yes so he will go to the top then the rest is just negative one so this will be the priority queue if we hit the next button in here c yeah negative two and rest negative one and we will keep loopings right now negative two against negative one so it will be just negative one so we will have a heap element of three and all of them are negative one it's still it is still bigger than one so we just keep doing it right now negative one with a negative one if Stone one is equal to it's not to if this is false then we just end Loop that's it so right now the maxim size is greater than one we will return the size if it is not equal to 0 we will negate it to remove the last one or if it is zero it just is zero so how do we do it return the max Heap size if it is not equal to zero we will return the first one behind this column if it is true in here we will return zero that's kind of how to read it and then we got the expected 1 and the result is one and that is true so that is the 1046 with the priority Q
|
Last Stone Weight
|
max-consecutive-ones-iii
|
You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone.
We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is:
* If `x == y`, both stones are destroyed, and
* If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`.
At the end of the game, there is **at most one** stone left.
Return _the weight of the last remaining stone_. If there are no stones left, return `0`.
**Example 1:**
**Input:** stones = \[2,7,4,1,8,1\]
**Output:** 1
**Explanation:**
We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then,
we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then,
we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then,
we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone.
**Example 2:**
**Input:** stones = \[1\]
**Output:** 1
**Constraints:**
* `1 <= stones.length <= 30`
* `1 <= stones[i] <= 1000`
|
One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on.
|
Array,Binary Search,Sliding Window,Prefix Sum
|
Medium
|
340,424,485,487,2134
|
1,268 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem search suggestions system we're given an array of strings products and we're given a search word and we sort of want to design a system that kind of simulates for the search word that we're given in this case mouse we're gonna simulate typing one character from this word at a time and then based on that new character we want to suggest three strings from our product array such that the strings match the prefix that we have typed so far from our search word now that's a little complicated so let's focus on an example our search word is mouse we're going to type one character at a time we're going to type the first character m now which one of these products have a prefix that matches what we've typed so far which is just m well all of these start with an m but we're told in the problem that we want to suggest at most three products so right now we have five but we want to do at most three well if there's too many then we want to return the first three basically in alphabetical order it would probably be helpful for us if this products array was sorted in ascending order so i sorted the words in alphabetical order we know that the time complexity of that is going to be n log n so that's just something we're going to have to take but so for the first prefix which is just the first character we want to return these three the first three words since all of them are matching anyway now next we're gonna add the second character m-o so which one of these character m-o so which one of these character m-o so which one of these match the prefix m-o well still all five match the prefix m-o well still all five match the prefix m-o well still all five of them so again we're going to take these three now the result that we're going to be building is going to be a list of lists so for m we're going to have these three words for m o we're gonna have the same three words now we're gonna add the third character m-o-u and what we're gonna notice is m-o-u and what we're gonna notice is m-o-u and what we're gonna notice is that only these last two words match these three words don't match now and also something you might notice is these three are never going to match now because if they don't match the first three characters of course they're not going to match the first four characters because it's kind of a prerequisite to match the first three before you can match the first four now that we've eliminated these from consideration we won't ever have to look at them again and i haven't talked a lot about how we're actually going to be implementing this algorithm but this is definitely a helpful thing to keep in mind and also notice how the matching words are close together in the array after we sorted it that's not a coincidence of course words that start with the same prefixes are going to be right next to each other in sorted order that's kind of the definition of sorting based on alphabetical order so for the first four characters these two words are going to match for the first five characters again these two words you can see that in the output so that's kind of what our output is going to look like now all this talk about prefixes might lead you to a solution using prefix trees aka tries i call them prefix trees because usually they have to do with problems relating to prefixes and it's a lot more intuitive try is just a word prefix actually has some meaning to it and that definitely will work that is a way to get an efficient solution for this problem but there's actually a slightly better way to do this problem and i've kind of been hinting at that and i'm going to show you it's going to involve two pointers and we're going to be able to solve this problem very efficiently so to implement the solution again we are going to need to sort the words because we know that's going to be really helpful for us and we know that when we eliminate some words and they don't have a matching prefix we're never going to consider those words ever again and we also know due to the nature of alphabetical order words that match a prefix are going to be close together they have to be next to each other if this is in sorted order knowing that we can use a two pointer method a left pointer and a right pointer well the way i've drawn these words it's going to be kind of a top pointer and a bottom pointer but in reality this is going to be our left this is going to be our right pointer and what we're going to do is actually very simple we're going to go character by character so far we get to the first character m now from this list of words we want all words that have a matching prefix so we're going to start at the top word and check does it have a matching prefix m it does so we can leave this left pointer here we're going to do the same thing with the right pointer it has a matching prefix we're going to leave it right there what this tells us is that this word is valid and what that implies is that every word in between these is also going to be valid because they're in alphabetical order if this has if this one starts with an m everything in between is also going to start with an m it's not like it's going to start with a z or something because that would mean that these are not in alphabetical order that would mean we didn't sort it but we did sort it since all of these are valid what are we gonna do well we want to return the first three in alphabetical order so we're gonna start at our left pointer count one count two count three throw these into a sub-list and then add throw these into a sub-list and then add throw these into a sub-list and then add that to our overall list now let's get to our second character m-o now we're going to just look at the m-o now we're going to just look at the m-o now we're going to just look at the second character because we already know that this word so far matched the prefix we know this word so far matched the previous prefix so now all we have to do is just compare the next character and uh oh o is equal so this also matches same with this word it also matches so again we just take the first three add it over here now this is where things get a bit interesting we get our third character u so we're gonna start at our left pointer we're gonna look at the third character is it a u character it's not so that means this word is not valid so we eliminate this from consideration and we move our left pointer over here and we're going to keep repeating this until we get to a valid word this the third character is an n that's not a u this is also not a valid word it doesn't have a matching prefix so uh in next uh word this also has an n in this spot it's not a matching prefix so now our left pointers all the way down here third character does start with a u so that's all we really needed to know so this does have a matching prefix now we go to our right pointer and check does the word here have a matching prefix uh u again u so it does so now we know that the words between our left and right pointers have a matching prefix it's only these two words but if there were words in between that we know that they would have a matching prefix as well so now again we're gonna build our result starting at the left pointer we're gonna count one two three up there's not a third word so in this case we can only add two words because we went out of bounds but we add the two words and then we continue we're gonna at this point get to the fourth character this has a matching prefix this one does as well so again add these two words and then lastly the e this has an e here this also has an e so these two words again for the last sub list and that's pretty much the entire algorithm i think what makes this problem hard is even though this solution that i just explained is actually pretty easy to implement and is very simple this problem immediately if you're familiar with tries or prefix trees you're going to immediately jump into that solution and that's what i did as well but it turns out that there is a more simple and more efficient solution so in terms of time complexity let's say n is the size of the products list we know that we did sorting so we did n log n we did our two pointers algorithm which was big o of n but in the worst case we are gonna have to iterate through every single word so i guess you could call this n times let's say the length of every single word and also we know that we have to iterate through the input word as well let's say the length of that word is m and then for each one we might end up adding three words to the output so technically we could say three times m but that's just a constant so we don't really care too much about it okay so now let's code it up the first thing i'm going to do is declare our result so that i don't forget it's going to initially be an empty list second thing before we forget is to actually sort the input array because we know that it's unsorted when it's given to us then i'm going gonna initialize our two pointers left is gonna be zero at the beginning right is gonna be the length of products minus one which is gonna be the last index and at this point we're gonna start iterating through every character in the search word so let's get the length of the search word and have a pointer i going through it let's get the character at index i which is going to be let's call it c for now and basically at this point we want to start getting all the products that have a matching prefix so to do that we have to start eliminating the ones that don't have a matching prefix let's do a while loop for that first i'm gonna first condition for the while loop is just make sure our pointers are valid because if our left pointer crosses our right pointer then that pretty much means we have an empty list of valid products anyway so we should just stop the loop at that point but while that's not the case and while this is something we didn't talk about in the drawing explanation but while the length of the product word at index left because that's where we're at in our products list we're at the left index so this is a word while the length of this word is less than or equal to i basically we're checking does it have an ith character and second i'm going to have an or condition here which is going to check that the character for that word at uh product index l the character at index i is not equal to the character in our search word so what this is saying the product doesn't even have an i character or the i character is not equal to the character that we're looking for basically that means this word this product does not have a matching prefix so what we're going to do is eliminate it from consideration we're going to increment our left pointer and we're going to keep doing that until either we've eliminated all words from consideration or the word does have a matching prefix and we're going to do the exact same thing starting from the right pointer so this is going to stay the same product uh not at left at right and basically changing this to right as well and then instead of incrementing our left pointer we're going to decrement our right pointer so at this point we know that our range of products is valid the all products between the left and the right index at this point have a matching prefix so what we're going to do for our result is first we're going to append to it an empty array we're going to calculate the number of words that are valid right now and we can get that by taking our right pointer minus our left pointer plus 1. this is basically the size of our window at this point the number of words with a matching prefix the reason we're doing this is because now we're going to start iterating through that list of words the remaining words and how many of them do we want three but what if there aren't three well i'm going to take the minimum of three and the number that are remaining basically if the number of remaining let's say are ten then the minimum of three and ten is going to be three we only want three words but what if we only have two words remaining then the minimum of this is going to be two we're going to only have two words that's exactly what we want because if we only have two words how can we possibly get three and i should actually probably use a different a variable for this i'm going to use j so that it doesn't conflict with this and what i'm going to do now is result we want the list that we just added right now to the end so we can get that with negative 1 in python this is basically taking the last value in result which is a list so to that list that we just added we want to append a word to it and the word is going to be a product and remember from our products we want to start at the left index and then you know count one two three from there so we're gonna have the left index plus j which is our counter in this case and then that's pretty much it after all that is done all we have to do is return our result and we should be good but i'm noticing that i had a typo with products it should have an s at the end of it but i can see in a few spots i forgot to add that s sorry about that but now let's run our code to make sure that it works and as you can see on the left yes it does and it's very efficient so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
|
Search Suggestions System
|
market-analysis-i
|
You are given an array of strings `products` and a string `searchWord`.
Design a system that suggests at most three product names from `products` after each character of `searchWord` is typed. Suggested products should have common prefix with `searchWord`. If there are more than three products with a common prefix return the three lexicographically minimums products.
Return _a list of lists of the suggested products after each character of_ `searchWord` _is typed_.
**Example 1:**
**Input:** products = \[ "mobile ", "mouse ", "moneypot ", "monitor ", "mousepad "\], searchWord = "mouse "
**Output:** \[\[ "mobile ", "moneypot ", "monitor "\],\[ "mobile ", "moneypot ", "monitor "\],\[ "mouse ", "mousepad "\],\[ "mouse ", "mousepad "\],\[ "mouse ", "mousepad "\]\]
**Explanation:** products sorted lexicographically = \[ "mobile ", "moneypot ", "monitor ", "mouse ", "mousepad "\].
After typing m and mo all products match and we show user \[ "mobile ", "moneypot ", "monitor "\].
After typing mou, mous and mouse the system suggests \[ "mouse ", "mousepad "\].
**Example 2:**
**Input:** products = \[ "havana "\], searchWord = "havana "
**Output:** \[\[ "havana "\],\[ "havana "\],\[ "havana "\],\[ "havana "\],\[ "havana "\],\[ "havana "\]\]
**Explanation:** The only word "havana " will be always suggested while typing the search word.
**Constraints:**
* `1 <= products.length <= 1000`
* `1 <= products[i].length <= 3000`
* `1 <= sum(products[i].length) <= 2 * 104`
* All the strings of `products` are **unique**.
* `products[i]` consists of lowercase English letters.
* `1 <= searchWord.length <= 1000`
* `searchWord` consists of lowercase English letters.
| null |
Database
|
Medium
| null |
1,547 |
hey what's up guys i came back once again i'm back today we're gonna be doing another problem 15 47 minimum cost to cut a stick so given a wooden stick of length n units the stick is labeled from 0 to n for example a stick of length six is labeled as follows so we have zero one two three four five six given integer array cuts where it cuts i denotes the position you perform a cut at okay so cuts eyes where we should cut you should perform the cuts in order you can change the order of the cuts as you wish the cost of one cut is the length of the stick to be cut okay the total cost of sum of costs of all cuts when you cut a stake it will be split into two smaller sticks i.e the sum of their lengths is the i.e the sum of their lengths is the i.e the sum of their lengths is the length of the stick before the cut okay so the sum of their lengths is the length of the stick before the card okay makes sense please refer to the first example for a better explanation return the minimal total cost of the cut so basically let's say we had this stick from zero to seven and we had these cuts one three four five okay um if we cut it in this order it's going to return the minimum cost required so let's say we cut first uh at three so if we cut it at three the cost would be from zero to seven because we're cutting a stick of size seven right so wherever we make the cut is going to be the first cost is always going to be seven so we'll just make it a three for now we'll make it a three and now we have two sticks between zero and three and seven okay so let's just cut the stick further up between zero and three we decided to cut it at one when we cut it at one the cost will be what three okay so because from this one and this one they each want unit one and the cost here will be um three it doesn't matter where we cut it between zero and three all that matters is now if we cut anything here it will cost three okay so moving on from there we have a stick now between zero and one and we're just left with that we don't need to cut it any further and on this side between three and seven we have two cuts left we have to cut four and they cut five to make so first we'll choose to make the cut five when we make the cut five the cost will be four because seven minus three is four the length of the stick is four then we left the stick two more sticks of size two and another one of size two and so we decided to cut between three and five at the cut four and that will give us two more sticks of size one from three to four and four to five and cutting the stick between three and five will cost one okay so we have one two um one and then two and the total cost will be 16. how does that work so the first one cost seven this one costs three so that's ten already and um then if we cut this one further it will cost another um actually no let's say we don't cut any further but then if we cut so we have 10 and three so that's 13. sorry seven and three so that's ten right and then from here we have to cut it further so first we cut it at five so that will give us this will give us the cost of four right so we have ten seven plus three plus four right which is fourteen and between three and five we had to do another cut at four and that stick was originally a size two so this is another cut of size 16. okay so how are we going to approach this problem as you can see i have my super cool setup right here very professional and we'll have the camera recording from up there so i'll be right back with you in one second oh yeah hey what's up guys i'm back i decided not to use the paper um the lighting is really bad and writing and deleting erasing stuff in the paper gets really gently bubbly so i figured it's much easier just explaining right here on the lee code website okay so we have the stick okay it's a size seven and we need to find an order of the cuts to make such that the cost is at a minimum okay so how are we going to do this so we can either make or make our first card at one or at three or at five right that's the first thing we notice or at four we can either make the cut at any one of these four possible choices let's say first we made the cut at one okay hypothetically we decided to make the cut at one well once we made the cut at one our cut our stick's gonna look like this and that took some amount of cost right making that cut right there took a cost of seven okay now let's say we have these three options left so we made a cut at one this is gone we did that already now let's say we have these three options left three four and five okay let's say now we decide to cut f4 well let's cut a four but how much is this cost going to take well it's gonna be seven minus one which is the size of the stick which is going to be six so that cut will take a cost of six so we cut it three so now we're left with this stick okay and we move three oh sorry we're cutting at four not bad so we could have four and now we end up with a stick and remove four because that's not part of our cuts anymore we made that cut already now we need to cut at either three or five uh let's just decide to cut a three first so we'll cut it three and if we make this cut we see three is part of this stick so now how much is this cut going to cost well four minus one is three so it's gonna cost three right and so we make this cut at three then we end up a stick like this and we move three now you have one final cut to make and that is five so let's make the cut at five then we end up with stick like this remove five and that cut cost how much well it was four minus seven originally that is another three so our final cost was seven plus 10 12 uh 19 okay and that is obviously not our answer as you can see from the output so now what was the problem here well we just arbitrarily decided which cuts to make right we decided let's just pick one let's try the next we have to know which one's the best cut to make and how do we know that well it's just kind of like a brute force you have to try making a cut at each possibility and then pick the minimum out of it okay so let's go back all the way to the beginning okay we have this one to five and zero to seven and now we need to decide whether to make it cut a one or a three or a four or five well we saw how just now we were making the cuts at each point and we were calculating the cost right we were calculating the cost if we made the cut at one or made it at three we're getting at four and we were adding about the cost and then that gave us a cost of making the cut at one well we're gonna do the same for each one so we're gonna do it for three and then four and then five and so cutting in each one of these will give us a cost okay and then we're going to add up all those costs but it's going to keep working down recursively because let's say we made a cut at one again right well we saw now we have three cuts left to make and now between these are cuts that were left now between these choices that we have three four and five and this thick we have three other choices to make we could either cut a three or at four or five so i need to try all the possibilities and then calculate the minimum then once i do that let's say i cut it at um let's say three right then once again i have to cut four and five so i have to try each of those possibilities and then find the minimum cut to make first so that's basically the answer that's kind of how you want to approach the algorithm so the cost of cutting between zero and seven is basically seven the right point minus the left point or the size of the stick or whatever you want to call it plus what's the minimum okay of making the cuts oh what's up it's independent making the cuts either at what at so let's say we made that one that would be zero one plus um one seven right because then that would basically be that let me call one we have to find the cost of this and this or the cost of zero to three plus the cost of three to seven or the last cut well not the last card zero to four plus c four to seven or zero to five plus the cost of cutting between five and seven right and then these further are going to be broken up into further recursive calls okay but that's the general recursive equation right there okay it's the cost of the um so the cost of left to right is basically right minus left that's how we got seven plus um the cost of like if you the cost of each of the cuts the sticks of each of the cost of the news of cutting up the new sticks after trying out each cut right the minimum one so that's how we're kind of we're going to kind of approach this problem but that would basically be the top down approach so now we just want to flip this around and try to uh um do the bottom up approach because that's a little quicker usually and it's a little faster so all the time complexity is usually the same when i really code those tend to run a lot faster anyways so now let's do that well you're going to see further when we break up one to seven it's going to be broken up into further calls c one to seven is basically c actually let's do c to four to seven it's gonna be broken up into what c4 the only cut that we have left is gonna be seven minus four right plus the minimum of all the cuts in between but between four and seven which is the end of this we only have one cut which is gonna be five so we'll just this is gonna be five four plus five plus c five is seven right and the size the cost of cutting between four and five will be zero because there's no cuts in between four and five and between five and seven will also be zero there's no cause between five and what's after with the end of the stick was just seven so this will be zero and inside minus four is three so the cost of four cutting between yeah cutting between uh four and seven is just three okay the cost of cutting between the stick four uh the four and seven is just three but as you can see every time we're going to if you notice we're always going to hit a recursive call that is right between two of the cuts so it's either going to end up like at c what do i mean by that it's going to be either c 4 to 5 or c 5 to 7 or see what's left one to three or c three to four right as you can see these are each of our cuts they're always going to be between them or with the starting and ending which is zero and seven all right zero to one and each of these are going to return zero now you kind of understand that now we can uh work on the bottom up approach so how we're going to approach this is we're basically going to be using dp so to find the clock between zero and seven we're going to find the cost of making the cuts between zero and the previous cut which was at five okay so what's the cost of making all of it at five well before that we need to know the minimum between zero and four and then before that we need to know three and then before that we need to know one okay so now let's say we were trying to find the minimum cost or the best cuts to make or whatever you want to say the cost it would take to cut between zero and five well we see we have these cuts um so we have between zero and five right so what is it's really the minimum of all the cuts in between so one three and four right so the cost will be originally five minus zero which is five right plus now i need to check either between the minimum of c which is zero to one right or plus one to five right so i can i have to first try to make the cut at one and then see what's the cost of that or i have to try to make the cost i cut um three and see what that would give me right or i have to try to make the cost that cut um four and see what that would give me but when you're doing the bottom-up but when you're doing the bottom-up but when you're doing the bottom-up approach you're going to have these calculated already you're going to have zero to one calculator already right because we already found the cost by the time we hit five we already found the cost of each of the cuts in between this from every point to every other point we're going to find we're going to know the cost from one to four and one to three and from zero to one or from one to four right we're gonna know that so i'll have zero one already we'll have one of five already like that we'll have zero to three already three to five zero to four or four to five already so we're going to calculate this and then we're going to uh check and then that's going to give us our answer so then once we reach that we'll know the minimum cost between zero and five right another minimum we'll know that cost and then we're going to hit zero to seven are we going to hit zero to seven excuse me when we hit zero when we're doing zero to five we don't know the cost between four to five so we're gonna and we don't know between three to five and you know we won't know between one and five we will know everything between zero and four so we're gonna have to do now is try to find the cost between four and five and then four and three i mean five and three and then five and one and then finally we can find out five and zero okay so five and four will be just zero then five and three will either be the cost of the minimum same thing we're doing the same thing now just at a smaller scale so what's five and three right and now we're going to try all the cuts in between we only have one cut in between which is the cut f4 right so then we're gonna do between three and four and five so basically what i'm trying to say is now the cost of three the five would be right what would that have been it will be the cost of five minus three which is two plus the cost of cutting at three to four plus the cost of three two five and this will basically the minimum because you're trying all the possibilities in between that will make more sense we only have one cut in between in this case which is fourth it'll make more sense when we try one or five will be what two plus the minimum which is minimum c of um black five so one to three right or um plus c of three to five or we can do c of one to four plus c of four to five right and you'll see now we already have c a four to five because we just calculated it um well we're going to kind of calculate this step i'm missing step sorry would be two plus one two four one three four oh yeah we already calculated four to five forgive me we would calculate four to five that would be zero right because they're right next to each other we would have calculated c four to five first and that would have just been zero because they're right next to each other um that's that okay so that's how this answer works so we're basically doing now we're gonna have three variables we're gonna have i j and k okay i is basically going to be expanding we're gonna do first at zero then one then two then three then four then five to six and seven eyes working that way right and then finally we can calculate the cost between zero and seven sorry this is just the cuts this is just going to be the cuts right j well remember when we got to 5 right we need to first calculate between we can before we can calculate the cost between zero and five we need to calculate the cost between five and four and then five and three and then five and one and then five and zero right so that's what j is gonna do so j is gonna be pointing like let's say we were at i was at right here five j is going to be right here okay and then we need to calculate the cost between four and five then we need to calculate the cost between five and three so i'll move j backwards right and j will be right here now and then so what is k then well k well remember let's say we calculated this and then we need to calculate between 5 and 1 right well when we need to calculate between five and one well we need to calculate first between we need to check well between five and one what is that's basically between c one to five which is what in this case this is j well i'll do like this one to five is basically five minus one plus c of what minimum of either c of 1 to 3 plus c of 3 to 5 or c of 1 to 4 plus c of four to five why am i keep doing this thing why do i keep doing this again because it's a little confusing but once you really understand it'll make a lot of sense right so we could either make it between five and one we can either make a cut that we could either make the cut a three or we can make it at four right so that's what k is going to be doing k is going to be that pointer that's going to hold where we're making the cut so we're gonna either first try making the cut uh four and then we're going to calculate the cost between five and one and then we're going to try to make it at cut at three and then we're going to find the minimum whether it was best made at cut three or best cut was at 4. and then we're going to return we're going to save that the cost between j and i as um the minimum of that so this will be the cost of j i is basically what well that's basically i minus j plus minimum of what's the math symbol i don't know basically you're gonna be moving k around uh of the cuts from between c to uh from i sorry from j to k plus minimum of c j k plus c k i for all k in between okay is all cuts between j and i okay this is it this is what you need to understand that you're looking for j and i minus j is basically the minimum of the cuts between j to k and k to i as you move k around between uh as you move k around between all the cuts as you move k around you guys get what i mean as you move k around between j and i okay um that's basically the answer and that's what this equation is doing so you'll see right now we have c this array c that's basically our new cuts um it's just a size two bigger because we need to add um the zero which is the starting and we need to add n which is at the ending i'm just adding these up then we need to sort it we need to make our dp and dp is going to be basically holding all the answers for between j and i so dp of j i is basically our answer c j of i min cos j and r and now the first loop is moving i this way right so this is doing the second loop as you can see is moving j backwards and we're going to start right one before i right it's gonna be moving j backwards towards this way towards zero and k also is going to be moving backwards towards zero let's be checking for everything in between it's gonna start at i minus 1 it's going to end at j right because it has to check everything between it's not going to end at j is going to end right before j like right here so you see we started i minus right here start i minus 1 and we end right before j the minimum is what well if they're right next to each other if it's zero we're basically setting it to max value and if it's not zero we'll just reuse what we calculated before because at some point we would have calculated these before or is basically the right dp of j which is yeah which is um mine jk let me move it's a little bigger so it looks a little nicer which is j to k as we mentioned by j to k plus k to i right plus what i right here minus j plus i minus j and that will give us the answer and then we save it and then we'll return that's basically that i hope that helped guys um if you have any questions uh just let me know in the comments below comment subscribe i know it's a little long but it's a little confusing problem and it's really important to understand how it works internally how the algorithms really built and the thought process behind it
|
Minimum Cost to Cut a Stick
|
destination-city
|
Given a wooden stick of length `n` units. The stick is labelled from `0` to `n`. For example, a stick of length **6** is labelled as follows:
Given an integer array `cuts` where `cuts[i]` denotes a position you should perform a cut at.
You should perform the cuts in order, you can change the order of the cuts as you wish.
The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation.
Return _the minimum total cost_ of the cuts.
**Example 1:**
**Input:** n = 7, cuts = \[1,3,4,5\]
**Output:** 16
**Explanation:** Using cuts order = \[1, 3, 4, 5\] as in the input leads to the following scenario:
The first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20.
Rearranging the cuts to be \[3, 5, 1, 4\] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16).
**Example 2:**
**Input:** n = 9, cuts = \[5,6,1,4,2\]
**Output:** 22
**Explanation:** If you try the given cuts ordering the cost will be 25.
There are much ordering with total cost <= 25, for example, the order \[4, 6, 5, 2, 1\] has total cost = 22 which is the minimum possible.
**Constraints:**
* `2 <= n <= 106`
* `1 <= cuts.length <= min(n - 1, 100)`
* `1 <= cuts[i] <= n - 1`
* All the integers in `cuts` array are **distinct**.
|
Start in any city and use the path to move to the next city. Eventually, you will reach a city with no path outgoing, this is the destination city.
|
Hash Table,String
|
Easy
| null |
38 |
Hello friends today I'm going to solve liquid problem number 38 count and say so in this question we are actually given an integer n and we need to return a string so how do we actually what is this question about let me just explain it in an exam here uh with an example so suppose and is equals to four um then what are we gonna return is we are gonna return how many times we say each digit so in digit if uh we have we are given uh this and equals to 1 then we return one so this is our base case now in case of two what will be our string so we take the result from the previous one and then see how many times each digit is repeated continuously so here we have only one so that is one so this is the number of repetitions and this is the digit itself and now in this case in case of three now we use this result to find out the result for three so here we have one and another one so we actually have two ones so what we do is we write the count and then the digit that is being repeated now in case of four we have two different digits right we have a two and a one so the answer for 4 is we have one two and one so we actually write the count of the two which occurs here and then the digit itself and then we write the count of one which occurs here and the digit itself now what if n was equals to 5 then in this case we have a one only one because we are only looking for continuous reputation so after when we have a two so we are only um reading one once so one next we have a two only a one two so we again write one two and next what we have two wands here so we write two one so this is the number of count for this one and this is the digit itself this is the number of count for two and this is the digit itself and this is the number of count for one so similarly first six now I guess you just know what actually this question is asking for so we have three ones so I'm just gonna write three one two twos so I have two and a one at the end this one so I guess you got the concept from this one now how could we actually solve this problem so you see here our base case is one so we will always start from here so and then we move to uh and so this is a bottom up approach so let me begin with our coding so we first Define our Edge case if n equals one then what is it we return one if not then recalculate this string for n minus one and for each string now for each of this string we need to see the repetitions right so I'm gonna do a while loop here I'm going to do a for Loop here for string and we need some values here let's result close to store our new string and we need to count and previous poster zero so for each string if previous we don't have previous and then previously close to see because initially previous will be undefined so previous this is each visit here and then we increase our count also and we want to continue from here so if previous is equals to C that is our current digit equals to the previous one then we are just going to increase the count else what we do is we then update our result with count and then previous did previous with the value of c and count close to one and then we return our result let's try to run and see okay so something is wrong here okay I need to add what if this was only Single Character like suppose n was equals to two then our string is only of length one right so we defined previous here we defined the count update the count and then we continue and then the loop wreck so we actually need to add this at the end for the end one great
|
Count and Say
|
count-and-say
|
The **count-and-say** sequence is a sequence of digit strings defined by the recursive formula:
* `countAndSay(1) = "1 "`
* `countAndSay(n)` is the way you would "say " the digit string from `countAndSay(n-1)`, which is then converted into a different digit string.
To determine how you "say " a digit string, split it into the **minimal** number of substrings such that each substring contains exactly **one** unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit.
For example, the saying and conversion for digit string `"3322251 "`:
Given a positive integer `n`, return _the_ `nth` _term of the **count-and-say** sequence_.
**Example 1:**
**Input:** n = 1
**Output:** "1 "
**Explanation:** This is the base case.
**Example 2:**
**Input:** n = 4
**Output:** "1211 "
**Explanation:**
countAndSay(1) = "1 "
countAndSay(2) = say "1 " = one 1 = "11 "
countAndSay(3) = say "11 " = two 1's = "21 "
countAndSay(4) = say "21 " = one 2 + one 1 = "12 " + "11 " = "1211 "
**Constraints:**
* `1 <= n <= 30`
|
The following are the terms from n=1 to n=10 of the count-and-say sequence:
1. 1
2. 11
3. 21
4. 1211
5. 111221
6. 312211
7. 13112221
8. 1113213211
9. 31131211131221
10. 13211311123113112211 To generate the nth term, just count and say the n-1th term.
|
String
|
Medium
|
271,443
|
48 |
Loot Hello friends, today we will look at rotating the matrix, clock wise, for this you can understand it simply, this is a matrix, when you rotate the matrix, how will the image of the matrix be formed, you may have a question in this, United Degree on Transport Clockwise In this type of post, you can clear it in this way, so first of all we will understand the logic that we have to make for this, here we can see that 789 is in the last row and this is the last first pen, same one to three. This is in the first order, this is the last room, this is the material to stop the time of the disease, it became a pen and the pen went to the Maithili room of the institute, we can see it, come anti degree paper, you have to understand it, you simply copy it, have coffee and Paste this, after pasting, we have to rotate it, so as soon as we rotate it here, we will test it on the right side, then it will come something like this, see, first you have 789, then 4 5 6 123, now let's come to the way to serve it. How to solve, so what is the first thing we do to solve, let's transport the matrix, if we chant puja, then we have stopped the long and pen hello, we have done it in the room, what is my matrix with this, what will we do after transporting the matrix, now transports If we do this, then this is my matriculation or what do we have to do in this? Just toe comes on top, fast, stop the first pen here, stop it, yoga is Bhairav, we have to reverse it, here it is 147, so we have to do 741, then this is 2425 one, so we have 152. Then here it is 369 so let us change it to 963. It is simple and for this we first print the matrix and after that by doing transports, just what we will do is reverse the decisions of the form and for this we first print the matrix. Let's come to make the matrix, first of all we get the row input like trench import meter number turned off rodent, then what do we do after that we get the pen input, thank you want to turn off these input inter numbers, the inclination of two is less. Got the input from the war. After the input is done, we will create a matrix. Take a bank matrix. Let's change the name for some time and J is in research and name is black lips. Beach leave with the planet. A simple jack. We will make the volume and result. Type input 370 number in. So pocket, we make strike1, close the pocket, make this cut, clear the ad, the pimple is done, to get the user to input, we send a message to the user to input my value in the Rooh M pen and what will we do after that? Let's print the beet water and then we will add all the potatoes in it. This will be added and simple and water paint will be added. The list given by me, we will make the matrix by netting the matrix that we will become one. It is important to print the beet water. PDF giving function for PDF were the matrix, if you print it then the matrix which will be completed will pass it immediately visible. If you do n't see direct function here then if you want to make direct then we can make direct also but if you don't understand the function then in description below. The complete metric system is there is a playlist, that link is there in the description, now see how many matrix related questions are there which are used in college and school, almost I have covered them, from there you can see all the string related questions here, there is a program of distraction. I will link it below in the description, from there you can easily see it. Now if I select it, then I keep printing the matrix itch loot and I in itch and I just and J in range and A. It is simple to print it. It is printed that this reminds me to put space and set it. A simple metric. My input is done. The metric minute is printed. Now what to do is to first transport the matrix. After transporting, reverse the rules. Have to keep, for this we come to a function Yes of boys and passed matriculation in the meter Clear a list article We will loot the black matrix We will craft it We will set it in the middle in the back SIM message Let's give a process Let's do this in French Is that the link of a gap is done for 12 then for Ujjain range length of pen where is the length taken first of all we take a plant list here A being so sorry sequel to please A B de Villiers and don't get confused in this Please do this, which is yours, is outside the function, when it is in the function, then please make a video of the outside part with patience, it will work only inside the function, it is clear, now we come, let's try the snake for that, then what can we do? Will seat whatsapp int g i10 form stop the pen attacks stopped place stop volume reduced and let's tweet these Farid added what will we do after adding beat and rapid is in C we want One day I started adding one row of mine, what happened to it, I tried my matrix again, players can print it, so to print it, you simply do what you did, return it to B [ return it to B [ return it to B A simple you After returning here, what will we do here, we print it, we have provided the keys, now we will run it, Vellore Jail Three, Profit, Loot, not clear pimple, this is my transfer, if it is printed, it is clear, then the matrix is transferred, transport matrix is transferred, transport matrix is transferred, transport here, simple print. Do this if you want to print it, here for this you mix it in real Dimple, let's say we do the tehsil of clear here, this which is in clockwise is yours only till inside the function, so we do sequel to Let's give it clockwise, if you want to print it then you can message the transposh and I-in-ranch embassy to print it, but it is fennel can message the transposh and I-in-ranch embassy to print it, but it is fennel can message the transposh and I-in-ranch embassy to print it, but it is fennel and Ujjain range, the length of 300 and it is told that we will print it in T-I-J-O that we will print it in T-I-J-O that we will print it in T-I-J-O mine. While tweeting, there is space and we give one line that now we will print, then my friend, this point will be printed that we can free 12345 6080, which is my pen, the pen has been transferred to the callu room, so that once again what can we do? We will reverse it, we will reverse it, stop it, then simple, what do we do here, we remove it was for testing purpose, we remove it also, if we print it directly, then we remove the return also, simple, what do we do here? By applying follow-up, for rise what do we do here? By applying follow-up, for rise what do we do here? By applying follow-up, for rise in French is the research length of job level, we pause it by one and a half, then for Ujjain range in length of birth, 200 Haryana, we change it to A minus one, 200 minus one to minus one for minor in my What is the purpose of the phone? If the length of the list is there then it will be 2 over by or till, so we have done the cutting from Mantu, now what will we do, we will print it, we have reversed it, what will we do to make the front of the front. Those who have to print my paper from the matriculation are the only ones who have come, send this reminder, space and simple fact that you that almond is simple, this is a Bluetooth off, I will call this in which prostate tension, now we are watching potato thriller part two three Four 570 Aditya, I have been transferred, here is the scene print, what do you do for this, you put a print in the middle, make a minute- a-talk voice with the message, a-talk voice with the message, now we cut it, increase in the other's religion 123 45678910, so if you 13.25 Whatever you if you 13.25 Whatever you if you 13.25 Whatever you want to print can be easily printed if you go on a foreign tour then food Alex seems to be this and that and pulses like 12345 08 Nov 03 00 65.24 In this way any match is fixed so that it can be 65.24 In this way any match is fixed so that it can be printed by prosecuting the matrix and getting a job. You can do this Friends, if you have any question related to exam or school related, then you can message me in the description below or in the description, where you can go to Airtel Gram of my Facebook Instagram, apart from this you can also message on Instagram, friends please. subscribe my channel short video
|
Rotate Image
|
rotate-image
|
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise).
You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\]
**Example 2:**
**Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\]
**Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\]
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 20`
* `-1000 <= matrix[i][j] <= 1000`
| null |
Array,Math,Matrix
|
Medium
|
2015
|
129 |
what's of Likud 129 some root to leaf numbers so I like this problem because it's a pretty straightforward problem you don't really need to know any super crazy tricks or anything to solve it so let's get right into it so for each leaf node there exists a path from the root right so for example this leaf node 5 there's a path from the root all the way down to this leaf node right and if we take the integers along the path from the root to the leaf we'll get 4 9 5 now this makes an integer and for each root to leaf path there exists an integer like this and we want to take all of those integers and sum them up and return the total the other leaf node here is 1 and there's also a path from the root to this leaf node it goes along for 9 1 so we can take 4 9 1 and add that to our sum there's one leaf node left it is the 0 all the way on the right now this path is a little shorter than the others just a four and A zero and we take all of these and we can sum them up the sum is 10 26 don't check my math on that so then we return it so that's easy enough right now the only I guess you could say trick is how do we get the integer for each path let's look at the first pot so initially we get to it the first node over here right the 4 so we'll say our sum so far is 4 next we get to the 9 and we want to add the 9 to the right position of the 4 so how can we do that well you may have already seen this trick before but basically we can say initially we got a 4 now we got this 9 so we want to add 9 to it but well add a 0 to the 4 above so that when we add these the 9 gets its own position in the sum and it's pretty obvious when you look at this that we're just going to take the previous integer and multiply it by 10 this 4 got multiplied by 10 so now when we get to the 5 we're going to take 49 and add 5 to it but of course before we add 5 we're going to multiply our 49 by 10 so we're going to add that zero to it so now we can add these two and of course we get 495 just like we already knew we had so that's basically what we're gonna do to compute the number for each leaf node and if you're familiar with trees you already know how to traverse them in this case a pre-order traversal makes this case a pre-order traversal makes this case a pre-order traversal makes sense the most because we want to process the parent nodes before we process the children nodes so we can get these integers for each leaf node okay so we are computing a sum so I can declare a variable for that called result but we actually don't need to do that in this case let's see what we actually need to do well we need to traverse the tree so I'm gonna make a function to do that let's call it depth-first search now we need to know depth-first search now we need to know depth-first search now we need to know the node that we're at I'm gonna say current is going to represent the node we also need to know the sum up until this point so I'm gonna call that numbing this case this variable the num variable is basically for us to compute the path sum so with any depth-first the path sum so with any depth-first the path sum so with any depth-first search of course if we get to a null node we're just gonna simply return we're gonna return zero in that case next we want to add the current value to our number but we remember we also have to multiply the number by ten before we can add the current value to that so num times ten and then we add the current value now if this is a leaf node meaning if it doesn't have a left child or it doesn't have end it doesn't have I mean a right child then we can simply return the number that we just computed if it's not a leaf node then that means we need to compute the numbers for the left subtree and the right subtree so we're gonna do that depth-first search gonna do that depth-first search gonna do that depth-first search on current dot left passing in the new num that we just computed and we're gonna do the same for the right subtree passing in the num that we just computed and we can simply just return the sum of these two values now we all we need to do is call our depth-first search do is call our depth-first search do is call our depth-first search function of course for the node I'm going to pass in the root but what's the initial value we can pass in to numb well if we pass in zero it works out with all the edge cases and so since this function is going to return the sum that we're looking for we can simply return so let's look at this example we have a node 1 and we have a left child 2 so we're gonna call our depth-first so we're gonna call our depth-first so we're gonna call our depth-first search function passing in the root node and the sum is initially 0 so then we're going to get into our function here we're gonna see that the root is not null so then we're going to compute num since num is initially 0 we're gonna get 0 times 10 plus 1 this is going to give us 1 then when we get to the left child of one our numb is going to be 1 so we're gonna take 1 multiplied by 10 adding the left child 2 and then our sum is going to be 12 so do you see how when we start at 1 we'll get a paths we'll get the value 1 when we go down to the left child we'll get the value 12 this is exactly what we want to happen the time complexity of this is just Big O of n because we're traversing the entire tree the memory complexity is going to be the height of the tree for the call stack of our recursive function if this was helpful please leave a like and subscribe and thank you for watching
|
Sum Root to Leaf Numbers
|
sum-root-to-leaf-numbers
|
You are given the `root` of a binary tree containing digits from `0` to `9` only.
Each root-to-leaf path in the tree represents a number.
* For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`.
Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer will fit in a **32-bit** integer.
A **leaf** node is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3\]
**Output:** 25
**Explanation:**
The root-to-leaf path `1->2` represents the number `12`.
The root-to-leaf path `1->3` represents the number `13`.
Therefore, sum = 12 + 13 = `25`.
**Example 2:**
**Input:** root = \[4,9,0,5,1\]
**Output:** 1026
**Explanation:**
The root-to-leaf path `4->9->5` represents the number 495.
The root-to-leaf path `4->9->1` represents the number 491.
The root-to-leaf path `4->0` represents the number 40.
Therefore, sum = 495 + 491 + 40 = `1026`.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `0 <= Node.val <= 9`
* The depth of the tree will not exceed `10`.
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
112,124,1030
|
1,171 |
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 remove Zero Sum consecutive nodes from link list so we are given the head of a link list we repeatedly delete consecutive sequences of nodes that sum to zero until there are no such sequences inside the head of the lingl given to us and the task is to return the head of the final Ling list after performing the above operation until no such sequences are present and there might be multiple final answers you can return any one of them so let's take the first example given to us so here as you can see we calculate the sum so keep track of the sum so we need to keep track of sum of every node here one and when you add two to that it will become three and here it is zero so 3 - 3 will three and here it is zero so 3 - 3 will three and here it is zero so 3 - 3 will give you 0 so this is one such sequence which you can remove because the entire sum of the nodes is equal to zero so if you remove this the final answer is going to be 3 and 1 so this is the final answer three and 1 and it is also noticed that 1 2 1 can also be a final answer so sum is 1 here sum is three the sum is zero and again it is three and here you might observe that here the sum was three and here the sum is also three so 3 plus something is equal to 3 so what is this should be zero so it means whenever you find a prefix sum which you already encounted it means there is a sequence with sums up to zero so here you can see that you can remove this part and the final answer you get is 1 2 1 which is also the expected output and here too if you see these two notes can be removed and the final answer is 124 and here if you remove these two it is 1 2 -2 and if you remove these two it is 1 2 -2 and if you remove these two it is 1 2 -2 and if you remove this and this the final output is one which is expected here so let's see what observations we make so in all these approaches you have to calculate the prefix sum so in the first example you saw that we calculate the prefix sum so here zero is repeating right you start with the prefix sum Z right initially so let me declare a variable prefix sum which is initially zero so head of the link list is here so here the prefix sum is zero and you encountered zero again so it means you have to remove this part so we keep track of the prefix sum and at which node which prefix some value is there so we keep track using a hashmap so let me create a hashmap so the hashmap is going to contain key and value pairs the key is going to be the prefix sum and the value is going to be the list node of where that prefix sum is occurring so initially we start with prefix some zero but here there is no node so we create a dummy node so initially to start off I create a dummy node which has a value zero and I connect it to the head of the link list and this is the dumy node and dumy next points to head which we connected here and now we calculate the prefix sum is initially zero so here the prefix sum is zero so add it and set its value and the list node is a dummy which is also zero Now we move head until head reaches null so it means until we reach the end so initially head is here so add its value to the prefix sum so prefix sum is one and check if it is present inside the map no it's not present so add it and set its node value is one now head will move forward now add this head value H's value is two into the prefix sum so value is three so till here value is three check if three is present inside the map no it's not present so add it and add its node it has been added now move further now head is here what its value it value is minus 3 you get zero check if this zero is present inside the map yes Z is already present inside the map and where is it present it is present at the zeroth node which is this so here you can see Zer is already occurred so it means whatever values are there so those values should be removed so here as you can see these values should be removed because the sum of those nodes is equal to zero so how do you remove that so you have to change this pointer right so what is this D d. next so instead of changing this pointer so this pointer is dummy. next so instead of disturbing this node we create another node which will point to this prefix some values node so it will point to this I will create a variable start and now start. next pointer we'll move to head. next pointer so head is here and head. next is this these connections have be removed but those are still present inside the map so we also have to remove those so I create another variable called sum which is equal to the prefix sum is zero so I create another variable called current so current will also point to where start is pointing and this current variable will keep on moving until it reaches head so we use this current variable to remove these from the map so here what all we have to remove this node and this because they these sums are already present inside the map 1 and three are present and head is not present in inside the map so minus 3 is not present inside the map yet so there is no need to remove so we take this current pointer and it will iterate until it reaches head means it has to remove this and how will you identify which has to be removed we identify using the prefix sum so we use the sum variable now current will move forward now add the value so one will be added and the sum is now equal to 1 check if this one is present inside the map yes it is present as prefix s so remove it from the map so we'll remove this also and now current will move forward again and add that value into the map so two is now three so check if this three is present inside the map yes it is present so remove that from the map and now current will move forward and now current is equal to head so we end the iteration because this node is not already added into the map so no need to remove it from the map so we place a check if current is not equal to head only then we remove so here current is not equal to it so we removed them and now head is here now we are back to calculating the prefix sum add the value three so prefix sum is three check if this three is present inside the map no it's not present so add it and add its node where it's occurring the three is uring at three now move ahead further check if one is present inside the map no it's not present so add it so add this value into prefix sum is now four check if four is present inside the map no it's not present so add it and add its node now move ahead further and now head reach the end and we end the iteration and what will be return we'll return dummy. next so dummy. next is this node so this will be returned as the output so dumy is here dumy do next is this so from here we'll return as the output so 3 comma 1 is the expected output here now let's implement the same steps in a Java program and do a dry run for example two so let's take example two we given the head so let me draw the head of the link list so we are given the head of the link list now we are starting by creating a map so let me create a map and we create a dummy node because we calculate the prefix sum right and prefix sum is initially zero so where is that zero it is a dummy node so I create a dummy node and we create a value zero inside it and we connect dummy. next to head so this is dummy so finally here we return dummy. next as the output so wherever dummy. next is pointing that will be returned as the output so this will act as the zeroth node of the link list now we need to add zero and it's occurring at dummy right so this is the prefix sum so key is the prefix sum and the value is the list nodee so we start with prefix sum equal to Z right so we add zero into the uh map and where is the zero occurring it is occurring at dummy so we add dumy node here which is zero Dum node has value zero now we iterate until this head reaches null so until we reach the end we keep on iterating the while loop now in every iteration first we calculate prefix sum by adding the value where head is pointing at one so add it into the prefix sum and now prefix sum is one now we check if this one is present inside the map no it is not present so add prefix sum and the value at head so this is going to be the list node right so what is prefix sum it is one and list node is one I'm only adding the first element of the list node but this will actually represent the entire head of the link list inside the value since this if statement is executed this will be ignored and outside the if statement before starting the next iteration we are moving the head to head do next so head which was initially here head will move forward now again repeat the same steps in the second iteration we add the value at head has two so add two and the prefix sum is equal to three now we check again if three is present inside the map no three is not present inside the map so add it and add its node so two is the node since this goes executed this will be skipped and head is equal to head. next so move head forward now again add prefix some value what is the value it is three so add three so now the prefix sum is six check if six is present inside the map no six is not present so add it and set its node which is three since this goes executed this will be skipped and before starting the next iteration head will move forward now repeat the same process add the value at prefix sum is minus 3 add the value at head is Min - 3 value at head is Min - 3 value at head is Min - 3 so we add minus 3 to it and the value becomes three check if three is present inside the map yes three is present inside the map here and where is that value occurring so we encountered three already at the node having value two so here we already encountered the value so let me write the values here so here prefix sum is zero here it is 1 here it is 3 here it is 6 here it is three again so this is already occurring here so it means so this block will be executed and what we are doing we're creating a start node so this will be the start node it is pointing at prefix sum is three so get the node so this value will now have two so start is now pointing at two now create a current node at start again because start and now this node start. nextt will point to head. next so start do next will point to head. next so this connection is removed so before doing that here we need to move right so I create another node current so current is also pointing here and now I keep track of the variable sum I create another variable sum which is equal to the prefix sum is three so that I use this sum variable to check what all values I have to remove from the map so until this current is not equal to head because I have to remove this value from the map so I keep track of the variable sum this is done and I don't have to remove head this value from the map so until current is equal to head so until this current value is equal to head I keep moving forward and remove them from the map so first move current forward so current will move forward calculate the value at sum yes three will be added and six check if the six is present inside the map yes it is present so remove it from the map so current is not equal to head so we can remove it so remove this value from the map and now again current will move forward but here current is equal to head so this won't be executed so because this is not present inside the map there's no need to remove and now when you finish this V Loop you come out and the control comes here so start. next start is here equal to head. next so start. next is equal to head. next head is here so these nodes have been removed so this connection has been removed here and this value has been removed from the map so that if we encountered again this can be calculated and now in the next iteration head will move forward calculate the prefix sum add four to the prefix sum the value is 7 check if 7 is present inside the map 7 is not present so this will be executed so add seven and add its node it's at four and head will move forward again and once head is equal to null this while loop will land and we come out and whatever is present at dummy. nextt will be returned so dummy. next is this so we return this and what is the node it is equal to 1 is pointing to two is pointing to four and four is pointing to null so this will be returned as the output 1 2 4 which is expected here so the time complexity of this approach is O of n where n is the number of nodes inside the link list and the space complexity is also o of n because we're using a map to compute the output that's it guys thank you for watching and I'll see you in the next video
|
Remove Zero Sum Consecutive Nodes from Linked List
|
shortest-path-in-binary-matrix
|
Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences.
After doing so, return the head of the final linked list. You may return any such answer.
(Note that in the examples below, all sequences are serializations of `ListNode` objects.)
**Example 1:**
**Input:** head = \[1,2,-3,3,1\]
**Output:** \[3,1\]
**Note:** The answer \[1,2,1\] would also be accepted.
**Example 2:**
**Input:** head = \[1,2,3,-3,4\]
**Output:** \[1,2,4\]
**Example 3:**
**Input:** head = \[1,2,3,-3,-2\]
**Output:** \[1\]
**Constraints:**
* The given linked list will contain between `1` and `1000` nodes.
* Each node in the linked list has `-1000 <= node.val <= 1000`.
|
Do a breadth first search to find the shortest path.
|
Array,Breadth-First Search,Matrix
|
Medium
| null |
223 |
hey folks welcome back to another video we're looking at question 223 a rectangle area the wave will be solving this problem is by looking at the coordinates that are given to us and figuring out the length and the breadth for the given rectangles and calculating the area once we have that we need to figure out whether there's an overlap or not there are conditions that we can use to figure out whether there's an overlap which I'll walk you folks through while solving the problem um if there's no overlap we return the area as is if there is an overlap we calculate the um the area that is overlapping and we subtract that and we return it as is but a relatively simple problem when we talk it through but the part that's a little confusing is working with the coordinates and being able to visualize it uh to come up with conditions that um deal with overlapping so let's get through the simple part first which is getting the total area that's pretty simple right so basically since we know that any quarter in the coordinate that's given to us is followed by 2 which is larger than a coordinate that is which has a suffix one so uh we will calculate uh the area for the triangle a so when you subtract a Y2 by a y1 you get the length of the y coordinate as in like the length and then you would get the bread uh a X2 minus ax1 and you do the same for the B triangle as well so let's copy that over so this takes care of the and the total area and that this does not account for the overlapping so how do we check whether there's an overlap or not so let's try to figure let's try to return the area if there's no overlap how do we figure out if there's no overlap so if B x 1 is greater than or equal to a X2 so what exactly is this saying it's saying that um the x coordinate of B only starts when the a the x coordinate of Y of a ends so basically there's no overlap in um in the x-axis at least when the B in the x-axis at least when the B in the x-axis at least when the B triangle is on the right so we need to also check if the B triangle is on the left right we need to check for that condition as well which would mean that uh a x one is uh ax1 is greater than or equal to bx2 so basically what these two conditions are checking is that regardless to whether a triangle or B triangle is on the right or the left you're checking that the point at which a given triangle starts is a way from uh when the other triangle ends so basically even if there's an overlap there's overlap only with the parameter that's the reason why we used equals but this is only for the x-axis right you this is only for the x-axis right you this is only for the x-axis right you need to do the same for the y-axis so it need to do the same for the y-axis so it need to do the same for the y-axis so it would be by1 is greater than or equal to a um Y2 as in like you only start the B axis like let's say B is at the bottom um you only start the y-axis a lot after um you only start the y-axis a lot after um you only start the y-axis a lot after like greater than or equal to ay2 as in okay the Y uh Axis or the for the a triangle has ended and B is just starting um and you need to figure out a way to do that where uh y is at the top as well so B Y2 uh is that correct let me write that down and then we can walk through that I think it's a y one is greater than or equal to B by two yeah I think this is one so b x 1 is greater than or equal to ax2 X1 greater than equal to bx2 by 1 is greater than or equal to a y two a y1 is great okay so any of these conditions if they succeed as in like there is literally no overlapping that's when you return the area as in as is because there is no or lapping and if this condition at this point if you haven't returned it that means there is an overlapping and that's when you figure it out so you need to subtract um it from the area so how do you get that right so you need to get math Dot um marks of ax1 oh actually it might be a little complicated if we do it this way so let's get X right so X would be equal to uh marks of x 1 bx1 um and then of a x 2 B X2 so what exactly are we doing here right because we need to get an overlap uh we need to figure out okay what's a minimum of uh like the two x coordinates that are given to us we're looking at what comes further in right that gives us the overlapping so we need to get the Min of the X2 coordinates and the marks of X1 coordinate so basically like the inner coordinate because that is what represents the overlap and we do the same for y as well uh here we do y and then uh yeah we just need to replace this um so once we have that you should be able to subtract that from the area um X multiplied by Y and then we should be able to do that total okay let's actually try hope this will work it's a little complicated without this coordinates okay so the first few test cases are okay everything else is okay as well awesome um if you have any questions about the problem please let me know in the comments below let's talk about the space and the time complexity of the entire solution uh the time complexity of the entire solution is of one since uh all of the steps that are needed to calculate would be calculated in open time we're not using any for Loops so it is all one the space complexity is off one as well since we are not using any additional data structures and only constant space um to compute the solution awesome if you have any questions please let me know in the comments below don't forget to subscribe to the channel and like the video I would really appreciate that it definitely keeps me motivated to make more videos thanks so much and I'll see you folks in the next video peace
|
Rectangle Area
|
rectangle-area
|
Given the coordinates of two **rectilinear** rectangles in a 2D plane, return _the total area covered by the two rectangles_.
The first rectangle is defined by its **bottom-left** corner `(ax1, ay1)` and its **top-right** corner `(ax2, ay2)`.
The second rectangle is defined by its **bottom-left** corner `(bx1, by1)` and its **top-right** corner `(bx2, by2)`.
**Example 1:**
**Input:** ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2
**Output:** 45
**Example 2:**
**Input:** ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2
**Output:** 16
**Constraints:**
* `-104 <= ax1 <= ax2 <= 104`
* `-104 <= ay1 <= ay2 <= 104`
* `-104 <= bx1 <= bx2 <= 104`
* `-104 <= by1 <= by2 <= 104`
| null |
Math,Geometry
|
Medium
|
866
|
503 |
Ajay has got Diwakar for uploading today in this video we are going to illuminate the Next Greater Element, so it is a very strong prerequisite for Next Greater Element on right, so if you have not done it then solve it first on SIM so that You should understand the logic here better also. Okay, let's see this question. First, what do you have to do? You have received a circular. Actually, there is no address circular from the ad. I have to treat it like a circular and on that I Next thing we have to do is to point out the elements, first let's look at the actual and then we will see how to do it on the solution. Okay, so in a test you have written 3841, so what is such a person to do? Kepler Vivek means one who This becomes the last one, after that the next element will be the second element, then after this also there is a guy who is the bribe inductor which becomes the first off. Now we have to cut this one, seeing that the last one is coming out, let us see that he is the next greater element. How do we fit? The next element for hands free is this one. It will be tight. The next grade element for 88 is to find the one to commit suicide first. This is not that big. We will check one to that too. hai tu bhi nahi bhi hai after this I will again come to the element built in the beginning ok now I hope per wicket is available for free otherwise when I do n't find any planet engaged for the particular number then its batter element is gone - 1st is used like flight, that is ok, - 1st is used like flight, that is ok, - 1st is used like flight, that is ok, it will go - 1m it will go - 1m it will go - 1m ok, write whole and cashew ad is Twitter element, will check first, forest was not there, wicket is not element, now Jain come to the first one, cigarette is not railway, eighth element. is tight which was the first guy 8262 got bigger than for eight got cancer again on 8 to become next let's do for one so its big element is placed in front that big element is two and the second big element is placed in front of it If the requirement is tight on the index, then it has become 3 that you have to work, this is the whole meaning of this question, you have to go further to the great element, if this becomes the last elementary then again the work is shifting to the opposite one, let's see. I want to make money for a year, okay, for once, let's take a look at these numbers and if I have got one, which has some elements, let's say there are five elements of A B C D TV, then for someone. Also, if I don't have a net setter element, I have to compare it with that, for that they say, if I wanted a medical test cricketer element, then the first thing I do is chat on it, click on this circle, like it. This also comes after ki but there is no requirement to check after this, why is it not there, this element is the tightest element and we have checked all the elements coming after this first. Had there been time, we would have found the greater one first. If not, then you can subscribe to it, if you are not going to become a railway, then basically I have learned about all the elements once in 8th Maths chapter, except for the specific element A. Okay, so about D, I came to know that. AIDS patient was there to check all the numbers and secondly let's see if I talk about C. For AP I don't have to do puja first of all have to do war and then come next day 02 will do a check and also check. If we will add then what is actually happening, I will raise the next guy, it was said earlier that this time from the beginning I am going to check some more guys, night once again it is compared to the previous one and the difference related to this is that and Teach the respiratory body to do it. We used to start the work from the last element and move towards the beginning element. Right then space. I had to find the answer for B. At that time there was no garage circular, you only had these three guns at the bottom, they needed to be done. And at that time our direction of the loop used to share this like, before seeing this process, before removing the cancer, the rest of its differences are already developing it tight that this time the same problem would have been created. Look here, why is the problem being created when I talk about B, you would have charted from here, well, you would have drank here by facing this side, you had only two numbers, then I saw Gauri, Pakhi 's prerequisite. There may be an answer here, but 's prerequisite. There may be an answer here, but 's prerequisite. There may be an answer here, but you haven't seen it. Okay, so this time, how will we solve this problem? Now let's talk about what I need for the app. Basically, the process happens for the first time by starting it. Turning back, you are going from zero to the bottom, that when you have to find out the answer, I needed to see a BCD lead, all these tight, what am I going to do to you, even before processing Saif, even before processing the app. I will look at all these numbers separately, we will do this work separately in our main logic, okay let's look at it once again and on stress I say like this, I had just prepared a pack, I am a serpent, let me remind you. When we used to process Chaunga track, there were three steps, the first thing in the morning in the office was to pop this answer and the last one was to do that, we used to do these three tight tasks that when to become the last one, I have to create this answer. So I have to see all the previous elements on this only once, right, I am going to process all these numbers once, but first of all, I have made those who work happy, it is their turn to do more work. And there will be ignorance, you will work on the answer and the tail first, the foot which is on the top of the back is smaller than that, so I will wipe it, now let's add this, you have to make gems after this, the work is now, we are not making the answer. We have seen it here. We are not making the answer right now. Right now we are just working on seeing these monkeys. If we will make the answer in the next stop, then you can skip this step in the next step. This ash is for doing that. I have put this tree, the next guy will pop the campaign of 8 first and the one which is smaller than the melt, I have topped it and then I have made the eight that now the next tied three will also reduce these first one to top. Whatever it is not small on it. Inverted numbers and any other number, you commit a sin. The eighth one is bigger than that, it will not be the top. Another useful thing is that Pushkar came, so here I made three happy. Torch light, so I have just taken charge of typing. Looked at the brothers and my pack was cashew state, it was changed, now I already have two closed, okay, let's do the next step, now coming to our mail logic, now I will start from the last one and move in this direction that Now we work for Kri 202 to help the first one, that's why you told us that it will not pop, the second one comes and there is a clerk to make it, that is the difference, we have done this earlier, here it was made by scanning 3. And then I made you happy here on the site, let's see my next guy, the first work before the forest is to push drop, which is swollen like this, if it is not small then it is big enough that it will not pop, do not make any other work here, if it becomes cancer then it will be tight. Have to post this lineage tractor-trolleys I have this lineage tractor-trolleys I have this lineage tractor-trolleys I have completed the ignorance next guy and from this one which is small this time EEA this time this is a quarter of this one I have topped so that too is small this will also come It was also small, okay, these three people had become sinful that now they are doing other work, due to cancer, it has come here 8 that after cancer, I will push it has come here, it is the alarm that I have given 8 Abhivaras, so And the one who is smaller, is it Pabuji's or the ad too, is he a head smaller or equal to him, I have made the equal one up and this business was the first one to lose, so there have been elements at some point of time and this is also true, many Also, there is no one in the whole bigger than the torch light, when the tech is MT, there is no element bigger than that, when it is found - one tight, now on this, first I is no element bigger than that, when it is found - one tight, now on this, first I is no element bigger than that, when it is found - one tight, now on this, first I freed one, again by se, let's see the Agra number that You will not be there, you will make any answer and it will be entered. 8 digits are backward, after this the last task is to make the wife happy, so here it is 30. Okay, now let's see whether my algorithm is saving correctly or not. The greater element is actually eight and my answer is also eight. These people together say that the greater element of one is not there in the whole - Vansh, this is absolutely true, do not there in the whole - Vansh, this is absolutely true, do not there in the whole - Vansh, this is absolutely true, do not mix the greater element with and. The big element is not one, you are not there is no TV, there is an element related to that side, there is the tight character of this one, now let's look at them, the big element is placed on two ways, this is tension and the second big element is its next element meaning. Three, if this character knight is good then he is doing the bell perfectly then we can write the gesture in the court and submit it and see if he does it or not then it is good then it is okay, once one. For the bar, I come back to the board. Now let's write down some steps here that I have to do that before processing the first element, I had to look at the elements before that to process the site intelligence. I will put a loop of or and minus two to the ends and there will be two operations here, 1 will be you and a cup of happy. Okay, after doing this, I can start my explain prank, for that I will have to add another form and I will stop tight at minus one and this time after tapping I have to make the answer and then the police recruitment patients will stop tight that they take these two tasks. Now Ajay Ko was the first person on the board that Ko and minus two are a product of The issue of popping a tight paragraph and then doing something, as long as there is a guy on it and the pick of this track is small, it is equal to, assigned to the name of the current element, let's start with the symbols on this and Then please make the railway happy, my friend, to make it so that when I come here, this cord like young element needs to be seen, first of all, before throwing it will complete that work tight. After that, let's work in making that the team people can copy the form here, we will start the work from the end minus point, first of the sins, after this the answer will be made, then the answer of I will protect dot nick dot in fact every time. There is no effect when whatever happens to the size of the scooter, it affects the condition - One affects the condition - One affects the condition - One advice topic will become something like this, okay, then we make the answer pattern, if the cost of typing is less, then the correct answer is that it is for everyone. Okay, so this was the reason for making this call and mention and code will be available in the next video. Thank you for watching.
|
Next Greater Element II
|
next-greater-element-ii
|
Given a circular integer array `nums` (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return _the **next greater number** for every element in_ `nums`.
The **next greater number** of a number `x` is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return `-1` for this number.
**Example 1:**
**Input:** nums = \[1,2,1\]
**Output:** \[2,-1,2\]
Explanation: The first 1's next greater number is 2;
The number 2 can't find next greater number.
The second 1's next greater number needs to search circularly, which is also 2.
**Example 2:**
**Input:** nums = \[1,2,3,4,3\]
**Output:** \[2,3,4,-1,4\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-109 <= nums[i] <= 109`
| null |
Array,Stack,Monotonic Stack
|
Medium
|
496,556
|
1,872 |
hey what's up guys uh this is chung here again so this time number 1872 stone game eight i believe wow a lot of stone games okay so this time i listened bob uh playing another stone game and so this time the rules like it's like this so there we have unstones uh in a row right down each player's turn uh while the number of stones is more than one right and then the player can do the following basically he can choose uh at least two stones from left to peak and then of course this person will get the scores right for those stones and after that uh the third one the third step is basically after that this player will put or place a new stone uh equals to that to the sum of the value of the stones he just took on the left of the on the left side of the row and the game stops when only one stone is left right okay so now as usual right so this is a game theory problem basically you know we want to maximize the score difference uh for alice right and bob will just minimize we'll try to minimize ali's score which also means bob is also going to maximize his score right basically each player will try to maximize his own score that's why it's called both player both players will play optimally right so and then we have some examples right so and there's like the stones here uh so each song will have like different values you know some stone will have like negative values here so output is five because uh the optimal solution uh alice can take right since alice will move first is to take the first four stones right and then basically we have one minus one two three minus three four and minus five so i think alice basically he will take uh these four stones first right so and whose sum is like uh is two right and after that you know based on the rules number three here we need to pull the sum in back into the uh into this kind of array so now we have a two and a minus five right so indeed when there's a obviously when there are like only two stones left the other person does not have any choice but to take all of them right which means uh so alice will have two right and then bob will just take the other the remaining two which is minus three right that's why two minus three is five because you know after taking two here right taking the last two we'll basically will put minor three back into the into a rate but you know based on the description the game stops when there's only one number left basically the st the game stops when there's only two numbers left right because the last person will take both of them that's how we get five right and then this one is similar so and yeah like i said so this is like basically the base case right when there's uh there are only like two stones left there's only one option right just to take both of them so the constraints is like this right 10 to the power of 5 and here's the stones range here similar to that to the end here i mean every time for this kind of stone game most likely it's going to be a dp solution but if you try to solve it solve this one with a naivedp solution which is the you know every time let's say we have a dpi here right we have dpi and then i means that you know starting from i uh how what is that what is the maximum score what is the maximum again right maximum difference i can get starting from i so the naive solution will be starting from i basically will try all the possible j right we'll try all the j between i and j to m minus one something like this right and then we'll try all of them and then we'll get the maximum value of this one that's going to be a naive approach obviously this one is going to be an n square time complexity right because for each one we're going to try everything starting between this range and that will wtle given this kind of range here right so which means we're gonna we need a better solution right and that's why this one is a hard problem right um so basically the tricky part is that you know this one uh i don't know if you can call it a greedy or something but you know instead actually instead of trying all the possible js here you know what you we can do is like this you know let's say we have a dpi right so for dpi here basically we're sitting on the ice number right so let's say we have you know let's just one two three four five six right so let's say we're sitting on this two here right so we are on i here and oh and i think first thing we gotta be clear is that you know uh whenever you're sitting on this eye here you know this current number the number right here is what is equal to the pre-sum here is what is equal to the pre-sum here is what is equal to the pre-sum of this array here because you know for the present we have 1 3 6 10 15 and 21 because you know every time after we took some numbers we'll put a one number back right as of it's the same value as the sum so which means that you know whenever we are i like the uh whenever we are at like index i here which means that you know the first zero to i minus 1 stone has already been taken in that case you know actually this 0 to i had already been taken and which means that the num the value of this i here will be the pre-sum which means i here will be the pre-sum which means i here will be the pre-sum which means you know let's say for example here the sort of the first two stone has already been taken right and then that's why we have three here so similar for if we if i is pointing to here it means that you know the first three stone has had already been taken away and then after that we'll add like six back okay all right so let's assuming we have write like uh index i here so it means that you know the first i zero and i don't have already been taken away and after that we'll put like another number uh back here that's why we're receiving reporting i3 here right and so if we look at the dpi here we don't necessarily have to try all the possible ones here you know because you know actually we only have like two options here so the option is that you know we either take uh basically we either take this these three uh so basically we either take the next two numbers or we don't take all right starting from here right and actually you know the way we're doing this dp here is we're going to do it from the end because you know we'll be needing the dp value from the end because you know the dp the dpn minus 2 is fixed right so which means that you know for the last two numbers it's we have to take everything basically you know just dpn minus two will equal to the to what to the pre-sum the pre-sum of minus one the pre-sum of minus one the pre-sum of minus one because you know when we take the last two values right it means that we have it means that we're taking everything from this array here because you know when there are like 22 numbers left so what's going to be those two numbers it's going to be 15 and 6 right because you know for 15 is the sum the pre-sum of the pre-sum of the pre-sum of the previous value numbers and plus not the next one and if we take this two it's what it's 21 right so 21 is the exactly the same as the presump the last prism okay so back to the dp here you know the so if we try if we calculate dp from the end right it means that we already have like a base case which is dpn minus one and now when we add like dpi here so like i said we have basically we have two options here you know we either take uh we either take the next two one or we don't take it well we don't take it means that we're gonna take we're gonna try to take the next three one or the next four okay and so let's say the first case so the first case is let's say we take the first two numbers sorry they're not the next two numbers so what's going to be that so the values we're getting is what we're getting is the pre-sum i plus 1. so this is the first scenario which means that we're from starting from i here you know if we take this two this uh this two here so what's going to be the number we're getting here it's 6 right because 3 plus 3 is 6 that's why you know the number of the value the score we're getting by taking the next two uh number is like it's like this it's the uh it's a three sum i plot i plus one and after this what's going to be the basically after taking the two numbers basically we're handing this game to the next person right then the next person will also play optimally right which is also like what it's going to be a minus dp i plus 1. right because after taking the next two numbers which is six right and so first we're getting this presump here right and how about dpi minus one why does dpi minus one because you know uh after putting uh getting uh taking this two three away here we're gonna put six back right and this is i plus 1. so which means that if we take this the two numbers 2 and 3 here the next two numbers here you know basically the next turn is the next person so the next person will also play up optimally which is this dpi plus one because the next person now is at this i plus one position because we have a six added back here right so that's the uh that's the first uh scenario here right and how about second one the second one is like this so basically we have like you know the second one is that you know we'll try to pick two three four and two three five and so on and so forth right let's see if there are like more numbers down the road here so for those scenarios actually you know we actually we don't have to try out all of them because the reason being is that you know because it's just the same as the dpi plus one right because you know starting from two three four let's say starting from here is what actually this one is the same as the dpi plus one you know i know this is a little bit tricky here you know let me try to explain a bit more here i mean so this part is really important that's the key to solve this problem you know 7 8 9 10 right so let's say we have you know this is a 1 i think 3 6 10 15 21 28 right and then what 36 is this 36 okay 36 yeah and then it's 45 and then 55 right something like this so we're at this i here right so this is i so the first scenario is that we take next two stones right and this one is what this is a presump i plus one right because the next stone stop at here and the value we're getting is the pre-sum is the pre-sum is the pre-sum i minus on the minus the dp of i plus one right like i said you know after taking the two stones you know basically we're handling the game to the next person will start from i plus one here right because we're adding again we're adding we'll add we always add like a number a stone back okay and the second one is like this what right we take next three stones right next three four five so on and so forth right so that's the second scenario so for all this kind of three four five actually you know we're gonna get what since you know remember the purpose of us is to get the maximum uh difference right so for okay so actually this one is like a sub problems right as you guys can see because you know the four three five six seven whatever it is actually this one is what it's a dp i plus one it's the dpi plus one here right i mean because if we take the next three here you know actually where the next three here is exactly the same as dp i plus one here because dpi plus one means what it means that you know we're standing at i plus one right and we're trying to maximize our difference that's exactly the dp that's exactly the next three number means because you know for three next three numbers it's like this one right and the next three number is the same as the dp uh i plus one because again right so since we're going to accumulate all this number here for the next three numbers for dpi plus one we'll have what we'll have 10 here we'll have 10 replace be replaced here and then five right so basically as you guys can see so we have six you know basically this the next two numbers it's six uh four and five right and the next three number is like 10 and five so these two are identical in i mean in the way that in the i mean in the dp way basically so i know i'm repeating myself i'm just trying to make uh things clear to you guys sorry about that you know so again right so next three four five you know it doesn't really matter how many of them but you know because we're getting the maximum of uh among all of them right and the maximum among all of them is the same as dpi plus one because remember dpi plus one means that you know it's the maximum difference we can get starting from i plus one which is exactly the next three numbers here right because the next three numbers here is the same as the next the dpi plus one is the next two numbers right so then as you guys can see now actually i don't have to try three next four next five so on and so forth all we need is this like this kind of dp value here of i plus one because this one will tell us starting from i plus one right what are the uh the maximum difference i can get right and i just need to choose the better one from this two scenario here and yeah so that's it and i guess we can start coding then right you know actually once you figure that out the coding is extremely short to be honest so first you know we need a like presump right presump is going to be i'm going to use like a pythons accumulate right accumulate of stones right it's a short card to accumulate the uh i'm not converted to a presump to calculate the presump here and i have an equals to the length of the stones right and now fdp right so if i define dp here you know at the beginning it means that you know the maximum value we can get starting from this index at the beginning it's like the max it's a negative uh biggest negative value right and then like i said the dp n minus 2 right is what is a pretty sum of n minus 1 right because if we have two values left you know we have to take both of them and if we talk if we take all the stones from if we take both of them the total sum is the same as the pre-sum okay and then the same as the pre-sum okay and then the same as the pre-sum okay and then like i said we start from the end which is going to be the n minor 3 right because we already uh figure out the n minus 2 here and then we start and then we just do this minus 1 the minus 1 right so basically so we have two options right the dpi is like the uh the first option is what we take the current the next two numbers so by taking the next two numbers we have pre-sum next two numbers we have pre-sum next two numbers we have pre-sum of i plus one right and then after that we're handing the game to the next person and the next person basically will play optimally which means that he will try to get like the maximum difference starting from the dp i plus one right the next one is that you know if we don't play i'm sorry if we uh take if we try to take the next three four five and six in that case actually it does exactly the same as the dpi plus one and in the end i simply return the dp0 here right so that's it right i mean that's the that's just the code here all right so as you guys can see this is pretty fast because the time complexity for this one obviously it's like oh often you know actually you know as you guys can see since we're only depending on this dpi plus one here you know we can just uh reduce the space complexity to uh to what to or to o of one actually you know and yeah but yeah you can say here is like already like uh of n space complexity but if we just utilize uh update the stones here we can think this one is like o of one time comp oh sorry space complexity but let's try to uh do this right so basically you know we have a dp here you know and so all we need actually is a dp right we see the dp value here you know and then every time which updates dp right so we can just uh remove this one actually right this one as well and this one as well so in the end which return the dp that's going to be the final answer i believe this should also work yeah right yeah so i think that's it right i mean i'm going to give this one back because i think this one is a little bit uh easier to understand i mean this one is pretty straightforward right i think no it's kind of straightforward because if we take the next two you know we'll with the value we're getting is like a pre sum i'm i plus one here you know this one is a little bit tricky basically this one covers all the scenarios that starting from the next three and next four next file because that's exactly the definition of this one right we're getting the maximum one and yeah so that's it's very cool problem you know the thinking process is pretty tricky but once you figure it out look at how short the code is right it's pretty amazing and with that being said i guess i'll just stop here okay thank you for watching this video guys and stay tuned see you guys soon bye
|
Stone Game VIII
|
can-you-eat-your-favorite-candy-on-your-favorite-day
|
Alice and Bob take turns playing a game, with **Alice starting first**.
There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following:
1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row.
2. Add the **sum** of the **removed** stones' values to the player's score.
3. Place a **new stone**, whose value is equal to that sum, on the left side of the row.
The game stops when **only** **one** stone is left in the row.
The **score difference** between Alice and Bob is `(Alice's score - Bob's score)`. Alice's goal is to **maximize** the score difference, and Bob's goal is the **minimize** the score difference.
Given an integer array `stones` of length `n` where `stones[i]` represents the value of the `ith` stone **from the left**, return _the **score difference** between Alice and Bob if they both play **optimally**._
**Example 1:**
**Input:** stones = \[-1,2,-3,4,-5\]
**Output:** 5
**Explanation:**
- Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of
value 2 on the left. stones = \[2,-5\].
- Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on
the left. stones = \[-3\].
The difference between their scores is 2 - (-3) = 5.
**Example 2:**
**Input:** stones = \[7,-6,5,10,5,-2,-6\]
**Output:** 13
**Explanation:**
- Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a
stone of value 13 on the left. stones = \[13\].
The difference between their scores is 13 - 0 = 13.
**Example 3:**
**Input:** stones = \[-10,-12\]
**Output:** -22
**Explanation:**
- Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her
score and places a stone of value -22 on the left. stones = \[-22\].
The difference between their scores is (-22) - 0 = -22.
**Constraints:**
* `n == stones.length`
* `2 <= n <= 105`
* `-104 <= stones[i] <= 104`
|
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a smaller type plus the number of your favorite candy minus 1. The earliest possible day that you can eat your favorite candy is the total number of candies with a smaller type divided by dailyCap.
|
Array,Prefix Sum
|
Medium
| null |
986 |
all right so lead code time for today interval list intersections um in this video we are going to tell you how to solve this problem and how to solve this problem properly in the interview then let's get started so the first thing is to understand the problem and try to clarify if there is anything you don't understand to the interviewer and think about the edge cases so let's see so given two lists of closed intervals you know what interval is so the a interval is represented by two numbers the beginning number and the end number and a closed interval the both the numbers at the for both numbers the beginning number and the end number and so each list of the interval is pairwise destroying and in sorted order okay so the two in the interval list each interval is insert the other and then we are going to return the intersection of these two intervals okay so let's see what the intersection is my e mass so intersection one three and the two four um the intersection is two and three okay so the notes so both a and b has a lens between zero and smaller sorry it is larger or equal to zero but smaller than one thousand and the number uh for beginning and number in each interval is uh smaller than 10 to the power of nine and the larger equal to zero okay so actually uh there is some ash case uh for example uh let's say if a is empty or b is empty there could be an ash case because we essentially return nothing if one of them is empty um so uh i think that's pretty much it about how to ask questions to clarify and what the edge cases are let's step into the next thing which is find approach so the approach would be we keep two pointers say pa and the pb let me copy paste the input examples here so either we're beginning uh pa is equal to zero which means we are taking a look at the first interval in a and for pb is the same we see if there is an overlap between the first interval of a and the first interval will be there is then we insert a intersection interval into the output which is 1 2 and now we will decide whether we are going to move pa to the next by one or pv to the next by one so um we see that the end number of the first interval is two and four the first interval b the end number is five so there's actually no room to find intersection uh for zero two now um so what we are going to do is we are going to move uh pa to the next by one so pa is equal to one and we do the comparison to see whether there is interval intersection between 510 and one five so there is the output five into the output so now same thing we are going to decide whether to move pa or pv so based on what i said uh we are going to move pb now because the n number is 10 for 510 and the n number for one five is five so there's no room to find a intersection in pa currently um that has a intersection with one five so that's why we move pv to the next by one so on and so forth we generate all the um of the intersections and insert them into the output so because we are going to um traverse each array each input array just once so the runtime is going to be o uh m plus n so m is the length of a and n is the length of b and space wise it's the same so i think we are good to go to the next step is to find the to do some coding to turn your idea into solid code so let's start to do some coding work so first of all we need to decide we need to initialize uh the output intersections let's say the list is list intersections this new link list and we need to define the two pointers pa and also the pb then it's about the in the while loop we see uh if pa is out of index or pba is out of index so we need to make sure that pa is smaller than a dot lens and pv is smaller than b dollars so we try to see if there is any in interval overlap here so let's say the begin number would be mass dots max a p a 0 b 0. so if there is an overlap then the b number would be the maximum of the big number from interval a and integral b and if there is a overlap for the ending number it will be the smaller one between the and the number of a and a number of b so let's say a p a one b p b one so if the big number is smaller or equal to end it means there is a interval overlap so we are going to intersections dot add new int uh begin and end and after we find the intervals we decide which one to move forward whether it is va or pb so like we have said we are going to move pa if the nd number of a is a smaller one so if a pa one is smaller than b pv one then we plus pa otherwise b plus pb and finally we will need to translate the last into the 2d array so intersections return enter sections dot to array into intersections dot size so after we click complete we need to do some sanity check first and then set up some other test cases to increase the test coverage so let's take a look at so let me let's use a simpler example let's say we have 0 3 and 5 10 and we also have the so this is a and for b we are going to use this one so at the very beginning pa is equal to zero and pb is equal to zero and the intersections output is a empty thing so we compare zero two and one five there is an overlap then uh based on the comparison condition uh we need to insert one two into it and move uh a to the right by one and now we see that we have a intersection new intersection which is five uh based on comparison here and we will move pb to the right that one okay and now we do the com when we do the comparison we see that there is an overlap still and we output 8 10 and uh we move pa to the right by one which is out of range so that's uh when we stop the well loop and then we return the intersection which contains the intersections array finally i think it should look good let's give it a shot by running the code okay compile arrow it is okay there is a typo here let's fix it okay so another typo online 35 as intersections uh again another thing it's in okay so it's intersection not interesting okay so now it has this input example let's submit this piece of code okay accept it you're good um regarding the test coverage i would suggest us to set up test cases like first of all the ash case like empty one of them is empty and the other thing is uh to include uh what i would say one task is one of the inputs in interval list is empty the other thing is try to introduce some intervals that may have overlap or not have having overlap uh so like what i was saying is suppose so the first example like this one is good but it's not very good to test if there is something not overlapping so in this case let's say 13 and let's introduce another one which is 13 and 23. so that one would be good because it essentially covers uh the non overlapping thing between 8 12 and 13 23 we are going to do that judgment so that's it for this uh specific question um please subscribe to this channel if you like it and thanks for your time watching this video i hope you enjoy it and you guys have a good day
|
Interval List Intersections
|
largest-time-for-given-digits
|
You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**.
Return _the intersection of these two interval lists_.
A **closed interval** `[a, b]` (with `a <= b`) denotes the set of real numbers `x` with `a <= x <= b`.
The **intersection** of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of `[1, 3]` and `[2, 4]` is `[2, 3]`.
**Example 1:**
**Input:** firstList = \[\[0,2\],\[5,10\],\[13,23\],\[24,25\]\], secondList = \[\[1,5\],\[8,12\],\[15,24\],\[25,26\]\]
**Output:** \[\[1,2\],\[5,5\],\[8,10\],\[15,23\],\[24,24\],\[25,25\]\]
**Example 2:**
**Input:** firstList = \[\[1,3\],\[5,9\]\], secondList = \[\]
**Output:** \[\]
**Constraints:**
* `0 <= firstList.length, secondList.length <= 1000`
* `firstList.length + secondList.length >= 1`
* `0 <= starti < endi <= 109`
* `endi < starti+1`
* `0 <= startj < endj <= 109`
* `endj < startj+1`
| null |
String,Enumeration
|
Medium
| null |
289 |
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem is game of life very easy problem so in this problem a board is given which is a m cross n grid where each cell has an initial state live represented by one or dead represented by zero so each cell interact with its eight neighbors okay uh horizontal vertical and diagonal using following four rules so there are some rules uh so what is given right a grid is given to us so this is a grid which is given to us and each cell right here 0 1 2 3 and 0 1 2 so here each cell let's say this cell can interact with its all neighbors so these all are the eight neighbors see these all are the eight neighbors this one two three four five six seven eight so eight neighbors this cell can interact with so right now this cell has zero value which means it is dead and one means it's live right so what we need to do is uh here some conditions are there the next state is created by applying the following rules to every cell in the current state so for to each cell right to each cell we have to apply these rules and we need to find out the next state okay we need to find out next state so what does that mean uh see this 0 can be converted to 1 or it can remain 0 only depending on some conditions and what those conditions are these conditions okay so given the current state this is the current grid which is given to us we need to return the next state that is we need to return the next state and how we will determine the next state we that will be determined on the basis of these rules so now let's see what these rules are see first rule is that any live cell with fewer than two live neighbors dies as if caused by under population meaning so see if there is let's say there is this live see there is this uh let's say there is this live cell right there is this live cell so how we will determine whether what would be the next day what will be the next state for this how we can determine it using its eight neighbors right using its eight neighbors and how we will determine it we will check that how many live neighbors are there if there are fewer than two live neighbors so if there are less than two live neighbors for this one so then this one will change to zero it will become dead so it will die this is first condition another condition that any life cell so let's say we have this live cell one we will see it's all eight neighbors okay we will see all its eight neighbors and if there are two or three live neighbors so for this one if there are two or three live neighbors right so then this will its next generation meaning it will remain one only next state will be one okay but any live cell with more than three neighbors three live neighborhoods dies by overpopulation so if there is one and all its eight neighbors we will check if there are how many live neighbors if there are more than three live neighbors like more than three live neighbors then this one will die it will become zero why because of overpopulation so see from these three cases what three cases are so see what three cases are first of all if live neighbors like here i am talking about live neighbors if we have a live cell we have live cell that is one so if it's live neighbors are less than two then it will become dead that it will get changed to zero one will change to zero but if this one life cell has live neighbors two or three then it will remain one only but if this live cell has more than three live neighborhoods then by overpopulation this will change to zero it will become dead so these are the three conditions last condition is for dead cell that if there is dead cell with exactly three live neighbors it becomes a live cell that is see that means that here if there is a zero like a zero cell right zero dead cell and if it has three live neighbors then it will become life so dead will change to life for example zero is there we will check all its eight neighbors and if it's eight neighbors uh in all eight neighbors three are the live neighbors right then this zero will change to 1 okay so i hope you understood uh this condition right let's quickly see this uh test case and here i have written it so let's quickly see that how it's working so see basically we just need to check right every time these conditions that how these conditions are working but before that see over here what is the dependency see here for every cell we have to check whether the cell is live or dead accordingly we have to check for the condition right and condition depends on what condition depends on the live neighbors how many live neighbors are there so for every cell we have to check whether how many live neighborhoods are there if live neighbors are less than two or if they are equal to three greater than three accordingly the lives the cell will change right so what we need to do is what we need to do for every cell right for every cell we need to find out how many live neighbors are there live neighbors how many live neighbors are there and how many neighbors are there eight neighborhoods right vertical horizontal and diagonal okay so this is the approach which we will be following that for every cell we will be finding out how many live neighbors are there and accordingly we will change it so see what we are doing over here let's see for this zero right for this zero so i am creating a matrix here basically we will be not creating a matrix we will be just changing in this matrix only but uh for like explanation purposes i am like making a this matrix so see first of all this zero is there right we are currently checking for zero comma zero cell this cell is dead right it's dead here it's zero so for zero what was the condition was that if there is dead cell and it has exactly three live neighbors then it becomes a life cell so we need to check if there are exactly three live neighbors see here there will be this will be a neighbor and this will be a neighbor right these three will be neighbors but here we do not have only one life is there right one life these rest are zeros so these are dead only one live neighbor is there but if we needed three so that this dead becomes live right so but here only there is one so this zero will remain zero only okay this will remain zero only right now let's check for this now we will check for zero comma one now zero comma one cell this one this is a live cell so live cell has uh what we will we'll check all these neighbors this is one neighbor no neighbors at the top this is one neighborhood and this is one in all eight directions right so this is right like this like if this is the cell this will be one neighbor and one neighbor also diagonally also this is one neighbor this is one so total eight neighbors so here for this one this live cell we have how many uh see there is only one live neighborhood right this is only one live neighbor so what we decided that if there are fewer than two live neighbors that is if there are live neighbors less than two here only one live neighbor is there so this one will change to zero this will become dead it will die so this year zero will come here zero will come now see guys do you think we should write 0 here because see we like i have for explanation purposes i have created this matrix but this 0 we will replace here only we will replace it with 0 right so see if i replace this one with zero here only see right now here there is one right now here it's one but we have checked its neighbors and this one is live and now it will change to the next state it will change to date so what i will do i will change this one to zero here i will not take extra space this is just for explanation purposes i will change it here only zero but i do think this is correct won't it affect this one for this cell it will affect right for this cell it will affect its result because this zero here earlier it was one right here so for this zero one was a live neighbor but since we change this one to 0 now for this 0 for this cell this the calculation will change right so this is not the correct approach we should not change it like this what we should do is we should replace that with some another number right we should replace it with some another number that is if live cell is changing to a dead cell right i will replace the live cell by minus one i will replace it with minus one so here in place of one i will write minus one right now see now i'll tell you what is the benefit of doing this so see minus one i replaced it with now i'll go to this cell now i'll check for zero comma two set this is a dead cell so i will check its neighbors how many neighbors are there for this minus one right i will take the absolute value so absolute value it will be one only which it earlier also it was a live cell right for this zero so that's why i have replaced it with minus one i can replace it with three also but like that but there's no benefit of three right because i have to somehow know that ok earlier it was a live cell so that's why i can take model a absolute value that is absolute of minus 1 will be 1 only so then i will know that ok here earlier it was a live set so for this 0 see how many life cells will be there this one uh these all are the neighbors right these three neighbors are there and there are only two live neighbors so for zero to change to life it should have three neighborhoods like three live neighbors so this will remain zero only this will remain 0 okay so see we are making the next state now we will go to this cell for this cell let's see so let me erase this it's very easy question right just we need to check the conditions every time and for each cell we need to find out how many live neighbors are there so now we are checking for one comma zero so this is a dead cell right this is a dead cell so it should have exactly three live neighborhoods in order to turn it to life cells right if this is the neighbor this is a neighborhood this is the neighborhood and this is a neighborhood so here c how many lifestyles are there one minus one will be taken and we'll take absolute only right so absolute of minus one will be one then two this is also a license and this is also life center so there are three license so for this dead cell we got exactly three live neighbors right we got exactly three live neighbors so this zero will now change to 1 but right this is for explanation purpose here will change this 0 only to i so i'll just remove this and here this earlier it was 0 right here now it will change to 1. but do you think again should we replace it because if i write 1 here it will change calculation for this 0 right so for this 0 it will take this as 1 but it should this is the next state right we are talking here when we calculate we are talking about current state so here it should be 0 only for this 0 so what i will do right i will change it with another number so i will take 2 here i will replace when i'm doing for a dead cell right when dead sign changes to life cell i will replace it with 2 here i was replacing with minus 1 when life was changing to dead now dead is changing to life i will change it to two right so similarly guys you can calculate for all other cells so this is how we are gonna going to approach this problem right let's see the code once it will be more clear and i will highly recommend just dry run the code once you have uh watched the video so see this is the function which is given to us right game of life and we are given this board m cross n board these all are the vectors right this is the all eight directions these are all eight you can say coordinates for neighbors now you might be thinking what is this basically c 0 comma 1 let's say you'll understand c this is very important concept it's used in graph also so understand it well so see if we have this right we have this we are we have to check all the eight neighbors so let's say this is the cell which we are currently on zero comma zero this is zero comma zero coordinate so this is let's say one this is 0 comma 1 this will be 0 comma 1 right this will be what 0 comma this is x right and this is y 0 comma minus 1 here it will be what minus 1 comma zero and here it will be coordinate one comma zero now what will be this one here see what will be this so here you see basically it's till this only right so here it will be one comma one here it will be what minus one comma one here it will be what this will be x minus 1 comma minus 1 and here it will be this one will be so this is like just your match right simple basic math we have to find all the neighboring coordinates so we have created like this so here it will be 1 minus one okay so these all x coordinates like zero all the x coordinates these all the x coordinates right i have stored here in this and all the y coordinates these one minus 1 0 minus 1 minus all the y coordinates i stored it here so this pair is one neighbor 0 comma minus 1 is another neighbor 1 comma 1 is another neighbor like that so then what i am doing is i am going to each cell right i have this nested loop in order to traverse in the matrix i will for each cell right so see for each cell we will be finding out how many life cells are there so for each cell how many live cells are there so for that i will be calculating uh c for we are calculated we have to calculate how many live neighbors are there so i'm going to each neighbor and finding out the coordinate of that neighborhood so rho plus dx of i d y of i meaning let's say row and column current let's say see current coordinate is let's say one comma zero right we are checking for this one so current coordinate is this is your one is row and zero is your column i have to go to a all the neighbors for this so what i will do first of all i will go to c i will go to this coordinate that is i will shift it row plus 0 comma 1 so it will be 1 this row 1 plus neighbor is 0 minus 1 right let's say so it will be 1 plus 0 this and this 0 plus this minus 1 okay so these will be the neighbor coordinates 1 comma minus 1 this will be the neighbor coordinates okay so in this way we find the neighbor coordinates and we check whether it's a valid neighbor valid neighborhood what we uh we are doing in this function we are just checking whether this coordinates lies in the range of the board or not right whether the lies in the range of board or not and also if the absolute value is one then meaning it's a live neighbor so just increment it the count then we are checking the conditions right so if the current cell is live and it's and the live numbers are less than two or greater than three so then this life cell will change to dead cell so what we do is we change it replace it with minus one right we replace it with minus one otherwise if it is a dead cell and it is exactly three live neighbors we change it to two and after that once we are done with this for loop wherever it's greater than equal to one right we change it to one when like for example where it is two right so it's greater than one so we'll change it to one because it's a live uh cell and then wherever it is minus one we will obviously change it to zero right so this was the approach right i hope you understood the approach and time complexity see time complexity is m cross n we are traversing uh and this 8 this for loop is constant because the 8 only is there so time complexity will be m cross n and space see space we are not using any extra space these are just constant spaces and uh yeah we are not using any extra space here so it will be more fun so let me know in the comments if you have any doubts you found the video helpful please like it subscribe to my channel and i'll see in the next video thank you
|
Game of Life
|
game-of-life
|
According to [Wikipedia's article](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life): "The **Game of Life**, also known simply as **Life**, is a cellular automaton devised by the British mathematician John Horton Conway in 1970. "
The board is made up of an `m x n` grid of cells, where each cell has an initial state: **live** (represented by a `1`) or **dead** (represented by a `0`). Each cell interacts with its [eight neighbors](https://en.wikipedia.org/wiki/Moore_neighborhood) (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
1. Any live cell with fewer than two live neighbors dies as if caused by under-population.
2. Any live cell with two or three live neighbors lives on to the next generation.
3. Any live cell with more than three live neighbors dies, as if by over-population.
4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the `m x n` grid `board`, return _the next state_.
**Example 1:**
**Input:** board = \[\[0,1,0\],\[0,0,1\],\[1,1,1\],\[0,0,0\]\]
**Output:** \[\[0,0,0\],\[1,0,1\],\[0,1,1\],\[0,1,0\]\]
**Example 2:**
**Input:** board = \[\[1,1\],\[1,0\]\]
**Output:** \[\[1,1\],\[1,1\]\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 25`
* `board[i][j]` is `0` or `1`.
**Follow up:**
* Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.
* In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?
| null |
Array,Matrix,Simulation
|
Medium
|
73
|
70 |
hello everyone let's look at climbing stairs the problem statement is we are climbing a staircase it takes n steps to reach the top each time we can only climb one or two steps how many distinct ways we can climb to the top example one input is two output is also two there are two ways to climb to the top it's one plus one or two second example input is three output is also three there are three ways to climb to the top it's either one a one two or two one this is another typical dynamic programming problem to find distinct ways to reach n we can first find how many distinct ways to reach n minus 1 and n minus 2 and adding them together gives us the result for n to use our memorization array it is so memorized equals memo i minus 1 plus memo i minus 2 and we already know member 1 is 1. memo 2 is 2 so we can simply have a loop inside the loop we add the previous two values to get the next value let's look at the implementation here the initial value is 1 2. so for this first element we don't need to care because n is supposed to greater than one so for number one that's one memo two is two let's have our loop and then let's copy this statement in and after the follow-up we simply return and after the follow-up we simply return and after the follow-up we simply return mammal n let's submit it passed let's look at the complexity here for space is o of n that's the size of our memorization array for time is also of n because we have this for loop here if you look at this equation again you might find this is an equation for fibonacci sequence you are absolutely right so like the fibonacci sequence for this problem you can also use recursion to solve this problem but the complexity is not as good as iterative solution thank you for watching if you have any questions please leave a comment below
|
Climbing Stairs
|
climbing-stairs
|
You are climbing a staircase. It takes `n` steps to reach the top.
Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top?
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:** There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
**Example 2:**
**Input:** n = 3
**Output:** 3
**Explanation:** There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
**Constraints:**
* `1 <= n <= 45`
|
To reach nth step, what could have been your previous steps? (Think about the step sizes)
|
Math,Dynamic Programming,Memoization
|
Easy
|
747,1013,1236
|
330 |
Luta Suspend Are Problem From Which Cold Be Considered As A Chronic Easy And Minimum Level Problem Bomb Blast Time For VHP When And Also Quite At That Time Element In All The Number One To Three For Wife In Element In The Return Of The Day That Commercial vehicle is me now so let's tree on maximum clear example we shape give in numbers one and free number ID and sisters equal to 600i neatu form numbers from pendrive view 6 it is done and looting directly on whatsapp maximum number of candidates for this unknown system Of this element of rs.10 unknown system Of this element of rs.10 unknown system Of this element of rs.10 specific food from maximum whole element mother in the deccan from every element of food example if not from suit with wondering how can only from one to three and from British minister a ko handed over ab hai tu gas number 2nd 282 Year to one of the two no items from one to three in one shift 2018 Form 5.23 Domestic shift 2018 Form 5.23 Domestic shift 2018 Form 5.23 Domestic servants sexual form for all elements in recent to remedies one to take only want to hear no evil return 1a that I am neither considered as nor example this Reference put in not arrest one to three will put inform maximum 600 all elements in the recent from maximum peel in between 6 12345 tours from one to three now maximum do that not see it from one of can form 2013 by adding one does but can not From courier so ki naxalite how will students who voted to address a ki hansini slice tenth with zero no what is the next number date i want one latest plus one so i want number one is my initial number som one is great for no Why Some Will Welcome No Money From Maximum One Elements Present From 121 Maximum This Tree Leaves Means Inform All The Element From One To Three For Inform 2all 2014 And Tree It And Went To One Of The Biggest Tree Surya Some Sentences About How Many Number Two Numbers After Two Numbers From One Form 2018 That Do I Have Only Option To Edit Subah Jauna This Point Endering I Dasham Vikram Samvat 1215 That's A Plus Two Plus One Plus 2 Jai Hind Se Aayi Can Get Now Too Seven Elements With This Element Status 12345 Seervi Elements Are Already In Us For Wealth From Nau On Ki Vacancy Date Clear Up To 7 Bihar From Nau To MP3 Ringtone White Part Plus World Biggest Panch Heeng Previous Song Bihar 30 Pulao Last Seen Respect to get what we do it is pet 5 plus two cigarette note 5 pro plus oneplus 5 151 we can do torch light plus four five plus cool at nine ten plus two 11th and 12th and you all elements are shoulder 5 plus two plus one Day A I An Initial Is Visible From This Year Which Can Tell Me To The Element Needed In The Unwanted Element Next To Be Present In The Dark At This Time Plus One Of It's Not Present And Are Examples For Years For It's Not Present And Ride Point Mintu Hydride Option A Ki Navratri Mahotsav In Hum Teras 150 Se More Numbers In Between When She Does Subscribe To Hai I Hope You Understand Why Obscene Needles Again Play List 700 Subscribe To Ki Unwritten Daal To Initially Aaya Samjh Mein A Demon Is One Witch is Equal to Two Voters Want White 10 Vikram Singh Somvanshi and Definition of Attraction Rates of Effort That Time Did Its Part Plus One Witch is Too Friend It is Too After Adding to Dancer Recruitment by Fun and Wife Bum Genealogy Test One Shedding 212 Completion Hai Ko Hogi Election Again After Free Iinifed Court Patna Mein 500 A Need To Wait For A Girl Saw A Beautiful And There Mental Salman Sabse Kam To And After Adding Food I Can Edit 79 127 Elements With This Element And what are the element electronic 120 no of posts tagged with subscribe now to and hear my som will welcome powerful planet can i go to i request to the name is ramayan stand the test zakhm ki now only that time next is 3110 to oil add this Banayenge Thirteen The Best Wishes For Us That Boat Or Website With And This Is To 13 Form Sure Element Some Scientific Observations And From Where These Elements With Aslam Festival Ton Mall Service Limited Number Of Factors That If At All That Just You Which Creation Cancer set to maximum my song again slice 250 answer of birth c rule 10 x n Plus Two Picture Sun Max Will Not Be Silent And You Will Need A Two And Numbers Thee That Laxman Singh Song Ganesh Temple In Ujjain Aa Raha Yeh Jeevan Varsha One And Half Inch 120 Elements That Hussain Islamic Constitution Adhwash Is Its President Wires Edit In Assam And Som Vikram Is Vansh Next That I Request To One Status 28 2013 But I Want Two Plus Two That Tomato Vansh School And S Naam Is Lahar Equal Two Plus One So Every Single Moment And Give May Some Will Be Completed Soon After Data Is Equal To What I Do n't Like Subscribe Now To 35th Number One To Three Elements Of The Day Am So I Miss You To The Procedure For The To After Certain Water Hotspot Turn Off Units Compound During That Thought 10327 Simply Address Well Stepwell Answer Vikram Tum Nikalta Hai Back To Elements Kapil Advance Sambhal Vikram Khatik Plus Cotton Latest 2017 To After Depositing Maze Items For Numbers 12371 Condition Will Return To Ki Rut Eye Drops Aap Rose Water And Hui A First Travels Making That the grains inside you The Number Africa Se Nervous Song Hai To Like Share Akot That In Flights And Iceland Fight Answer 10 And Makes All Video Song Vice Chancellor Healthy Sexual And Makes All Soldiers And What Do This Is Mirror To The Number Track Plus One Element Want To Avoid Using Its Elements Present In Our Saugandh Only Option Is To-Do List Will Plus Saugandh Only Option Is To-Do List Will Plus Saugandh Only Option Is To-Do List Will Plus One Plus Like This In Spite Of Conduct And 9 Maths Element Hai Call Karna Sham Vikram This After 10 Sallu Oil For It's That Na My Invite Them And Text Message Amazon or equal to and half of all the condition all the requirements of birds and helps I will continue traversing did not behave servi all elements and condition indiscriminate element is the modern Neetu of moral elements of chapter included 38th hot scene in example divine 80 so After adding som plus one and to oil instrument me answer this site more once more elements by others on jain included year and you will continue and ninth chemistry turn on or equal skin threat of western answer a previous song ss my aap soch and 10 problem type like And share please like and share my recipes thank you
|
Patching Array
|
patching-array
|
Given a sorted integer array `nums` and an integer `n`, add/patch elements to the array such that any number in the range `[1, n]` inclusive can be formed by the sum of some elements in the array.
Return _the minimum number of patches required_.
**Example 1:**
**Input:** nums = \[1,3\], n = 6
**Output:** 1
Explanation:
Combinations of nums are \[1\], \[3\], \[1,3\], which form possible sums of: 1, 3, 4.
Now if we add/patch 2 to nums, the combinations are: \[1\], \[2\], \[3\], \[1,3\], \[2,3\], \[1,2,3\].
Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range \[1, 6\].
So we only need 1 patch.
**Example 2:**
**Input:** nums = \[1,5,10\], n = 20
**Output:** 2
Explanation: The two patches can be \[2, 4\].
**Example 3:**
**Input:** nums = \[1,2,2\], n = 5
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 104`
* `nums` is sorted in **ascending order**.
* `1 <= n <= 231 - 1`
| null |
Array,Greedy
|
Hard
|
1930
|
1,011 |
welcome to code Sutra in fact this is the first problem that I have solved on this particular Channel about a month ago in this video I'll be discussing about lead code problem number 1011 capacity to ship packages within DDS the approach to this particular problem might not be very intuitive but once you understand this problem right you will be able to solve straight away six to ten problems on lead code or any other problem okay the idea of this channel is to discuss a pattern rather than just solving a problem so without further Ado let's get into the code in this problem you are given port a and Port B okay and you have a ship in between you have to ship all these weights from Port A to Port B within the given number of days in this problem one two three and four are the given weights and they have to shift all of these weights in the two days and what is the minimum capacity of the ship to do so for example you can decide to ship like this first day you can ship one weight the second day you can ship all the other three then what is the capacity of the ship the capacity will be 9. so the second approach is you can shift first two elements and the remaining two that is three and seven so the capacity will be 7 that is the maximum amount of these two that is 7 right so similarly you can decide to shift all these three on day one and four on the day two so what will be the capacity then the capacity will be 6 right because the maximum of these two and that is our required answer so if you look here the capacity was nine seven and six what is the minimum of all this that is six right so what are the quick observations that we can draw here let's look at this so what is the minimum capacity of the ship that you want it is four right that is the maximum weight your ship can never be lesser than this even if I give you here 10 days Can it can the capacity of the ship be any lesser than that no right because you have to carry four so that is the first observation that the minimum quantity of the ship will be the maximum beat and the second one is I will just give you one day okay then what will be the quantity it will be 10 right because you will be shifting all of these weights together right so we know now the range is 4 to 10 why because 4 is the minimum quantity of the shape that is the maximum weight that is even if I give 10 days or 20 days you have to shift the maximum weight so that will be the minimum range and what is the maximum will be the sum of all the elements that is 10. so we know the minimum range now we wrote the maximum range what we will be doing here now once we know the minimum range and the maximum range let's pick a random element for example let's pick the mid element only 7 is it possible to shift with weight 7 yes we saw here right it is possible to shift with weight 7. so if it is possible to shift with weight 7 do you even want to check 8 9 and 10. no right because you can shift it with 7 only the capacity of the ship can be 7 only then why do you want to check with 8 9 and 10 so can this be marked with red and can we remove that part yes we can do that so let's pick another random number let's pick five is it possible to shift in five days no right it won't be possible because why because we can shift one day today it will be taking three days we'll be not be able to shift in five eight if the capacity of the shift is 5 we cannot do that so can we easily remove both five and four if it is not possible with five only will it be ever possible with four no right we can easily remove this part as well so that is the idea of binary search we'll be picking up the mid element and we'll be eliminating the search space for example what I said is if it is H we can eliminate all the elements greater than 8 similarly if it's a lower number we can eliminate all the numbers lesser than that so that is the idea so how do you do this let me this is what I have explained this initially the left will be 4 the right will be 10 will be picking up a middle element that is 7 so is it possible with 7 let us check it see for now I will come to the implementation of this part how to check this but for now think there is a magical function that will say you s or no okay so we will check with 7 the output will be yes you can actually shift this so we will be eliminating all the other three so once we eliminated all the other three our new answer will be equal to 7 right because you can shift with 7 that will be our new answer and once you can shift with 7 are left or our right will change to 6. now what is the new MID 6 plus 4 that will be 5. can we shift with Phi no we cannot shift with five so similarly both of them now will point at six so now what is our new MID will be 6 is it possible with 6 yes it will be possible with 6 and we will update our new answer I will come to the pseudo Court of both of the problems okay so let's get into the magical function how do you I was talking about the magical function right that will say whether you can shift within D days or not so let's get into this magical function so how do you implement this for example you are given five days and the weight is 18 what I will be doing is first whatever we can send in day one can we include the ship first wave yes can we include the second in the same day the rate is 3. let us write the current weight of the ship currently and current required days that will also be equal to 1 actually because you need at least one day right and the current rate will be zero so the first day what is the current rate you can you include it yes the second one three can you include it yes then again you will be adding three to it six the weight will become six has it increased more than 18 no so you can do it in one day only then what it will become 10 then it will become 15. so can you include this 6 in the same day no right because this will become 21 let's do this 21 and the required days will get increased to two so since this is becoming 21 we will remove that and make it to the current element so that is the idea that we'll be doing here then again we will add the second element that is 13. so since it has not increased above 18 the required days will not change but for the next element it will become again 21 so we will increase the number of required Days by 1 and this will be changed to 8. so at the final ending what we will check is if the required days is less than or equal to the current days then we will be returning true if not we will be returning false so that is the idea of this magical function so here's the code for the magical function so initially we will be having required days is equal to 1 and the current rate will be equal to zero and we will be checking whatever logic I spoke about right we'll be increasing the current weight and if the current weight is actually greater than the capacity what we'll be doing will be increasing the required Days by one and we'll set the current date to I this particular element and if the required days is greater than the number of days that is available we will return false if not will be returning true so this is the these are the three inputs that we should be passing to this particular function that is weight we have to pass the weights and we have to pass the number of days and also the capacity of this particular ship okay now let's talk about the pseudo code of the original problem that is we will be having a left and a right and we'll be having answer initiated uh so what we'll be doing we'll be checking if it is possible with mid number of days whatever we will be getting and we will be checking if that is possible or not if it is possible we will reduce the rate to Mid minus one else will be increasing the left to Mid plus one so that is the idea I will get into the code part so before getting into the code part actually 932 percent of the viewers of my channel haven't subscribed to this channel so if you are one among them please do consider subscribing the channel if you are learning and enjoying the videos the second thing is just like in this problem we discussed a particular pattern and if you learn this pattern you can solve eight to ten problems similarly in this placement series or interview series I will be talking about patterns and not just about problems so if you are interested please do have a look on that so this is the code of the binary search that we'll be using that is we'll have a left and we will have a write and the left and right will be changed here what is the left is the maximum weight like we discussed initially right that is you have just got one day so that will be our left that is the minimum quantity of the ship the capacity of the ship that is required and the maximum all right will be equal to the sum of every element so once I have got that you will initiate the answer to the worst possible answer that is equal to the maximum so that is what we have initiated and at every step this answer gets changed to either mid or it doesn't get changed so finally after all this will be returning the answer so this is the final code of both the functions that is combined so thank you for watching the video
|
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 |
994 |
Hai Bhai Kalyan Loot Se Hai Dish to Shri Ram Hope it will be very good and will grow well with our placement pressure series Our question of today is That is very good and why is it a standard question And only and only why, a lot, now that we have moved ahead, graphs etc. will be read, TV etc. will be read, then in that also we are using this lesson of why and without any delay let's move on to the explanation, our friend Prashant with us on the dictionary explanation. Which is dance to Hyderabad, so this question, first of all let me show you that it is so famous in the interview, micro fennel is a light Amazon Samsung ticket for ultimate tips, what is this to us, this cigarette has been given to us 728 in which we have orange kept orange shade either If there are oranges in the great, then it can either be cured or starts getting spoiled and it has orange in it to do zero different that like here and selected why but zero bodies and two represent here Orton orange is placed and on WhatsApp Why friends on st and this phone is ok what we have to do is to find out how much time does it take to get a huge fire and inch whole of your grade road accident if in it's possible tank printer time minimum type when we speak You must have been robbed of everything. All the mornings must have been spent. If this is not possible in print - 110, how will I be with you? I print - 110, how will I be with you? I print - 110, how will I be with you? I feel like I have some idea of what happened that I am feel like I have some idea of what happened that I am feel like I have some idea of what happened that I am finding an approach in the inauspicious memory, which will be discussed with us. To do but still very good program people here can help us gas sufferers Front's mid-day meal one time favorite is based here mid-day meal one time favorite is based here mid-day meal one time favorite is based here that see Chand first of all the question was once understood in the question that this is that first of all this We have protein and what will be this Yagya in India, next to us and will road it. Okay, now if it means that these four cards which are in reduction or in North South East West unmarried direction can be offered then stand with us next time. How many will these two rotten colleges have become, now they will also rot in their North South East West, do n't think here or there and make fun of your words but this is it, if you have to leave it, then this Yagya will punish it, we will do it's okay. Then after the next one, this orange one, what is its opportunity for climbing, what is its focus, sports for now after making this pack, now this one point, we will give it a little in the next time, how much time did it take in total, so first of all do this one process. Process team four, so this is four units, meaning at one time, the one who is offering this is an Italian, so you have to return this unit time once and understands this, there are some other examples, now we are assuming that we have this as well. Na this and MS Word now what time will it be next ring which and miding or else we it will rot and absolutely it will rot that this is the yagya torch light thing 121 how many roads and next but the setting this road came and these people Now see, subscribe in that condition, now for this diner, we decide at home that particular box and inch and next how many times, first of all we asked whether the author's Vestige 120 is how much and it is rotten, this orange is a little Tell me and MS Word tell me when the name is looking at how many oranges are there in their proximity which is this effect flight, so this one here could have this front color and its Rishi has sent the teams towards your RSS, we have seen these three and these Just have to check the proximity of these two and this third one from here because this Congress has mixed it, those whom they had cut, they have jointed them and offered them, now their people can do Yagya, so see whom they can do. This is given at this very moment, this person can know everything and can understand this in advance Sanju, there is no meaning and who can do this can be done, this is this and but if you see, we have this child, at what time next, this is left, but now we have As many Chhaths have passed, our work is at that place, so we have to do two checks, one is brother, which day is it, Ajay has to do it and the next one, what is the thing to be done, what is it that all are rotten, so to do this. The job is Gyan Director, he is Curator Akshar, now your data structure is best for this you have to spend some time with the code itself and then Ganesh ji Ka is a little better even on the fault and at that time, if you have given a little peace ticket, then according to that It is not old, first of all, what will we do, if we use great chilli, then first of all, we will travel in grade and what will we do, we have stored one roti and I, why protein, what will we do with all the oranges in this roti, their coordinator has come to the store. People like if we come to this example then first of all the roots will be strong store and open any store that China and submit and one more thing we had to know that all and MS Word is there so for that I all Both on Orange's account, like in this, if what time is our bus, 927 operation, if Seven Orange has left till then, it means that now we do not have to clean anything else, there are deficits in the heart and arms, there is no appointment, so will we start for this ? Total number and ? Total number and ? Total number and interest So here the theorem of total people interrupted them that how much total orange shade playlist is rotten that it means henna total how many more injected and rotten persons and what has been stored in it that it is orange shade then Now why till he becomes MP, we will do this operation, it is ok and this is the method, what will we do with it, who all are rotten at this level till now? We will extract it and at this time, who will rot at its Nick Justice time, in this inch and a half, which is currently being lifted, which is currently being rolled, we will cut the second point and post it, then see who will come first and who will we have- Which are connected and who will we have- Which are connected and who will we have- Which are connected now, we have to rotate this and this because we have these, please call them 996, it means that it has become free, now what to do is we have to extract the value of pure one by one. Because I have fixed it one by one and at a moment we have stored a lot of force, we will quantize how many have been left, when not installed will become total, it means that all our roads have been done and this will not happen again. Total number of businesses on the notice means we can't respond to all. Return mention to Indore Stadium. This is the only thing we are doing now. We will straighten one. Let's first of all accept this one to kick the point that what will happen now? He will roast as many people as he can stop in his Vicinity, so Shetty Hero could have joined him in the Vicinity, he has equaled and that we who have been there, his account is self-employed, here he self-employed, here he self-employed, here he needs the tournament, worry and 12 % Why is it not working? So needs the tournament, worry and 12 % Why is it not working? So needs the tournament, worry and 12 % Why is it not working? So we have discussed well in the playlist with distance correction that if you use robocaller then you can see here from there but here also it is understood that the second sentence should not work for processing money because inside So we will store it in our own because right now it has rotted itself and is done. Next time it is a candidate for road in our neighborhood, then we will mix it. Now we have understood this point in the roti wala death. Okay, now after that, sequence second because we will take inside like this, cut is practical Yogendra store, if we check with that, then this can be another, this can be a note, so we will make it two and store it as coordinator village esx were next. We will go to the level third one which is from the beginning till the initial roti so this bitter now which one in its vicinity can note this we did this by getting up so till now we went to peace point to 0630 paltu work our Pass first of all 310 more we have and two more Saeed and team who cry their account has increased MP3 now one by one we will straighten in these days and check whether this is in their mixing proximity and this note If you can, then look at its proximity, there is no problem left. No, this roti has already this zero means something, so something does not make sense, there is nothing above, therefore, there is protein in the city. This is Indian, there is a special team for this, there is a possible ready, here in this video, there is a possibility of Colorado because back on the bat show, you told that we will check after its withdrawal, how will the production be done pregnant for that too, and see once again. Takes in Kurd here what I did a cardinal direction define care we have to go left we have to go on this also expire and on minute less than that go left know Prashant left side question what will we do x minus one and that solution testing Version Incomplete Left Right Jaana To Then What Will We Do Questions More Asked Above Or Neither What Will We Do Actresses Plus Minus Jana Hai Tu Hai 21 22 23 - And Accepted S To 21 22 23 - And Accepted S To 21 22 23 - And Accepted S To Ab Jo Pair Problem Sharp Opposition To Kya Pair Ban Raha Laptop These are Left Right Captain's 09 - 09 - 09 - 50 - One does 50 - One does 50 - One does n't matter much, one does this, it doesn't matter to him, okay branch, now we will enter four operations using the same method, Network Hey, what is this we did first of all Points 1202 IL is est 14304 direction I have set now and travels in it will update And this will be updated in four operations, now some have been updated in all four directions, we have to check what is possible, if this is the matrix, if it has not gone out, then this hut, I will fry it 2 inches and will do that in the matrix. Are inside and inside the matrix which is the coordinator and he is fresh orange till the wave save with us it means that the next step can smile okay then we will add the difficult but if that is not one it means Bittu is one then we have What possibility can there be of one? There can be tattoos from zero to one, which cannot be one, it means it is Singrauli MP, so there is nothing to be done, it means it is already ready, I am not doing anything in this too, so in this will. Continue If it is not so, it means that the range that we have on the Oregano Coordinator and Give Expression to New Boycotted has not yet been proteinized, Govil, we got up and turned 6, returning the lion, others will note it and Our tutor will do something to this coordinator so that then when we check to promote that yes, there is more ground in the soil, then we can see that the coordinator located in this fort does something, okay and if they do so, then we have A time is the subject of character but here the police team has noted on it, then the bank has increased. If you believe then this saliva has not happened that if we don't wear rotary then why will our rotating person enter why this protein person can't do commentary? When we find such a candidate, note it down. If we do not find such a candidate, you are a robot, I will not add anything and there is a balance, we have to extract all that first, then it means that I will not update the time. Now it's time to go to the breakout and these are how many total orange system have we stored and how much total and these as if we had stored separately if rotating Its total number of all interested will be that much then the minutes return time which we have stored in that - in the time which we have stored in that - in the time which we have stored in that - in the time table is on the final that datesheet is very simple till the court but later on yes later on you will find it very easy meaning Gurjar Sir 1st O'clock That's the introduction to you, so where should you go on the website, so episode 9, how will you go, 4.15 Start Using Now 4.15 Start Using Now 4.15 Start Using Now Edifice, if you like record quite a bit on September, thank you, then try to write some code once, we have discussed it completely. The decision which will also be seen in the actress in the graph of our Leo, I should make such a low plane, friend, I have explained here 100 datesheets, if you liked the video, like and share the song, play the song, decades of watering, thank you.
|
Rotting Oranges
|
prison-cells-after-n-days
|
You are given an `m x n` `grid` where each cell can have one of three values:
* `0` representing an empty cell,
* `1` representing a fresh orange, or
* `2` representing a rotten orange.
Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten.
Return _the minimum number of minutes that must elapse until no cell has a fresh orange_. If _this is impossible, return_ `-1`.
**Example 1:**
**Input:** grid = \[\[2,1,1\],\[1,1,0\],\[0,1,1\]\]
**Output:** 4
**Example 2:**
**Input:** grid = \[\[2,1,1\],\[0,1,1\],\[1,0,1\]\]
**Output:** -1
**Explanation:** The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
**Example 3:**
**Input:** grid = \[\[0,2\]\]
**Output:** 0
**Explanation:** Since there are already no fresh oranges at minute 0, the answer is just 0.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 10`
* `grid[i][j]` is `0`, `1`, or `2`.
| null |
Array,Hash Table,Math,Bit Manipulation
|
Medium
| null |
211 |
hello everyone welcome to quartus camp we are at 28th day of january lead code challenge and the problem we are going to cover in this video is design add and search words data structure so here the problem statement asks us to design three methods or a class word dictionary which has three methods the first method is to define the data structure and the second method is to add a word to the data structure and the other method is to search over the data structure so if you look at the problem statement the first thing that's tight strike or stuck your mind would be having a set as a data structure because it is easy to add a string and search for the string using a contains word and maintaining it as well so there are two drawbacks by using set first one is our test cases are not only searching for any word but also words with uh dots so we have to search for words uh with the regular expressions or something pattern matching so if a word is having dot a d then you have to look for a word that has any first character but then the other two characters must match and same goes with the other one so we can't achieve that in a set or it's it is bit complex when using a set so what would be the uh efficient data structure to do this let's so as the problem statement require us to process the given input words character by character we need an efficient data structure that stores the word and search them and help us to search character by character which is very clearly try data structure so which is not something really new to us we have used it already in our coding videos to construct dictionaries and find and search words so those of you who haven't worked in tribe which is pretty simple we are going to see how it is going to work and as we all know that is a really nice data structure to work and play with words before getting into the actual implementation of it let's understand the concept and how we are going to solve this problem using try so try is nothing but a simple data structure that helps us to store the words which are having common prefixes for example here uh the examples given are blue so let's start by having the root node from root note the first character we see is b so from b it is going to be a tree structure okay we have constructed the first word the second word given here is band so we are going to insert band to a data structure the first thing we are going to notice is b already present yes b is the first child which is already present so which is already been there in the tree so we have to look for the next character a is b is immediate child is a no so we have to create a node that inserts a and store it so the next character is n so from n we are going to from a we are going to store again and then from again the next character is going to be d so going moving forward to our next word which is mad so we are going to look for m in the tree so m is not there so the we are going to insert that as a root note from our immediate child of her vote so the next character is a m is not filled with a so we are going to fill a next to m and then the next character in mad is d so we are going to fill d so going to our final word which is max so max is having the first character m which is already there in a tree as the very first character the second character is a the immediate character to m is a that is also present the next character or the last character is x so we are going to insert x here so this actually constructs the word mad at max right so this is how the insertion operation works that is we are going to look for the prefixes and join them as a right or a left sub tree so now how it will be useful for us to search a word consider we are going to search for the word mad so now what our algorithm is going to look is its first character so first character is m it is going to look for the first character in the immediate child of the root so it is present so the second character is a we are going to look for the immediate child of m whether a is present or not yes a is present and the next character is d we have two options or two nodes after a so if any of one is d then we can return true so yes there is d as well so this is going to be true in the search function so now consider another word which is bang so as usual our algorithm is going to search for b so in b is there and the next character is n is there and the next sorry a is there the next character is n is also there but can we return true to this no because this is not the word that is given in our input we have given only band not band so in this data structure how do we identify that is the end of the word so to identify the end of the word because uh we can simply we have the word band in our data structure but that is not the actual word even in the input so to indicate that we are going to have a marker to with each node that says whether that is the end of the word or not so with let's say we have the variable as is word or is end of word however you want to so let me in short form write it as uh iw so with every node we are going to have a boolean value that says whether it is a word or not if it is a word then it is going to put a y if not it is going to put a false so for every word it is going to be false only end of the words are going to have true same way d and x are going to have true all other words in the data structure are going to have false so by this we are going to identify whether that is a end of the word or not so every time we are going to search for a word our data structure is going to look for the characters and by the end by when it finds the last character it is also going to check is word is true if this also satisfies then only it is going to return true if not it is going to return false so this is a simpler concept of this data structure and there is another criteria that we want to cover which is pattern matching for example let us say the example is m a dot so let's insert one more word consider we have one more word m a r s mars we have already m and a i have included r and s and its end of word s is going to have t and there is one more word cat so let me insert it somewhere here c is the first word a is the second character and t is the third character and which is having t as its last pattern matching other things are having false okay now let's see the example m a dot so in this case our algorithm is going to look for m first yes m is there a next is also there so there is one dot so we have to have one more character as child of a which is also having is word is true why because we have only three characters and the next character we find in next to a must have t so let's look at the algorithm we have three possible characters which is d mad are in mars and x which is also end of max so in this case we have uh end our search in d itself because we have one more character whatever character may be and that is having is word is equal to true so we can directly return true so this is similar to other pattern matching which is dot d or dot a d so in this case first character itself is dot so our algorithm is going to look for all the possible characters in the root node and from there it is going to proceed so this dot can be c this dot can be b and this dot can be m as well so we have all three choices so we are going to traverse in all parts that is possible so the second character say so from these three choices we are going to pick the which is having a as its next character so if you see we have a and cat a in one band and a in mad max mars and everything we have three choices now so the next character is d so we have only three characters now our algorithm is actually going to look for a d which is an immediate child of a which is also having is word is equal to true so in this case uh first option is cat so we have dot a and the third character is d which is not matching our a d so this is not going to be the path we are looking for which is a false so the next year we saw is in band so we have a the next character is n which is not matching d so we are going to skip it so then comes m a so we have again three choices which is d r and x so in this case let's leave d first and go for the example r so if you see uh the character r doesn't match d so we are skipping it here the character x doesn't match d so we are skipping it here we have d and also t so in this case we are going to return true for example if there is another word exist which is having m a d e made in this case we have match d with the first case mad as well as the third case made so they both have the prefix made and made but here e is having end of the word true but d is not in this case again becomes invalid in this case is the true case and we are going to return true so hope we made some sense with this is the overall logic we are going to implement in our code but uh this is bit clumsy how actually in which way we are going to implement it let's see so here are the three given methods the first method is to define our data structure so how are we going to implement our try in algorithm so usually try will be uh implemented using character array so again we are going to have a character array of size 26 so each position or each index is going to represent an alphabet a to z so as i said first root node is going to start with having 26 index starting from 0 to 25 where we are going to place the characters so which is which are the uh first characters of the word from each word again they are going to have 26 characters to its children so each character is having a array of size 26 let's see the same example we have taken bad max and mad so here the first word is bad so let's see we are going to insert b here and the second character is a so second its b's child is going to have a and the third character is d so from a there is another node which is again having 26 sized array and we are going to insert d in it so let's say d is the fourth character so it is going to be somewhere here so the first word is added if suppose the second word is bad then b is there a is there and the third character is g we have to insert g so g will be the child of a so from here we will have one more array which is again of size 26 in that we will be inserting g somewhere in its position so yes we have covered both the words bad and back same goes with max so first character is m so this is going to be placed in some somewhere in the position here in the very first array which had be also because these th they both are the first characters in the uh words so now max is going to be inserted so from m we're going to have one more array which is going to have space for all characters and we're going to insert a and a's child is going to be x and a's child is also going to be d which is for mad so now d and then dot so this is how we are going to construct our uh try and each node will be having a marker is word to indicate whether it is end of the word or not so yes this is how the complete data structure is going to be which is pretty simple so once you see the code you're going to get it by visualizing it so let's go to the code now so yes let's go to the first method is a place to declare our data structures so as i said we are going to have two items in a try node the first item is going to be the array yes as i said we are going to have array of size 26 and a boolean variable is word which is going to mark the end of the word so that's it let's move on to the add function so here's the code for add word function so we are going to declare a try node which is nothing but which is going to hold uh children of 26 characters or 26 trinode and the boolean word is what boolean character variable is what so now we are going to take a word which is gonna uh be inserted in from the input like add word bad is coming then this word is gonna be hit and from the word we are going to iterate each character and if the character is equal to null then only we are going to put the character in the index if not if it is not null which means prefix of that word is there already with the first character is there already we are going to simply uh insert the rest of the characters so if it is equal to null then we are going to insert it at the position that is c minus n is nothing but we are converting that to an integer index and putting it in the try node if not if it is not null then simply we are going to assign that as the current node so that the rest of the characters will be inserted as part of its children and finally after iterating all the characters and inserting all the characters of the word at the last word we are going to insert is word is equal to true so yes this is a simpler function once you imagine what we have pictured you will understand it very well so let's move on to search method so here comes the search method in search method we are going to call a helper method which is nothing but a recursive function to search for the word in the data structure so it simply calls the complete uh it sends the parameter as the character array of the search word and then 0 is nothing but the starting index of the word so it will iterate till the size of the word because if we want to find a word of size three then it is gonna iterate or call its function thrice to identify the word and root is nothing but the very first character of the word or the root note then here comes the match method which is helping us to match the match and find the given word recursively so let's first go to this function directly this line directly so which is a straightforward recursive method which is going to check if the character the children of that node at that position is not a sequel to null which means if we have to search for the word pad and there is no pad in the data structure there is no p in the data structure then which has to directly return false that is what we are going to first check if the node dot children is equal to the character or not if suppose there is a word that says dap but uh the word pad is not there we have to check for pad in that case p is there the data structure but that is not the immediate children we are searching for so hope you understand it has to be at that height of the tree so that it is the current it is at the current position correct position so now if it is not null we are going to search for uh the next character that is the character at index plus one and in its children so now the node is uh first character then its children would be the characters at the level two so it keep going on and matching it and finally will be returning true or false based on the search so this is the straightforward method if uh the given words are characters if not if it is a dot then we are going to take all possible children at that level and from there we are going to explore its children by calling everything recursively and then if everything matches then we are going to return true and where we are going to give the go to return true because here is uh the check if k is equal to length of the given characters which is nothing but we reach the end of the word to the last character and the words is word is true then we are returning true if not the words is its word is false then we are returning false yes that's it and this is the overall code of this problem hope i explained it clearly so let's run and try yes let's submit yes the solution has been accepted under trunks in 76 milliseconds so thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
|
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
|
303 |
what's going on so i decided let's do the ring some query for immutable so i just did a mutable one which is uh use the fenwick tree could have also used a segment tree which i'm um i'm gonna learn those in a bit but this is this problem just requires using a prefix summary it's very simple so literally uh i would go through it is um something like this create a self.prefix equals self.prefix equals self.prefix equals zero indexes plus nums um for i in range of one true length of self.prefix take self.prefix at i plus or equal to self-taught prefix at i self-taught prefix at i self-taught prefix at i minus 1 plus nums at i minus 1 because uh so it starts out as zero uh wait it starts out as zero then this would be zero let's say i have a ray so let's say i have the rate of negative two zero three negative five to negative one so then i'm gonna start my prefix array by putting a zero in front so those are right here and then it goes to the first thing which would be it takes the previous weight at i so negative two and it increments it based on the previous value yeah that won't work because uh the previous value is you know what so it's gonna be negative two then we go to the next one which is i equals two and it's like oh my value is zero so i add zero to the previous value which is negative two then i add three to it which is one then negative five which is negative four then i have two which is negative two and have the negative three yeah so this should work and the sum range will be um j minus soft uh prefix i so let's imagine if we start at zero right so if we start at zero if we go from zero to four we want to subtract the zero if we want everything because zero is just going to be the zero and then we want to subtract the thing at four right well let's see zero one or zero one two three four so the fourth element would be here but the fourth element is the fifth element in my prefix array so yeah i have to add one to this that was actually accepted let's see if this time complexity is good enough okay it is so um interesting thing is i'm actually just gonna look around real quick because i think it's a dynamic programming um yes i'm kind of curious what how can you use dynamic programming you don't need that oh you know what prefix summary is dynamic programming i just never thought about it's a type of dynamic programming because you're solving smaller problems like you solve the problem of the sum to this range and you saw the problem system to this range so it's a bunch of um solving similar problems to be able to solve this problem yeah i see now okay all right so hopefully this is helpful this problem is um range some gray immutable i was supposed by leeco
|
Range Sum Query - Immutable
|
range-sum-query-immutable
|
Given an integer array `nums`, handle multiple queries of the following type:
1. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`.
Implement the `NumArray` class:
* `NumArray(int[] nums)` Initializes the object with the integer array `nums`.
* `int sumRange(int left, int right)` Returns the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** (i.e. `nums[left] + nums[left + 1] + ... + nums[right]`).
**Example 1:**
**Input**
\[ "NumArray ", "sumRange ", "sumRange ", "sumRange "\]
\[\[\[-2, 0, 3, -5, 2, -1\]\], \[0, 2\], \[2, 5\], \[0, 5\]\]
**Output**
\[null, 1, -1, -3\]
**Explanation**
NumArray numArray = new NumArray(\[-2, 0, 3, -5, 2, -1\]);
numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1
numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1
numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3
**Constraints:**
* `1 <= nums.length <= 104`
* `-105 <= nums[i] <= 105`
* `0 <= left <= right < nums.length`
* At most `104` calls will be made to `sumRange`.
| null |
Array,Design,Prefix Sum
|
Easy
|
304,307,325
|
1,637 |
hey everyone today we're working on leak code challenge 1637. in this challenge our input is an array called points and we're given coordinates with X and Y values and they want you to return the widest vertical area between two points such that no points are inside the area so what does that mean what are they asking for here and it tells us that a vertical area is an area of fixed width extending infinitely along the y-axis so extending infinitely along the y-axis so extending infinitely along the y-axis so the widest vertical area is the one with the maximum width so when I first read this what's a little bit confusing about this is the fact that they're telling us that a vertical area basically has infinite length along the y-axis so if infinite length along the y-axis so if infinite length along the y-axis so if we look at the an example that they give us here it's telling us that this is going to extend infinitely up and down along the y-axis so what up and down along the y-axis so what up and down along the y-axis so what controls the area here the controlling Factor actually has nothing to do with the Y value it's only the distance between the X values so what we're looking for is the maximum width between two adjacent points and what we don't want is to look for example between this point and this point because this would have a containing point in between so we're looking at the adjacent Point values along the x-axis and we're comparing the along the x-axis and we're comparing the along the x-axis and we're comparing the distance between them so the best way to do this would be to take our input array and we want to start by sorting them by the X values so we're getting them in order of how they would lay on the plane in terms of the x-axis and then once we do that we're x-axis and then once we do that we're x-axis and then once we do that we're going to iterate through the array and we're going to find the distances along the x-axis the x-axis the x-axis between each point so and so we can determine which one gives us the maximum width or the therefore the widest vertical area so getting into the code we're going to start by running the sort method on our input array passing a b and we do need to sort this by the x value so this is going to be a at the zero index minus B at the zero index so that will sort our array then I'm going to create a variable called Max diff set that equal to zero next we're going to iterate through our array and I'm going to start at one I'll show you why in just a second I less than points.length than points.length than points.length I plus okay and then what we want to do is we want to set our Max diff value here equal to whichever is greater which is the current Max diff or now we're going to do our subtraction to compare the X values of two adjacent points so we'll start with points at the index of I and then we need to grab the x value which is zero and then I'm going to subtract that from points at the index of I minus 1 and at the index of zero so that's why we started our iteration at one not at zero because this will be points at I that's uh essentially this value right here minus points at I minus one so it's always subtracting going back one element in the array so that will come out with either a positive number or zero if they both have the same x value and then we're calling math.max value and then we're calling math.max value and then we're calling math.max comparing it to our current Max diff value whichever one is greater will be set to the new Max diff and then we should be able to return that value and there we go we have a solution for this one so hopefully you found this video helpful let me know if you have any other ideas on how you would solve this one and have a great day
|
Widest Vertical Area Between Two Points Containing No Points
|
string-compression-ii
|
Given `n` `points` on a 2D plane where `points[i] = [xi, yi]`, Return _the **widest vertical area** between two points such that no points are inside the area._
A **vertical area** is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The **widest vertical area** is the one with the maximum width.
Note that points **on the edge** of a vertical area **are not** considered included in the area.
**Example 1:**
**Input:** points = \[\[8,7\],\[9,9\],\[7,4\],\[9,7\]\]
**Output:** 1
**Explanation:** Both the red and the blue area are optimal.
**Example 2:**
**Input:** points = \[\[3,1\],\[9,0\],\[1,0\],\[1,4\],\[5,3\],\[8,8\]\]
**Output:** 3
**Constraints:**
* `n == points.length`
* `2 <= n <= 105`
* `points[i].length == 2`
* `0 <= xi, yi <= 109`
|
Use dynamic programming. The state of the DP can be the current index and the remaining characters to delete. Having a prefix sum for each character can help you determine for a certain character c in some specific range, how many characters you need to delete to merge all occurrences of c in that range.
|
String,Dynamic Programming
|
Hard
| null |
67 |
hello welcome to my channel today we have leeco 67 at binary so give two binary string a and b return the sum as a dot binary string so now we have a b here 11 plus one when one plus one is equal to zero and we have additional one added to the second digit and then you have two added to another digit so we come up one zero so in here the same uh so we add up so it's binary numbers when they add it so this is a binary number that output so to solve this solution we have a carry when we add up more than one then have a carry and carry on for next digit that's how we start the solution and let's take a look at the code now we have string builder output go to a new string builder so after this we have a carry equal to zero now we can make a link starting from the end of the string called a link equal to a dot length minus 1 b length minus 1 and then we'll have a while loop so what they are not eight length they go equal to zero or b length bigger or equal to zero or let me see carry equal 1 then we need to keep looping now we check if ailing bigger or equal to one make it bigger than or equal to zero sorry and then at that case we put that last digit to carry which is plus or equal so it's a dot character at a length minus oh come on zero so now the character in here minus zero will be the integer which is the number at that location we add that to carry so carry have that number after that we minus length by one a length by one so now the carry have the a-link in there a link digit in the a-link in there a link digit in the a-link in there a link digit in there so now we have the digit in b link so b length bigger or equal to zero then we have to get that number we character at b lane minus zero same as that b lane minus now we have both number put it to the carry so what do we do to the string builder will have insert third at the first location at the beginning that what we need to add is carry divided by actually carry mod 2. so carry mark 2 will be the digit remain after divided by 2 so carry if they're bigger than or equal than 2 then carry will be one so now you can see if carries two so carry will remain two if scary is skilled to three then carry also become i mean can we become one because one is for next digit so now you have a carry right here so after the carry then this is while loop is done the last time you have this output build up and you can just return this output and make it to a string for the output and that should be yeah that's it cool and this solves the problem so if you still have more questions please comment below and i will see you in the next video thank you bye
|
Add Binary
|
add-binary
|
Given two binary strings `a` and `b`, return _their sum as a binary string_.
**Example 1:**
**Input:** a = "11", b = "1"
**Output:** "100"
**Example 2:**
**Input:** a = "1010", b = "1011"
**Output:** "10101"
**Constraints:**
* `1 <= a.length, b.length <= 104`
* `a` and `b` consist only of `'0'` or `'1'` characters.
* Each string does not contain leading zeros except for the zero itself.
| null |
Math,String,Bit Manipulation,Simulation
|
Easy
|
2,43,66,1031
|
203 |
hello everyone welcome to codas camp we are at 11th day of november eco challenge and the problem we are going to cover in this video is to remove linked list elements so if you observe the problems that has been asked during the normal eco challenge are mostly easy category problems so it is always good to revise the basics and in today's problem we have head of our linked list as our input and integer value 6 and we have to remove the nodes which are having the value given in the input and return the head of the linked list without those nodes so which is a very basic linked list problem you must have already crossed but it is always good to revise the basics and it is very good problem for those who start learning what is linked list so let's understand this with an example so here is the linked list given in the problem statement as usual we are going to solve any linked list problem using two pointers or single pointer because pointers and linked lists are always go based together so now we have to iterate through the given linked list and check if the value of the node is equal to the given value of the input if that is the case then we are going to remove the connection and establish a connection between the nodes ignoring the node which is having the value so let's start having a pointer current which is going to iterate through our list and check whether the next value is the given input value or not so consider in this example the given input value is 6 so we are going to search for the nodes whose value are 6 and remove them so let's first check current dot next is 6 or not we are right now at the node 1 and we are having our pointer current at node 1 and current dot next is 2 so it is not the value we are looking for so i tried the pointer towards the next element so now current is 2 so 2 dot next is 6 or not yes it is six so in that case we have to remove the connection from current to six and establish the connection from two to three so now r6 has been removed from two and the connection has been made from 2 to 3 so now our current dot next is not 6 it is 3 because 2 dot next is 3 so we are checking whether 3 is 6 no it is not so let's move our pointer to 3 so now again we are checking three dot next that is current dot next is six or not no the value is four it is not the value we are looking for so i trade a current pointer to four so now again check whether the next value to current is six or not yes it is six so in that case we have to remove the connection from four to six and establish the connection from four to the next value to six so we are now checking whether the next value is null or six it is null which means we reach the end of the linked list we don't have any more nodes to iterate so that's it our linked list has removed the connections or remove the nodes from the given input and establish the new connection and here is our output so this algorithm is going to work and we go of young time complexity as we are iterating the linked list only once and constant space as we are not going to use any extra space to establish this since we are performing the same operation again and again that is removing the node which has the value we can do the same algorithm in recursive way but for recursive algorithm we required the memory stack for each call so linear is the best possible solution for this problem so let's go to the code now so yes let's start so before getting into the actual algorithm i have said while explaining the first node will have the current pointer and we check every current dot next is the searching value or not but what if the first node that is the head of the linked list itself is the value so in that case we have to put a base case that so we are checking whether the head itself is the value then we are moving the head to one step ahead so until if what if there are four to five values continuously are the integer value given in the input which means we are going to move our head pointer ahead that many times we find that value in our linked list so now getting into the actual algorithm so yes we are iterating our pointer to next node until we face a null and we are checking if the value is equal to the value given at the input if that is the case then we are connecting current dot next to current dot next if not if we did not find the value then we are simply going to iterate to the next node so finally we will be having the interconnected nodes after removing the actual value nodes so we have to return our head as a result so yes this is it let's run a try yes so let's submit yes a solution has been accepted we have completed today's problem and it is running in zero milliseconds so thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
|
Remove Linked List Elements
|
remove-linked-list-elements
|
Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_.
**Example 1:**
**Input:** head = \[1,2,6,3,4,5,6\], val = 6
**Output:** \[1,2,3,4,5\]
**Example 2:**
**Input:** head = \[\], val = 1
**Output:** \[\]
**Example 3:**
**Input:** head = \[7,7,7,7\], val = 7
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 104]`.
* `1 <= Node.val <= 50`
* `0 <= val <= 50`
| null |
Linked List,Recursion
|
Easy
|
27,237,2216
|
225 |
hi everyone today we are going to sort of delete all the question Implement stack using fuse so Implement a lasting passed out stack using only two cues the implemented stack should support all the functions of normal stack push top pop and empty and here is a definition of each function and we have actually follow-up questions and we have actually follow-up questions and we have actually follow-up questions for our questions that implement the stack with only one queue so I'll show you uh two ways like two queues and one queue um to solve this question okay so let's write the code with two cues so some function is very easy no need to explain so um so I Implement a simple function first so first of all self.q q1 equals we use so first of all self.q q1 equals we use so first of all self.q q1 equals we use a DQ and uh we need one more Q so let's say Q2 and the so push function is very simple so self dot q1 dot append and X so we always append data to q1 yeah this function is finished and empty function also very simple so this function is check whether um q1 has data or not so that's why ranks of self Dot q1 equal zero and that's it so pop and the top is a little bit complicated so let me explain uh with like a diagram or drawing the picture okay so let me explain this pop function and the top function so this is a stack function so usually um stock if we pop the data from stack so we popped this last value right but we Implement stack with Q so Q usually like a fasting and fast out that means so this data is a fast forward to data so how can we popped the last value as a first popped value in this case so it's simple um so we iterate through all data one by one in q1 except last value and then every time append the pop data to Q2 so that means so first one so we popped one and the append q21 and then we take a 2 and then append the 2 to Q2 so now q1 has only last value three so in the case we can easily uh popped last value from q1 so take a three and then so this is like a popped value so that's why we should return three in this case but before that um so in push function we always push append data to q1 right so I think it's a good idea before return We swapping q1 and the Q2 so that uh we can easily operator uh in other function especially like a push function so in push function we don't choose like a q1 or Q2 just we can choose only q1 because of this swapping so yeah it's really easily done value and then now q1 is empty and Q2 has so one two so in this case uh just a swapping q1 and Q2 so that's why in the end so let me change it here so this empty list should be Q2 and this one too is q1 and this is a pop function so three our three will disappear so now q1 has one two and then when we execute boost function so new data is appended in the last position so let's say like a four yeah so this is a pop function okay so let me explain um top function so actually almost same as Pop function so first of all it takes all numbers um one by one except last value and uh take all values and append to Q2 so now take one and append Q2 and then take a 2 open the to Q2 so now q1 has only three so this is a little value so like a Top Value um but in this case um before we return three so take so first of all um actually uh we copied BC to a simple variable so now um simple variable has so let's say top value equals three and then um so this is a top function so we have to keep this three so that's why we return this value so after copy three to simple variable we execute Pope and append 3 to Q2 like a sleep and then after that um as I explained earlier so we swap the q1 and the Q2 so in the end so this one should be q1 and then this one should be Q2 so q1 has one two three and the Q2 has empty list and then we should return this three and then in like a push function we can append um data to q1 so like a four pipe something like that so we don't use q1 over Q2 in push function yeah so that is a top function so let's Implement two functions okay so let's implement the pop function first so as I explained earlier so why length of self dot q1 is greater than one in the case on self Dot Q2 dot band and self Dot q1 dot pop left so we take a data from q1 and append it to Q2 and after that so q1 has only one data so that is a popped value right so popped opt value oops value equal self dot Q qm dot left and after that so before return the popped value so as I explained earlier so swapping q1 and Q2 so self Dot q1 and as self Dot Q2 equal so n equals and this should be Q2 this should be q1 and then after that just return popped value so that is a pop function and let's Implement a top function so we do the same thing so y so length of self dot q1 is greater than one so in the case self.q2 dot append and so in the case self.q2 dot append and so in the case self.q2 dot append and self dot q1 dot pop left so after that so let's uh I can pick the last value so top bar equals self Dot q1 and uh so that's it so after that save dot Q2 dot append and there's self.q on oops Q on dot left and there's self.q on oops Q on dot left and there's self.q on oops Q on dot left so we have to keep the last value because this is a top function and then after that I'm swapping q1 and Q2 so save Dot q1 and the self dot Q2 equal so let me copy this and then this should be Q2 and this will be q1 and then after that just return and top part yeah that's it so let me submit it algorithm and the time complexity of this solution should be so push and empty functions are one and then pop and the top functions are order of n because we equates to all numbers except to raspberry so that should be n minus one so remove the constant number so time complexity should be order of n and the space complexity is order of Android so that's simple so next so I will Implement a solution with one only one Cube okay so let's light a solution with one queue so self dot Q equal take you and the push function is little bit complicated so let's Implement other function first so pop function is very easy just to be done self dot Q dot left so we popped the V Pop Fast value and the return that's it and the top it's all the things dot save dot q and we don't have to take the value so just pick the first value and so that's by zero and that's it so empty should be same as negative 2q so ranks of self dot Q equals zero and that's it and let's Implement a push function so first of all I'll open the input data to cube so self dot Q dot append and X so now so let's see the other function so pop function uh pop the first value and return and the top function is the first value and return so this x value should be the first value in the queue so that's why we rearrange the values order of values so how can we do that so we use a for Loop and in range and the end should be length of self.q minus on so except last length of self.q minus on so except last length of self.q minus on so except last value so we don't have another queue right so that's why we need to append the same queue dot append and then take the value from the beginning one by one so left so that we can rearrange all the all values right so last value should be first value with this for Loop so that's why we can easily execute pop function or top function yeah that's it so let me submit it yeah it looks good in the very center algorithm and the time complexity of this solution should be so pop top and empty functions are one and the push is on so very simple and the space also order of n 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
|
Implement Stack using Queues
|
implement-stack-using-queues
|
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (`push`, `top`, `pop`, and `empty`).
Implement the `MyStack` class:
* `void push(int x)` Pushes element x to the top of the stack.
* `int pop()` Removes the element on the top of the stack and returns it.
* `int top()` Returns the element on the top of the stack.
* `boolean empty()` Returns `true` if the stack is empty, `false` otherwise.
**Notes:**
* You must use **only** standard operations of a queue, which means that only `push to back`, `peek/pop from front`, `size` and `is empty` operations are valid.
* Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations.
**Example 1:**
**Input**
\[ "MyStack ", "push ", "push ", "top ", "pop ", "empty "\]
\[\[\], \[1\], \[2\], \[\], \[\], \[\]\]
**Output**
\[null, null, null, 2, 2, false\]
**Explanation**
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // return 2
myStack.pop(); // return 2
myStack.empty(); // return False
**Constraints:**
* `1 <= x <= 9`
* At most `100` calls will be made to `push`, `pop`, `top`, and `empty`.
* All the calls to `pop` and `top` are valid.
**Follow-up:** Can you implement the stack using only one queue?
| null |
Stack,Design,Queue
|
Easy
|
232
|
237 |
Hello Hi Guys Welcome To Your Dreams Media Ji Today Will Go Through The Day To Problems From June Challenge Did Not Please Like Video And Don't Forget To Subscribe To This Channel Show Me To Right To Delete Function In Nursing Link List Jeevan Access Only To The Node For Example Diwan Agdat Input Least This Session and Will Not Be Deleted Dozens of Times in Note 510 Result in Leadership B 419 The Question Is That System List Will Have at Least Two Elements All the Note Values Will Be Unique Elements All the Note Values Will Be Unique Elements All the Note Values Will Be Unique The Giver Note Will Not Be Bacterial and Will Always Be Avail Mode of the Link List Glass Need Not Returning From You Function New Delhi Note Mathil Finalist Not Be Deleted End Perimeter Hair Oil Happiness-Prosperity Structure For The Last Not Need Not Be Only Happiness-Prosperity Structure For The Last Not Need Not Be Only Happiness-Prosperity Structure For The Last Not Need Not Be Only Giving Not Be Deleted Video not here In The Amazing List This note is required and see how will do it that this list is a visualization of this being given new tweeted notified in typical from coconut they want to delete a noted with just one next point of speedunnodu and connected to the next to Dhawan blacklisted which looks something Like this but you will not find the previous node show will convert note 5 to next month end delete Dinesh node next Note5 is note 151 suite piece value of route 521 set the next turn on 2.1 1995 seems to have next turn on 2.1 1995 seems to have next turn on 2.1 1995 seems to have very little done not The Final List Will Look Like This Is The Time Complexity Problem Is Arrangement Of Some But All Sorts Of Water Into Java Coding Description Gulf Ki Thank You For Watching My Video If You Like Video Please Like Share And Subscribe To Our Channel Account For More Videos For More Interview Problems But Their Mind Section What You Think About The Video All Should Be Given To Make A Video On One Of Your Problem Statement To Comment
|
Delete Node in a Linked List
|
delete-node-in-a-linked-list
|
There is a singly-linked list `head` and we want to delete a node `node` in it.
You are given the node to be deleted `node`. You will **not be given access** to the first node of `head`.
All the values of the linked list are **unique**, and it is guaranteed that the given node `node` is not the last node in the linked list.
Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:
* The value of the given node should not exist in the linked list.
* The number of nodes in the linked list should decrease by one.
* All the values before `node` should be in the same order.
* All the values after `node` should be in the same order.
**Custom testing:**
* For the input, you should provide the entire linked list `head` and the node to be given `node`. `node` should not be the last node of the list and should be an actual node in the list.
* We will build the linked list and pass the node to your function.
* The output will be the entire list after calling your function.
**Example 1:**
**Input:** head = \[4,5,1,9\], node = 5
**Output:** \[4,1,9\]
**Explanation:** You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
**Example 2:**
**Input:** head = \[4,5,1,9\], node = 1
**Output:** \[4,5,9\]
**Explanation:** You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
**Constraints:**
* The number of the nodes in the given list is in the range `[2, 1000]`.
* `-1000 <= Node.val <= 1000`
* The value of each node in the list is **unique**.
* The `node` to be deleted is **in the list** and is **not a tail** node.
| null |
Linked List
|
Easy
|
203
|
106 |
in this video we are going to discuss if you have given the in order and the post order Professor how you can build up or create the banuity but before going to deep inside the problem let us understand what is the traversal what is the in order to reversal what is the post order triggers right so you know this is the binary tree so and this is the representation of the planet in the form of the array so if you see 25 then 15 then 50 25 15 58 this is the representation of the humanity so first we understand how to create the in order anyway it would be the there in your questions but let me understand what is the in order for this TV so when you write the in order you always keep the three things in mind where parent and the right side so first is direct who we present the parent and I will present the right so first let me take one small uh tree so suppose this is the tree 25 and the 50. for this what is the in order so that I went right this is the web parent and the right and the post order it's the L r o means first if you consider for the website then right side and then the parent so what is the post order for this tree so first we have then right and then the parent this is called a traversal so just that is make the uh in order and post order for this given uh binary let me check how we can find out for the big tree so if you see here for the in order where I went right so what is the left if this is the tree what is the left for this one but again if you consider this is another sub TV right if you end up consider this is your another sub TV right so again you have to start what is the web for this so this is the four right so this is the wrapped most so we have to start from here so four right we give the four then parent and the right what is the parent 10 and then the right 12. then again this sub 3 is the done the website is done now we have to do the parent what is the parent 15 and then what is the right side is another sub TV and for that this is the parent and we don't have the that this is a null and we have the right so again you have to do the left parent right there is no left the directory you have to write the parent and the right side so now we have done this part so website is done then you have to write the payment parent is 25. then again you have to do the same thing for this side so you have to go the web then the parent then the right so if this is the sub TV then this is the left and for that this is the web so it start from 31 and his parent is the 35 and there is no right side here so we can skip then this part is done then you have to write the parent payment is 50. then this sub 3 this is the parent this is the website this is the right side so left side 60 parent and the right side so here is the sub 3 60 then 70 and 90 right so 60 70 90. now let me put that the post uh post order means we have to write five and so again come for this tree this is the sub TV for this is the sub T so this is the web this is the light this is the private so 4 12 10 so this is the 4 12 10. if thus this software is finished then come B sub 2 we don't have the left so only the right and the parent so 24 and parent is the 22. if this part is done this web sub TV we have sub TV then we have to write the parent so this complete was the L this compute is the r and now the parent is the 15. right now we for this tree this or the subtree we have done website subtree now go for the right side safety so this is the one sub TV for that this is the sub TV so we have to do this is l r o so R is not there so we have to write the 35 31 and the 35 right l i o so 31 nothing and 35. once you've done that come this right side we have the 60 90 this is L this is R this is O 17 16 1970 60 90 and 70. so this part is done this partition so f is done R is done 5 is 50. and if you see this website is on right side is done and this is the 25 so what happened that and this is the presentation for the binary so in your problem statement you will be having given the in order you will have the post order and they are expecting to write the binary which you are expecting the output of these three so now let us understand that what is the some special properties are there if you see the post order your last digit is always the you know if you can see this is the last is always the root so what you have to do you search this 25 means we have to start our scanning from the post order from the right side take the right most 25 search this 25 here so if you do one the indexing you can do the indexing 0 1 2 3 4 5 6 7 8 9 10 11 12 if you see here 0 1 2 3 4 5 6 7 8 9 10 11 so once you get the root you have to search the root inside the in order so here is your 25 right so step first take the right most element that is your root element search the element and if you see here your if you start from here so I will give name the index this is the post order right so I will say the P IND post order ending so we can find out this is the 12 volt and this is nothing this is the if this is the array so I can say the post order event minus one right this is your pH so once you get the PE is 25 search the 25 here in the in order and if you see we will get the one index that is the chord index you can give the index and index is the six now the benefit is that you know l o r means if this is the parents so then must be this part of the website select safety and this part is the right sub t and you can see the 25 or the website is this element and all the right side is this element right so again if you and if you find out this number here this 4 10 12 15 24 25 if you can see this number 4 10 12 24 this one it will from here to here is the website because here fio so this is your left sub 3 and from 31st to 50 this is your right sub 2. right so once you get the 25 this is your 25 now for the 25 what is your website this is the web sub TV for this web sub TV what is your in order so for the website what is you in order with this 4 10 12 15 20 24 and what is the post order website 4 12 10 24 22 50. right and if you see for 25 right side in order this is the website and this is the right side in order 31 35 50 60 70 and 90 and what is the post order for the right side this is 31 35 60 90 70 and 50. now you forget everything now you again start what you have done here you have to do again here and you know the end of the post order is above the root so what is the what is that here root is the 15. so make the U the 15 is the root and you have to search the 15 here this is a 50 here right and if you know the indexing of things 15 here indexing is the 5 here this is the five or this indexing is the pipe here this is the three indexing right so you got the 15 here same thing you do here this 50 must be or the uh the parent right so here in this case this is the 50 because this is here find out this 50 here so this 50 indexing is the 11 and this 50 is indexing is the 9th right now you can see this your T is constructing this so 25 15 50 25 15 and 50. so the main thing is that the last element of post order is the root for that Subway or TV right if you know then it is easy so how it is working now let me explain the logic behind that so what you have to do first step take the right most because we were in the recursive because you are doing the same operation here so this is the perfect tree fit for the vehicle seat recursive operations to do you have to find out the last element search the last element of the post order inside the in order and make the individual tree that's it so if this is your index or you can see the root index why I'm saying the root index because for the sub T that is going to become your uh The View right so if you want to make one method right give method one thing I have to pass so I have to pass the in order starting so I start and I end and pass the both away the post order or in order okay so starting time and take one variable for this element so I can say this is the p and starting time you're playing n is the 12. right starting time your I started with a 0 and the i in would be the 12. right so make one root element with from the post order right so post order which index t ending foreign 50 then 70 when it is reduced one by one so first we will construct the right side sub tree then construct the website sub TV so every time you have to minus it for the next payment next root element once you get the root then you have to construct this part how if you consider that part first you have to find out the root index how you find out the used index root index means the element of the root you have to search in the in order so make one for you that be run in order is starting and ending what is the starting so I is equal to I start I equal to I in I plus and search this root value is nothing that is the root element inside the in order area the moment I will get put that value into the root index so in this case our root index is the six once you get the root index your job is easy because now this is the one part another is the this part so for the right side tree for the right side three you have to call the same method this time what is the I start the same I start we are not going to change anything but the ending is the root index minus one because root index is the 6 mine is still only 24 right here is ending so root index minus one and for the website we have to call the same method and for the start from the index plus one and the tab in right so it will root index plus 1 I in the both a so this is the complete code let me show in the laptop then if you understand how it is working that so first we create one recursive method that name given the value and I say I need uh for the in order is starting in the ending right so this is our ending is started and in order ending and I need this both a right and first I will check if any time our I start is getting an I end means that is we have to stop it because this is the concede method and we need one termination a statement so in that case if you P start any time is p ending means we have to stop here and return the null and then first what you have to do you have to take the from the post order take the last element right so take one index here give the name e and p in initializing with the post order length minus 1 right as you discuss on the board right so and then this post order P ending will give the parent first parent right and then create one root element foreign of the post order and for the next time we can decrement right so it is going from the right side to the website okay and now as you discussed that make one root index that we have the this we have to search this root value inside the in order right so start one for you I start from I start means it is starting from the in order to array and it will go to the I in and here we have to search if this in the in order I does match with the root value right this just now we create the good value if it is matching means I got that root index inside the in order so keep those value in you would index and break this for Loop now no need to further inquiry right so now we got the root index and from where we have to divide so we have to first start from the right side because your in the post order we your parent ID from the right side you are taking from the right side so root dot right side is take that call this method again and for the right side what you have to do we have already discussed that it will start from the root index first one and I in and of course these two array in order in the post order and for the left side it will be with I start and root index minus 1 as you discussed on the white bullet once you have the root Index this complete side website is for the starting and minus the root index and the right side index plus 1 till the I interact so for the website I start from I start to the root index minus 1 and of course post order right and you have to return the layout once you got it now we have to call this method from here build I have to pass the I start starting time I started the zero ending time what is the I start I ending at the end diameter right so in order dot length minus 1 right at the end and then we have to pass the in order in the post order let me check this code does work or not so run this post order ORD right this is a typo and it should work actually it is accepted here right so if you case this use case it is working and if this use case it is also working and yeah it should work is accepted so if you see uh this is over or your code this compute your code and code is very easy right once if you don't understand the code go to the Whiteboard and from White would come here and we have the better understanding please don't forget to subscribe this Channel and like this to promote this channel thank you very much
|
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
|
1,849 |
hey everyone welcome back and let's write some more neat code today so today let's solve a brand new leak code problem just from the elite code contest that just ended a second ago 1849 splitting a string into descending consecutive values so this is a pretty standard backtracking problem so we're going to be handling this recursively with backtracking and by that i basically mean this is a brute force approach because we're going to be handling basically every single possible case so it's pretty straightforward of an explanation we are given a string s it only contains digits right so 0 9 1 whatever it contains digits we want to split the string into at least two integers so we do have to split it at least once we could split once twice whatever however many times so and we want to split it such that every single integer is in descending order and not only descending order but descending by exactly one value so for example if we split this string such that it looks like this two different integers right what does this value evaluate to well it has a couple leading zeros but we don't care about leading zeros so this evaluates to 90. this has a single leading zero and again we don't care about that so this evaluates to 89. so let me ask you are these two values in descending order yes they're in descending order are they descending by exactly one yes they're descending by one right so in this case there does exist a valid way to split them so we can return true right we would return true in this case what about this string can we split this in any way that it will be in descending order not really because look it only has leading zeros so no matter how we split it there's gonna be a one at the end and that one is going to be greater than whatever comes before it so it's going to be in ascending order right it's going to be increasing not decreasing therefore we cannot have it in descending order by exactly one so we can return false in this case so let me ask you is there like a really neat pattern that we can solve this problem super efficiently like law or linear time definitely not we are going to basically handle this in the brute force approach so notice how there's no restriction on what the first integer is right so we can brute force that what we can do is we can try just the first digit by itself as our first value or we can try the first two digits by themselves as our first value or the first three digits as the first value and so on right there's never a restriction on the first value but every value that comes after the first value has to be exactly minus one right so if we had five as our first value the next value has to be four and then three and so on so let's visualize this a little bit how would the decision tree or our backtracking tree look like take a look at the left hand side that i'm doing so the first case or one path of our decision tree would just be one digit right just the first digit and the next path could be two digits right and the next path could be three digits and so on right we'd have four and then all the way to n so let's redraw that so one two right three all the way to n digits right so and then this is going to be continuation of that right we're just gonna continue so let's say we got the first one digit then we'd want the next digits uh continuing right the next one digit the next two digits so on and so on until we don't have any digits left inside of our entire string so based on this idea this decision tree right you can see that we're going to have n branches right in the worst case we have n branches and then and the height of the tree is also going to be roughly n so you might think okay the big o time complexity is going to be proportional to n to the power of n but realistically it's going to be more efficient than this because we are going to be doing some kind of pruning right when if we let's say for example our first uh digit was 90 then as we continued to brute force other digits right let's say we got a 75 or a 80 and you know 60 or whatever none of these digits are exactly one less than 90 so we wouldn't continue on the debt for search path for these for any of these decisions so in our decision tree so we're going to cut them short you'll see exactly how we're going to do that in the code so just a little visual example of this let's say this was our input string what would kind of our decision tree are backtracking decision tree look like well remember i'm gonna say okay well one decision would be just the first uh value for the first digit one decision would be the first two digits uh one decision would be the first three and another decision would be all four as our first value so you can say that these are going to be our decisions 4 43 4 3 2 and 4 3 2 1. and then we're really just going to continue on so let's say remember the first digit so meaning this first kind of row has no restrictions this value could be anything any of these values could be anything but now when we go so for example from this 4 we have three decisions right our first value so we can't consider this four anymore but our first value could be three another choice could be 32 another choice could be three two one so these are our three choices right but remember now these values actually have one restriction they have to be exactly one less than this value are any of them exactly one less 32 is not one less they have these values have to be in descending order by exactly one so this simply will not work this also simply will not work right it's not one less hey but a good thing here is we have a three is exactly one less than four and you know kind of by looking at this you can tell that the correct order is going to be four three two one so that's kind of you know this is kind of just a quick rundown of what the uh result is going to be and we can verify that this you know this decision this path along our decision tree is the result because it's in descending order by exactly one so that's gonna end up being the solution we're gonna end up returning true because we did find a valid way these other three paths will not end up working i'll just tell you that right now but you can probably tell by looking at this that there's not going to be a valid solution but this is just kind of a visualization of the decision tree and what we're actually trying to do we're brute forcing this we're checking every possible path if any of them work out we're going to return true okay so remember we're going to handle this recursively but the first thing i'm going to do is get is determine the first integer that we're going to get from our string so i'm going to brute force this right we're going to potentially try the first digit the first two digits the first three digits and so on so let's run through let's run i through the entire uh string except we can't go to the up until the last character because we know we need at least two we need to split the string into at least two separate numbers so once i have my index i'm gonna go from the beginning of the string to that index i and so this is a substring to that index i so i plus 1 so this is the substring from index 0 to index i and this is a string right now but we want to convert it into an integer so let's do that and let's assign this to value so we have our first value and remember there's no restrictions on what the first value can be but for every value that comes after it needs to be exactly one less than it needs to be in descending order by one and so this is the part where we're going to do our recursive backtracking i'm going to call the recursive function dfs for depth for search just because it's shorter i prefer that and so if the if our dfs if our backtracking returns true meaning we could split the string then what we're going to do is ultimately return true through the entire function but if we never end up splitting the string properly then after the loop executes we're going to end up returning false but now it's time to actually fill in this dfs function i'm going to define it up above over here so we only have to pass in two parameters the index that we're starting at so for example see the value if we if the first value was simply just contained the first index of the string then the next index can be zero plus one right it can be the remainder of the string except the first character so that's what we're going to pass in here so we're bringing up so for our first parameter we're going to pass in i plus 1. we also need a second parameter to determine what the previous integer was right what our previous value was so that we can make sure it's in descending order by exactly one so the other parameter i'm going to pass into this dfs is going to be the value that we just calculated now the base case is going to be if our index is out of bounds meaning our index reached the end of the string so if it's at position length of the string in that case we can return true because there's no more characters left but you can see that this base case is never going to evaluate from this function call because we're never we're not actually iterating through the end of the string i is never going to actually be at the end of the string because see we do have that minus one over here but now let's actually get into the main part of this algorithm it's going to be at the depth first search backtracking is actually getting going to be pretty similar to this portion that we wrote with just one small difference so we're gonna iterate through the remainder of the string from the starting of index to the end of the string this time we don't have a minus one here because we can actually go to the end of the string this time because remember we only have to split this into at least two separate values and once again what we're going to do is simply get that sub string so in this case we're going to start at index and then go to j plus one and we're going to convert this again into an integer and then assign it to val now again we're going to do basically the exact same thing that we did down here but with only one difference in this case remember this is not the first value that we're computing right with the first value that we got there were no restrictions but in this case there is a restriction this value that we just calculated has to be exactly one value less than the previous value that we calculated so we have to determine we have to verify that val plus 1 is exactly equal to the previous value and if this is true only then can we call our debt for search function in python the way this works is if this evaluates to true then the second portion of the and condition is actually going to execute so this is not going to execute if this were false so that's kind of what keeps our function pretty efficient right we're kind of pruning here so this is not going to be super inefficient even though it's backtracking so the first parameter is going to be the starting index so we ended at j in this case so we're going to pass in j plus 1 and for the value we're just going to pass in the value and so if both of these were true that means that we were able to split our function in that case we can return true and similar to down here if this entire loop executes but we never end up returning true that means we were not able to split the string in that case we can just return false and this is actually the entire code you guys if you're a regular viewer of mine you know that this is basically how i solve all my backtracking problems i basically follow this formula we have a nested function usually depth first search inside of our root function and then you know that's just kind of the standard way that we solve and then we just brute force through it so i hope that this was helpful for you if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon
|
Splitting a String Into Descending Consecutive Values
|
maximum-absolute-sum-of-any-subarray
|
You are given a string `s` that consists of only digits.
Check if we can split `s` into **two or more non-empty substrings** such that the **numerical values** of the substrings are in **descending order** and the **difference** between numerical values of every two **adjacent** **substrings** is equal to `1`.
* For example, the string `s = "0090089 "` can be split into `[ "0090 ", "089 "]` with numerical values `[90,89]`. The values are in descending order and adjacent values differ by `1`, so this way is valid.
* Another example, the string `s = "001 "` can be split into `[ "0 ", "01 "]`, `[ "00 ", "1 "]`, or `[ "0 ", "0 ", "1 "]`. However all the ways are invalid because they have numerical values `[0,1]`, `[0,1]`, and `[0,0,1]` respectively, all of which are not in descending order.
Return `true` _if it is possible to split_ `s` _as described above__, or_ `false` _otherwise._
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** s = "1234 "
**Output:** false
**Explanation:** There is no valid way to split s.
**Example 2:**
**Input:** s = "050043 "
**Output:** true
**Explanation:** s can be split into \[ "05 ", "004 ", "3 "\] with numerical values \[5,4,3\].
The values are in descending order with adjacent values differing by 1.
**Example 3:**
**Input:** s = "9080701 "
**Output:** false
**Explanation:** There is no valid way to split s.
**Constraints:**
* `1 <= s.length <= 20`
* `s` only consists of digits.
|
What if we asked for maximum sum, not absolute sum? It's a standard problem that can be solved by Kadane's algorithm. The key idea is the max absolute sum will be either the max sum or the min sum. So just run kadane twice, once calculating the max sum and once calculating the min sum.
|
Array,Dynamic Programming
|
Medium
|
53
|
55 |
Hello guys welcome back door sign in this video will see job game problem this is from list to date 154 248 coding challenge this problem is also known as the minimum number of dams to reach and bird in this problem is a subset of this problem solve this Problem IS Currently Have A Lower Cost So Let's Look At Problem Give Me To Start Jumping From Dahej Must Subscribe Possible To Be Written As You Can See From This You Can Take One To Three And This Will Be Possible For Him In This Way You Will Regret And Visit 2009 2013 subscribe The Channel Afton Falls Sense The Starting Index With This You Will Make Maximum and Zero Number of Times You Can Never Crossed End Reach Index ₹1 Note Rich Index One which can never ₹1 Note Rich Index One which can never ₹1 Note Rich Index One which can never is the end index in all its A very intuitive and decorating solution Discuss what you are doing so will start from starting index and tourists and 109 rates in the number of times Jul 10 2012 and tracking code very long time from the position subscribe this Video in 109 This is not feasible for long Test cases for understanding of how can be improved solution Wikinews here memorization and used to improve this application will take place in the year will be explained in number of tourists and videos Subscribe Personal problem represented in the form of you can see you will give you do n't No You Can See From The Opposition From This Thank You Can Make From This Point To All Of You That I'm Going To Give Exams And To Do This To-Do List That I'm Going To Give Exams And To Do This To-Do List That I'm Going To Give Exams And To Do This To-Do List 210 From This Indexes Vyathiri Love You Can Make 302 201 More From This Is Not Possible To Depart From This Point To That Veer Is The Written A Letter To Your Observations And Always Will Be What We Can Do As We Can Just Make One Jump 800 To 1000 Will Obviously A Simple Way To Find Solutions Chapter Maximum Project Distance Which Can do subscribe and you will receive the distance from sydney with love what will be given point what is the longest distance from 10 maximum per distance and they will always be subscribe to terrorism maximum of this index one so they are currently 800 and they can reach Maximum Friends Vansh Since Reachable This List Enter Maximum Which Can Now Be Rest So I Will Just Update Dec 21 Nov 19 2013 Amritsar Distance Is Index To Subscribe Maximum On Distance Between You To 9 Setting On Is Not Want To Know From This Maximum Subscribe Reset Seth But This Addictive View From This Point Virver Distance From Only 498 Updated Datefabe Skin 10 We Can-Yes We Will Do Subscribe Button Video Maximum Per Distance Davidson Point Subscribe Now To Receive New Updates 216 Index From This Deal This Day Reachable Dedicated Patience Sum Points on the left side of this intense prayer which causes to make a long jump handsfree off but even more than the current To reach subscribe will not be able to this post our example which example only difference is not in the previous 300 will take available reachable which will initially 2011 process from this au from this point index maximum intellect which can be reduced taxes which resembles they will update No I Will Be Attentive Where They Can Reach Maximum 21 Great Quotes Will Updated From 2nd Maximum 4600 Will Updated The 26 Subscribe Now To Receive New Updates 686 Will Not Updated On Quotes 66 We Can Jump Is Will Move To The Point Not Disappointed You Can See Only 6 points Amazon medium distance trains will stop the return for this is not reachable from the return of Rebel currently not go beyond this will return of the world subscribe channel subscribe channel subscribe channel duty chala stand 19 feet battery saver British your New Hind this website More than Subscribe They will update the distance to the receiver Distance from which will not be reachable subscribe The Channel subscribe Skin will Kundru without doing any such act for the time complexity of the central Gautam is just once Vishya must have single traversal and space complexities one only Hope You Are Able To Understand Solution And User Principle Solution In Different Languages And Comment Section Everyone Can Benefit From Languages And Comment Section Everyone Can Benefit From Languages And Comment Section Everyone Can Benefit From Like Share And Subscribe My Channel Like This Video
|
Jump Game
|
jump-game
|
You are given an integer array `nums`. You are initially positioned at the array's **first index**, and each element in the array represents your maximum jump length at that position.
Return `true` _if you can reach the last index, or_ `false` _otherwise_.
**Example 1:**
**Input:** nums = \[2,3,1,1,4\]
**Output:** true
**Explanation:** Jump 1 step from index 0 to 1, then 3 steps to the last index.
**Example 2:**
**Input:** nums = \[3,2,1,0,4\]
**Output:** false
**Explanation:** You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 105`
| null |
Array,Dynamic Programming,Greedy
|
Medium
|
45,1428,2001
|
412 |
and answer of I equal to I as a string which we should written there if none of the upper conditions are true so let's say the given n is 3. then the answer array you have to write an answer that is one index which the indexing should start from what so 1 comma 2 comma 3 so from 1 till the nth number we could see one uh if at first we have to check if they are divisible by both 3 and 5 how do you check for disability equal to 0 if both the visibility happens true in such case created Facebook how do we do if we look into the answer it contains an array list of type string so we have to declare the error list that is of type string and Name by answer so answer equal to new arraylist so once you have this how do you add the elements to the at least if both conditions are to I modulus 3 is equal to zero I modulus 5 is equal to zero then answer Dot add off here that feasibles if this case becomes wrong then we check for single conditions of these two that is if it is only divisible else it will be only divisible by 3. that is true then you have to do answer dot add a fish next again else condition else if condition that is true than Earth you add bus if none of these cases happen you just need to add I but how do we need to add I as a string so what do you mean by that if you see the answer your eyes is in the double quotes right because other list of type strings we have to return that assist you but we know that I is an integer so how do we written I we cannot do answer dot add of who answered dot add off I know this is not possible this will take i s is true or else we cannot give particularly one or two that is not possible how do we do so given I convert into string given in integer I convert into a string using the function we know integer is given dot two string of I so this has to be entirely has to be added two answers so answer Dot add of this integer to string of I this is the last case so quickly we shall record this at first very decline an arraylist or type integer not type sorry string yes and that is named as answer equal to new array list so run the follow for print I equal to 1 because sum must have decided from 1 here and answer is one indexed so we start from I equal to 1 Plus if I modulus 3 equal to 0 and I modulus 5 equal to 0 that is true then answer dot add off is push every single case else if I model is 3 equal to 0 then answer dot add off this I receive next connection I model is 5 equal to 0. then answer dot add off bus last will be the else part will be answer dot add off we have to convert I to string so integer dot to string of I so at the end we return answer okay yes successfully submitted if you haven't read us please drop it in the comment section will come up with another video next session and please subscribe to the channel for more such videos and keep learning thank you
|
Fizz Buzz
|
fizz-buzz
|
Given an integer `n`, return _a string array_ `answer` _(**1-indexed**) where_:
* `answer[i] == "FizzBuzz "` if `i` is divisible by `3` and `5`.
* `answer[i] == "Fizz "` if `i` is divisible by `3`.
* `answer[i] == "Buzz "` if `i` is divisible by `5`.
* `answer[i] == i` (as a string) if none of the above conditions are true.
**Example 1:**
**Input:** n = 3
**Output:** \["1","2","Fizz"\]
**Example 2:**
**Input:** n = 5
**Output:** \["1","2","Fizz","4","Buzz"\]
**Example 3:**
**Input:** n = 15
**Output:** \["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"\]
**Constraints:**
* `1 <= n <= 104`
| null |
Math,String,Simulation
|
Easy
|
1316
|
1,817 |
all right let's talk about the final user active minutes so you have a locked log array so log i represent id and time so the multiple user can perform action simultaneously and a single user can perform multiple actions in a seven minutes but the problem is uh the uam the user active minutes for a given user is defined as a number of unique minutes so basically uh this question i reread the question a couple times and i still didn't get it uh until i see some other explanation so this is pretty much a solution so here's it so the id 0 so i have id i have minutes right so id 0 uh you start or you do the work at minifi right you know i do y you do the word mini 2 and then id 0 you do a minute 2 id 0 to mini 5 and then 1 you have uh 3 mini 3. so the idea is like if you have a segment even though it's actually duplicate you cannot use it so you get rid of the file right and uh for every single id uh this is the size of two right so when you want to return the value and then you have an array in array size of k so size of k of a new end size of k right so you have started from one to k right and then this is size of two right so it's going to be um okay so initial you have zero right so imagine this size is five and there's a size of two and basically just uh increment one and then you have another id which is size of two so you increment your size of two which is two so therefore the answer is actually 0 2 0 and the second idea for this one um you have 1 and then the time is 1 2 is actually 2 and 3 so this is size of one size of two so size of one section two following array so this question is pretty straightforward we can actually use a hash map so look at it this is a key this is a set right you cannot have duplicate so this is pretty much it and then you create an array to traverse the hash map and here we go so i have attached map i have indigo and i have essence and that's a story major right i'm gonna tell map and then you have me now i traverse a lot all right and then i need the initial on my headset right so the method put it after so i'll put a lock new apple id and then i'll initiate a set right then i will get my id first and then i will add a number to the hash size right now i need to create an array i'm going to go result i'm going to go new in k size of k return result right and then i need to traverse my map uh so it will be in k e so it's going to be map of keystone right now i need to uh increment based on the size of the current key right so it's going to be resolved at network size right and since we're sorting from a risk this uh starting is zero so you need to subtract by one increment so this is pretty much a solution and submit all right so let's talk about time in space so this is going to be space and this is space as well this is all of k this is all of n and definitely all of n is greater than o all of k so this space is all the fun and this is all the fun for the time and this is all of the size of the map but size of the map is always uh less than normal right so time uh it's going to be olefin as well so this is a solution and i will see you next time bye
|
Finding the Users Active Minutes
|
calculate-money-in-leetcode-bank
|
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`.
**Multiple users** can perform actions simultaneously, and a single user can perform **multiple actions** in the same minute.
The **user active minutes (UAM)** for a given user is defined as the **number of unique minutes** in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it.
You are to calculate a **1-indexed** array `answer` of size `k` such that, for each `j` (`1 <= j <= k`), `answer[j]` is the **number of users** whose **UAM** equals `j`.
Return _the array_ `answer` _as described above_.
**Example 1:**
**Input:** logs = \[\[0,5\],\[1,2\],\[0,2\],\[0,5\],\[1,3\]\], k = 5
**Output:** \[0,2,0,0,0\]
**Explanation:**
The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once).
The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.
Since both users have a UAM of 2, answer\[2\] is 2, and the remaining answer\[j\] values are 0.
**Example 2:**
**Input:** logs = \[\[1,1\],\[2,2\],\[2,3\]\], k = 4
**Output:** \[1,1,0,0\]
**Explanation:**
The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1.
The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.
There is one user with a UAM of 1 and one with a UAM of 2.
Hence, answer\[1\] = 1, answer\[2\] = 1, and the remaining values are 0.
**Constraints:**
* `1 <= logs.length <= 104`
* `0 <= IDi <= 109`
* `1 <= timei <= 105`
* `k` is in the range `[The maximum **UAM** for a user, 105]`.
|
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
|
Math
|
Easy
| null |
1,920 |
hey everybody this is larry this is me going over q1 of the weekly contest 248 built away from permutation uh hit the like button hit the subscribe button join me on discord let me know what you think about this problem um yeah and i usually go over this in my discord after the contest so if you're into doing contests uh come to discord and hang out because i don't know how to feel like they're not that many uh groups doing that but anyway this farm is built away from permutation so this one i don't think i don't know to be honest if you're watching this thanks for your support i don't know why you're watching this per se this is pretty straightforward once you took the time to really read it i was really slow on reading it but well yeah after i kind of really understood it was just a folder right you just basically mapped an answer away to index to the numbers of index which they even tell you in here so i don't know i would just it's just kind of weird to read and especially if you're trying to read it quick but that's all i have for this one uh obviously it's gonna be linear time so yeah um and in your space if you want to go over that which is output sensitive and lower bound um that's all i have stay good stay healthy um and you can watch it watch me solve it live next loading oh it's my internet or is it their internet it's hard to say looks i'm not going to get a quick q1 but that's okay let's go focus say what um is that someone like that oh everything is slow today also that's not the right answer hmm maybe i don't know how to do this okay now just this way everybody just tell you but okay fine okay that was hard to read uh yeah thanks for watching everybody hit the like button to subscribe and join me on discord let me know what you think about this farm uh it was a tough contest so i hope you did well uh yeah stay good stay healthy to good mental health and i will see you later bye
|
Build Array from Permutation
|
determine-color-of-a-chessboard-square
|
Given a **zero-based permutation** `nums` (**0-indexed**), build an array `ans` of the **same length** where `ans[i] = nums[nums[i]]` for each `0 <= i < nums.length` and return it.
A **zero-based permutation** `nums` is an array of **distinct** integers from `0` to `nums.length - 1` (**inclusive**).
**Example 1:**
**Input:** nums = \[0,2,1,5,3,4\]
**Output:** \[0,1,2,4,5,3\]
**Explanation:** The array ans is built as follows:
ans = \[nums\[nums\[0\]\], nums\[nums\[1\]\], nums\[nums\[2\]\], nums\[nums\[3\]\], nums\[nums\[4\]\], nums\[nums\[5\]\]\]
= \[nums\[0\], nums\[2\], nums\[1\], nums\[5\], nums\[3\], nums\[4\]\]
= \[0,1,2,4,5,3\]
**Example 2:**
**Input:** nums = \[5,0,1,2,3,4\]
**Output:** \[4,5,0,1,2,3\]
**Explanation:** The array ans is built as follows:
ans = \[nums\[nums\[0\]\], nums\[nums\[1\]\], nums\[nums\[2\]\], nums\[nums\[3\]\], nums\[nums\[4\]\], nums\[nums\[5\]\]\]
= \[nums\[5\], nums\[0\], nums\[1\], nums\[2\], nums\[3\], nums\[4\]\]
= \[4,5,0,1,2,3\]
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] < nums.length`
* The elements in `nums` are **distinct**.
**Follow-up:** Can you solve it without using an extra space (i.e., `O(1)` memory)?
|
Convert the coordinates to (x, y) - that is, "a1" is (1, 1), "d7" is (4, 7). Try add the numbers together and look for a pattern.
|
Math,String
|
Easy
| null |
191 |
Hello friends welcome to my channel here solve C problems and prepared to the C interview today's problem number is 1 191 number of one bits write F function that takes the binary representation of the insigned integer it Returns the number of one bits it has El known as the harming weight mhm so let's solve it actually this problem is extremely easy so if you can see example one it has n in binary representation and we need to count ones in this number how we do it so we Define some variable answer equals to Z and while n greater than zero we will uh check the bit of the last ah we checked if the last bit has one or zero in case of one we increment we will increment answer how we check the last bit to do it we can get mod one mod 2 of n model 2 as a result we will get the last bit after it we will divide n by two uh it moves all bits to the right so second bit will be on the first place and in the next iteration we will check second bit let's do it in the code first of all let's create answer variable and return it and in while loop let's check while n greater than zero increment answer modular n mod 2 so if the last bit is zero uh we will increment answer by zero in case of one increment by one and the last thing division by two so that it solution let's check test pass submitted this solution has time complexity of n because it depends on the length of n in binary representation and memory complexity of one because we only need answer variable so that's it for today thanks for watching see you tomorrow bye
|
Number of 1 Bits
|
number-of-1-bits
|
Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the [Hamming weight](http://en.wikipedia.org/wiki/Hamming_weight)).
**Note:**
* Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
* In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 3**, the input represents the signed integer. `-3`.
**Example 1:**
**Input:** n = 00000000000000000000000000001011
**Output:** 3
**Explanation:** The input binary string **00000000000000000000000000001011** has a total of three '1' bits.
**Example 2:**
**Input:** n = 00000000000000000000000010000000
**Output:** 1
**Explanation:** The input binary string **00000000000000000000000010000000** has a total of one '1' bit.
**Example 3:**
**Input:** n = 11111111111111111111111111111101
**Output:** 31
**Explanation:** The input binary string **11111111111111111111111111111101** has a total of thirty one '1' bits.
**Constraints:**
* The input must be a **binary string** of length `32`.
**Follow up:** If this function is called many times, how would you optimize it?
| null |
Bit Manipulation
|
Easy
|
190,231,338,401,461,693,767
|
1,637 |
hello everyone welcome to my programming club today we will be solving another daily code Challenge and the challenge name is widest vertical area between two points containing no points so let me explain this problem statement in my own words uh basically what you are given is you are given an 2D array a 2d array of points or say coordinates where X and Y coordinates are given to you for each point and so on there are let's say n number of points okay and this whole array 2D array is points AR so what the question or the problem statement ask you to is you have to find the maximum width between two points such that there are no other points between those two points on the X AIS along width along the x-axis so we are not concerned with the x-axis so we are not concerned with the x-axis so we are not concerned with the y-axis here only xaxis we are concerned y-axis here only xaxis we are concerned y-axis here only xaxis we are concerned with you can read the problem statement also if you may like uh here it's given that there are n points on a 2d plane where each point is represented by X and Y coordinates return the W widest vertical area between two points such that no points are inside that area Okay the vertical area is an area fixed with of fixed width extending infinite long along Y axis okay so we are not very much concerned with what the y coordinate will be only x coordinate will be taken into account it is assumed that uh it is y coordinate will be extended infinitely as mentioned in this problem statement okay the wide widest vertical area is the one with the maximum width so you have to return what will be the maximum width that can be possible just that uh in between two points there are no other two uh no uh points in between okay so this is what you have to return Also let's have a look at the constants also size of the array will be of order 10 to power 5 and as you can see there are two coordinates in each point x and y and those will be ranging from 0 to 10 to^ to^ to^ 9 okay so let's take a example then we will be able to understand uh in a clearer way how the approach to solve this particular problem goes let's take this example the second one let me zoom in I think it should be clear now okay so let's uh first of all as we are not concerned with uh Y coordinates I will not be bothering about them okay so I am just let's say deleting them for now okay so let's arrange them in ascending order on the number line okay so first this one will come whatever the y coordinate me I am right now denoting it with Y only so then again there is a one again okay and then there is five then there is eight in between I think we missed three so it is so one we have taken this we have taken and this we have taken now comes five okay and then comes eight okay and then comes N9 okay we are not concerned with Y coordinates only x coordinates so we are sorting the points according to x coordinates in ascending order points according to x coordinate in a sending order also you may ask why only in ascending order why not in descending because it's uh it makes sense uh since on number line it will be starting from zero and then 1 2 3 is also in ascending order okay so ascending order now you just have to pick two consecutive Pairs and see what's the difference here it's zero here it's between 1 and 3 it's two here it's three and then here it's one okay so what's the maximum one I think three is the maximum one this one so you will be returning three that's pretty much it for this problem uh this is the approach and let's have a look quick look at the implementation okay so since we are not concerned with uh Y coordinates so we will only focus on x coordinate of each point and we will be sorting each point uh sorting uh this points array according to x coordinate uh according to x coordinates okay and then in ascending order then we will be finding out the maximum width which also satisfies the condition that there are no two points in between any two consecutive points since they are in sorted order so then for each pair of consecutive points pardon me if some spelling is incorrect I hope it does not affect understanding of the approach then for each pair of consecutive points uh you will we will find the width and update maximum width you will take your maximum width zero since it may happen that a point is repeated according to the x coordinate why does not matter really here so we will be starting with zero width okay and then we will simply return our Max width that's pretty much it for this problem then we will return Max width okay so that's how we will be solving this particular problem if you are having any doubts or any queries in general then please feel free to ask them in the comment section thank you for watching have a great day ahead
|
Widest Vertical Area Between Two Points Containing No Points
|
string-compression-ii
|
Given `n` `points` on a 2D plane where `points[i] = [xi, yi]`, Return _the **widest vertical area** between two points such that no points are inside the area._
A **vertical area** is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The **widest vertical area** is the one with the maximum width.
Note that points **on the edge** of a vertical area **are not** considered included in the area.
**Example 1:**
**Input:** points = \[\[8,7\],\[9,9\],\[7,4\],\[9,7\]\]
**Output:** 1
**Explanation:** Both the red and the blue area are optimal.
**Example 2:**
**Input:** points = \[\[3,1\],\[9,0\],\[1,0\],\[1,4\],\[5,3\],\[8,8\]\]
**Output:** 3
**Constraints:**
* `n == points.length`
* `2 <= n <= 105`
* `points[i].length == 2`
* `0 <= xi, yi <= 109`
|
Use dynamic programming. The state of the DP can be the current index and the remaining characters to delete. Having a prefix sum for each character can help you determine for a certain character c in some specific range, how many characters you need to delete to merge all occurrences of c in that range.
|
String,Dynamic Programming
|
Hard
| null |
445 |
Hi apni sister absolutely back tu take ranaaj in this video we will be discussing a problem statement numbers so what have we given in this question create two non empty lists and what are those two non empty lists telling non negative inteasers ok And what it said is that the most significant digital will come on the first position, okay and H of there note container single digital, all the notes in my link list, what will they contain, it will contain a single digital okay and add you Number and D are the sum of the link. Your number has to be added to both the links and the sum has to be returned. Add the numbers in both the link lists and add in the same way. I have to return that 7 8 0 7. This is the first thing to be returned. If this was my number then how could I simply add the number 72 five six four so four plus three equals you 7 and 6 + 4 = 10 1 will go in my carry and 7 and 6 + 4 = 10 1 will go in my carry and 7 and 6 + 4 = 10 1 will go in my carry and 5 + 2 + 1 is 8 and this is how much Mine will go 5 + 2 + 1 is 8 and this is how much Mine will go 5 + 2 + 1 is 8 and this is how much Mine will go again to 7, so what is this to me? If I get some answer, then what am I doing? I am going to sum every value from here onwards. If I have any value greater than 10, then carry it and send it to your next digital payment. Okay, so this is my question, I am talking about whose numbers, so we can easily sum them, but whenever I talk about English, what am I seeing? First, I am summing these two, then I am trying to sum myself here. When I am moving, something is happening that the pointers should be in this direction of mine, but the Singrauli Lingli is fine, in that we only have the path to go forward, fine, we have our previous note near this note. If the address is not loaded, then what do I have to do with both my lists? If I have to reverse it, I will reverse it. So, I have explained my reverse logic player in it very well, so you see it once, how will I reverse it? And who will you point to? Seven is fine, what will happen to me is four, my limit will be noted, four will be my limit, then I will find six and the six is mine, who will I point to, five, six is mine, who will I point to, five, six is mine, who will I point to, five, so what I have done to these two lists here, I have simply reversed them. I simply because now I had to move in this direction, now I simply what can I do while moving from here, you can calculate your SAM, so first of all see what will I do, I will take the dam note, what will this do to me? You will get help, there will be a reference note that what will happen to me next, it will be the head of the link list with my Sam, so here Pay P is the point, initially it will point to Dami, so see what I was doing here, I was also forwarding my carry, so I If one carry is also required, what will be the initial carry? For zero, I need two pointers. C van and C are ok, so the value on C van is three. The value on C2 is four. 3 + 4 + what is the carry value? If it is 7 then 3 + 4 + what is the carry value? If it is 7 then 3 + 4 + what is the carry value? If it is 7 then what will I do, I will make my 7 a note of 7, whom will I test next to the previous one, where will I take the seven note and the previous one, I will take it on seven, okay and I see, it was my seventh now, so what would I carry? I will divide it by 10, which is my actual value, so 7/10 is zero, so from here, my 7/10 is zero, so from here, my 7/10 is zero, so from here, my carry forward will be how much zero. Okay, if these two notes are reduced, then I have to change my C1 to C1. K will have to come next. C2 will have to go next to C2. Now I will do it again. What is zero plus four plus six? What is 10? So here comes a reminder, usually 10's is zero, so zero is I will make a new note. Okay and Which one will I attach next to my previous one? I will attach my zero note. I will take the previous one next to the previous one. That zero will get a point. Okay and how much was my value in it? 10/10 So for this, what I have done in it? 10/10 So for this, what I have done in it? 10/10 So for this, what I have done here. How many vans will the carry be propagated from? Okay, and I have added these two notes to both these lists, so C van will go next to my C van and C2 will be next to my C2. Now again I One plus two plus five, how much is 8? So I will create a note named eight and attach 8 next to the previous one. I will go next to the previous one and from here, how much will my carry be? It will be 8/0. So how much will my carry be? It will be 8/0. So how much will my carry be? It will be 8/0. So from here, which will be My carry will be propagated, that zero will be propagated, let's clean it up a bit, okay carry will get zero from here and what I have to do is move my C1 and C2 pointers also to my next, okay C1 pointer will point to me here and C2 pointer will not be mine but in this case, how much is my carry zero and how much is C1 is 7 and see what I am taking in C2, place C2 is mine or C1 is mine, whoever will point to it, then I will give it to him. If this is my tap, then I can add zero to it, will there be any difference from zero otherwise what am I doing, how much is 7 and which one am I attaching next to my previous one, I will attach seven and take the previous one next to the previous one, okay and I What am I doing, I will move my current to the next current and the carry which will remain is 7/8, my carry will become next current and the carry which will remain is 7/8, my carry will become next current and the carry which will remain is 7/8, my carry will become 0 again, so my life becomes null, C2 becomes null and my carry also becomes zero, so in this case I stop. I will do it because I have added all my notes and the carry that I was propagating has also become my zero. Okay, and then what will I do, I will tap the next one of my dummy, then it will disappear from here. It will be fine because what I said was that I was reversing both my linklists so that I can easily move in this direction but this will not be my answer. What will be my answer? What will I have to do again for this? I will have to reverse my I will have to reverse all these, so my answer will be something like this: something like this: something like this: seven will point next to eight, zero will point next to zero, what do I need first to point again to zero? I need a help function of my own, River Set, so I copied it and what will I call it, I will call it my reverse and both of them will be head for one of mine, this is the white logic, how am I writing it, so you can see it from there. The previous one is fine and where will my previous one go on the current one and where will the current one go on the English one, who will have to find it, okay this one has become my reverse one, now this video ad, if you talk about number then watch it. If my student is null or in the list, I have to return such a list, not equals, you will not be different, then I will return this list, respect to vice, if both of these are miss, what will be my logic, what should I do? What I do before creating was I was reverse my album ok and reverse this I reversed both the list and after that what I am doing is list will be note which will point to the initial dummy and a c1.25 If any value is kept out of these three, then let me travel and I also have to give zero, okay and then here I will take the value, well C1 dot C1 not equals tu agar null hai because it is possible that anyone can be my null. So if it gets canceled, I do n't do C1.9 in it, then what will I do in it, n't do C1.9 in it, then what will I do in it, n't do C1.9 in it, then what will I do in it, if it does n't take my seat, what will I do in it, okay and then what I told you, what we are doing is making a list note. Or I tell him to delete it, okay, the new list note value is okay and the one that will be my carry, how much will it propagate in the next, that will be my value divided by, okay, so what happened to both of these, I made a new note in it, I added my Sam's one. Gave value to the team, what do I have to do, who to attach in the next of my previous, to attach my digital okay and where to move the previous, this one will also be less in the next of the previous and if my life is not equals you are null. So I have to take C1 also to the next of C1 and if my C2 is not equal to null then where to take me for that seat ok next bring situ also ok next this is my simple reduced I am here If I come out of it, what will happen to me who will be the head of my list? This is my list. The one who will be the head of the list note, whom will he point to? The next note of his dummy is fine and I also have to remove the dummy note. What about the next note? I will do this will make my dummy connector, the dummy is fine, I have to reverse it to make it, then I ran it. Accepted and Submit and Thanks for watching the video mix you check out my link list play list.
|
Add Two Numbers II
|
add-two-numbers-ii
|
You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first 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 = \[7,2,4,3\], l2 = \[5,6,4\]
**Output:** \[7,8,0,7\]
**Example 2:**
**Input:** l1 = \[2,4,3\], l2 = \[5,6,4\]
**Output:** \[8,0,7\]
**Example 3:**
**Input:** l1 = \[0\], l2 = \[0\]
**Output:** \[0\]
**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.
**Follow up:** Could you solve it without reversing the input lists?
| null |
Linked List,Math,Stack
|
Medium
|
2,1774
|
149 |
hi guys in this video we are going to discuss the daily lead code challenge for 8th of January the problem's name is Max point on a line Max points online it has been categorized as a hard problem however it's pretty simple to do I don't know why they have characters it has a hard problem the only thing you're required to do this problem is simple basic mathematics so let's get started with this question so the problem states that given an array points where points I is equal to x i y i represents a point on the X Y plane so these are the X and Y coordinates of the points return the maximum number of points that lie on the same straight line so for example in the first case we had three points now we can draw a line on this on the system wherein all the three points are falling on that line so we'll return three because on a single line we were able to plot all the three points what about this so over here we were having one two three four five six points in total if we do this kind of a line we could have got uh like three points on the same line so a line from here to here that would have got us three however we try to draw this line and with this line we are having four points on the same line so we'll return four so we have to just return the maximum number of points lying on a single line so how can we do this so over here one thing to note is that the constraints are pretty linear so lenient so the constraint is just 300 points in total so even a n Square solution would just require 300 into 300 that's 90 000 computations in total that was easily get done by the OJ or the online judge so yeah order of n Square would be appreciated or it would be easy to do over here or even a n Square log n or a n square root and solution should be fine n Cube might you know might fail this but yeah NK would do so we are good with that so what we can say is so since this was the points and we can draw any kind of a line right even if it's not on a point we can still draw it but it won't make sense so a line would only make sense if it's at least connecting two points then only it makes sense to make a line right at least two points should be connected only then we want to draw a line if it's not even connecting two points we won't draw a line so what we can say is that I'll be iterating for all the points so this is the outer loop and in the Inner Loop I want to iterate all the other points so yeah what I basically mean is let's say the outer loop has a point x i y i so inner loop has a point x two y two I hope this means it makes sense and the basic mathematics we know is that the slope of a line can represent a line and the slope of a line is given by y two minus y one by x two minus x one simple basic element of mathematics I hope everyone knows this at least so what we can say is in these points y two minus y two and x two and Y two and x 1 and y one this Loop would be Y 2 minus y1 by x 2 minus x 1 that is easy if we consider the outermost point at the innermost point so outer and inner point so this would be the slope what we can do is that we can use a data structure over here let us say I am using a map in order to store that in a single slope how many points are happening or how many points are occurring so I can say let it be a map of slope and then it is a so slope would also be like represented by a float and a integer can represent the number of points on that slope then what I can do cool so once I am done with this then I'll say increase my Max of slope right because I was able to add more points on through the slope itself so increase my slope and once I get out of this inner loop I can say my result is equal to maximum of result or whatever I was getting from this Loop right the maximum element I am having in this map so maximum in map that is something I can do so what next so there are there's one thing you have to watch over here so for example their duplicates Point let's say so a point can so let's say this is point a is having coordinates two and one there could be another point that is having the same coordinate so there would be one on top of the other so now when will we calcul when will be calculating the slopes for point a two this Loop right so automatically whatever point a would connect so B would also connect the same right so how can we keep a track of that so we can use a variable let's say called duplicates so we'll initialize duplicates with zero right and whenever I'll find a duplicate so a duplicate can easily be found by like we can say that x coordinate so x one is equal to x two and Y one equal to y two if that's the case then the definitely the point is duplicate and I will increment by duplicate variable at the end when I am calculating my result answer so I will add duplicate to the maximum in the map I hope this is simple to understand and this in turn should give me the result so yeah that's it one concept Still Remains so the point is that we are over here storing the float values for the slopes right so slope is basically y two minus y one over x two minus x 1 right so we are storing it in a float the problem with float says that even two values so let us say we are having let us say 2 and 10 and we are having one by five so technically both of them should have the same answer I hope you understand that at least so the answer they should be having is 0.2 the answer they should be having is 0.2 the answer they should be having is 0.2 but what happens is when we store floating points in our system so the answer could very vary by a bit so it is possible that this answer becomes 0.2 is possible that this answer becomes 0.2 is possible that this answer becomes 0.2 to zero one this would become let us say 0.20002 or anything of that sort so it 0.20002 or anything of that sort so it 0.20002 or anything of that sort so it would differ by a small number and then the problem happens is that these two would be considered as different slopes although these two should have been the same slopes so how can we tackle this so we can use a simple thing known as gcd or the greatest common divisor what we can say is that X Y 2 minus y 1 is getting divided by x 2 minus x one so let us cut out the common factors or the common devices so we'll find the gcd of both of them we'll find the gcd of D let's call it d y for E let's call it DX so we will find the GC of D A and D X and then what we can say is that when I am storing the values of the slope so I do not want to like store the entire slope what I want to do is I'll just store Y2 minus y1 divided by G and x 2 minus x 1 divided by G so that would make sense right because we are actually storing the individual values so these are not in terms of floating Point numbers they are actually in terms of decimals itself other actually in terms of integers itself so these are integers so that's fine on top of that we are actually dividing it by G so even G is a g is a divisor of them so it won't make them a floating byte number they would still be a integer value so yeah that's it about it now with that knowledge we can start coding it up while coding I'll try to explain more about it if you have any doubts I hope uh while coding it up they become clear as well so initially we are having points so the base case is if points size is just one so yeah we are simply written one I hope that makes sense then we will start iterating our points so let me call the outer Point as point one or the point in the outer loop is point one the point in the either inner loop as Point uh two so point two so what I can say is also let me create a data structure for me where I can store the slopes so I wanted to store the slope in terms of slow in terms of pairs so that's pair of intent and end so that would give me the number of points that are on this particular slope so let's call it slopes itself makes more sense at the end of the algorithm I want to return the number of points that were present so let's call it race I'll be running less after all of the computations also there could be some duplicates as we discussed so we are going to write duplicates over here so initially the duplicates is set to zero in the algorithm what we'll do is that when we are reversing over it so we can say DX is equal to 0.20 minus 0.10 and d say DX is equal to 0.20 minus 0.10 and d say DX is equal to 0.20 minus 0.10 and d y that is the difference in the Y X A Y coordinates is point to 1 minus point one and the g that is the common divisor is okay so for the common divisor we when we are taking a gcd so we need to take the absolute values it shouldn't be given with the negative values so yeah that's like this and then we can say if DX was 0 and d y was 0 so if d x is 0 that means X is equal to X1 is equal to x two if device is 0 that means y1 equal to Y 2 if both of them 0 that means it's a duplicate point so I will increment duplicate else if not if it is not that case then what I can say is that make a slope right and on to that slope add these values so that is like d x and d y so d x divided by G and d y divided by G and DX divided by G and incremented up I hope this makes sense this was easy so let's say already a similar slope was present earlier then the account would be incremented if the same slope was not present in the in this map then it would make a news Loop of this value and give it a value 1. cool so once we are done with this then I'll come out and I will say okay get me all the slopes in slopes or this would actually round represent the number of points so let's call it P right and it's appear so it should have two values actually so let's call it the first is the slope itself the other are the number of points let's call it P my result would be maximum of risk comma duplicate plus P so my result in totality could be either whatever I'm I am having as of now or the number of duplicate points because the duplicate points actually for another same uh same place so we will have to like add them up because no matter what kind of line we are drawing they would always be counted plus P so the line I was drawing whatever points were available on that particular line at the end I can return res so one thing more that you should know over here is that when I'm using this particular algorithm I initially I'm using my duplicates a zero but wait uh would that same point won't be considered because let's say when I am calculating a slope between two points A and B right so I am only saying that increment the slope by one so I'm saying that the value of this slope is one but actually the number of points on this slope is two then how are we calculating that so the way we are calculating that is that when we are using this into duplicate is equal to zero so the outer loop and the inner loop would actually run for the same element so let's say the outer loop contains the X element uh so the element index I so inner loop will also at least run once for the or would run exactly once for the element at index I so at that time DX would be 0 d y would be 0 and we would be incremented our duplicate so our duplicate is going to get incremented when the outer and the inner loop is running for the same element so yeah that edge case is also covered now let's try to run it up okay that's so error I'm getting that okay so I have taken duplicates over here let's do it duplicate the error so it's saying that okay you have taken slopes over here and you got slope so let's call it slopes yeah this works let's try submitting it up yeah this summits so yeah this was the solution for this video I hope the problem looked easy to you although it had a hard tag with it if still you have any doubts let me know I'll be more than willing to help you out thanks a lot guys
|
Max Points on a Line
|
max-points-on-a-line
|
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_.
**Example 1:**
**Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\]
**Output:** 3
**Example 2:**
**Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\],\[2,3\],\[1,4\]\]
**Output:** 4
**Constraints:**
* `1 <= points.length <= 300`
* `points[i].length == 2`
* `-104 <= xi, yi <= 104`
* All the `points` are **unique**.
| null |
Array,Hash Table,Math,Geometry
|
Hard
|
356,2287
|
1,704 |
So today we will not make labor in which we will slowly challenge the late December and solve all the problems. Today the first question is so determine if strings are half alive so let us look at this question on the right foot like come man take we have some swing given. Like it is given in book, then we have to divide them in equal half and this will always be the same given to us. If it is given in question, then we have to divide it in one more half, the vowels in both of them are equal. For example here. There is a vowel present o We can see here there is a vowel present and here there is a vowel present which is o So we can say that this is our string so it has this condition which is here which vowel is our. Hain A I O U anything can be present here and it can be small or it can also be capital, so by dividing both of these strings in equal hands, the number of vowels in both of them is equal. When it comes, we will tell him that our equal is dead in hand, okay, so we have to simply return row, like in this case, we can see that in both of them, OK, our value is equal to 11, so we will return that which is sting. Answer will be our output, we will return true, we will simply, so if we have given the second text book here, okay, then we will divide here, okay, then the value is here, the value of A is over, so we see. We can say that the bubble here is different from the other hand and here the number of A is different, the number of A here is different, so I can say that we will return half in this, it will be False because here the number on pay ball is also not equal on both the sides then its code will be quite simple, we just have to check that both of our halves are equal, there should be some vowel present here where both the accounts should be equal. So here, like I have written the code here, as if our time is not wasted in the court, then simple will be given in our function, so what will we do, first we will check so on, we will check here, we are present here and if vowel. If present then we will store his account, then just like that, what we will do is that we will search here, we will put a loop here, from zero to half of the length and we will count here the number of bobbies who will be present and we will put it here. We will put a loop in half and check the length of the bobby here and then we will return it. If both of them are equal then you will just get the result 'A' as if you are you will just get the result 'A' as if you are you will just get the result 'A' as if you are seeing by hand that if there is a capital letter here or there is a question. Can be long and small, then AIOU, if we give, we will fall. Okay, now we have done count plus, here we have also done corn plus, and if the accounts of both are equal, it means that which is Ours will come out and we will give it to him, like here the value of both is different, Van and Tu are coming and here we will pay A and here we will return the discussion of falls, if we submit it, follow the series and I have given its solution in the description below. Kindly check it out. Thank you for watching this video. See you in the next video.
|
Determine if String Halves Are Alike
|
special-positions-in-a-binary-matrix
|
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half.
Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters.
Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "book "
**Output:** true
**Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike.
**Example 2:**
**Input:** s = "textbook "
**Output:** false
**Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike.
Notice that the vowel o is counted twice.
**Constraints:**
* `2 <= s.length <= 1000`
* `s.length` is even.
* `s` consists of **uppercase and lowercase** letters.
|
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
|
Array,Matrix
|
Easy
| null |
127 |
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem but before going forward if you have not liked the video please like it subscribe to my channel and hit the bell icon so that you get notified whenever i post a new video so without any further ado let's get started so problem is word letter it's very basic problem uh let's see what the problem is a transformation sequence from word begin word to word end word using a dictionary is a sequence of words such that every adjacent pair of words differ by a single letter that means what they are saying that we have to find a transformation sequence from a begin word like this begin word is given hit is given and we need to go till the end word that is cog we need to start from hit and we need to go to cog and how we have to transform this word hit to cog we have to every time differ we have to every time change a single letter that is if you see here this hit this word hit is changed from hit to hot and there is only one letter difference between both of these i and here it is o then from this hot it's changed to dot and in this there is again a single letter difference h and d similarly from dot to dog here t is different here it's g so only every time one word is getting changed like one sorry one letter is getting changed and every time all these words should be in the word list this word list is given in the problem and all these words which we will create like which we will change to all those words should be in the word list right so let's uh over here the end word is cog so here we reach to cog but see this cog is also present in the word list let's see the second test so in the second test case we have hit begin word is hit and end word is cog but if you see cog is not in the word list hence we cannot reach we cannot uh create cog from this word begin work so output will be zero there is no valid transformation sequence so all these words hot dog dot dog see all these are in the word list then only we can convert into this word right so i hope you understood the problem what the problem is let's see how we can approach it see this is the begin word which is given to us and these all are the words in the dictionary that is this uh this list which is given to us now all these words here are from that list so see what we have to do we have to every time see this word is hit is given to us now we don't know which letter to change we can either change h also we can either change i also or we can change t also right now over what we are over here what we are doing is we are changing this hit to hot that is hit too hot so here what is changing i is changing to o and rest of all the characters are same h is same t so here i is changing to o but this i could be changed to any letter from a to z we don't know that this will be changing to o we don't know that we can change this i to any letter between a to z so how many see how many uh like ch possibilities could be there from this h i could be changed to a and then it could be hat then from this i could be replaced by b so h b t could be then it could be h c t so every time this i could be replaced by any letter from a to z right now here we are replacing it with o right now do you think this word could be taken as a possibility no why because this word hat is not in the word list it's not here so we cannot use this so this is not a valid case why this hot was a valid case where we are changing i to o because this hot was present in the word list that is if you see here in the second question they are saying that a second point they are saying that every s of i s i means every word which is we are creating these all words these should be uh in the word list and they're saying that begin word is not necessary that it will be in the word list it's not necessary that begin word should be in the hotly in the word list see over here hit is not in the word list but the end word should be in the word list this cog should be in the word list it's not here so output is zero so one thing like which we got it from this problem as of now is that this word could be like each letter because we have to change one letter only one letter if you see over here between all these words only one letter is changed adjacent pair of words differ by a single letter only one letter is changed so any letter we have this word hit this word is there which is hit each letter of this word either we can change h could be replaced anything from a to z or what we can do is we can replace i with any letter from a to z or what we can do is we can replace this t with any letter from a to z right over here what we are doing is we are changing this hit to hot so we are choosing this thing and in this we are replacing this i with o a to z from a to z we are choosing o letter and we are replacing i with that and this hot is present in the word list that's why we are choosing this word right so this is one thing clear this is clear that okay how we are choosing the letters and how we are converting them so we can change this also this i also now see what we have to do is if you see over here this thing is clear i hope this is clear now let's move to the second part of the question so see what we were doing is we were converting hit to partner and then we have to check whether this hot is in this word list or not right now it's a list so if we have to search for this hot whether this hot word is in the uh list or not we have to search in the list so that will be of end time is there any possibility that we can do the searching in o of one time could can we do that yes we can do that we can use either unordered hash unordered map we can use either unordered map or we can use unordered set so since here we just only need to store these words there is no key value pair some like sort of thing so we can we only just need to store these words so we will be using unordered set let's have our unordered set in another set searching is of one so it will be o of one time to search this hot is in the set or not that is it's in the word like these words or not so this is second thing which we saw from the uh problem so two things we have seen till now let's see what algorithm we will use to get to the end word how we will reach the end let's create this thing first we are changing hit to what then we are going from hot to dot and then from dot to dog we are going and went from talk to so this is happening right every time see a single letter is only changed a single letter is being changed here i is changed then here b is h is changed then from here its t is changed and from here its dns c is changed right now if you can see this is a path right this is a path you are starting from this and you're reaching here so this is chart this is end this is start this is end if see you can visualize this as a graph how these all are the nodes of the graph and this is a starting node and this is the ending node which you have to reach from this you have to go to all the paths so see from this hit also we can there could be a possible way to go to uh we can change this i to a let's say so this could also be a path but this is not a valid path why will not choose this path because hat is not in the word list so that's why we will go to this path from this hit you can also change it to hct i or you can change this h i t to h you can replace with g so g i t get but you will not go to these parts because these are not in the word list similarly for this let's say dot you can change this dot to you can see you can change it to court d you can change to c but you will not go to this path because this chord is not in the word list so this could be visualize as a graph where there are multiple parts and you have to go to the correct part path at the end and now which algorithm which graph algorithm you can choose either you can choose dfs or you can choose bfs so what will be beneficial using here is c in this problem what you need to do you need to find shortest transformation sequence now short test wherever the shortest word come now bfs will be used bfs right so we will be using bfs here right let's say let's see how now let's see how so we have thought that okay we will be using graph and we will be using bfs so let's see how we can do bfs so this was hot right so this was hot yeah now let's start the traversal so in vfs we are doing bfs traversal in bfs what we do we uh now we are doing dry iron so let's see that we are over here taking a q this is a queue q and initially in the queue we will be adding hit the begin word which is given to us in the problem this hit is given to us right now see what you will do is we will also in this kuna what we will store we have to store how many uh we need them these how many words we have to do so how many transformations so 1 2 3 4 5 transformations so 5 is the answer let's store that also so here we can do one thing we can store this we can take a variable ladder and initially we can give it value one or let's not take this right like that uh we can do one thing this in the queue we will be storing what we will do is in the queue we will be storing a pair of the beginner word like the word hit and right now how many transformations it requires so from this one transformation will be done so we can give one here right see now initially we are like we are taking one because oc one transformation will be required now so we are taking one here right so now let's start the traversal so see what we will do we will pop this from the queue this gets popped so what is hit what is it and right now this uh count is one so this hit word now we can choose each letter of this word and we can replace it with a to z letters right so we will have a loop this for loop will pick each letter h i t so this will pick each letter so let's say we have first h so this h could be replaced from any letter from a to z so there will be again a loop for a to z and we will be changing this h to a then we will be changing it to b then we'll changing it to c like that we will be doing that right so let's say what we do over here is but yeah we will be changing but see none of this will be in the so let's take an example for this only see what we do is uh let's say we have replaced this edge with b i t bit now we will check whether this bit is in the word list or not it's not no so we will not take it so in this way none of a from a to z if you replace h with a two z any letter none of this those will be in the word list so none of them will be taken in the queue now let's do one thing now uh we will take letter i let's take letter i so this i will be replaced from a to z so let's say this uh i we are replacing with o h i will be placed with o and t right so h o t we are doing it now we will check whether this in the word list yes it's in the word listener so now this will be added in the queue so in this queue so that now we can take this so from now we will be taking this hot and will replace its letters so hot will be added in the queue and its count will be one we will now because after we have done one trans uh transformation we have done one transformation so one is the current count since we have done one transformation from hit to what we will add one in it so one plus one will be two so here two will come right like this now what again we will do is we will pop from the queue now q does not have this q has this as the first element so we will pop this from the queue it will be hot we'll come here and the value is two so here uh what we can do is this hot uh for each letter uh let's say first of all we can from this what where we are going to dotner so we will replace let's say h we take h first letter and we replace it with d from a to z uh we will be checking we'll be changing it to each letter from a to z let's change it to h to d so d or t dot now this dot is in the uh this and so we can add it in the queue so q will be d o t and count will become three count will become 3 2 plus 1 3 also if you see then after this dot you can conver you can replace this h with l also so l ot will become h will change will be replaced from a to z to l so l o t so this ello t is also in the this lot is also in the uh word list so this also will be added in the q this could be a possibility so from this hot either we can go to dot or we can go to lot right anything could be done so both of these cases will be considered so we will add this also in the queue lot and it's also will be 3 right so now let's see what we will do so after this let's uh this will be not in the queue now again we will pop from the queue so dot will be popped out its count is three so this dot we will replace uh let's say let's uh from this dot we are doing dog so let's replace this t with g so each letter we will be replacing with a to z this dot we are t we are replacing with g so dog is in the uh q so what we will do is we will add this in the queue so dog will be added in the queue with count four right and then what we will do is uh we will go to the next in the queue so q now is lot so this lot could be changed to c we can change this slot to um log so this could be change to lot we can change this t to g so it will be log so this log is in the word list so we can add it log and this also will be 4 right so now let's go ahead now we will again this is not in the queue so we will pop this so we will have lot and its count is four this is popped so lot we have taken sorry lot we have taken already so now we will take dog this one so its count is four so this dog could be converted these could be converted to uh could be changed to c so this will be cog and cog is in is our end word so how many four plus one five transformations we did similarly also if you convert this log like here we will return the answer because we found the end word but suppose if we did not find it so from this log also we can get the end word so we can change this l to c and log cog we can get that also in five transformations four plus one so this is where this is how we will be doing it using bfs what we are doing is first of all we have taken a queue we took a queue in the starting we added the begin word and then we were popping each word and we were replacing it with each letter with the uh a to z letters and if those letters were in if those word that was created were in the word list we added them into the queue because that could be the next transformation right so let's see the code for this i hope you understood the this approach just you know like it would be very great you know informative if you dry run the code once after writing now or before writing just try it on this code once you better understand see what we are doing is we have taken the set we have taken this set uh in which we are storing all these words so that we can get them in we can search in one time we discuss this right so that o one is the searching time then after that we are taking this q and if you remember in the queue what we were adding in the queue we were adding uh the string and the current count of the transformation so here we are we have created this pair curly brace brackets and we have this begin word and the count so we are uh traversing this queue until it's not empty this is the classic vfs right this is bfs uh every time we are popping from the queue so from the queue which we will get a pair of string and integer because we are adding string an integer this is a pair which we are getting so word will be the first p dot first that is this will be the word current word and the count will be second p dot second then we pop this from the queue and then if we check if this word is equal to the end word we will return the ladder right and over here we will erase it also from the dictionary because we have already taken it so we can erase it from the uh this dict and then what we are doing is we are for we have for loop this loop and what we are doing is we are going to each letter in that word we are traversing on each letter that is if we have dog we go to d first then we go to o then we go to g and for each letter we are changing it to all the letters from 0 to 26 that is a to z that is like this we are getting the letter like this sky uh adding the current count current number in the sky of a so that we get the letter why we are storing the present letter this c let's say we have to convert from dog we have to convert to dot so here i will be converting g to t i will store this g somewhere let's see in a character see this variable we are storing this g later and then i convert this g to t and then i if this is in the list i will add it in the queue now i have to again check all the other possibilities now so that is for example uh i have to check i have to uh replace this d with all the letters so this g should be this right now my word is this dot i have to go back to this word because i have to now see for all the possibilities of this d i have to change replace it with a to z so this t could be now replaced with the earlier letter like which was earlier present so d or g and then i can change this d to c o g d e o g anything right so that's why we are over here storing this later so once we are done with it we will again replace it with the what was earlier present at this place and then we can just return 0 if this is not like a return from here so i hope you understood the problem and the approach uh let me know in the comments if any doubt if you found the video helpful please like it subscribe to my channel and i uh i'll see in the next video thank you
|
Word Ladder
|
word-ladder
|
A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`.
* `sk == endWord`
Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return _the **number of words** in the **shortest transformation sequence** from_ `beginWord` _to_ `endWord`_, or_ `0` _if no such sequence exists._
**Example 1:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\]
**Output:** 5
**Explanation:** One shortest transformation sequence is "hit " -> "hot " -> "dot " -> "dog " -> cog ", which is 5 words long.
**Example 2:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\]
**Output:** 0
**Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence.
**Constraints:**
* `1 <= beginWord.length <= 10`
* `endWord.length == beginWord.length`
* `1 <= wordList.length <= 5000`
* `wordList[i].length == beginWord.length`
* `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters.
* `beginWord != endWord`
* All the words in `wordList` are **unique**.
| null |
Hash Table,String,Breadth-First Search
|
Hard
|
126,433
|
123 |
hi everyone welcome back to my YouTube channel and today we'll be discussing next problem based on stocks which is again one of the hardest problems of Heathcote so I want all you guys to please pause the video for once and please read the question so I hope you all must have read the question for all those who have not understood the question let me explain the question for once so what the question says is that you give in an array which contains the stock prices and you can make at most two transactions and you have to maximize the profit so suppose let's take this example one two three four five so suppose they use my on this D and you sell on this thing now you can again by on this day and you say long distant this means you have completed two transactions when you put on this day and you sold on this trip this means you have completed one transaction now you're left with only one transaction so this way you have to maximize the profit so profitable first transaction was three minus one similarly profit in second transaction was five minus three which is 2 which is 4 so if you do the transactions this way the profit would be 4 you can modify the way you won to make the transactions and you have to maximize the profit this is the question so I hope you all must have got the question let's move to the approach ok so how would we approach this question so suppose this is the price array which we are given okay no I need to make at max two transactions right so and I need two Maxima is this what I would do is I can actually make a break here which means I have to do my first transaction in this sub array and I have to do my second transaction in this survey but actually I can make a break here also which means that I have to do my first transaction in this sub array and I have to do my second transaction or in this sub array so what is so my actual so if I knew what each index what is the left profit plus right profit if I calculate this left profit plus right profit for each index and then I just need to find the maximum of this right that which index give us the maximum value of this left profit plus right profit right now let's calculate the left profit so suppose I take this summary as this area as the example so I've taken this array as an example and I'm calculating left profit for each index if I only have this summary the profit is zero actually right the profit is zero because we have to buy on this degree and salome this thing so profit is zero no profit for this thing so again I have two possibilities whether to involve this be in transaction or not if I wrote this thing transaction then I have to find the minimum in the left sub array because only then I can make the maximum profit rate because when I buy when the stock price is minimum and sell on this P then only I can make the maximum profit so what is the minimum in the left sub array it is C only so 3 minus 3 is 0 or I have one more possibility which is I do not involve in transaction on this table I do know if I do not involve in transaction on this stage my profit is actually stored in the previous index only which is again 0 so my maximum would of 0 comma 0 is actually 0 now let's come to this example again two possibilities either to involve a transaction on this day if I involve in transaction the minimum in the left sub area is 3 so my profit if I involve in transaction on this day is 4 - three equal to two and if I do not - three equal to two and if I do not - three equal to two and if I do not involve in transaction on this day which means what is the profit in this severac and the profit in this sucker is actually stored at this so maximum of 2 comma 0 is actually 2 so now I move to this index the minimum among this is 3 so if I model transaction on this day it is 0-3 which is I mean a loss and my is 0-3 which is I mean a loss and my is 0-3 which is I mean a loss and my second possibility if I do not involve in transaction on this day which means my maximum profit is 2 and maximum among - 3 comma 2 is 2 so profit is this index - 3 comma 2 is 2 so profit is this index - 3 comma 2 is 2 so profit is this index is 2 similarly for this index also it will come - for this index it will come - for this index it will come - for this index it will come in - for this index also it will come in - for this index also it will come in - for this index also it will come in - and for this index also know what this - and for this index also know what this - and for this index also know what this index what is the minimum is 1 so 4 minus 1 is 3 if ah so 3 is the profit which I make if I involve in transaction on this thing now if I do not involve a transaction on this day which means the answer is so maximum 3 comma 2 is actually so this way I have calculated my answers which is a left profit for each index so this is my similarly let's calculate the right profit area for each index so if I want to find the right profit if I involve only on this T in the transaction my answer is 0 because if you buy on this day and sell on this say the profit is 0 actually now if I now for this index which involves this sub-array there are two involves this sub-array there are two involves this sub-array there are two possibilities again whether to involve a transaction with this thing which means you will buy on this fee and you sell on the day when the stock price is maximum in the remaining sub area right because you have to buy first and then only you can sell so you will buy first so in the earlier for the left of it I was calculating the minimum of the remaining severely lifts of a rake but in this case I will calculate the maximum in the heights of area so what is the maximum in the right sub-array is the maximum in the right sub-array is the maximum in the right sub-array maximum is 4 so if I involve in transactional misty my profit is 4 minus 1 which is 3 or if I do not involve in any transaction on this thing which is actually stored at this index so maximum amount 3 comma 0 is 3 similarly we calculate for this index also maximum among the right if I involve in transaction on this day is 4 so 4 minus 3 is 1 and if I do not involve in transaction on this day which means profit in this sub array is actually stored at this so maximum in 1 & 3 is 3 similarly we will maximum in 1 & 3 is 3 similarly we will maximum in 1 & 3 is 3 similarly we will calculate for this index also which means maximum 4 minus 0 is 4 and if I do not involve in transaction then my profit is 3 so maximum on 4 over 3 is 4 similarly we can fill this complete area so this way I have completed my booth Diaries which is left profit as well as the right profit now so I have got my left profit also and my right profit also now what could be my answer make update here which means I calculate my left I have to make a transaction in this submarine and I have to make my second transaction in this remaining sub-array my profit is 0 plus 4 which is sub-array my profit is 0 plus 4 which is sub-array my profit is 0 plus 4 which is 4 now if I make my transaction first transaction in this summary my answer is 4 and if I make my second transaction in this summary my profit is food so the total profit which I can make is 4 similarly we can calculate for each index by summing up to do surveys queries so now I've got my son for each and every index or each and every breath now I can easily calculate maximum among this survey this array which actually takes off in time so maximum on this array is 6 and as you can see my answer is also 6 so what is the complexity so complexity of making this left prophets uh Barrett was off in similarly cap making this right prophet array was also orphan then summing up and making this array is also often and calculating the maximum is also of M so my net time complexity is o of n right now let's move to the code of this question so this is the food so if net prices array which is which contains our prices of stocks on different days so if I if my size is less than 1 then I return 0 obviously my profit would be 0 I am making a mini array in at once which is actually calculating the minimum in the left sub array suppose this is the index so this index will contain among these three indexes for this index it will contain minimum in this array so this is my mini so this is the way I am calculating my minimum in the left array I hope you will get this good this is a very easy good similarly I am making my maximum marry which actually contains my maximum in the right and so for this index my maximum is maximum in this array for this index my maximum is maximum in this area now for this index my maximum is maximum in this array this way I am calculating my maximum will de array and I'm scoring it in the beginning of D so this is my for calculating the maximum now I have made one array for storing the left profits similarly I have made one error for storing the right profits this is the way I am calculating my left profit and storing it in the array similarly I am making my right profit and then I am calculating the maximum among left profit plus right profit for each index and I finally returned my answer oh I hope you have got this question that's it for to realize make sure you subscribe my channel and hit the bell icon so that you can get notified next time when I am on YouTube and then lots of love this is arm will sign off
|
Best Time to Buy and Sell Stock III
|
best-time-to-buy-and-sell-stock-iii
|
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
Find the maximum profit you can achieve. You may complete **at most two transactions**.
**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
**Example 1:**
**Input:** prices = \[3,3,5,0,0,3,1,4\]
**Output:** 6
**Explanation:** Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
**Example 2:**
**Input:** prices = \[1,2,3,4,5\]
**Output:** 4
**Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
**Example 3:**
**Input:** prices = \[7,6,4,3,1\]
**Output:** 0
**Explanation:** In this case, no transaction is done, i.e. max profit = 0.
**Constraints:**
* `1 <= prices.length <= 105`
* `0 <= prices[i] <= 105`
| null |
Array,Dynamic Programming
|
Hard
|
121,122,188,689
|
724 |
hello in this video we are going to discuss the lead code problem number 724 find pivot index they will give you an array as input you need to return the pivot index what is remote index if you sum the elements from the left at the same time if you sum from the elements right the total of the left side elements and the right side elements must be equal right for example if you add 1 plus 7 plus 3 you get 11 at the same time if you add the right side elements 5 and 6 you will get the total of 11 so left some left side elements sum and the sum of the right side elements are equal at this point you need to return this index what is the index 3 if you don't find any of the pivot index in the given array you just return minus 1. this is what they are saying okay how to solve this problem to solve this you need to find the total sum first of all you just run the array from left to right that is looping the array and find the total sum of the array for example 1 plus 7 8 plus 3 11 plus 3 is 11 plus 6 18 plus 5 23 sorry one seven eight eleven um 11 17 22 28 first you need to find the sum is what 28. then you need to Traverse from both side right yeah you need to find the left sum at the same time you need to find the right sum so we creating and left to position and right position okay we create an left position then right position for the left position we assign 0 because we start from this point for right position we are giving the total sum what is that 28 we just assigning as the second step then the third step most important step to solve this problem again we Traverse this array to find the left sum and write sum so I Traverse this array from layer which direction this direction okay then I add every element from left side right left side have 0 so I add every element while looping right if the name of the array is I just add every element for every iteration okay from left at the same time write is what we have the total value so I subtract what every element while it trading right when while doing this mathematical operation when left and right is equal that point is Pivot right for example I just Traverse this array first I subtract the value of first element from the from this right Point what is that 28 minus 1 we get 27 right at the same time what we get 1 right I add the first element from to the left index same day ah now this is not equal so I just move to the next element seven so I subtract a again what we get 7 27 minus 7 we get twenty at the same time what this is not equal so at the same time I add this is not equal so I move to the next element what three if three is subtracted what we get 17 right 17. if 3 is subtracted which is not equal so I add 3 plus that is what eight plus three right that is eleven ok once again I subtract 17 minus 6 we get 11. we already have the adding value of 11 both are equal at which Index this index I just return the index number as 3. right let's move to the coding path first I need to find the total sum so I assigning a variable name sum I just Traverse the loop uh sorry travel study from left to right so I greater than what is the name num start length I just completely Traverse the array then okay how we can get the total sum just adding every element for the entire Loop right nums I we will get there total sum then I create left binder and a right binder left sum equal to zero the same time in write some c equal to what we will assign the total sum value right then again I Traverse the low ah sorry array I get num star length right length I plus then what I am going to do I subtract every element right every element I also check for the rights sum equals equal left sum have some we just return that position so return I we need to move from left also right left sum plus equal to I'm sorry we just add every element from the left and the subtract if subtract from the right side if the right sum and left sum is equal at any given point of time we just return that element index if no element no such element present you just written minus one pivot nums spelling mistake sorry for that yeah he submit the problem thank you for watching
|
Find Pivot Index
|
find-pivot-index
|
Given an array of integers `nums`, calculate the **pivot index** of this array.
The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right.
If the index is on the left edge of the array, then the left sum is `0` because there are no elements to the left. This also applies to the right edge of the array.
Return _the **leftmost pivot index**_. If no such index exists, return `-1`.
**Example 1:**
**Input:** nums = \[1,7,3,6,5,6\]
**Output:** 3
**Explanation:**
The pivot index is 3.
Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11
Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** -1
**Explanation:**
There is no index that satisfies the conditions in the problem statement.
**Example 3:**
**Input:** nums = \[2,1,-1\]
**Output:** 0
**Explanation:**
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0
**Constraints:**
* `1 <= nums.length <= 104`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/)
|
We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1].
Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i].
|
Array,Prefix Sum
|
Easy
|
560,2102,2369
|
1,255 |
Yes, hello, this is Live Coding Paris. Today, we will solve the problem with lead code 1255, Maximum Score World Form by Lateral. The difficulty level of the problem is hard, but the correct answer rate is a little over 70%. As of little over 70%. As of little over 70%. As of today, March 7, 2023. Since it is a problem with a high level of discussion regarding the date, I think you can think of it as a hard problem that can be solved easily. So, we will try to solve the problem right away. Well, first, we will set it like this in the basic form. Then, we will solve the problem in the world. We're going to count. Python is quite good, and there's a kid called counter that's really good at things like this. Yes, if you do it like this, we'll have four words in this world called poison, dead good. If you do it this way, as you can see, poison has been added to the word once. The kit goes in, then the dead goes in, and then it goes in. And if you put a function like this in the counter like this in front, this doggy will count one D through the counter function, one 51 G12 a, two G1 O for g55d, and so on. So, if we print it out and run it like this, the correct answer is not important, so if you look at it, there is one D, 5 1, G1. In the second array, there is one Ciana, one T1, one D, two D, one A, etc. This is the information we want. It goes in. So, you can do the letter count in the same way. As for the count, yes, if you do it like this, it is Lettuce. If you do Lettuce like this, it will go in the same way, like how many A's, how many B's, etc. And we do the world count as preprocessing. You said you would calculate the world score in advance. This way, you create an empty array and count it. If you repeat the loop like this, the data here will be removed one by one and filled in here. And the score value we want to enter will be initialized to 0 and this world count. If you look at the way to go around the array here, if you put these two, ch and count, does it use the item of the count? If you test it like this, it doesn't put the separator, so the first one, Diana 5, G1, is output like this. As for the second gun, here we go around the outside gun gate once. This is the second time. Tiana Dead is D2 followed by A and then Good is G1. So, you can use letters like this if there are more counters, right? That word. You can make it. So, now we add it to the world score. In the score, we now have this. Since we received the input like this, we use a child called ord and subtract a from ch, subtract it like this, and get the index of the number child. If there are 2 ds that are multiplied by the score and the count, we should get double the score. If this is not the case, we are like a cat without a letter. What happens in that case is that the world score is just set to 0. Since it is an uncountable word, we will change it to 0. And since there is no need to do anything more, just apply the break. So, here, in the append of World Score, we can put it in like this. This will create the array called World Score that we want. Here, now It will call Solve by backdragging with the recovery function. Solve starts from number 0, so the current score is 0 and an initial value called letter count is passed. You can use a few a's, you can use a few b's, etc. There is information like this. If you pass those things over, we will now subtract one from the force score from the solve from the def to the in function. This should have an s attached to it. Just in case, I don't know. Let's subtract that and do it like this. If you pass it on, we will get the current position from the current position. comes in, and then the score made so far comes in, and the remaining letter count that I can now use comes in. If the ending condition is the same length, it has been given to the end. Then, in rt, I add ret or this. Wait a moment, this is it. Since it is a score, I will make this the current score. Yes, if you do this, the value below will be updated. And now you can quit. And here, in order to use the evening variable rt, in Python, it is called a non-local keyword, is called a non-local keyword, is called a non-local keyword, and so on. You have to walk. If you walk like this, there is a syntactic effect of this type that allows you to enter and use this let used as a contagious variable. So, after doing this, the world count brings the word count to the current position, and now with this child, we can now analyze it. I'm going to do it. I'm going to process something. So I brought it like this, and I get the count of the word that is currently in the current position for all of these words. If I compare all the ch in the count for all words and do this, I get the count of the word in this word. There was only one CH. If you only receive ch here, only the dog comes over, so there must be more counters behind it. If we use this d here, does it have to be one or more that we can use? If you are satisfied with ch, you can now use that word. You can make it. So, you make it. In the process of making it, originally, you simply pass one force in Solve like this, and then you put the word at the current position in the current score. You can add the score and pass it over like this, and you can do a meta count and pass over the laptop value. When you do this, you use this letter count, so you have to subtract the amount you used. The part to subtract goes here, and the part to roll it back is here. We have to enter the video, so let's start with the subtraction part. Yes, if you turn it like this, the letters used in the letter will appear, the letters used will appear in ch, and the number of questions used will appear in the counter. So, subtract the counter value from ch to the letter count like this. You can update it like this. In Python, these laws are quite convenient, so they are quite helpful when dealing with strings or something like this. So, you can rollback by adding a plus to the same path. If this is not the case is not selected. You can return it here. Since you copied this and did not select it, only the force is increased and the score remains the same. If you call it like this, the problem will probably be solved. Since the code is still a bit long, a compilation error may occur, and first of all, what I have confirmed that everything is correct, and if I submit it, I can confirm that it is the correct answer. I have solved today's problems up to this point. I solved the problem I had been doing, and I solved one problem that I had been doing for a long time. If it was helpful, please subscribe, like, and set an alarm. If the code works well, I solved it. Since you may not be able to see it, let's try enlarging it a little. If I explain the code like this, we take the initial value, count the number of words, count the number of letters, create a score for the word, and then find the initial position we need. I hand over the current score and letter count, and when Solve ends, if I go all the way to the end, I update the larger value between the current value I obtained and the previous maximum value, and then I get the word I need to use at the current position and that word. If all counts are included, if you can make it, in other words, if you can make it, subtract the words used when making it, add the score you made and the current score, and then move on to the next stage. It maintains the score and restores it to the previous state. In this case, if you cannot go to the right child to use, or if you have been to the right child in advance, you can call the left child in this way, and the current score will be maintained as is, only the location will be passed, and the rental count will not change. There is no. If you do this, the problem will be solved. Yes, thank you for listening to the lecture today. If the lecture was helpful, please subscribe, like, and set the alarm. Thank you.
|
Maximum Score Words Formed by Letters
|
reverse-subarray-to-maximize-array-value
|
Given a list of `words`, list of single `letters` (might be repeating) and `score` of every character.
Return the maximum score of **any** valid set of words formed by using the given letters (`words[i]` cannot be used two or more times).
It is not necessary to use all characters in `letters` and each letter can only be used once. Score of letters `'a'`, `'b'`, `'c'`, ... ,`'z'` is given by `score[0]`, `score[1]`, ... , `score[25]` respectively.
**Example 1:**
**Input:** words = \[ "dog ", "cat ", "dad ", "good "\], letters = \[ "a ", "a ", "c ", "d ", "d ", "d ", "g ", "o ", "o "\], score = \[1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0\]
**Output:** 23
**Explanation:**
Score a=1, c=9, d=5, g=3, o=2
Given letters, we can form the words "dad " (5+1+5) and "good " (3+2+2+5) with a score of 23.
Words "dad " and "dog " only get a score of 21.
**Example 2:**
**Input:** words = \[ "xxxz ", "ax ", "bx ", "cx "\], letters = \[ "z ", "a ", "b ", "c ", "x ", "x ", "x "\], score = \[4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10\]
**Output:** 27
**Explanation:**
Score a=4, b=4, c=4, x=5, z=10
Given letters, we can form the words "ax " (4+5), "bx " (4+5) and "cx " (4+5) with a score of 27.
Word "xxxz " only get a score of 25.
**Example 3:**
**Input:** words = \[ "leetcode "\], letters = \[ "l ", "e ", "t ", "c ", "o ", "d "\], score = \[0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0\]
**Output:** 0
**Explanation:**
Letter "e " can only be used once.
**Constraints:**
* `1 <= words.length <= 14`
* `1 <= words[i].length <= 15`
* `1 <= letters.length <= 100`
* `letters[i].length == 1`
* `score.length == 26`
* `0 <= score[i] <= 10`
* `words[i]`, `letters[i]` contains only lower case English letters.
|
What's the score after reversing a sub-array [L, R] ? It's the score without reversing it + abs(a[R] - a[L-1]) + abs(a[L] - a[R+1]) - abs(a[L] - a[L-1]) - abs(a[R] - a[R+1]) How to maximize that formula given that abs(x - y) = max(x - y, y - x) ? This can be written as max(max(a[R] - a[L - 1], a[L - 1] - a[R]) + max(a[R + 1] - a[L], a[L] - a[R + 1]) - value(L) - value(R + 1)) over all L < R where value(i) = abs(a[i] - a[i-1]) This can be divided into 4 cases.
|
Array,Math,Greedy
|
Hard
| null |
1,470 |
Work in this field Ajay Ko Ki A [ Ki A [ Ki A Hello Everyone Welcome To New Video Hindi Video By Going To Discuss Another Problem From Light To Turn Key Problem This Problem 1470 Successful Problem Hi Problem Appoint Consisting Of Entertainment Channel Subscribing Do n't forget to subscribe, now we are the first to subscribe that 347 no issues, if we are given the value of these, then what size will be our result, that is our breast size because 321 now our extraction is here. Before we do that, we have to set a pin from here, video from here, what is the actress, 180 ghee, what is our difference, we have to maintain this, our answer will be, you can contact it from here, so this is What do we have to do in the program? Active 1251 Can be optimized like the Commission has asked this question, if I am an operator, then with the help of these three projects, we will solve this problem. Let us look at the water side, we will divide the routes into two streams. What will we do in the route force approach? In the routes approach, we will We will make a new one and what will we do in that darkness, what will we do, we will do this, okay, so first of all we will make one, the result is this is our subscribe toe's neck, what will we do in it, our values toe village, how will we do this, what will we do the most Subscribe to first 10 2012 Hey, what is this and what will we do inside it, like this, what will we do inside it, now our answer is son or the result further makes these certain, this is ours and plus one, this is our hair, this is something like this, after that we What will we do inside it, as it will come to us when it is finished, then subscribe it example 12515 and subscribe, fill it up here, what will we do now i20, now the answer is of the type which is our glue subscribe also person 8000 for this because What we mean here is here, press 1234, so here we are 90 A, whatever is there will come to our here, okay, then this will increase by one of ours, so will go, this time it will be a person, that is, our value will go. Like Vansh will be updated here it will be jan21 and after that came our I our two big because here we are talking so here we are what it is so we like 2018 that our five is so answer 823 wood answer add 2025 Will go 2012 here Next our Ghaghra's this is ours 1431 1234 So what do we do here from the village here will be here and again 2018 19 will be a few seconds which will be ours 1012 So what do we do here if we which our The answer is plus one here so answer subscribe and so and this is our and after this we will do our return and if we three 500 that our time off that our people how much time is going on then the Android which is directly in People will ignore us here because we will have a very big rally, so we can do it if we impose excise on it looks like subscribe, use extra space to tow all these elements directly which is on our channel. Before subscribing to subscribe, here I first declared a variable wait equal to zero for how many subscribe numbers like 2014 run that record 2012 and subscribe plus one like and subscribe this is our result subscribe Appointed hello hi son second want let's front and let's see our is happening and it has started from our which from people to people so what will we do now we here we will try to do it so let's see Objective of this approach: What do we have to do in optimize approach? Here approach: What do we have to do in optimize approach? Here approach: What do we have to do in optimize approach? Here we have this extra and if we do not want to use it, then how will we do it? Whenever we have such questions where we do not want to express, then what do we have to do? You will have to pay a tax in this form, subscribe that the youth 12345 should do their wale, here we are a that along with the woman, turn on the to-do list along with the woman, turn on the to-do list along with the woman, turn on the to-do list and break the five best with and take seven cares. Our together with means here this both here and here this both here what we will do is in this way whatever number will be the number here and see whatever number will be here and said from there that in between In between, what can we do, take the number, then we will consider it for example, what should we do by taking 1000, how will we start it, so what do we have to do, whatever is given. example2 village, this is ours now here, how will we do for this position, whatever our number is here, we do, we are in this position, what will we do with these Z plus who here But fourth here, what is ours here, if we were here, then it was 1000, so this is how you would use it, how do we use it here, how do we appoint our face, 251, after that, our 100 here, and our tension here is, how much is it ours instead of 1007, okay? So this is our detail A. Let's remove this a little bit from here, so it may be a little bit confusing, so let's remove it. Now if we have here from our place, I can do this and how do I divide it, what do I like and here. If I take it, will I install it from here which will be our number here and which of ours if I take a reminder of this then we will get the pors which will also be for this induction program schedule of 1000, so with this we can start the two numbers. Now, like we get the numbers from where we want to do this in the village, where do we get our phones from, where do we give people in our village, if we get this appointment from where to where, what do we do about our looks and what we do here about our elements? We will do it here, subscribe to the channel 20123 go to this index divide it by that we will get the district over here and after that we over here we and do that we do and over here we do this we over here We will come to this here, what do we do here, if we knot this, if we in the last here, we in one of 235 417, which is our correct answer, so let's write something for this, so what will we do in the angle of this, we will run a loop. Is equal to zero to electronic and inside this, we inside this, which is our * * we will * * we will * * we will mix this, we will remove this, we will give it the name of hello hi plus and half inch plus and this we will store the division, one for the events is that If that happens, then divide it and if our number is two plus 1954, because our channel is subscribed till the village, then two * - 121 here, select one minus one plus one, here we will do plus one, then till where is our one minus. Where forest rights are from our entire village, we will finally subscribe Yogini electronic and update the number here and what we will do inside this, we will subscribe our channel, we will do * * * Shyam plus ki kya karenge plus hamara jo name set If it is I Plus, then here you will like it. Okay, here we have to do this, after that as our follow ends, here we complete our festival, now we do it inside this, we do it, I Plus and divided into A Plus one, whose group is this, whose is this, our half inch plus, like ours, this, we will return it as our own, we will subscribe our space-time for this, subscribe our space-time for this, subscribe our channel, if you did not subscribe our channel, then see here. Subscribe to Space Complexity, it is now an independent option on time, it is a much better optimization than ours, so let's write for it, here above our interview, what will we do and what will it do, it will last till 2030 and will update and inside this we will add our plus. Update subscribe do that come in whatever our place equal here put equal will not equal in this we melt this use equal and emphasize that if I change this and subscribe this should you be straight what do n't you take then we have this one Which is for the sake of don't forget to subscribe our channel and do n't forget to subscribe, we will call it the name of which thing is this off that i plus and aye plus and id. We will add this number first we told minus one plus one by opening that and our Have come A plus end is one if we take its modular then the percentage is 100 like if these two get together and we will turn our then subscribe this I accept it here for our test case so joker solution submit it and from the problem. He writes that our committee should have seen that our solution has been successfully accepted which is our Omega of One Time Complexity Institute in Space Complexity. Let's see what we have to do for the A bit boys operator. What will we do for use operator? First of all, we should know some operations from end and left side, these four operations. If you know this then you can watch the subscribe video by clicking on I button. Here, if you do not know this then you can watch it. If you can, then subscribe to this channel. If we see our number, how many are there to do, then we will need tablets for this. Why is this because 1024 who are appointed at our 1020 Store, 1234 five subscribes, 12345 more than 60, this is our number. So one simple thing, if you subscribe to this channel of ours with this number, then our full 50 here will be completed. This one and this one will no longer be our one. This is our Ghaghra. Whose representation is this? This is our 102 representation. So what will we do now? All the numbers are there, so here we are sorting 12 by 12 numbers, so it is okay to sort two numbers, sorry for the spelling mistake, the number has to be stored in which, so how can we do this, if our number is 102, then you can do this. Can's picture after that when how many total then we are the ones who will do it last time like we did the last time subscribe this you will wear what will we give it to this number of ours 19 2013 and appointed for 17th number again we It is disgusting to divide it into 2 parts. Subscribe to divide it into 2 parts. Now we need to do this. Let us do this. First of all, subscribe to our channel, meaning if I am in the village, after this 123456789 10 What is this for us? This is our today's number, so if I am here, our number will be there even before this position, no matter how hard we try, our number will come here and now after clicking on this number, we will do more with it and this number. With which on the last time and subscribe and if we do more of these two numbers 2010, this is our tab here, something like this will come 12345 780 Nautiyal and before this one of ours, this number of the whole soldiers, this one of ours, this point is this. The second number is and here is our second number which is how we will complete this year by doing this, now how will we do so let me tell you what we have to do first of all if we see what we will do call that where from where to where justified equal to zero. Up to 1000 and will give you a bigger one and whoever our dad adds that removes the name from our name plus, we will cut it, okay no issues, we will give it tension lips and after setting an alarm, we will do more about it. Number at I is okay you 28 and do this so first of all this will happen and do that with the destruction of this and this ends some subscribe here we are appointed here is our soft set i plus end is that is our equal It will be done and like the flu will end then our medal will be created in this type, these two apk files will be created, after that this will be our subscription like this and after that after the operation, we will get a particular here which if We will mark this and do something like this in the village and subscribe and share and subscribe now we got all this then how will we get value from it that is the question but what will we do if we run a chord again then where will it come from i equal to zero We will add up to 1000 and plus and what we have to do inside this is we have to set two numbers inside this so what do we know if we add this number and this number with 1023 if we add with 102 If appointed two in one is equal to zero number given with na plus and 1024 if I am going to get someone else and on last time and call we got something if we will add it with temple Udaipur if I see our Number something last time what happened if I was looking for 302 then it became ours what did it become of ours we checked for it then something like this type of time remembers so this was it became this subscribe to and After what we did with this and this, what happened to our 102, if I do this and this, what happened with this and ours? If both the values are even one of these promises, If both the values are even one of these promises, If both the values are even one of these promises, then it allows us to become, then this complete shades became ours, after that, after doing one, two, three, four like this, it should be 123 45678910, if we do it with 1023 that 1023 Train here with 123 45678910 abstinence if I scan with this with 102 then we get our something like this and by adding 151 da0 and whatever number it will be with this is our with which is our earlier number and if we convert this number Save this is ours, subscribe and 113 ours is ours, we are meeting here at our position and are doing so, we have taken this accused as our own, now we * want it, so what do we have to do in the entry own, now we * want it, so what do we have to do in the entry own, now we * want it, so what do we have to do in the entry * what happened to us * what happened to us * what happened to us Whatever alarm set of ours is I plus end, we will shift it to the right so that we will make ridership of it. Templates from this and after that what we have to do is whatever our are at to * whatever our are at to * whatever our are at to * will do to call that side. If we are getting it from the person, then we will cut it. Okay, this name is ours and according to this, of Star Plus One, this is ours, like ours is complete, so let's go and do this and its result is this last solution, this is the most First T-20 and within this we have subscribed, here I could have done this, meaning I could have written this and so many other parts above, so here I have subscribed to both of these so that you can see first of all, after that I have done more that I If we look at this example, then our name Saunf i plus end i.e. Hero our name Saunf i plus end i.e. Hero our name Saunf i plus end i.e. Hero plus Reel means we left the third index, train type, left the woman, train times, after that we changed it to number two, meaning And what we did with you is what we just saw, so here I am, I will come, see, we must have done another flip, where did this security come from 120 to electronics and here what we did, whatever you will have to do with 40. After that subscribe us and subscribe to my example for gas let's go to our solution of chapter Amit submit and let's see our result this is ours and this is our sector-16 run if we this is our sector-16 run if we this is our sector-16 run if we look at this problem And this is our time complexity constant quantity which will be our time complexity for this problem and what will be our Omega option here also Omega open earning time quantity will become omega twain soaked 80s if we use this Press Complex To Hum Extra Solution If you liked then please like thank you for watching my video
|
Shuffle the Array
|
tweet-counts-per-frequency
|
Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`.
_Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`.
**Example 1:**
**Input:** nums = \[2,5,1,3,4,7\], n = 3
**Output:** \[2,3,5,4,1,7\]
**Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer is \[2,3,5,4,1,7\].
**Example 2:**
**Input:** nums = \[1,2,3,4,4,3,2,1\], n = 4
**Output:** \[1,4,2,3,3,2,4,1\]
**Example 3:**
**Input:** nums = \[1,1,2,2\], n = 2
**Output:** \[1,2,1,2\]
**Constraints:**
* `1 <= n <= 500`
* `nums.length == 2n`
* `1 <= nums[i] <= 10^3`
| null |
Hash Table,Binary Search,Design,Sorting,Ordered Set
|
Medium
| null |
93 |
everyone today we are going to solve a restore IP addresses lead code problem so in this problem the input is a string and we have to find all possible valid IP addresses for the input string let's go to the problem description a valid IP address consists of exactly four integers separated by single dots each integer is between 0 and 255 inclusive and cannot have leading zeros for example these are the valid IP addresses and these are the invalid IP addresses given a string s containing only digits written all possible valid IP addresses that can be formed by inserting dots into s and you're not allowed to reorder or remove any digits in yes you may return the valid IP addresses in any order and the constraints given are the maximum length of the string can be 20 and it has only digits so if the string has any other extra characters also it's invalid anyway they have given we will be getting only digits so from this what can we understand about the properties of IP address the maximum length of an IP address is 12. and the minimum is 4. so the length is ranging from 4 to 12 and each valid IP address has four integers or segments separated by three dots and each integer range from 0 to 255 and the length of each integer is from 1 to 3. so this is how an IP address palette IP address will be anything which is changing from this properties then we consider is an it has an invalid let's say invalids an integer has starts with 0 1 5. this is an invalid value for to be present in an IP address again if it starts with 0 7 this is again invalid let's say it is 300 it is again invalid because it is not within the range 0 to 255. and if it has only 0 if the integer is only 0 then it is valid so let's think once how can we get all possible combinations of IP addresses from the given string so we have to try all possible values by placing the three dots in the given string and if we are able to form a valid integers in all four segments of the IP address then we can say it is a valid IP address if it is not valid we are not able to get a valid IP address with the combination which we took we have to backtrack and find the new way of finding a valid IP address so the concept which we have to apply here is backtracking let's say with a simple example so if the string is one the possible IP address which can be formed is 1.1.1.1 we cannot form any other IP address from this string so this is the only valid IP address that can be formed let's say I'm adding an extra one here so now we have five ones and after adding the dots we will have 1.1.1.11 we have reached the end of the 1.1.1.11 we have reached the end of the 1.1.1.11 we have reached the end of the string and this is a valid IP address so this is this can be added to the result now can I increase the length can be maximum of 1 two or three so since there are no other digits left I have to backtrack and go to the previous one and form another valid IP address let's say 1.1 address let's say 1.1 address let's say 1.1 I'm adding 2 like taking to 1.1.1.1 yes this is again a valid IP 1.1.1.1 yes this is again a valid IP 1.1.1.1 yes this is again a valid IP address let's say I'm considering first segment to be of length 3 triple one is it a valid yes and then it is within the range of 0 to 255 so I'll add it next I'm placing a DOT and considering one segment then two segments and I am it to place another dot but I don't have any digits or any uh string character remaining in the string we already reached the end of the string so this is an invalid one we don't have any more characters or digits left to form the four segments so we will not go in this way and we are done with expanding the first thing let's expand the second one let's see we are at having two digits 1.11.1.1.1 yes this is a valid again 1.11.1.1.1 yes this is a valid again 1.11.1.1.1 yes this is a valid again and from here I am trying to do one dot triple one dot again as we discussed like here the end of string is reached but there it is still a DOT left to be placed so this is again invalid one so we'll backtrack and go to the go to go and place the dots or expand the segment third segment if we expand the third segment we'll be having 1.1.11.1 which is again valid and in the 1.1.11.1 which is again valid and in the 1.1.11.1 which is again valid and in the same way we can try the combinations and find d valid and invalid ones so I took this simple example as it will be easy for us to find all the combinations so for the given example two five one three five the same way the uh the all combinations should be formed the tree can be found backtracking tree and then recursively we can find all valid IP addresses uh let's dive into the code so we have to return the result which we will be backtracking and finding all the combinations and adding the uh string to these results so I'll have a backtrack method foreign there I'll pass the string and the start index which is initially zero and data set and for I have to keep track of number of dots that I have placed initially it'll be zero and a string Builder where I will be forming the IP addresses from here build it on the result after that tracking is done so this is the Backdraft method which Returns the results so it will return now list of string track string yes and the second one is the integer the start index one is the result arraylist then we have the number of dots which we have placed which we will form the current IP address so we have to find okay let's say normal backtracking thing when a string is a valid IP address if we have already placed all four segments are formed then we will add that str2 string to the result and written this otherwise we have to backtrack and find for each combination so let's see first the segment can be of length one I can be one and I can go up to three I press place so we'll check if that segment is valid of that yes comma start index and I so what this is this valid method do whatever the properties we have discussed here will have a utility method that will help us in finding the current uh segment is valid or not if it's going to be a valid then I'll append to the string buffer which is substring of s dot substring of start and start plus the length after that we'll proceed to the next index so foreign start index will be start Plus I and sorry this should be reserved that result then dots and the strangled let's incrementally pause here and decrement the dots for the next thing so now the second option will be Drive so for checking for the next combination we have to remove the added one foreign list of strings so that it is easy for me to use it here and then I'll just remove Str Dot size minus 1 the lastly added string I'll remove and here I'll make use of the string method string function join and the character sequence will be Dot and add the valid IP address so let's come to the uh this utility method which is going to return true or false so it is the return type is Boolean is valid of the string send this down index so in what cases this will return true if left equal to 1 and yes Dot carrot start is not equal to zero that means it's an it's valid ones if yes Dot substring of chart command start placement your plan equal to 1. then when it can never be invalid right so we'll directly return true and F length equal to 3 and yes dot substring of start comma chart plus length dot compare to 255 is greater than zero then again we'll return drop if a length equal to 0 and sorry length is three and yes Dawn carrot Dot equal to 0 that means it has leading zeros then build return false or gray even greater than one in other cases this is for valid method what are other Edge conditions which we have to check is if the remaining dot you have to compare the remaining called dots and the remaining um characters that is left to form the IP address let's say remain reminds us dot length minus Dot and then remaining number of dots is 4 minus if remain dots is greater than Germans then it is invalid so we'll just return the result one more condition if that remains or if it remains is greater than to remind dots into three so each segment can have only three characters right so if there are like two dots left so you can place uh you can maximum have nine characters if you have 10 characters then it is not valid so in these two cases we'll just return the result so I think we are all set let's see let's try and see we got a missing written okay beat and return here let's add that okay the thing I have missed this condition and I less than remaining okay something is free oh I think I need a small nose thing that I should be less than or equal to remains and uh yeah I think we are all set now oh let's run the code and see yeah I did cause everything so we can see that the output is all the valid IP addresses yeah thank you for watching I hope this helps
|
Restore IP Addresses
|
restore-ip-addresses
|
A **valid IP address** consists of exactly four integers separated by single dots. Each integer is between `0` and `255` (**inclusive**) and cannot have leading zeros.
* For example, `"0.1.2.201 "` and `"192.168.1.1 "` are **valid** IP addresses, but `"0.011.255.245 "`, `"192.168.1.312 "` and `"[email protected] "` are **invalid** IP addresses.
Given a string `s` containing only digits, return _all possible valid IP addresses that can be formed by inserting dots into_ `s`. You are **not** allowed to reorder or remove any digits in `s`. You may return the valid IP addresses in **any** order.
**Example 1:**
**Input:** s = "25525511135 "
**Output:** \[ "255.255.11.135 ", "255.255.111.35 "\]
**Example 2:**
**Input:** s = "0000 "
**Output:** \[ "0.0.0.0 "\]
**Example 3:**
**Input:** s = "101023 "
**Output:** \[ "1.0.10.23 ", "1.0.102.3 ", "10.1.0.23 ", "10.10.2.3 ", "101.0.2.3 "\]
**Constraints:**
* `1 <= s.length <= 20`
* `s` consists of digits only.
| null |
String,Backtracking
|
Medium
|
752
|
1,219 |
Hello viewers welcome back to my channel I hope you are doing all the video this time uploading today's problem is path maximum gold in gold mine grade security dash kholo video every time you all the position of love you khan tweet difference more than once Visited Several vid0 Got You Can Start and Stop Collecting Gold from Any Position in the Grade The Favor Gold Show Basically Virva Android With Numbers 202 Problem The Thing 1202 And Share It Is The 2020 Soe In The Sale Value Scan Vid0 2030 You Are Not Alone To Visit Datsun Birthday Wishes Gold And Proceed So You Can Start From Any Position In The Great Subscribe To Identification Of The Smallest Pata Or Covering All Notes And All Salute Record Anything Basically So Long As You Don't Have 200 Beds And Vivid And One More Thing To Remember Tweet Seervi Video Two-day Visit To Draw Pintu Subscribe 108 Subscribe Button Like Subscribe And Share You Can Take 680 Subscribe 6 Coins Adhir And Subscribe School 567678 Possible And Collective 130 Flights Subscribe 9 Agencies Subscribe Width Him On All Subscribe To Peerless Get Bigger Exam Se 1000 500 to 1000 Positive Dry Air Chief Editor Sudhir Awal and subscribe 713 mode 29th april President Subscribe subscribe this Video and Mother Land Question definition of 15205 to 1000 likes Subscribe and Issues Rather Than 100 Different Look at the God Verification Button President Subscribe subscribe and subscribe this all the water where it is possible right and subscribe he chamar gold collector for the giver to solve the problem of business site on Thursday what is gold channel to subscribe and subscribe the Video then subscribe to shravan column se ho basically choice of equal function will Have To Pass In The Calling To The Blind Man Subscribe Like Comment Share And Subscribe 10000 Doctor David Subscribe To That So All Of Them Are Satisfied Inventor And Reminders Vidrew Member Visiting Red And Explain The Current Track 1 April Current God 20 Don 2 -The God 20 Don 2 -The God 20 Don 2 -The Key Other Direction Set So What Vivo Difficult To Do Left Right Left Do Subscribe Toward All Four Directions From This Position With It's Getting Old Is Gold Do n't Forget To Subscribe To The Channel And Don't Forget To Subscribe And Subscribe My Channel Thank You Updated On Half Current Gold Digger Collector Siddharth Will Be Keeping Track Of The Method For Giving Flight 120 Gram Gold 12k 210 What Is The Thing We Are Going To Create Max Gold Crop And Overall Mexico Tracks And Not Good Quality Of Midnight And Good Railway Line To Customers Suna Number Roy Must Subscribe Channel Subscribe Video subscribe The Video then subscribe to the Video then subscribe to subscribe and subscribe Home What Ever Gifted Maurya and Overall Max Gold and Not Withdraw All Match Dekhne Great Moral Citizen Update Simple Sequence Sudhir Vote ID Enter into a number of migrants traveling doing the same time Ambrose End Subscribe Mintu Install Channel Not Subscribed Final Oral Hundred and Half Hundred This Problem Subscribe Dadri The Current Se Lettuce Drama Us Loud Explanation for This Particular Problem for Positive Results Comment in Problem Questions Page Write in the section Subscribe My Channel Subscribe Channel And Also Share Subscribe Thank You Will Get Notifications For All My Videos Thank You For Watching Problem
|
Path with Maximum Gold
|
longest-well-performing-interval
|
In a gold mine `grid` of size `m x n`, each cell in this mine has an integer representing the amount of gold in that cell, `0` if it is empty.
Return the maximum amount of gold you can collect under the conditions:
* Every time you are located in a cell you will collect all the gold in that cell.
* From your position, you can walk one step to the left, right, up, or down.
* You can't visit the same cell more than once.
* Never visit a cell with `0` gold.
* You can start and stop collecting gold from **any** position in the grid that has some gold.
**Example 1:**
**Input:** grid = \[\[0,6,0\],\[5,8,7\],\[0,9,0\]\]
**Output:** 24
**Explanation:**
\[\[0,6,0\],
\[5,8,7\],
\[0,9,0\]\]
Path to get the maximum gold, 9 -> 8 -> 7.
**Example 2:**
**Input:** grid = \[\[1,0,7\],\[2,0,6\],\[3,4,5\],\[0,3,0\],\[9,0,20\]\]
**Output:** 28
**Explanation:**
\[\[1,0,7\],
\[2,0,6\],
\[3,4,5\],
\[0,3,0\],
\[9,0,20\]\]
Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 15`
* `0 <= grid[i][j] <= 100`
* There are at most **25** cells containing gold.
|
Make a new array A of +1/-1s corresponding to if hours[i] is > 8 or not. The goal is to find the longest subarray with positive sum. Using prefix sums (PrefixSum[i+1] = A[0] + A[1] + ... + A[i]), you need to find for each j, the smallest i < j with PrefixSum[i] + 1 == PrefixSum[j].
|
Array,Hash Table,Stack,Monotonic Stack,Prefix Sum
|
Medium
| null |
1,371 |
Hello viewers welcome back to my channel Divya Ko Into Some Very Interesting Read Problem No. 170 Longest Born in WWE Champion Account Okay so let's understand the problems that will give you strength as returns follow difficult in this will give a number of times the egos are amazed To and you and stuff you want even number of times okay I will make you have to review our this name is okay in that the longest serving is taken out which should have the age of all the years and this frequency counter of all of them should not be the same okay Now I have to remove it, okay, let's see, just look at the exam input. Okay, Khas said no, I can only get Mini C-W-O no, I can only get Mini C-W-O no, I can only get Mini C-W-O and this is our long sub channel 13, in which if I kill all the things, then there will be a frequency problem. Let's see like this any point is two is if e can two is that someone record two have that and you are you previous record 06 2010 do okay now zero York City it's like those numbers are okay so we have to put against that Number, so who is this person, so my voice is ahead and so all this shooting of things is coming. Okay, so one can think of something like this, such a delicate model, then can be straight, like this, A B C D O, something. If everything is not nothing then everything is like this which will always be completed by all the people okay then this is our question seeing how to do how to develop then how is it then it can absolutely be 727 when do you meet Long long all this Gare Natthu given som must have taken out music training Take out some time like this That's the first time It's been put here in the same minute That's the complete changes You can use limit masking in this What will we do That people see when their wife This side's symbol is that side's ok sure let's take our first and second side so tell any voice mail in it why what record do we take the name of the list loot 12 sting we have this fixed and this let's change them what are you Will definitely consume it like Basic Intuition is long as they are the longest to extract questions, all this is for the scan tuition of UPA, we used to add elements in it, we just check our own that If it is pregnant then we do not change it. If it is percent then on that day we cannot change it. So let it be and it is recent. Okay, so we are like this. Waist is fine, so till here we said that we have whatever is spread on it, suppose I am in this street 225, we have taken out that one spoon of clove survey number and till here the time is twenty five, so for that we know that here From till now, there will be zero oath, only then both of them are work front family, okay then how will it come out till now, swear 8 - Till till now, swear, you will tell this, log survey has been done, 8 - Till till now, swear, you will tell this, log survey has been done, 8 - Till till now, swear, you will tell this, log survey has been done, okay then the same concept, if you want to install a simple system then What we have to do is that if we have this one which is recent to me from a long time ago then we take out its index and try to add it to our tears by doing indexed pages and express - it will our tears by doing indexed pages and express - it will be on 98100. Now let's see how to put it. Let's see how we put it, so let's do the first thing, how should we write in Bigg Boss, how will we put it, then I will come back to you, we can give a gift to you, like our count is Chirauli. Kitne fit hai 32bit hai to ke channel head goals ki Bigg Boss the last date like ki radiation se variety vacancy jis media missing army vacancy specific ko vacancy due time yesterday evening e can so this is what I did what next a what is this What advantage have we got, what advantage have we got that at this time, this one and we have to find out that I need the number one weakness, all that, all his balls, here there is shooting, so initially what happens to us, initial is also ours, what will happen to the condom gets looted. And let's grind the input of the skin here, okay, who took the police vote, this is our alarm, okay, it doesn't matter, go ahead, friend, I am not able to do it, okay, so I am the thing here and how to deal with the loss of respect. It was spread that if there is no bill then it will not make any difference to us in the end, all these balls are still in the same account, so this sugar ad, this one, how is our quality, first of all, it will be one in itself, which is a problem in our answer. If you can wait, then lunch is fine, let's take loot, it's fine, now the worry has come forward, but the contest has been stopped from me, it is possible that yoga can come, the frequency of all is current events and all the vice presidents of A lot of people will always be happy because the thing that has to be set is okay, there should not be any grip, but it can also be that if it comes, then it is all weak and chicken two that it can, then how much has it become for us, these three one There is more capsule and till t&c, is more capsule and till t&c, is more capsule and till t&c, what will Bollywood do during this period, will our bill be reduced, will there be any change and still I have taken out the length of all the frequency accounts till the time we get copies of this fort, this also carefully. Our cancer of hair will velvet, this is also not possible, so there is no sign in it, any file is completely killed till here, that is, now we have done it, now we cannot do the problem, but till now we cannot do this also because we can MP3 has done this and if this is done then this also cannot be done by the person who is the security of the country, this is what will get cancer, I am fine my husband, this is honorable, when I have to do this, now I look at this one, what to do, section 30 of 80. Tell me one thing, it is not MS Word, nothing will happen, but if it is a vegetable, then I have given the answer to all these things, Maths is our strength, it is drinking tea, it is computer and electronics, so I have made it full, so it will be three, it is not right. If it is done then it will be done that this is good, it's a week, what else will we do and these two are good, okay, let's see what is Kishan's problem, now send a message, loot, okay, I think I have ghee We will do it after 5 minutes that Viroli this fiber it's okay five girls so I am saying print money from it friend so do it with this friend do it with humans okay I am in this tell me one thing at the time of any journey Tell me one thing, small things, accept, I want to say that the sequence is not making sense, meaning, right now, this number of ours is all zeros in it, there is mud in it, so what does it mean and I would like to tell that from tomorrow onwards, there is nothing in the vegetables. Okay, so if it remains zero, it is telling that the discriminator is flute and on the other hand, it has also become double, it is telling and the sequence is there, support me, I am telling you how much it is for some people and I will say first for the serials. Okay, so this will make it one, it's good, okay, so it is saying that the audience has become 1, meaning more swelling, it has returned back to zero, two, friend, if it is an industry, what kind of quality is the machine, that even a little bit has come back. Will do it okay back and if the sequence is done then if anyone remains one Naina this means high frequency and this committee has taken the number of one incident meaning this note is to be taken with a spoon and just flipped the committee and if you feel like having an event then take this. Okay, now it is Monday for pav, so what will we do now, initially what will happen to us that we will have 5 minutes of vegetables against health committee. Okay, you are above Yadav, whatever we do in the morning, there will be starting and one in the question. That's why I take it in the map and definitely take a bar of forgiveness in which people add to the playlist and I put these Amla's of mine and look at zero minus one and take it completely so that if there is a Taurus string from the beginning, it is becoming Sachin. If the whole Malwa answer is our mixture, in this case, this whole house will be ours even and even in this saree, how is it on the ends of some wax paper, express 0.2 three paper, express 0.2 three paper, express 0.2 three 500 index, that the aroma is already printed that I Send a message to you here on this special one for five minutes that this is the full length of what both of you should do and what not to do, this gang has put Shri Dal Laenge, he is wearing a disgusting mask, it is okay, please forgive me, it has become wrong, do it. Where is the phone, this is one thing, then what do you do, I take this one, let's take this film, the list is court, okay, please food, I am the first character, okay, we made Bigg Boss and it is such a thing, we will make a badman. There is no mask, we will make this mask that the gang and the first elastic password will tell all that our first character is okay now but can tweet about us then it will be up to the maximum okay and then that's how the game came to know how we It turns out that now you see, we have made a mask, even on the vine, its value is zero, here the withdrawal tax is on, hence the growth index, looted Maruti 800 MB, I checked, I, you, ours are already pregnant before others, okay, I am already a painter after zero. So next - now ours is on them - next - now ours is on them - next - now ours is on them - now you will say by making Dr. Ball, friend, how can you say that I will be your first student, there will be all the vacancies between me and whoever else is there and how will this Chakrawal think about this? Got the mix let's do that obscene word Om Shanti Om that towards her Gaya that's seen that okay let's see what I was saying brother tell me one thing that I'm saying R U think like Do it loot specific you are taking that is the symbol of sakta that Edison Jiya qualification you commissioner Dr I am someone crazy, I have here the one with the brain Ajay Kumar Lallu ji which is 122 meaning what happened to this What do you mean brother, whether it is what it is or not, I am just saying that it should be of Gurjars, it should be both, here you are making it in the middle, what happened in the middle, so what happened in the middle, tell me one thing in the middle. If this has happened then our love may have become one of them or it may be that of BJP people or this of Zero but while coming here, all those changes happened in between. They went back to zero, they went back to zero and this is what is left, which is hit till the starting point, confirms 100 that these are the frequencies, I am saying that our yagya then potatoes, stomach mask, now the woman is in between this You might have opened it, you might have closed it, but by the time it reached, whoever would have reduced all these values back to zero, and time it reached, whoever would have reduced all these values back to zero, and time it reached, whoever would have reduced all these values back to zero, and zero means zero, when it reached zero, it became one and this was left, now you will say. Man, this is still one, isn't it, okay, so how are you saying that everyone is present in it and that if they stop Bigg Boss, then what will we have to do? Plus he will invest his wickedness next one what will be happening now it is closing this one is okay this become it means this intense and this contest and where it would have got it is the same time here is the email you okay Here also there is a character that it is fine and it must not have come in the middle, okay, you tell me when did Niti become a medium, health is fine, now it must have been found somewhere in the middle, is it back to Nirahua or is it back then got back? So, are these two okay, now I am saying that it is closed here, you are in this banta, now I should not use it or do something solid, I will start its coming, so I have only two left that China will ring. So this will be ours, this will only happen, so I will give you our answer, no, I will be the president of you, I will be the index plus twelfth, this silicone was indicating the pick, I understood that the said Kishore Yadav, so you are on this question. Let's come in addition to Da That has changed the rally of cinema Indians must change Which appears to have only done the wicket Not now not now but and we will check it is a mask How much percentage is it anyone To 12345 loot bodies and a more like now look see what happened to you and earlier with this essay then one of them blew the matter forward ordered this good man came back like did this it became zero Okay, these days have passed, now which is the lowest number on which we can contact, everything is fine, okay, then our arrangement is how to edit the photo, all these people were already present with us, okay brother - Ravi Kishan on Malik This Akhand okay brother - Ravi Kishan on Malik This Akhand okay brother - Ravi Kishan on Malik This Akhand Express Jaipur to - Express Jaipur to - Express Jaipur to - Loot Gaya Hai will do some quantity with Simti and in this Moscow will not have any problem, you can fit inside it because everything I have is still fine so this four of ours will be inside and we will be able to fit in this matter. But we will not put it, first of all, this zero percent of our Godhead, I will not only do nothing but will increase this of ours, but here you are that this should not be anything of ours, so what is and vegetables are waiting brilliantly which is the end. Will he run to the side, do they print or are they eligible, ok, don't do it, brother, I am not the answer till now, thank you, but what will be there in that, shampoo hand free came on 0232, looted the kitne dor kitne ho gayi at masking tape, our sentence did not happen and Raisin came brother 15, this is not our 3rd bill, there is no problem, add some points to us and add it to this also, we will not add it because we printed the rate from the Red Fort, where is it from our college, it will call back, on the contrary brother. There will be no benefit in our tears that both of them have become more and we have FD account but we have to check our own, I have this PAN in our account, this difficult war, this zero, this will become these diseases, this will become strong, you will become a ton, it has been looted. The first patient is Can U, so what is our maximum till this is the year 2009, so you must have understood how to do that, how to you have some questions, dual the milk, so the first thing we have to do is first this, what should I do, we This is what we have to do to take the tension of Eid-ul-Fitr, we have to do to take the tension of Eid-ul-Fitr, we have to do to take the tension of Eid-ul-Fitr, our 0.5% does it, this is our first and our 0.5% does it, this is our first and our 0.5% does it, this is our first and second step, okay, so if we do one thing, 2018 Jhala should, I had prepared the previous chapter till these days that spelled If you had thrown him out, what would you do now? Episode 106 is 25 Google Web that this will be looters or Ayodhya and Twelve, this will become daily, come to a few channels, okay, we have always done this to everyone, what to do now? It will be that a team of Tantra 98100 tailor you to me, why not just me, you want all our friends, send one that will show its volume and give MP3 song on the other side, it is good, it is different, it means don't go to us already, it is happening. Protest Facebook Okay, what will happen now, then we will wait for spring tide, do Cricket MP3 202 tomorrow, if you are at home, then when the first character comes, I will check the phone number, I will have to find out that it will stick in the purse and I will present all that. Okay, where have you gone now, mobile honey, which appointment is this, Lutyens' children like this, Lutyens' children like this, Lutyens' children like this, what will you have to do, these people, we will have to correspond to that weight and health and set the darkness, how will we do this, see this. How to do it, if we turn on any of our based ones, if we like 0, if we have to set it's pin, how to do it, I have to set it to melt scan, how to do it, not this mask, and okay, it's joint. What will happen if we do it? Okay, and if the end was set then it would have to be set, the outcome would have happened, the name of the subject is set 03, Princess, if we have to cut, then our eraser mask is that by adding that table and doing, from whom? Where to make one phone, leave your laptop, only at what time, every what time, at what time, every post you post and you have to like this page, this is a front arm hole, this is a fan, this is a stool MP3, if you know, Raghava is ours, she is speaking first 06 ki I am saying, without it, leave one because this MP3 is made only. If Mishra does it, he will target one, this one will come here and it will go to 70 to arrest the ticket robbers. Previous song again Bigg Boss If it is set, then it has to be set and it has to be set, mask, want to, which pick, mask, and in the loud band, the MP of which has come in the laptop, okay, that China, what do we have to do, now improve this map of ours, the president is but innocent. You will insert and if not the painter is the fixer thief that if this tweet is not in the mask present at the present era of fiction on your day also how to insert is that happened that put this index plate show more a tip Ravi maximum should symptoms of About 19 Loot Lo Hain This House If there is nothing then what would have happened if I would have tweeted that the organizer of the tape Maxo Maximum Ko m to meat and eggs is good ok whatever the purpose is II - whatever the purpose is II - whatever the purpose is II - Hai MP on this work That I - MP C is more important, turn it That I - MP C is more important, turn it That I - MP C is more important, turn it on mixed, that the bill is blowing dust, 13 showed that maximum OK, this MP told the trainees, Om Shanti Om, come in today's video download, problem has happened, my device is normal. If there are 101 innocents, do it, I am alone, when I shoot for scientific reasons, I am on this, a Saiyan keeps submitting, a photo is gone, okay, if there is a good Muslim, a coin mix of masking and training, okay, so come, that is quite something good You must have liked your solution and if you liked it then please like this video and subscribe the channel. Thank you.
|
Find the Longest Substring Containing Vowels in Even Counts
|
minimum-remove-to-make-valid-parentheses
|
Given the string `s`, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.
**Example 1:**
**Input:** s = "eleetminicoworoep "
**Output:** 13
**Explanation:** The longest substring is "leetminicowor " which contains two each of the vowels: **e**, **i** and **o** and zero of the vowels: **a** and **u**.
**Example 2:**
**Input:** s = "leetcodeisgreat "
**Output:** 5
**Explanation:** The longest substring is "leetc " which contains two e's.
**Example 3:**
**Input:** s = "bcbcbc "
**Output:** 6
**Explanation:** In this case, the given string "bcbcbc " is the longest because all vowels: **a**, **e**, **i**, **o** and **u** appear zero times.
**Constraints:**
* `1 <= s.length <= 5 x 10^5`
* `s` contains only lowercase English letters.
It is the empty string, or It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string.
|
Each prefix of a balanced parentheses has a number of open parentheses greater or equal than closed parentheses, similar idea with each suffix. Check the array from left to right, remove characters that do not meet the property mentioned above, same idea in backward way.
|
String,Stack
|
Medium
|
2095,2221
|
784 |
Hello everyone welcome today breaking bad luck this letter this competition and questions withdraw from every individual and subscribe for more ko blind aur toothless yo honey dr hain to FD sensitive yantra in witch karte hain aur lower caste lines of kindness and need to Have Tried To Convert Tweet Seervi Word Origin Thursday Can't Change The Game Play Around With The Same Position Of This Was Happy Spoil His Inner Were Request Problem Fuel Tuesday Face Per Dengue Into Your Hair With PC Arya Krishna Navami Into A Great You will hear classes 132 back to work with this train will stop at least they can do that trend of Congress Fifth Chapter Note Ajmeri Gate Capital I have belt scan through every thing Hindi Network Industry Board also contributing factor of day and night in and in Do the thing is done The Amazing subscribe The Amazing 132 views and we have information 2 hands in this proves penf three length its low response track to just weight reduce along with channel caring entry letter to see water commission which came in Front of the match david o that your body participated in were live from the best possible price and on the letter it is suspected that individuals new playlist distic that android hollywood they calculate permissions continue letter's per hour of sleep must subscribe and subscribe the channel Also members of subscribe to and list of spring combination suicide in your string in burst gold import latest politician in this age how to go into from this contest mauni this combination dot government in the portal to his annual character sindhi are from starting And Travels And Subscribe My Daughter To Convert In To Capital Letter Written To A C It's Absolutely To In Sports Award To Kaithal That Bigg Boss And Want To Give Its Territory In The String Into Location On Kids To Help Subscribe Don't Subscribe To The Channel forget a perverted time another with a price equal to a parrot two people is foursome 285 pimple to the latk hai na mintu travels through every thing e aaj tak its formation of birth combination is that our news room of these are five plus one guys combined Family's father's scandals looted Lakshmirvedvara, then who did it happen to Jhal? The candidate has said that North Kashmir and the robber scientists are at a distance of one meter. New Delhi News Cream Acid 149characters. Save in entered, words, dogs etc. due to Gastric Problems WhatsApp Status With Which Ne Vriksha Now Catering To Give Me Two Drops On Quarter Notification And Note Chappal Converted To Cost Dengue Of Free Water Events Of Endowment For The President Scientific Evidence From NCTE And Show More Hua Tha Question Is Last Updated On That Aishwarya Good Boy Veer That Redmi Do Ko Luta That Invest Me Akshay Transport System Save A Recommendation Letter In This Voice Mail Porn Film Do Shri Radhe Krishna Good Morning A Quiet A That Account Is Pimps And Naseem Simple Badi Dhak Hai Iss Platform Vid U Jhal Update Sudhir Vve Triple Ha A Broad This Is A Medium Question Andher End Tak Hum Idli Penthouse Pet Of Processes Of Solid Speed Breast Cancer Lung Cancer Of Solid Speed Breast Cancer Lung Cancer Of Solid Speed Breast Cancer Lung Cancer Awareness Questions Page Under Construction In Electrical Machine Please Like Subscribe Thank You Thank you
|
Letter Case Permutation
|
insert-into-a-binary-search-tree
|
Given a string `s`, you can transform every letter individually to be lowercase or uppercase to create another string.
Return _a list of all possible strings we could create_. Return the output in **any order**.
**Example 1:**
**Input:** s = "a1b2 "
**Output:** \[ "a1b2 ", "a1B2 ", "A1b2 ", "A1B2 "\]
**Example 2:**
**Input:** s = "3z4 "
**Output:** \[ "3z4 ", "3Z4 "\]
**Constraints:**
* `1 <= s.length <= 12`
* `s` consists of lowercase English letters, uppercase English letters, and digits.
| null |
Tree,Binary Search Tree,Binary Tree
|
Medium
|
783
|
835 |
hey guys welcome back to another video and today we're going to be solving the leeco question image overlap alright so in this question we're given two images a and b and these images are represented in binary square matrices of the same size so the size of a is the same size of b and binary just means that it's only zeros and ones and we translate one image however we choose so we can slide it to the left right up or down any number of units okay and then we place it on top of the other image so after the overlap of this translation is the number of positions that have a one on both images okay so if there's a one or in one position after a certain translation the other one is overlapping on top of it okay so note also that a translation does not include any kind of rotation and what is the largest possible overlap all right so after the question is a little bit confusing so let's try to understand what that actually means and let's just look at an image to explain that okay so over here we have two matrices or and think of each of them as an image so this over here is image a and this over here is image b so we have two images and they have some sort of values of zeros and ones in some positions and note that they always will have the same size so over here we have two three by three binary matrices okay so our task is how many overlapping ones do we have when we put these images on top of each other so for example we're only going to translate the image a so you could translate both of them but just for simplicity we're just going to say that we're only translating image a so over here if we put image a on top of image b so in this case image a would fit directly on top so over here right on top of image b would be image a so how many ones are overlapping so in this case we have a one in the middle and we also have a one in the middle so those two are going to overlap we have a one on the top right for a but this is a zero so there's no overlapping the same way we have a one on the bottom right but um a doesn't have a one in the bottom right so in this case we only have one overlapping which is for the uh one which is in the middle for a and b so what we can do here is we can move a in uh right in either of the four directions and we can translate it how many other times we want in order to get the highest number of ones so let's say we move the a matrix to the right by one unit so if we move to the right by one unit we're gonna have the starting of it over here and it's going to cover these two row columns and it's also going to have a column which is kind of out of bounds so this is going to be that out of bounds column over here and this is how our matrix is going to look like so this is going to have the 1 this is going to be 1 then 0 1 0 and then 0 1 and 0. so this over here is actually slightly better so how many overlapping ones do we have so we have one overlapping over here and we have one overlapping over here actually sorry we have one overlapping over here this is this does not have an overlapping and we have another overlapping over here i know it's a little bit hard to see but just imagine moving the entire matrix a to the right by one so in this case we actually end up with two uh overlapping ones which is better than our previous solution so now what we're going to do as it is it's over here at this position and we can perform even more translations to it so we can move it to the up we can move it down left whatever we want so we already know the answer so for just for this case we're going to move it down so when you move it to the down we already moved it to the right so the starting is already over here now we're going to move it down by one so the other border is going to end up being over here we're going to have an extra column on this side here we're also going to have an extra column going below the b matrix so this is how it's going to look like and if you write the numbers as it is so over here we have one so as you can see we have one overlapping over here we have another overlapping and then we have zero here one year and then this ends up being zero then this is zero one and zero if you're confused by what i'm doing all i'm doing is i'm just copying down this matrix so you can see how it looks like when we put both of them on top of each other so as you can see over here we have three overlapping ones over here and over here so in this case we're gonna output the number three so this is the question and this is what it actually means so now let's actually try to understand how can we solve this question so let's just go through one which seems kind of intuitive and uh more logical at least to me so what we're going to end up doing is we're going to iterate through each of our matrices so we're going to iterate through matrix a and matrix b and for each of them we're going to end up storing wherever we find the value of 1. so in this case we found so let's go through a real quickly so we find the value of 1 at this position so what we're going to do is we're going to store that in some place so we're going to store this position so this is at a position of zero comma zero so how do we know zero comma zero so the row is at an index zero and the column is also at an index zero and the first value is going to represent the x value per se and the second value is going to represent the y value okay so let's go to the next value over here we also have a one year so we're going to add the value one comma zero right and then over here we do not have a one so we're not going to add anything so this way what we're going to do is we're going to iterate through each of our matrices and we're going to add all of the indices and the locations which have a value of one so let's just go through this real quick so we have uh one over here so this is going to be one comma one and then we have another one over here so this has an index of two comma one it's just x comma y that's it similarly i'm going to do the same thing for b so now we got both of our values and let's just say they're both in lists so both of them are inside of a list and what we're going to do is we're going to iterate through list a and we're also going to iterate through list b and while we're iterating through them what we're going to be doing is for each instance of a so for each instance where we find a value of one so for example we find a value of one at the index zero comma zero so we wanna see how can we move this matrix so that we can move it in such a way that this corresponding one is overlapping with this one over here so how do we move this matrix over here so that this one goes over here so how do we do that so there's several different ways to do that and you can kind of go through it step by step so you would move to the right by one and you would move down by one so but how do we actually write this in sort of a program so to do that it's pretty simple all we're going to do is we're going to find the difference in the x and y values so what is the difference in the x value here so it's going to be 1 minus 0 and for the y values we also have 1 minus 0. so the x value here is going to represent the horizontal translation and the y value is going to represent the vertical translation so over here we're going to end up with one comma one and this is supposed to be a negative sign so one minus zero so this is the translation so if you move this to the right by one and you move it down by one then in that case they overlap each other so normally i know it's a little bit confusing you would think uh going down to be negative one but in this case going down is positive one going up is negative one okay so yeah so this is how we have it and we're going to do this for each and every value so now in this case this value of 1 in order to get it over here we have this translation so we're going to store this somewhere then after that we're going to see how can we get this value over here to overlap for this value of one we're gonna perform the same steps we're gonna do one minus zero which is one and then two minus zero which is two and then this is going to be another value which we store in our dictionary so we're gonna keep adding these values to our dictionary so for example over here we are going to end up with 2 comma 2 and obviously we're going to end up adding 2 comma 2 to our dictionary so currently our dictionary has these three values so how does it actually make sense and they're all going to have a value of one so all these are the keys with the value of one so how do we actually find out what the maximum overlapping numbers are so now we're done with all of the iterations for this element against that of b so now we're going to move to the next uh value so before we move on to the next iteration it's gonna be this value but i actually did a small mistake and this is actually not equal to one comma zero instead it's zero comma one so sorry about that this is actually zero comma one okay so now that we have that we can move on to our next iteration which is 0 comma 1 over here and we're going to perform the same steps so we're going to see so we're going to go to 0 comma 1 which is this and our goal is to make it so that this value over here so in particular this one over here has to overlap with each of the ones in the matrix b and we're gonna do the same steps so over here we have zero comma one and one comma one so that ends up being 1 minus 0 and then we have a 1 minus 1 which is 0 giving us 1 comma 0. and since 1 comma 0 doesn't exist we're going to add that to our dictionary that's a 1. okay next step so we have 1 comma 2 so that's 1 minus 0 which is 1 and 2 minus 1 which is 1. but do notice that this value already exists in our dictionary over here so we don't need to create a new instance of it so in this case what we're going to do is we're going to go to that original value we're gonna add the value plus one so it was originally one and now it's actually going to be two so you can kind of understand the pattern and this is going to keep going up so why does this actually work and what is going to be the end answer so if you keep going on our values are going to keep adding up and to a point one of them is going to have a value of three well we know that because this is that is the answer for this question so we get that by iterating through everything in a and everything in b so what's gonna happen and what this is basically telling us is when you perform the translation one comma one you have two things that are happening so this value changes and it overlaps onto another one so that causes one overlapping and this value also changes which also causes another overlapping and just to kind of i'm just gonna skip a few steps so uh normally you would do this along with this and then afterwards you're gonna go to this number over here and you'll do the same thing over here and once again when you come over here with this value one comma one you're going to end up with one comma one again so in that case we're going to go here and add a value of 1 again and this is going to end up being 3 so you can see how we got our answer and all it's telling us by performing the translation 1 comma 1 we end up with getting three ones which are overlapping on top of each other so what we're gonna do is at the ending we're gonna take all of our values from our dictionary and we're gonna return whatever the maximum value is and in this case that number is three so we're going to end up returning three so now let's see how we can do the same thing in code all right so let's start off by defining the two lists that we have so first we're gonna have a list so this list is gonna store all of the a values wherever we have the value one so i'll just call this a underscore one and it's going to be an empty list and then we have gonna have the same for our second matrix b so b underscore one is equal to an empty list as well so now we need to add um the tuple values of the x comma y index to this uh array over here so what we're going to do is we're going to iterate through them so we can just do for i in range length of a and the reason we're just taking the length of a or we can take the length of b is because they both have the same shape so it doesn't matter and then we're going to do for j in range of length i okay so we have this over here and now what we're going to do is we're going to check whether that whatever value we currently are at so we can get the value we're at going to the i index and then going to whatever the j index is and we're going to check if that is equal to 1 we're going to add that to our list over here so in this case we're in the a matrix so we're going to go to a underscore one and we're going to use dot append and we're gonna append a tuple values of i comma j and now i'm just gonna copy this over here and i'm gonna do the same thing but instead we're gonna do it for b so we're gonna check if that whatever value we're at is the same for b is equal to one for b and if it is we're going to go to b underscore one and we're going to append that value so by the ending of this list we're going to end up with both of these uh lists completely filled with the x comma y indices of wherever there is a value of one so now we're going to go on to the next part which is storing these values in some sort of dictionary so i'm going to call this dictionary d and it's just going to be an empty dictionary and we're also going to have an answers variable and this is going to have a value of 0. so over here what we want to do is we want to iterate through each of the a underscore 1 values and the b underscore bond values and we want to see what sort of translation the a needs to take in order to overlap that particular one with the b value so in order to do that i'm going to do for uh a underscore x and i'll also get the a y value so a underscore x comma a underscore y in our a underscore one uh list and we're also going to iterate through everything of our b underscore one list so the same way i'll just do for b underscore x and b underscore y in uh b underscore one okay so after we get this we want to see what is the translation we want to do so i'll just call this translation and the translation is going to be equal to the bx value so b underscore x minus the a underscore x value and um this is going to be inside of a tuple so instead of brackets so this is going to be the translation for the x axis and for our y-axis we're going to take b and for our y-axis we're going to take b and for our y-axis we're going to take b underscore y and subtract that with a underscore y okay so this is our translation value and over here we want to check if that value exists inside of our dictionary so if translation in d so if that is the case if it does exist and we're going to go to our dictionary go to that translation element and we're going to increase its value by 1. so if it does not exist then we're going to create a new key with the key as translation so translation and it's going to start off with a value of one and if it does exist well we're going to increase the value by one okay so that's going to be it for our dictionary and each time we go inside of this we're going to change the value of whatever the answer is so the answer is going to be the maximum from the previous answer so whatever our previous answer is it's already stored in the answer variable so for our first iteration it's going to be a value of zero so we're gonna choose between that value of zero or by whatever this value by just going here and to be more clear we're going to go to that specific key and we want to get whatever its value is so that key can have some sort of value and let's say that value in the first iteration is a value of 1. so in that case we're going to end up changing our answer to be a value of one so let's say after a few iterations that uh we find a greater value which has a value of two so in that case our answer is gonna end up changing from one to two so that's how our answer variable is going to end up changing and each time by the ending it's going to have the maximum key sorry a value in the values list so uh at the ending since it has the maximum value we can just directly return our answer variable okay so i made a really small mistake over here i wrote length of i and i is just an integer value so instead let's just do a of zero sorry okay and this should work so submit okay so i ended up spelling translation incorrectly okay i'll just change the name of this so instead of calling it translation i'll just call it something like tr so this is going to be tr and hopefully it is accepted this time okay there you go so our submission was accepted and finally thanks a lot for watching guys do let me know if you have any sort of suggestions and don't forget to like and subscribe if this video helped you thank you
|
Image Overlap
|
linked-list-components
|
You are given two images, `img1` and `img2`, represented as binary, square matrices of size `n x n`. A binary matrix has only `0`s and `1`s as values.
We **translate** one image however we choose by sliding all the `1` bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the **overlap** by counting the number of positions that have a `1` in **both** images.
Note also that a translation does **not** include any kind of rotation. Any `1` bits that are translated outside of the matrix borders are erased.
Return _the largest possible overlap_.
**Example 1:**
**Input:** img1 = \[\[1,1,0\],\[0,1,0\],\[0,1,0\]\], img2 = \[\[0,0,0\],\[0,1,1\],\[0,0,1\]\]
**Output:** 3
**Explanation:** We translate img1 to right by 1 unit and down by 1 unit.
The number of positions that have a 1 in both images is 3 (shown in red).
**Example 2:**
**Input:** img1 = \[\[1\]\], img2 = \[\[1\]\]
**Output:** 1
**Example 3:**
**Input:** img1 = \[\[0\]\], img2 = \[\[0\]\]
**Output:** 0
**Constraints:**
* `n == img1.length == img1[i].length`
* `n == img2.length == img2[i].length`
* `1 <= n <= 30`
* `img1[i][j]` is either `0` or `1`.
* `img2[i][j]` is either `0` or `1`.
| null |
Hash Table,Linked List
|
Medium
|
2299
|
1,382 |
hello guys welcome back to Tech dose and in this video we will see balance a binary search tree problem which is from lead code number 1382 and a prerequisite before watching this video is to watch my video on check if a given binary tree is a BST so the link for this video will be in the description below you can go there watch that and come back to watch this video again this topic is based on balanced binary search tree we will discuss all the follow-up problems at discuss all the follow-up problems at discuss all the follow-up problems at the end of the video so stay tuned till the end are you ready to take your programming skills to the next level well you are at the right place Welcome to our data structures and algorithms live interview training program interview those get ready to dive deep into the world of efficient coding and problem solving in interview those you will get a solid understanding of key data structures such as array stack queue he Breeze and along with that you will also Master powerful algorithms based on maths geometry graph and dynamic programming what sets interview those apart from other courses is the live interactive format you won't just be watching the pre-recorded sessions be watching the pre-recorded sessions be watching the pre-recorded sessions but you will join me along with other passionate Learners in real time where we will be covering the concepts together imagine having the opportunity to ask questions engage in discussion and collaborate with your fellow Learners it's a supportive Community where we all grow together but it doesn't stop there we will dive into Hands-On coding exercises solving real Hands-On coding exercises solving real Hands-On coding exercises solving real world problems and you will get to work with the interview assignments that will showcase your newfound expertise taking interview dose has already been a game changer for a lot of students and working professionals it didn't just help them to improve their coding skills but also boosted their confidence for tackling complex problems the live interactive sessions make all the difference unlock your coding potential by taking the first step forward contact us on WhatsApp for more details let us now look at the problem statement in this problem given the root of a binary search tree return a balanced binary search tree with the same node values if there is more than one answer then return any of them a binary search tree is balanced if the depth of the two sub trees of every node never differs by more than one so it is talking all about the balance Factor let us now look at some examples for better understanding let me just recap about what exactly is a band research tree for a binary search tree given any node if it has a value X then its left sub tree must have all the values less than x and the right subtree must have all the values greater than x this is true for all the unique values in a binary search tree but if you don't have unique values if you can have repeating values then we can take equals element on the left side or on the right side whatever but take it just on one side and be consistent with your assumption and your code as well now in this case if we talk about only the unique values then let's see if the first tree given is a binary search tree so if the root node is 7 then all the elements in the left subtree must be less than 7 and all the elements in the right subtree must be greater than 7 is this true yes it is true in this case right so the property is true for seven but we have to recursively check for all the internal nodes it's not like if the root follows the property it will always be a band research tree let's check for four if we are at 4 then all the elements in the left subtree must be less than 4 and all the elements in the right subtree must be greater than four so yes this is also true and leaf nodes are not required to be checked now if we go to the right hand side let's check for 9 all the elements on the left side must be less than 9 and all the elements on the right hand side must be greater than 9 and this is true as well therefore we can say that this is a band research tree but if you do the same kind of checking on the other tree that is the second one you will again say that this is a binary search tree but this is not the case why because in the first scenario we didn't exactly check it with the range of numbers like the root node is allowed to have any value in the range of minus infinity to Infinity which is actually excluding the infinite values right so we can have any value at the root node but as soon as we go to the left hand side the range will get divided now if I have all the unique values then the left hand side will have range of minus infinity to 7 but not including 7 because all the values are you unique in this case which we are assuming so is this 4 falling in this range yes now this 4 will actually divide this range into two parts in such a way that the left hand side will have minus infinity to 4 not including four the other side will have 4 2 or what seven but not including four and not including seven is this two falling in this range yes is this 5 Falling In This range yes so these all nodes are actually following the binary search tree property now if we check on the right hand side the range will be from 7 to Infinity not including 7 and not including Infinity this is nine yes it is falling in the range hence if the range will get divided into two parts on the right hand side you don't have any elements so no need to check there on the left hand side the range will become 7 to 9 not including 7 and not including nine but this 6 is outside of this range therefore this 6 is not following the BST property hence this tree is not a BST but the first tree was a BST if you check with this range bifurcation I have already discussed this in detail with the code in my video on check if a binary tree is a BST so you should watch that now once the recap has been done if a given tree is a binary search tree then by property in order of a BST always gives you a non-decreasing order of element that non-decreasing order of element that non-decreasing order of element that means ascending order of elements so let's say that this is a bsts it is a BST now the height of the BST can be order of n because it can be a skew tree as well like it is given in this case so how to actually balance it now a balanced BST is a binary tree where the height is guaranteed to be of the order of log n right so how to guarantee that the height will be order of login so before moving on to the solution let's just see the expectation right so this is the given question and you can derive the in order by doing the in order traversal on this given tree and you will always get non-decreasing order of element non-decreasing order of element non-decreasing order of element now if you balance this then you will not have just a single unique tree but you can have multiple balanced binary search trees I have already given three possible answers there can be more possible answers as well so we have to return any one of them all of the answers are correct so we don't care about which answer are we returning but it should guarantee a balanced BST now let us look at the solution now the solution says that the step number one is finding the in order which will give you non-decreasing order of will give you non-decreasing order of will give you non-decreasing order of element that means ascending order so you can easily do that by in order traversal now the second technique is based on the merge sort algorithm or you can say something like band research where binary partition on ascending order element maintains the ascending order and what do I mean by this let's see if I have to do binary partition on this like we do on merge sort then we will take a low on the leftmost side and the high on the rightmost side and we will do low plus High minus Low by 2 which will give me a mid value now whenever you get a mid value you have to make this as a node so make this as a node and then in the left subtree you move this 1 comma 2 and in the right subtree you move this 4 comma 5. with new ranges on the left hand side you pass this as low and this is high on the right partition you pass this as low and this as high right now if you again find the mid value for this you will see that this particular value will be the mid value and so make this as a new node on the left hand side actually you do not have any problem on the right hand side you just have to so this will be your low and this will be your high so this particular value will be your mid so make it as mid and there will be no other values now you will actually go back in recursion backtrack and then on the right hand side you will see you have a problem 4 comma 5. make 4 as the mid value because 4 is your low value and 5 is your high value on the left side you don't have anything on the right side you just have 5 which is low high and mid all these values are same so this will be the final structure if I redraw this it will look like this you have three one on the left side then you have two on the right side then you have 4 like this and you have five so this will be the final structure and this is guaranteed to be a balanced binary tree so the important intuition for this problem was to know that if you do binary partition on ascending order element it will become a balanced binary search tree this is the important point to remember what was the time complexity that we took the step number one took order of end time and this step will not take more than order of end time so it will be n plus n which will be order of n now don't confuse this second point to be n log n because we are not iterating through all the items but just we are finding mid using low and high and array Random Access is already order of one so if we are doing it n times it will be order of n so the time complexity is order of N and since we are creating a new tree you will see this in the code that I am creating a new tree therefore the space complexity is order of n now let us look at the code and once we are done with the code we will look at all possible follow-up problems this is the code for follow-up problems this is the code for follow-up problems this is the code for the problem of balanced BST we are just given the root node as we know that the first step is to get the in order so this is the code of or traversing and getting the in order into an array so I will store all the inorder values in the in order array and after that we will call the construct balanced BST so this particular code is based on your divide and conquer just like your merge sort algorithm using binary partition in this case I am sending the in order array which is ascending order array and then I am passing the initial low value which is 0 and this is the high value right and so whenever we go we just check the boundary condition of low should not be greater than High otherwise you just calculate the mid value right and simply make two partitions you create a new node at the current position store the current value there and then make two partitions so one will be from low to mid minus 1 and the other side will be mid plus 1 to high and this is your entire recursive solution let us now look at the follow problems these are some of the most important follow-up problems which you important follow-up problems which you important follow-up problems which you can get actually this algorithm is based on divide and conquer so anyone can ask you questions based on divide and conquer the code is very similar to merge sort hence you should know the implementation and working of the entire mastered algorithm this algorithm is also similar to binary search which uses binary partition using low high and mid very similar to your quick select algorithm or you can say quick sort algorithm as well then you can be asked questions on balanced binary tree what is a balanced boundary tree and one such important implementation is in AVL tree so if you have a lot of time left in your interview and if the interview is meant to be much more harder then you can get how to implement AVL trees so this is very important generally people ask Theory questions on red black trees but we don't expect any interview question on red black trees apart from a couple of theories and then this is also an important question check if a tree is a BST this question can come if you did not explain this current problem properly and so the interviewer might check your understanding on BST I hope this video was helpful if you want the PDF of this entire video lecture then do follow us on telegram the link will be in the description below you can also follow us on Instagram where we keep updating about the interview tips see you guys in the next video thank you
|
Balance a Binary Search Tree
|
balance-a-binary-search-tree
|
Given the `root` of a binary search tree, return _a **balanced** binary search tree with the same node values_. If there is more than one answer, return **any of them**.
A binary search tree is **balanced** if the depth of the two subtrees of every node never differs by more than `1`.
**Example 1:**
**Input:** root = \[1,null,2,null,3,null,4,null,null\]
**Output:** \[2,1,3,null,null,null,4\]
**Explanation:** This is not the only correct answer, \[3,1,4,null,2\] is also correct.
**Example 2:**
**Input:** root = \[2,1,3\]
**Output:** \[2,1,3\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `1 <= Node.val <= 105`
| null | null |
Medium
| null |
521 |
foreign welcome back to my channel and today we are going to solve a new lead code question that is longest and common subsequence one the question says given to string a and b return the length of the longest and common subsequence between A and B if the longest uncommon subsequent does not exist return -1 and subsequent does not exist return -1 and subsequent does not exist return -1 and then comma subsequence between two string is the string that is a subsequence of one but not the other a subsequence of a string as in the string that can be obtained after deleting any number of character from s for example APC is a subsequence of aeb DC because you can delete the underlined characters a e b d c is okay and the right characters with p e d and to get ABC otherwise other subsequence of a EBT include aebtc AEP and empty string so what we have to do here is guys we have to check for that if a is not equal to P then we have to return that whichever has the highest length of subsequence we will return that value so let's start solving this question and just before starting to solve this question please do subscribe to the channel hit the like button press the Bell icon button and book Marti playlist so that you can get the updates from the channel so what I'm gonna do here is I will check if a is equals to P if they are equal then I will return -1 if they are equal then I will return -1 if they are equal then I will return -1 and return Max and learn a and then B so if I run this code now I will be getting my answer so what I have did here is guys it's simple that I've checked if a is not equal to p means if a is equals to B I will be just saying that return minus 1 that's all they are what they have did here they have returned minus one if you see in example number one however if they are not equal if you see the example number second and third first and second a is equals to A B is equals to BBB so they have just checked whichever has the highest length we have to return which have whichever has the greatest land we have written there so I will be checking Max I will be using Max function in which I will be checking these two values and if they have uh not equal they will come here and we will be checking that whoever has the longest length we have to return there so that's all we have to do here thank you guys for watching this video If you like this video please comment in the comment section that you like this video and if still if you still have any doubt ask me in the comment section so this was all for today thank you guys for watching it and see you next time
|
Longest Uncommon Subsequence I
|
longest-uncommon-subsequence-i
|
Given two strings `a` and `b`, return _the length of the **longest uncommon subsequence** between_ `a` _and_ `b`. If the longest uncommon subsequence does not exist, return `-1`.
An **uncommon subsequence** between two strings is a string that is a **subsequence of one but not the other**.
A **subsequence** of a string `s` is a string that can be obtained after deleting any number of characters from `s`.
* For example, `"abc "` is a subsequence of `"aebdc "` because you can delete the underlined characters in `"aebdc "` to get `"abc "`. Other subsequences of `"aebdc "` include `"aebdc "`, `"aeb "`, and `" "` (empty string).
**Example 1:**
**Input:** a = "aba ", b = "cdc "
**Output:** 3
**Explanation:** One longest uncommon subsequence is "aba " because "aba " is a subsequence of "aba " but not "cdc ".
Note that "cdc " is also a longest uncommon subsequence.
**Example 2:**
**Input:** a = "aaa ", b = "bbb "
**Output:** 3
**Explanation:** The longest uncommon subsequences are "aaa " and "bbb ".
**Example 3:**
**Input:** a = "aaa ", b = "aaa "
**Output:** -1
**Explanation:** Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.
**Constraints:**
* `1 <= a.length, b.length <= 100`
* `a` and `b` consist of lower-case English letters.
| null |
String
|
Easy
|
522
|
168 |
Hello everyone, welcome to my channel, this is an easy question but very famous. It has not been asked by me. This has also been asked once in the company phone interview. Excel seat pen title. The name of the question is IT has not been asked by me. Microsoft and benefits and this Let's look at the question, it is a simple statement that you must have been given an integer named pen number. Ok you have returned its corresponding pen title. Further it appears in axle seat. Apne axle seat. You must have done it. Ok you have given the integer named pen number. Whatever pen title is there corresponding to it, you have to return it in the axle seat, but look at the example axle seat, if you open the axle seat, the title of the pen in it is something like this, it is B C Di and So On Jab S Ho. Then it repeats again like this. Okay, so look at the example. An example has also been given here that if yesterday the interior is given as mine and the caller number is given as one, then what will be its output. It will be okay. Yes, if you have given then it will happen. Now look one more thing, you have given one more example, otherwise see what will happen, now see how I am writing in pen, with those things which you already know, I will explain them very easily, first I will tell you that. So, how was the decimal number represented? Power of memories. You already knew that it is at the zero position, but you should remember one more thing. You will know that if I have to find out all the digits of this number, then remember how they were found. Keep taking reminders, which is its tense. It is a decimal number. Keep taking trimentors from ten until it becomes zero. Okay, as long as it is greater than zero, keep taking reminders, then I will keep getting digits. You are one and one is this. If you have done it earlier also, I had to call the digits as a reminder. First, okay, what is a reminder? If two comes, then okay, I wrote two in my result. Okay, after that, let's move ahead. After that, now it is the same, now you have become 12. Now I want one digital, so remember the name is equal, you make the number 10 becomes 12, now what is my number, one has become one, now my number has become one, okay, so should one be greater, give it zero, yes, then look now. It will come here what is one modal body, what is one, then I got the reminder, then I wrote it here, okay, now look here, what will happen is 1/10, it will become zero, then look here, what will happen is 1/10, it will become zero, then look here, what will happen is 1/10, it will become zero, then this vile look will end. Look, I will get all the digits. It is gone, even if it is found in reverse, we will reverse it, we will reverse all the digits in the string, what is the problem, look, we have got all the digits back, it is ok, we have got all the deleted ones back, so friend, this is it You have given me a number, now what have you given us in this question, don't look at the number, if you have given a pen number, then we will tweet it in a similar way, but remember the decimal number, which is one, three, four, five, six, seven. Nine ten means look after 10 then it starts becoming three one you one three one four and so on ok but remember what was happening in the pen number, it went from A to S, after that there was change to A S one so see There is a change after 26 letters, but look at the decibel, there is a change after 10 letters, it starts repeating, these 10 numbers are written, after that look, after one, again one has gone, this one has gone here, then you have come here. See, here it is completed after 26 units, so it was a sincere decimal, so it is repeating after 10 things, that is why see, we used to divide by 10, we had to play with every utensil, but here when we used pen number. Will delete, if we deal with the number of axle seat, then what I said is that it repeats after 26, otherwise what will we do, we will solve this question by doing only 26 instead of 10, we will follow the same method from the rest, if not anything fancy, that is why I want to say, relate the things, no, you have got the pen number now, but it is like a normal number, it is decimal and it comes in the size of 26, okay, it is clear till now, so I will write the code from the above. Whatever this code is, I will write the same code immediately, look at the multiplication in it a little, what will happen, that will also be understood by you, what have you got, okay, I will take out a reminder, so okay, I have taken out a reminder, okay, so what is my reminder, what is my pen number? Number 28 is given. Okay, so let's see. Reminder is the period of 26, so we will deal with 26 only. Okay, so 28 modulo 26, what is 26? I will do 26. This thing has become clear and I am writing by relating it. Okay, so what will happen here? If you do 28/26, only one will come, okay, you are there, then in the question it is said that A is which is, One is B which is It is you, it is C, which is three, it is given in the question, okay, so look here, a1 is b2, so why did I come here brother, you had come neither, what do I have to write for you, B has to be written again. I will come up, okay, zero will go to A, so this zero will go to A, and A will break my look, here 0 > 0, break my look, here 0 > 0, break my look, here 0 > 0, no, okay, here one will come, remember, then what is 1%, A is okay, now then what is 1%, A is okay, now then what is 1%, A is okay, now look at our The answer has come in reverse because now the number of 28 is no. It is an obvious thing. Last time too, the reversibility was done. When I had written about it, then 12 will reverse it. No problem, if you reverse it, then the answer will be A. Now it's ok, the answer will be 'A', now it's clear till now, ok, the answer will be 'A', now it's clear till now, ok, the answer will be 'A', now it's clear till now look, match the code, copy paste it from this three-line code, copy paste it from this three-line code, copy paste it from this three-line code, didn't do anything new, just here it was 26, there it was 10, here it was 26. And why is there 26, I have told you that too. Okay, now the point has come, remember this reminder, first you came, then one came, so for you I wrote B, for 1 I wrote A, so where will they come from, so in some map. Can be stored, the first question is that I will keep a map. Science, from which model are we taking it? It is okay from 26, so I am going to store it in the map, brother, if there is one, then there is A, there is B, if there is, then there is B. Isn't this map, when I want to do that, who will do that? There is a simpler way than that. Look, you must know that 67 is C's 68 and so on. Okay, so you think for yourself, if I add one to the character of A, then what? A will go to it's value add +1 to it then 67 A will go ok then B will add +1 to it then 67 A will go ok then B will add +1 to it then 67 A will go ok then B will go ok what does it mean that whatever value I get of reminder I will add one to it ok what does it mean that if the reminder is one then One plus A is ok, A means 66, so 66 + 1 will become 67, so One plus A is ok, A means 66, so 66 + 1 will become 67, so One plus A is ok, A means 66, so 66 + 1 will become 67, so what does 67 mean, it is done, okay, but remember the reminder one, but the pen of the axle seat, how am I updated? One is saying that. And you are saying B and C is three, okay then what will I do, whatever reminder comes, I will make it minus one, then instead of making 67, I make it minus one, then 66 is A, so if the reminder is one, then see. What am I taking 66, I am taking A, okay like this mother, you are taking reminder, okay, if I add A to it, how much A will go, 68 A will go, if you mined it will become 67, okay, and remember you mean B was only Na, A1 was B, Tu was even clear, 67 means B, according to the value of S, it is okay, I am telling you again as a reminder, if we take Ma, three is okay, then I will add A to it, then it will become 69. But what I said is that look according you question C means three okay but look here 69 A Gaya 69 is equal to di here if I do mines one then 68 A Gaya is 68 so what I am saying is that I simply What will I do with the reminder I am getting by modding it? Remember what I used to add in the reminder, I used to add one and minus one in it. Till then I was getting the character because I will keep adding in the result plus this equal you are clear till now everything must be going well in the last we will reverse the result ok so let's see if it runs for 28 or not if it is 28 then 28 reminder pen What will be the number 28/26 What will be one will be 28/26 What will be one will be 28/26 What will be one will be Back to one will be A Okay, here what will happen is one plus 6 minus one So 66 is A So what is the value of S of 66 is A Well, what will be the carbon number? 1/26, this will be what will be the carbon number? 1/26, this will be what will be the carbon number? 1/26, this will be zero, then the look will end and reverse the result. Now the correct answer is right. Just one. Look at the corner due to which things get messed up, it is your power, if you take mother, here is a multiple of 26, mother, this is only 26, mother, take this multiple of 26, mother, then see what will be the problem here is modal zero A. Will go to zero. Now see here what will go to zero plus 66 - 1 brother, this 65 is gone and what is 65? plus 66 - 1 brother, this 65 is gone and what is 65? plus 66 - 1 brother, this 65 is gone and what is 65 is something else. If you look at the chart of S then it has gone wrong. Here we have gone wrong, okay 26 What should have been the answer for s, should have come s, but it is not known whether it is a, okay, now think for yourself from here, it is 66, we have to calculate how much should be added to 66, only then we will have to add 25. S will come ok so 25 means how much is 91 so I have to bring 91 ok so in 66 I got ₹ 2500 66 A was ok this in 66 I got ₹ 2500 66 A was ok this in 66 I got ₹ 2500 66 A was ok this was I should have added 25 here I had a reminder zero and minus na minus one added Okay, so now think like this, you can solve it like this also, there is a pen, no pen, if you subtract the number then see what will become of 25. Okay, now look here, 25 modal, 26, how much will it be back to 25 a. Now see what I will do, I will put a reminder plus one in the result, just remember that a little while ago I was saying that A is 25, I wish I knew the addition, I had come up with it, so look, I reduced it to 25 by subtracting it and making it 25 + 1. But I got it ok and making it 25 + 1. But I got it ok and making it 25 + 1. But I got it ok 25/26 zero will come yes this is my answer 25/26 zero will come yes this is my answer 25/26 zero will come yes this is my answer so what is yes for 28 see it completely dry and I am showing you ok 28 see 28 pen mines 27 done 27 What will happen is one, okay now see my reminder is one plus A, what will happen is B, A will go, because if this happens then 67 A will go to 67, then B will go to A, so here A will go to the result, A will go to B, after that look 27 We had made it 27 / 26 Will it 27 We had made it 27 / 26 Will it 27 We had made it 27 / 26 Will it go to one Will it go to zero Is it zero Yes okay So 1 - I have again done this to zero A will go okay So 1 - I have again done this to zero A will go okay So 1 - I have again done this to zero A will go Mines mines every time Okay now look 026 Zero will go to one Now here Pay attention, reminder, this is zero, this is plus 66, so back to 66 C A, and what was 66, A was the value of S. Okay, and that's it, after this, zero will become 26 zero, now it will end up being reverse B A. If that too will come, this was my answer, okay small, what did we fix, this one, the Lord understood with dry iron, here it is okay, understood directly and made a mistake, only then I learned and learned the mistake when the modulo was zero. This one was when I was making a mistake, so from there I fixed myself, you will not learn until you make a mistake, it was short fine, if you did not find the solution in one go, it was a trick, but it was necessary to make a mistake only then. If you want to learn then it is okay, then we have also seen from the direct that it is correct, okay, now I will tell you about its time complexity here, remember, any number is Maa, you take it, you divide it by Tu every time, then by Tu, then Tu. Remember, what was the use of time compressor? Why did you use time compressor? Because every time we were dividing the name by 'Tu', Because every time we were dividing the name by 'Tu', every time the name was divided into two hands, we used to remove one half, that is, our size was reduced by two every time. ' our size was reduced by two every time. ' our size was reduced by two every time. ' Bye Tu' This used to happen, Bye Tu' This used to happen, Bye Tu' This used to happen, hence time complexity is no log of name, you are the base, but look at the number here, it is getting divided by 26 again and again, so what will happen to it, Dr of Kalam number, which is Kalam number, you are the best. 26 is your time complexity. It will be fine, but this is a very good question, it is special for interviews, it is fine, so I am here, I am able, you have written it in the help code, quickly stop late, let's finish it by submitting. Okay, so the solution is quite small. And we have dealt with it very well, this is how we deal with numbers, okay, you will get the Java code in the comment area or in the link given in Get Up, okay sir, let's start quickly. This is the string, my result is ok, we will keep entering the answer in this. As long as we give a pen number that is greater, we will keep going till it remains zero. Ok, we will keep going on pen number minus mines. Once the reminder comes out, the reminder is equal, take the pen number, we are doing 26. Yes, which character is it, you will know now, reminder, here yesterday we used to divide the number, pen number 22 is equal to 26, you are reverse hitting the result and the result is fine, now see Karan number A = this is the shortcut, now see Karan number A = this is the shortcut, now see Karan number A = this is the shortcut, you can do it like this. You can also write the pen number, it is the same thing, so here I have written A = 26, okay, let's see it directly by submitting the run, A = 26, okay, let's see it directly by submitting the run, A = 26, okay, let's see it directly by submitting the run, hopefully the run should be done, there should be no problem, isn't it was a very simple code, it was good. Any doubt would have been understood from this. Resident D common area tree, you help and next video thank you.
|
Excel Sheet Column Title
|
excel-sheet-column-title
|
Given an integer `columnNumber`, return _its corresponding column title as it appears in an Excel sheet_.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
**Example 1:**
**Input:** columnNumber = 1
**Output:** "A "
**Example 2:**
**Input:** columnNumber = 28
**Output:** "AB "
**Example 3:**
**Input:** columnNumber = 701
**Output:** "ZY "
**Constraints:**
* `1 <= columnNumber <= 231 - 1`
| null |
Math,String
|
Easy
|
171,2304
|
341 |
Hello Guys I Am Lalit Agarwal Welcomes You All On Your Own Coding Channel Code Face Made By You Made For You So Let's Start Now Today's Lead Code Problem Aaj Ki Lead Code Ki Problem Kya Bol Rahi Hai Achcha Before Moving Towards The Problem Na One Minute Session For those who have understood this problem well and who want to try it once on their own, see the question which is literally a very easy question, you just have to do it yourself, what is it here that you can understand this very easy concept. You can see from this because what is said here is that Max 500 can come, it can come nested, why because what is the size of its nested list, Max 500, this means in the worst case scenario, 500 lists can come in this one. Inside the list he said, okay, so what formula can I apply there? I understood that if I go directly, I will get stuck somewhere, okay, then what formula can I apply here? You can assume that you will iterate over this list normally and say it is okay and wherever you find another list, it is okay, there you will call back the same formula and try to understand carefully that you are doing this list. He said, okay, then we will create some function where we will call ourselves to flatten this list. He said, okay, if you get an integer there, then it is very good, you will move to the next one, and if On moving, we got another list. If on moving to the next one, we got another list, then to resolve that list, we will call back our same function. Do you understand by doing recursive calling? If you give then what will happen as soon as you make recurs calling that now you will move back inside this list then the int will say ok leave this too then this 211 came out very easily as if there will be problem here like this one. I said ok, so it got integrated very easily, then after that now it got listed, as soon as this list was passed to itself, what did I do, I called this function back in that function very easily. He went out and said, okay, now these six have come back in a list, so the function will be called again for this list, so which function is this, the recursive function is done, think about it a little in this way and The question will be answered very easily. Well, those who have not understood the question, there is no need to take tension. First of all, you are going to understand very easily what this question is trying to say, after that we will build its approach and then Finally we will move towards its implementation. Look, understand what the question was saying. In the question, you have given a nested list, that is, this is a list inside a list, it is okay, there can be multiple lists inside this list, okay. And this does not mean that like there is a list and then there is another list, this is not a multiple list. What does the next list mean that like this is a list, there is another list inside it too. And there can be multiple lists as well. Have you understood this? Yes brother, you have understood. There is no doubt in this. Why do you have to return? What do you have to return? All the nested ones are here. Everyone has to be removed, ok and as soon as what was coming first, one was coming and said ok, then you have to bring one, then after that one was coming, said ok, you have to bring one, after that two was coming and said ok. You have to bring two, after that one was coming, he said, okay, you have to bring one, after that, one was coming, he said, okay, you have to bring one, this is what you have to give in the output, that is, you have to give yourself a vector in the output and you have to bring one. Did you understand what Ned is writing? Said, Yes brother, I understood, there is no doubt in it, the question should be clearly clarified. Okay, now how will you approach this? We will try to make a function of your own. Said okay. If yes, then you have created a function, given the name of the function anything, said ok, inside it you will call your list, now what will you check as soon as you call this list, first of all you will do a simple check that you are iterating inside the list. With the loop of ' you are iterating inside the list. With the loop of ' you are iterating inside the list. With the loop of ' Okay, there is no problem, first of all this element came to me, now this element came, I checked what to tell, this element is in the list, I said, 'Bhaya, this is the tell, this element is in the list, I said, 'Bhaya, this is the tell, this element is in the list, I said, 'Bhaya, this is the list, yes,' so I list, this is the list, yes,' so I list, this is the list, yes,' so I made the condition of 'Y'. List is inger said made the condition of 'Y'. List is inger said made the condition of 'Y'. List is inger said list is list so back I called this function for this list ok yes Samjh said this thing yes brother I kept a pointer here and at this point of time I called this function back Called the function, now it came back to the function, on whom will the loop of four run on it, okay, on it, the loop of four will run on it, said yes, brother, did you check the condition of it, whether it is in the list, said no. Bhaya, if it is not in the list, then it came out of the condition, that means it did not go into the condition, after that it checked that yes brother, this is an integer, very easily get it inserted in that final vector of yours, a value and then again it went to four. Now this one is on top of the one, okay is this one list, said no, it is not a list, okay this was also our integer, we have come, okay this then the entire function of this is over because the size of this list is over. I have already said 'f' brother, this is returned back. said 'f' brother, this is returned back. said 'f' brother, this is returned back. Return back to what. It is back on the same pointer which I had used for the first time. I said ok, now here the condition of 'f' is over. I said ok, it will not go to 'else' said ok, now here the condition of 'f' is over. I said ok, it will not go to 'else' said ok, now here the condition of 'f' is over. I said ok, it will not go to 'else' then back to 'four'. When the loop went into the loop of four, then back to 'four'. When the loop went into the loop of four, then back to 'four'. When the loop went into the loop of four, then what second element did it get? What is it an integer? Said, Yes brother, What did it get? What is it an integer? Said, Yes brother, it is an integer. It will be inserted easily somewhere, there is no problem, then back it got a list. It got a list. Will he repeat the same function again? Brother, was it such an easy question? Said, Brother, it was just such an easy question. The three functions he had asked for are all three functions. Just build this function, all three functions will be completed very easily. How? First of all, what did you do? Globally, you created a vector. You said, okay. Globally, you created a vector and globally, you also created an index. You said, okay. Then what did you do? You created this function. Now in this function, you created What did Apna do? Understand well what Apna did that here Apna gave the list. Said ok, now here in the loop of four, how can you run the loop of Apna i = how can you run the loop of Apna i = how can you run the loop of Apna i = 0 end blah But do n't run like that here, even by mistake, the reason being behind is that you don't know whether your element is a list or an integer, so when you go ahead and cast it, you may face problems, so here your What has he said - your What has he said - your What has he said - take whatever type of list comes, if integer type element comes then it will automatically become integer element and if list type comes then it will automatically become list, it will not give error otherwise it would give error. He said, "Okay, it's a simple thing, there is He said, "Okay, it's a simple thing, there is He said, "Okay, it's a simple thing, there is no problem, now this loop of four has come." He no problem, now this loop of four has come." He no problem, now this loop of four has come." He said, "Okay, in the loop of four, we have this one, let's check it with the example of the said, "Okay, in the loop of four, we have this one, let's check it with the example of the said, "Okay, in the loop of four, we have this one, let's check it with the example of the second one, we have considered the first one as ours, so here we have one." Aapna said ok, so one has here we have one." Aapna said ok, so one has here we have one." Aapna said ok, so one has come in its own element. Apna has come, what did you check in its condition, is it an integer, if it is true, then what will you do? Apna will normally push it inside v. Element dot get integer, take out integer from this element and push v inside v, what was your vector, there should be no problem, said yes brother, it is clear, it will not go in else, okay then go back and take Now what have we got, this has got the list, okay, so this loop of four has run, now what has come in the element, this nested list has come, I checked back, is this an integer, said no brother, now this is not an integer, ours. What did he say when he went to others, call the function of create list? What is the name of this function called create list? Bulaaj bhaya, this function you have called back from others and what element have you given at this point of time. Dot getlist means pass the list of what has come to this function which you have done, there should not be any problem anywhere, now it went to this function and after going back it will now get this list. He has got it back for this, he ran a loop of four for this particular list, it is okay there, now here, what has he got here, he has got four, said, is it okay in its condition, is it an integer, said, yes brother, it is an integer, it is Four is a particular integer. Okay, so I pushed it back inside the v, so one was already four. Now the pushback has been done, then after that, the loop of four went back. After the loop of four, this is the six. It is also closed inside a list. Okay, this six is there, so it is closed inside a list. Okay, this six is there, so it is closed inside a list. Okay, this six is there, so it is a single character, but what is it? If it becomes inside the list, then what is the condition that failed because here this integer is not there, so where did the else go? I went back to the others and got a call for these six. I understood this same function and said, yes brother, I understood, there should not be any doubt anywhere. I said ok, I have understood this function well, after that now these three If you had to manually build the function, then first of all, what did you do? It asked for the next iterator, then what did you do with the next iterator? What did you do in the nested iterator? Whenever the nested iterator is called, it means What is that if you want to make your list nested, then you did not do anything, started the index from zero and called the create list function and here your main list which you got at that time is your nested list. He gave it to this function and said, okay, now why did it start from the index row, because as you suggest, 146 have already been created. Yes, what has the question said at every point of time that I will give you the index, you have to tell me that its Whether the next element is present or not or I will run a while loop where I will check next, whether the next element is present or not, means whether it is nested or not, here you have to return true or false if you have given true. If returned, then I will call the next value. He said, OK, so I understood what you did in this function. He said, nothing, so you called that function and set an index to zero. Done said ok, now first understand this function, what have you said in this function you have simply said whether the next value of the index on which you are standing is present or not, then your simple Checked bool to return true or false and this is a nested function here, what did you return that whatever is the size of your index now, is b more than that? What is the size of v? What is your vector? Within which its own nested list is present, if it is more than that then of course it will return true, it means that the next index was present, otherwise it will return false. No problem, no problem. What did you do here? Did you return the next value? How did you return the next value? Did you return v and what did you do to the index in it? Plus, it will first return the index value and then automatically add a value to the index. Increment will also happen like what will be the index? One I hope you have understood well, still if you have any doubt then comment box is all yours and they are there for you. After submitting, you are watching. Submit very easily. Okay, you tell me what will be its space complexity and time complexity. Look, first of all, if you are making its space complex out of brick, I said yes brother and inside that you were doing all these push backs, then apart from that, space complexity will be. And if there is something specific, otherwise we were making the space complex, because of this, why did it become off n and it will definitely be made because what has to be done to Apne, we have to get it returned, how to say, okay, so this vector of ours means off a, so our Space complex is done, now let's talk about time complex, time
|
Flatten Nested List Iterator
|
flatten-nested-list-iterator
|
You are given a nested list of integers `nestedList`. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.
Implement the `NestedIterator` class:
* `NestedIterator(List nestedList)` Initializes the iterator with the nested list `nestedList`.
* `int next()` Returns the next integer in the nested list.
* `boolean hasNext()` Returns `true` if there are still some integers in the nested list and `false` otherwise.
Your code will be tested with the following pseudocode:
initialize iterator with nestedList
res = \[\]
while iterator.hasNext()
append iterator.next() to the end of res
return res
If `res` matches the expected flattened list, then your code will be judged as correct.
**Example 1:**
**Input:** nestedList = \[\[1,1\],2,\[1,1\]\]
**Output:** \[1,1,2,1,1\]
**Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,1,2,1,1\].
**Example 2:**
**Input:** nestedList = \[1,\[4,\[6\]\]\]
**Output:** \[1,4,6\]
**Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,4,6\].
**Constraints:**
* `1 <= nestedList.length <= 500`
* The values of the integers in the nested list is in the range `[-106, 106]`.
| null |
Stack,Tree,Depth-First Search,Design,Queue,Iterator
|
Medium
|
251,281,385,565
|
735 |
Ajay ko a firewall welcome to line repeat step exactly date 28th October write charge religion ho to problems acid calibration difficult problems were given are sports officer representing a strong for each sexual positive and negative left subscribe to find the state of the states After All Relationships Tip Posters Meet Someone Will Explore Tip He The Same Size Electrode Does Mother Same Direction Will Never Meet And Saddam Only And Deposit This Rumor To Martin - 500 Fear Death In This Positive Meaning Right Method To Martin - 500 Fear Death In This Positive Meaning Right Method To Martin - 500 Fear Death In This Positive Meaning Right Method Meaning Of Some Positive Illmo Tubelight Negative Immortal Hits Executive Se 10 Minutes Collect Tense Positive Which is the Number Patience 2 - 5th Positive Which is the Number Patience 2 - 5th Positive Which is the Number Patience 2 - 5th and 8th Month to Write a Sentence with One Five in Terms of Absolute Value Year - But Will in Terms of Absolute Value Year - But Will in Terms of Absolute Value Year - But Will Explore Effect of Haze - Compound Paaye Explore Effect of Haze - Compound Paaye Explore Effect of Haze - Compound Paaye Cotton Hai Ki Electric One More Examples Share 8th - 600 Value Jersey United States 8th - 600 Value Jersey United States 8th - 600 Value Jersey United States Positive Set Mode Own Right - Negative Saving Positive Set Mode Own Right - Negative Saving Positive Set Mode Own Right - Negative Saving Mode To The Faith But When The Collide Perception Number Seven Desk System Market Solve Will Exploit Sweet Will Have MP3 Similarly He Attend Through Management Software Tool Motor Right - Saver Mode On Left Saudi To Motor Right - Saver Mode On Left Saudi To Motor Right - Saver Mode On Left Saudi To Lotus Ayurveda India To - - - - Prevent Lotus Ayurveda India To - - - - Prevent Lotus Ayurveda India To - - - - Prevent Next9 That Butt In This Movie Don't Forget Thumbs Mein Flats For Example Subscribe 90 Yes Brother Engine - Mein Bhed See What Happens Yes Brother Engine - Mein Bhed See What Happens Yes Brother Engine - Mein Bhed See What Happens Ki Side Share Price Move Into Right Manner Smooth Mention Scenes Both Fan - Wiring SIM Smooth Mention Scenes Both Fan - Wiring SIM Smooth Mention Scenes Both Fan - Wiring SIM Value Worth Electrode Share Both Worlds Pendant Will Yadav Yes This Pack Martin Ayodhya Se Mere Boobs 510 Hai - Paye Ban Paye Rate - Paye Ban Paye Rate - Paye Ban Paye Rate Jai Hind Ke Is Des Moines Yudh Right Dushman Tubelight Desmond Tutu Left Right In The Recent Write-ups Yudhishthir In The Recent Write-ups Yudhishthir In The Recent Write-ups Yudhishthir Electrode But Not Least to subscribe The Channel Please subscribe and subscribe the Channel Please Click on Torch Light from here.the first Torch Light from here.the first Torch Light from here.the first reply is Dasham Length and Airtel B.Ed Lesson reply is Dasham Length and Airtel B.Ed Lesson reply is Dasham Length and Airtel B.Ed Lesson Length and Mom Numbers in Between and Number from Don't pay attention to the right side 2.1 Point to the Don't pay attention to the right side 2.1 Point to the Don't pay attention to the right side 2.1 Point to the element Radhe-Radhe subscribe The Amazing element Radhe-Radhe subscribe The Amazing element Radhe-Radhe subscribe The Amazing spider-man subscribe and subscribe the spider-man subscribe and subscribe the spider-man subscribe and subscribe the Channel And subscribe The Amazing Hai 220 My IS Greater Than 20 Minute Motorcycle And Due To This Abuse Developed In This Happens Only During British Rule And Condition IS MOVING AT LEAST 10 MINUTES EACH DAY THAT IT'S JUST AN ASTEROID PIMPLE HISTORY OF A GREAT 10 AND HIS TEAM OF CHAIN SNATCHERS WHO IS THIS IS GREAT 10 AND HIS TEAM OF CHAIN SNATCHERS WHO IS THIS IS GREAT 10 AND HIS TEAM OF CHAIN SNATCHERS WHO IS THIS IS THE CONDITION 19.06 TO SEE WHAT WE CAN DO WHEN THE CONDITION 19.06 TO SEE WHAT WE CAN DO WHEN THE CONDITION 19.06 TO SEE WHAT WE CAN DO WHEN THE CONDITION IS HER ANDROID HOW WE CAN ARRIVE AT THE FINAL Result Inducted In Order To Create A Good Tours Subscribe And Share Subscribe To 102 Hua Had Indicated This Layer Dwarkaites Afshan Saifi The Amazing And 1000 Years Boy Genocidal Directly On Play Store Sanjay Bring To That Disposition And When Vomiting Diarrhea Dysentery Now This Condition Will Not Be Satisfied With Life On So I Will Not To This Position And They Will Not Speak Now Festivals Candy Crush Like Subscribe And Festivals And Is Licensed Under CC0 1968 Effigy Of U Ki Apes Luto A S D F Z Plant That Can Be 10 condition 100 condition like it is equal to is this festival of sexual dishes subscribe The Channel and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to the Page Members Singh and Lo OK and the Siddhabali from this they know What Will Happen If They Don't See That Gives Pain In Office Late Se Is Great And Absolute Value Of Yesteryear That I Subscribe To I do any condition remaining that STF is laser history of my face so let's check one example tasty of high schools in members 2m 10 minutes pakaayenge iske members 2m 10 minutes pakaayenge iske members 2m 10 minutes pakaayenge iske arrange iske apk file The Amazing Subscribe - - - - JE Click Subscribe Button Subscribe - - - - JE Click Subscribe Button Subscribe - - - - JE Click Subscribe Button And Subscribe to my channel now to receive new updates and more in Ayurveda - - OK bye take one more in Ayurveda - - OK bye take one more in Ayurveda - - OK bye take one more question ki NTPC mein example of 80 2 - 502 ki NTPC mein example of 80 2 - 502 ki NTPC mein example of 80 2 - 502 Dar-Dar Judge Saat Aath Se Zara Show The Bachelorette of Dar-Dar Judge Saat Aath Se Zara Show The Bachelorette of Dar-Dar Judge Saat Aath Se Zara Show The Bachelorette of Vice President to subscribe to the Page if you liked The Video then subscribe to The Amazing Subscribe Now Subscribe To That Now Will Go To The Next Loop This Condition A Great 10 And Taste Your Purchases Not Lose 20 Welcome To The Spot Vikram Too Difficult Condition Now Is Keeping Track Of Channel Subscribe SUBSCRIBE DIRECTLY AG SUBSCRIBE AND A REQUEST TO A S D F G J JUST DIRECTLY COPING SPECIALLY THIS SCHEZWAN FORWARD THIS ONLY ONE SUBSCRIBE THE CHANNEL AND SUBSCRIBE THE CHANNEL SHOULD BE THE SUBJECT IN THIS REGARD THIS 2.5 BE THE SUBJECT IN THIS REGARD THIS 2.5 BE THE SUBJECT IN THIS REGARD THIS 2.5 INCH SADA COMPLETENESS Of Disbelief And Saving 2018 19 2012 That Solution Of Your Slider Code For The Buddha First Posted Length Of The Point Declare Ion Jewelry Fever This Is Zero Angeles One Jhalawar Elgin Hello Message Send Length According To Same Condition Semantic Asteroid Straight Fire Bigroad 0 Ki And Stars Of J0C Decade I 10 Minutes Check Botany Stuart Broad Wright Some Space Tradeoff I Think Not Celebrate 150 Years Due Difficult To Strength Of Cheese With Water Slide Show Members Happy 192 Destroy Bodh Website Ing So I'll Be - Man Sanjay Viplav Ing So I'll Be - Man Sanjay Viplav Ing So I'll Be - Man Sanjay Viplav 20 Conditions Will Be Easy And Sacrifice License Canceled Ashrafi Greater Noida Fix Halki By Patel Remove Gel Types Of Removing Dress Nothing But A Plus Mohan Ji Power And The Spot That's Why Iceland J&K Power And The Spot That's Why Iceland J&K Power And The Spot That's Why Iceland J&K Soldiers Put Mobile Phones - - - - And Soldiers Put Mobile Phones - - - - And Soldiers Put Mobile Phones - - - - And Share And Subscribe This is greater than or equal to zero ungli dhan enter in this function held with his condition has not in that case how can see free see plus and a prosperous and also for the condition lighter apr improvement in the night before The Time To Of The Value Of Yourself Into History Of Doing This Rather Than 200 Ko Subscribe This Video Plz Subscribe The Channel And Subscribe The Main India Influent Ki Gurjar Ke Sajjan Aayi Ki Training Expert 90 Vacancy Lajaaye Goodbye And See Plus Ki Aisi Result Off key request on streets of it and they can return the result so let's submit jamshedpur appointment once ok heer and bean k 209 recent ko a suitcase patient time 10 that instructor association questions page bright to comment section and he is the like button hit Bell Icon to get notification for all such videos thank you
|
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
|
137 |
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 single number two so in this question we given an integer array called nums where every element appears three times except one and that element appears only once we have to return the single element as the output and we have to build the solution with o of n time complexity and O of one space complexity so in this case the output for this example is three because three is appearing once and in this case the output is 99 because 99 is appearing once where rest of the elements 0 and one are appearing three times each so let's look at first approach which comes to the mind which has space complexity of O ofn so we are going to count the frequency of every element inside the map and store it in a hash map and we'll iterate through the hash map and check which element is appearing only once and that will be our output so let's take a look at the code so first I'm creating a map so I create a hash map here now I iterate through the input array AR so this is the input array let's take the first example so we iterate through the input array 11 10 1 from the starting so I is pointing here we check if that element is present inside the map no so this block will be executed so we put that element and set its frequency to one so one will be added and its count is one now let's go for the next element it is 10 check if it is present inside the map no it's not present so this will be executed so enter 10 and set this frequency to one the next iteration I is pointing at 1 num is one check if it is present inside the map yes it is present so get its current frequency of 1 is 1 so 1 + 1 = 2 so two will be is 1 so 1 + 1 = 2 so two will be is 1 so 1 + 1 = 2 so two will be inserted into the value of one now go to the next element I is pointing at one check if that element is present inside the map yes one is present get its current count is 2 + 1 so three so insert count is 2 + 1 so three so insert count is 2 + 1 so three so insert one's value as three and we reach the end of the iteration in the next iteration I will go out of bounds now we iterate through the entries inside the map from top to down there are two entries inside the map we take the first entry so I use entry interface and use this entry object to through the map check this entry I'll get its value if check if its value is equal to one no if it is not then go to the next entry is two get its value is one check if it is equal Al to one yes it is equal to one so get its key so this is the key and store it inside result and we finished all the entries inside the map we come out of the for Loop and return whatever is present inside result has the value 10 so 10 will be returned as the output so in this case the time complexity is O of n which is fine but the space complexity is O of n but we are expect to solve it using o of one space complexity so let's take a look at the second approach so let's take this example now that we can't use any extra space we have to find the solution in place in this case one is appearing three times two is appearing one time and three is appearing three times expected output so this is not very common to get into your mind that we have to use bit manipulation to solve this question in the previous question single number every element was appearing twice so if you do XR of every two elements it will get cancelled and the single element will be returned as the output but in this case every element is appearing three times so we cannot do XR operation because there are odd number of occurrences now we have to convert these AR elements into their binary format so one is represented as you know the 8421 code right so this all will be zeros and wherever you need the sum this will be one two will be represented as 0 1 0 and three will be represented as 0 1 because 2 + 1 is 3 so these two 0 1 because 2 + 1 is 3 so these two 0 1 because 2 + 1 is 3 so these two bits will be set and now we know the count of one so one is appearing three times so let's write this three times two is appearing one time so let's write this once and three is appearing three times so let's write this three times and now this is the zeroth bit this is the first bit this is the second bit and this is the third bit and so on there will be 32 bits for an integer right all the rest of them will be zeros so this will be zero for everything so this is one this is two and this is three now we need to take the sum of every so this will give you 1 + 1 + 1 + 1 + 1 this will give you 1 + 1 + 1 + 1 + 1 this will give you 1 + 1 + 1 + 1 + 1 this is 6 this will give you 4 this will give you 0 and this will give you 0o and all the 32 32nd column will also be zero rest of all will be zeros now if we take these digits this digits should be a multiple of three right so if you mod three you should get zero so the zero bit is zero and for this if you do 4 mod 3 you get 1 which is not equal to zero so this is the observation which will help us to Sol the question and rest of all are zeros so 0 mod 3 is 0er and this is our output right we are doing mod 3 because every number should occur three times that is why we are doing mod 3 but which number is appearing only one time which is our output two is appearing only once that bits digit will not be divisible by three so here you can see four so three are coming from this 3 + 1 four so three are coming from this 3 + 1 four so three are coming from this 3 + 1 is coming from this 2 and this 3 + 3 + 0 is coming from this 2 and this 3 + 3 + 0 is coming from this 2 and this 3 + 3 + 0 this is coming from one this is coming from three and this is coming from two so it means that the zero bit in two is having value zero so with this we can find out zero this one is coming from the number two so this will be one so with this we can form our output which is 2 so 2 is 1 0 and 1 0 which is equal to 2 will be our output so to check which bit is set to one or zero we can use mask so using the left shift operator with the mask so mask is equal to 1 left shift of the I so I will range from the bits that is the length of 0 to 32 so in the beginning 1 Z will give you some value 1 shift of 1 will give you the some value one shift of two will give you one value and so on one left shift of 32 will give you some value so these are the bit positions to know which bit is set or not so this will give you so like here we are finding out the mask using a for Loop now we have to play with this mask values now we have to iterate through the number present inside the array AR we iterate from starting to end and we pick the first element in the beginning and I will reach the end and this will happen for every element inside that so we do num and operation of mask so if this is not giving you zero if it is giving you value greater than Z then you increment a variable called sum the sum is going to be the sum of each bit in first iteration we get the sum value as six next with this six in the next step after this you have to check if the sum when modul by 3 is not giving you zero with this we will identify the number which is appearing only one time so this can be written as if some modulo 3 leaves a rem remainer of one or if some modulo 3 is Le leaves a reminder of two then we build our answer which is this which corresponds to this value two so answer will be built by doing our operation with the mask and this will happen for all the 32 bits and finally we return our answer now let me code it up and then we'll do the debugging so that we get the complete understanding of the code so we given the input AR and N is the length of that AR we don't need this we can directly find out since we have to return our output which is an integer variable representing the element which is appearing only once so let's create it I'll name it answer and initially it will be zero now we iterate using a for loop with all the bits that is from 0 to 32 now we have to find the mask right so mask will be one left shift of I and I declare I'll declare this outside the for Loop now I will iterate through the elements inside the r RR using a for Loop now we have to build the SU of every bit right the sum operation will be found out for every bit that is 32 bits so initially I'll create a variable called sum and initially it is zero and now I will build the sum so if that number and mask is not equal to zero then we increment sum so sum is equal to we'll add one to that sum because Zer doesn't have any value so whenever it is one we have to increment it by 1 like here as you can see wherever there is one we increment it so 1 2 3 4 5 6 so six will be stored inside sum now that we have the sum we have to check if the sum is divisible by three or not modul 3 is not equal to zero so this you can replace by this condition if some modular 3 is equal to 1 or some modular 3 is equal to 2 because for example if you take any number so let's take first num is equal to 4 if 4 modul 3 is equal to 1 because when you divide 4 by 3 you leave a rem remainer one if num is five and if you divide it by three it leaves a remainder two and if you take six it leaves a remainder zero so these are the three possible values for remainers and we are checking if remainer is not equal to zero so it means remainer is equal to either 1 or two so you can replace that with Su module 3 is equal to 1 or if some sum modul 3 is equal to 2 then we build our answer using an R operator with mask so answer or equal to mask so answer is equal to answer or mask with that we'll get our final output in our answer and outside the for Loop you can return answer as the output so here this is one left shift I right and now let's try to run the code so I've taken the same example and I place two break points let's try to debug it so here mask value is one we iterating to that some will be incremented by one Su is two sum is three sum is 4 sum is 5 now the zeroth bit is set to six we're checking if six leaves a remainer zero no it doesn't so that bit is not part of the answer correct right 0 1 0 and 0o bit is 0 this gave a reminder of six so that bit is not part of the answer now some value is being built for the first bit Su value is equal to 4 some 4 mod 3 is equal to 1 this condition passes and that bit is being stored as the answer so first so we get four so 4 mod 3 is 1 in the first bit's position two has the value one so now answer so answer value is being updated by two here as you can see answer as the value two now it will do for the second bit and Here If You observe the from the second bit to the 302nd bit two has zeros in it so that won't be part of the final output so this condition will never pass and final output will remain as you can see I'll keep moving forward I three i 4 I 5 I6 7 so this will happen until I equal to 32 because this Loop will come compulsory learn for 32 times so as you can see after 32 we got a final output so until 32 answer was two and finally here so result has a value two and two is being printed as the output I'll paste the same code here in lead code and change ARR to nums and let's try to submit the code and solution has been accepted so the time complexity of this approach is of n because we're rizing through the input nums array from left to right from starting to end and the space complexity is O of one 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
|
Single Number II
|
single-number-ii
|
Given an integer array `nums` where every element appears **three times** except for one, which appears **exactly once**. _Find the single element and return it_.
You must implement a solution with a linear runtime complexity and use only constant extra space.
**Example 1:**
**Input:** nums = \[2,2,3,2\]
**Output:** 3
**Example 2:**
**Input:** nums = \[0,1,0,1,0,1,99\]
**Output:** 99
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-231 <= nums[i] <= 231 - 1`
* Each element in `nums` appears exactly **three times** except for one element which appears **once**.
| null |
Array,Bit Manipulation
|
Medium
|
136,260
|
387 |
Hello hello friends in addition to withdraw into a discussion see list to problem solve tunic character in string give one of the simplest portion mostly used in the elephant according to screen in grams you will gain benefits from already tourism find the first not repeating character industry and return Index Back Pimples Flute In This Is The First 90 Example You Subscribe Egg Beater Input 999 Characters Simply - Shyam The Characters Simply - Shyam The Characters Simply - Shyam The Who Is The Input Singh Only Contents Lower Case English Latest Know Let's Discuss With Logic Logics Pretty Simple Values English Logics Pretty Simple Values English Logics Pretty Simple Values English Alphabet Name Bus Reddy Problem Central Excise Officer English Channel Not Subscribed * The Match David 150 140 Characters Not Subscribed * The Match David 150 140 Characters Not Subscribed * The Match David 150 140 Characters and How to Identify the Character C - and How to Identify the Character C - and How to Identify the Character C - Subscribe to Character Do0 - Key Value of Character K 1997 On Do0 - Key Value of Character K 1997 On Do0 - Key Value of Character K 1997 On Service to So Inductive Represented Characters Page Will Calculate Character Position Points 181 A Minor Boy Death 9 7 The Answer Is Level 100 Index 11th President Character Neither Will It Is The Director Kabir They All Can Attract subscribe and subscribe this Video like Share and subscribe the Channel and that in such cases will simply return - and that declare and interact with size 06 A b p news different keep track of character caught in the string tries character input thank you will increase character com vidmate app ke value increase accounting character no valid and second if 2.5 not repeating this page will second if 2.5 not repeating this page will second if 2.5 not repeating this page will quit well-written content has equal to One quit well-written content has equal to One quit well-written content has equal to One 's spread said that Desh 's spread said that Desh 's spread said that Desh Jhal's Bhim's f-35 no account to exhausted Bhim's f-35 no account to exhausted Bhim's f-35 no account to exhausted and unique character lets return - Paun inch and unique character lets return - Paun inch and unique character lets return - Paun inch ke miding latest avoid falling fast unique character function with multiple inputs and outputs hai ek rishta hai output and ads patient video thanks for Watching please like this video and subscribe the Channel thank you
|
First Unique Character in a String
|
first-unique-character-in-a-string
|
Given a string `s`, _find the first non-repeating character in it and return its index_. If it does not exist, return `-1`.
**Example 1:**
**Input:** s = "leetcode"
**Output:** 0
**Example 2:**
**Input:** s = "loveleetcode"
**Output:** 2
**Example 3:**
**Input:** s = "aabb"
**Output:** -1
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of only lowercase English letters.
| null |
Hash Table,String,Queue,Counting
|
Easy
|
451
|
1,290 |
We are preparing for the charity show, but at the same time, if you have some good impressive resume in your resume, then your chances of getting shortlisted in the show increases a lot. Okay, so anything development schemes like this platform code me. Reaching the office, this video, where very good programs are available, why are the programs good now, then at Simple Rigveda, you are made to work in a real developer environment on real life projects, as is the case in your normal company and internship. Okay now added to the program will have rich interesting security which you guys can mention can do extensive testing in your get up okay your development scale will be improved along with you have impressive projects in english okay But this platform has brought links of breads here and this question, so if you people take this course because gender testing in the news, you will get extra tempo stand discount on it. Hi everyone welcome to episode number six of liquid series of whatever you are till now. Have you watched the new episode that this app is going to make a hello call? Solve a very simple question. The name of the question is Convert Binary Number in Earliest Possible Tk. The name of the question is quite big. Explain what a question is, so it is okay. First of all we read the questions statement, then the questions statement is given head which is reference note Waseem least the value of which no dinner English youth is ok American President and not there are telling list hold hidden in renunciation of number Ok one number But the binary number inside it is now converted into decimal. Okay, so first of all let's know a little bit about SMS and so let's computer notepad that now here we have some decimal numbers and They also have binary fission so one of my this lineage two of one patient 103 of 3714 of 1005 of 1016 510 phone okay so decimal to binary conversion if you don't know that jacket there are many resources some you will get YouTube lectures to Convert from Decimal to Binary But in this question we have to convert the left measurement to decimal. Okay so this is very simple to do this is very simple so we have a winery number track number 10 this way this number is face Now what do we have to do, we have to start from here, zero plate se ok hai tu re sutti 102 race-2 ki paavan tour ek tu re sutti 102 race-2 ki paavan tour ek tu re sutti 102 race-2 ki paavan tour ek stree power does to our free tourist price foreign tourists 225 update hum inko masal lena hai saunth this place In This One * lena hai saunth this place In This One * lena hai saunth this place In This One * Tourist Power That Plus Space For U0 * Tourist Power That Plus Space For U0 * Tourist Power That Plus Space For U0 * Tourist Bury That For This Class A Plus One * Restore Power 2F Replace The A Plus One * Restore Power 2F Replace The One In Tourist Feast In Plus0 Into Two Days Before Plus One * Tourists Power Days Before Plus One * Tourists Power Days Before Plus One * Tourists Power Phase Festival from the Giver Minor Irrigation Okay so this is very simple to do this is easy dress no will see how they can convert ignorance least to decimal okay we click whatever data inside this will be life medicine 0 no in the final form elts exam prep six If we make six then this one fun and 0.2 convert into six decimal fun and 0.2 convert into six decimal fun and 0.2 convert into six decimal area please convert by lips but for this what we have to do is something tourist 2002 re Sutti Pawan Tour 102 Okay now how will we know this thing on particular note two How much power should there be? Difficulty. Okay, so for that you guys know that last then tower on glass from 2004. The power will find third last. The power looted. How to know that we are third last. These are the settings. Date will never be able. To know that okay, so one solution to do this is that you reverse the link, the reversers will have 2012. Here you know that power is not required here because 211 has to be placed here, power of two is here. I have to keep two, okay 10 minutes simple but reverse, I have not even taught you yet, I will teach you further in this subject but it is not very efficient, there can be a better way than this, white, if they can use reversal without reversal, then only we can do it. By finding the length of the first if but its length is known so its length is tight 3 to the length office list now what am I going to do which is my father and I will keep the power free - 110 next to that when will keep the power free - 110 next to that when will keep the power free - 110 next to that when I go there will be power I will keep yours - I go there will be power I will keep yours - I go there will be power I will keep yours - two, then next to that, when I go, I will keep our power free - 3. Okay here, 200 one will keep our power free - 3. Okay here, 200 one will keep our power free - 3. Okay here, 200 one here because it is being made here because the battu will remain so the length but for that I should know, so for the lens I need one. You will know how to apply reversal, okay now we have two ways, one is your reversal, after the police reverse the case, one is yours, first make an appointment and keep decreasing the value of the power of two, okay now there is another way. That's teams se patient way in single hydration okay now that way one big listen carefully plate se m standing at the very first note I'm on follow and I don't know how much power of two should be here that's not even the length Know and this is not even the reverse list ok so now I will assume that the acquisition in the last not the following list is 10 glasses of wee or just like that wow how much should it be the last not here should be 200 ok then I will go ahead And going forward I will come to know that she was not the last, there is a record here so I will say ok now I am standing last so I will make 2000 here and whatever notes I have left behind I will get a power from them. I will have to increase the right one. To increase the power, here we left only one note behind, there I had pressed the power two key, so now I had to do that one. If there were more notes like this, then I would have lost the power of all of them. If I have to increase it, then it simply means that I have to multiply them all by two. Okay, so now I have to multiply them by 19. Switu's PowerPoint is okay, the one with Nav I Will Move Ahead and Mrs. Glass is also mine. It was not the last one, okay, but now the dead body of the owner, note or 120 and all the notes that are following me, I will read power one on them, domino, I will multiply them all by two, okay, so here I will have to click on it. It will be inferior and if you have to activate Jio SIM here then it will be 2012 but I will not multiply it by the fourth number there. Okay, I will go there and will not verify all this. What will I do? Yes, I will keep them together, keep my mind together. Okay, I will keep them together, I will divide them, now let me select it and show how I am going to make it famous, so the initial will be identified as Sir, I will keep the answer as Apna Vishal, also zero, okay, the answer is 15201 style, as soon as I first Coming to the Wali Road, I will assume that this is not the last knot, okay, so there should be 200 here, this dam built on 101 and 125 of How To, I will fund you in my answer, now my answer will become one, okay, I will leave from here. Now I will move ahead, as soon as I move ahead, I will come to know that yes, there are two chords here, so should I multiply the previous answer by you or will I read its one power of two, then type with tears. After doing the answer welcome to is fine and here 250 multiple wife magan so I also have to add this thing outside plus one witch will be the vice chancellor then when you will be free it is fine which was the answer of the past that was one to that I have to Multiplied by 2 very smooth, power of 2 and had to be added suit with me two and what I just added current note value battery Edison pure total answers woman is loot then let's move ahead I will know that there is one more note here now As soon as I know that there is more, then they have the previous answer, I will have to multiply the tuition, okay, because I will have to increase the power, 123 exactly two six and here I am going to cut, I am going to velvet this note 200 test one. Multiple Devices 126 Final match will be played in this way Khushi Now let's do this as soon as possible and write it down then I will administer it as true and the answer is equal to zero and then for more list note Star Temple is exactly two heads okay that After while this time is not like world channel, as long as I keep moving the time forward, is it okay? So, first of all, what am I going to do, I am going to discover a new note, listen, notice, answer multiply will be exactly two, okay answer medical I want to end answer I add vashikaran wale note value to type value will be at that attempt all multiplied by tourists 2008 hona hai but dresses nothing but one to usko nahi likhe se chalta answer plus record to days * record to days * record to days * A tourist 2001 ticket now After this I have to increase the tempo from temple to temple next key and finally from here lettuce submit dress key and record accept okay so you guys go quickly and submit the end network quickly seeker this was very simple episode next episode of birth Key Intact Episode Will Learn About His Attendance Is Near Very Good Question Is Going To Be Okay Friends I Have Learned About This Episode
|
Convert Binary Number in a Linked List to Integer
|
make-array-strictly-increasing
|
Given `head` which is a reference node to a singly-linked list. The value of each node in the linked list is either `0` or `1`. The linked list holds the binary representation of a number.
Return the _decimal value_ of the number in the linked list.
The **most significant bit** is at the head of the linked list.
**Example 1:**
**Input:** head = \[1,0,1\]
**Output:** 5
**Explanation:** (101) in base 2 = (5) in base 10
**Example 2:**
**Input:** head = \[0\]
**Output:** 0
**Constraints:**
* The Linked List is not empty.
* Number of nodes will not exceed `30`.
* Each node's value is either `0` or `1`.
|
Use dynamic programming. The state would be the index in arr1 and the index of the previous element in arr2 after sorting it and removing duplicates.
|
Array,Binary Search,Dynamic Programming
|
Hard
| null |
1,749 |
hello look for another lyrical problem today we are going to try 1749 maximum absolute sum of any supper range so Subaru is a continuous array yeah from the nouns for example 203 are subarues and two and three are continuous yeah because from here we know that nums L plus 1 and the numbers are minus one yeah we know that the Subaru are continuous we first need to set the maximum of the sum of the sub arrays yeah but inside the numbers it can be negative or positive yeah if it is always be positive numbers it is easier but here we also have negative numbers yeah so according to this array and also we need to calculate the separately normally this is a dynamic programming problem and we can also check the lesson nouns it is the 10 to the power of five so we're going to use the on to get the result yeah so for this credible nouns because there are positive so we can calculate the maximum of the positive numbers maybe this is a 23 it is a 5 yeah or maybe here is another negative number for example this is a negative minus four and minus three and minus four maybe minus seven yeah but absolute of minus seven it can be uh bigger number so this can be the result seven I mean here this number is a minus four yeah but what should we do normally for dynamic programming for this kind of a problem and we know that it is a continuous sub problem we can use a dynamic programming to get the previous state and then get the result we will Define three variables so I'm going to define the maximum of nums so this means at each place the maximum of the num at this point yeah I'm also going to define a minimum num so this means at each index what is the minimum of number for example at this index the maximum from 1 to -1 we this index the maximum from 1 to -1 we this index the maximum from 1 to -1 we know that the maximum should be minus two yeah if we include this minus the three so one of the minus is three the maximum should be minus two so what would be the minimum so the minimum we can only include this minus three so it is a only minus three it is a minimum and this minimum can be the result yeah so this would Define two variables and another variable is a result is just used to tuck the maximum and minimum yeah so from the beginning every number should be defined as a zero then we are going to use the DT for only enough so for any number inside the nouns we're gonna check the max number so what is the max num so the max number for example 1 to minus three the max the maximum number from this point the minus three to this point let me copy this array here maybe yeah we can understand it clearly about what I mean so yeah if I go from 1 to -3 it means at so yeah if I go from 1 to -3 it means at so yeah if I go from 1 to -3 it means at this point so what is the maximum of num so it should be Max of Max num yeah because before the maximum is zero from the beginning the maximum through the Plus for example yeah I will go from the first num it is one so the maximum through the Plus this in and also this number n can be the maximum so from the first operation the maximum should be one yes and then we can also calculate the minimum of num so it should be mean of minimum num class n with this number n yeah what about the first Loop so it is a one because maximum and minimum is what 1 plus this number maximum and minimum is zero so zero plus is number one it is a still one and this one is one yeah so from here the result should be the Max of result with Max num and absolute of minimum number because this minimum can be a minus numbers if it is a negative number it can be bigger than this maximum number yeah so here we don't you need to use absolute for maximum number because even maximum number is negative for example minus one but this number is always a positive so this is why we don't need to use absolute for maximum of nouns yeah next noun yeah now let's go to the next position if we go to -3 so what is the position if we go to -3 so what is the position if we go to -3 so what is the maximum num so it is a Max of a maximum yeah before the maximum is 1. so the plus is this number in so it is a minus two and this number is -3 so the maximum two and this number is -3 so the maximum two and this number is -3 so the maximum is a minus two when it goes to this position so what I mean by the maximum and the minimum num it means at its state what is the maximum num at this state it means it will be it can be uh several numbers or it can be only one number for example it can be one and minus the three together it is minus two be the maximum amount maximum of numbers yeah maximum of num or it can be only minus three for example minus three is the minimum of num because for the minimum of num we're gonna take the minimum from the minimum number plus this minus three yeah and one plus minus three it is minus two and this number n is also minus the three so we're gonna take this minus 3 as a result but for our final result we're gonna take the result with the maximum num and absolute of minimum amount yes I know it is sometimes confusing but basically for dynamic programming if it is a continuous sub array we should attack like this yeah so this is a the result now let me run it to tag if it really works yeah as you can see it works now let me submit to the two tag if it can pass all the testing phases yeah as you can see it's pretty fast and it passed all the testing cases and the time complexity is just opened because we only use the one Loop yeah so for dynamic programmings basically it's very important to understand what is the sub problem and what is the previous state what is the next state so here we use the max num and minimum num as the current state yeah so what is the transformed from the current state it is from the previous state plus this number n or it can only be a number and yeah but this is not yet the final result we have to for its position we have to check this result yeah because for each placement we have to attack for example when we go two and three so at this prison the maximum is five yeah so the result here is five yeah but we have to compare go to the next one so when we go to the next one it is still five but we yeah because two plus three is still five but it's when we plus this minus four it can be a smaller number but it's not every result should be maximum of result with those two State yeah thank you for watching if you think this is helpful please like And subscribe I will upload more lead code problem like this see you next
|
Maximum Absolute Sum of Any Subarray
|
sellers-with-no-sales
|
You are given an integer array `nums`. The **absolute sum** of a subarray `[numsl, numsl+1, ..., numsr-1, numsr]` is `abs(numsl + numsl+1 + ... + numsr-1 + numsr)`.
Return _the **maximum** absolute sum of any **(possibly empty)** subarray of_ `nums`.
Note that `abs(x)` is defined as follows:
* If `x` is a negative integer, then `abs(x) = -x`.
* If `x` is a non-negative integer, then `abs(x) = x`.
**Example 1:**
**Input:** nums = \[1,-3,2,3,-4\]
**Output:** 5
**Explanation:** The subarray \[2,3\] has absolute sum = abs(2+3) = abs(5) = 5.
**Example 2:**
**Input:** nums = \[2,-5,1,-4,3,-2\]
**Output:** 8
**Explanation:** The subarray \[-5,1,-4\] has absolute sum = abs(-5+1-4) = abs(-8) = 8.
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
| null |
Database
|
Easy
|
1724
|
819 |
hello welcome to my channel again i'm here to do my angelico challenge today we have litko 819 most common word just like what he said it's most common word so now the input in here will be a string we're looking for the most common word in here except the band word so we take out the bandword so hit had appeared three time but expanded so we cannot use that word so looking for the other word ball appear two time so it's the most uh frequent appearance uh word let's output that one ball in this case and i will just code it out i think that's better for explanation uh let's see so we have a set of string that keep track of as set now we have a spans headset to keep track of all the band word string in the s in band so n dot add s right cool so now we have all the bandwidth in band headset done now we need hash map we need a map there string integer is the appearance how many frequency of how many times they appear so string is the number and how many times they appear in the hash map now we have hash maps done we need to look through the paragraph um we need to process this one to make this because we cannot uh process the special character so we need to do parallel grab dot replace or so here's it's going to be a regular expression that um ignore a to z a a2 z this is the expression 2 is space so now anything is not a to z will be placed by a space in here now after this we will oh also lower case in lower cases it's not case sensitive so we can also um two lower case split by space now we replace all the special character with space and then put the whole entire string to lowercase and split them with space and then we have a this is the array that we have and we have to look through word inside this array now we have this word then people ask me if here's the special comma we just placed by a space now we have two space so when you split you have ball split out and here we'll have empty string because here's space an empty string and space enter so like that so we have empty string captured in the map so if the band does not contain that word right and what we can do is map that put the word and map dot get word oh actually or default word so if word doesn't exist we default give it to a zero and then plus one if it does exist they will get map.get word they will get map.get word they will get map.get word plus one all right so we put that inside the map again to update it so now we have map done map will remove this empty string because we have a lot of empty string uh even right here so we remove that one and we keep the string called result which is the max um common word this string is this one and four we have to loop through all the key inside the map dot key set right map loop through the key set and if we sell dot equals this one and that's or map dot get key bigger than map dot get we sell that mean in that case that mean key have much higher frequency than map i mean then we sell then we place key result equal to key cool so after that you should get the most frequent result in here so now we return the result as the solution output and now you see a ball is out getting outputted cool and this is one of the solutions for this one i believe it's a lot of solution also even better than this but i'm just trying this to get comfortable with map and hashmap so if you have any question please comment below and i will get to solve your concern otherwise and i will see you in the next video bye
|
Most Common Word
|
minimum-swaps-to-make-sequences-increasing
|
Given a string `paragraph` and a string array of the banned words `banned`, return _the most frequent word that is not banned_. It is **guaranteed** there is **at least one word** that is not banned, and that the answer is **unique**.
The words in `paragraph` are **case-insensitive** and the answer should be returned in **lowercase**.
**Example 1:**
**Input:** paragraph = "Bob hit a ball, the hit BALL flew far after it was hit. ", banned = \[ "hit "\]
**Output:** "ball "
**Explanation:**
"hit " occurs 3 times, but it is a banned word.
"ball " occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph.
Note that words in the paragraph are not case sensitive,
that punctuation is ignored (even if adjacent to words, such as "ball, "),
and that "hit " isn't the answer even though it occurs more because it is banned.
**Example 2:**
**Input:** paragraph = "a. ", banned = \[\]
**Output:** "a "
**Constraints:**
* `1 <= paragraph.length <= 1000`
* paragraph consists of English letters, space `' '`, or one of the symbols: `"!?',;. "`.
* `0 <= banned.length <= 100`
* `1 <= banned[i].length <= 10`
* `banned[i]` consists of only lowercase English letters.
| null |
Array,Dynamic Programming
|
Hard
|
2234
|
152 |
Hai Voltage Ki Bhi Talking About Lootkhor Problem Maximum Product Savere Profits Test Cases Name Find Content Class Ninth Is Illegal Business Verdict Product Do Subscribe The Supreme Sacrifice Me To Find The Maximum Product Savere Bhatkti Complete Sharing Your Voter Products 35.23 - 26 - - - - Sharing Your Voter Products 35.23 - 26 - - - - Sharing Your Voter Products 35.23 - 26 - - - - Subscribe Products from subscribe this Video Product Withdrawal Subscribe to the Intersection Example This Clothing on 100th Productivity subscribe and subscribe the Channel Please subscribe and subscribe this YouTube Screen Products Positivity and Teachers Day Subscribe to Qualification Maximum Udayveer VHP Ne Subscribe Must Subscribe Like And Subscribe To A Super Fighting Sub Maximum Product To Maximum Protector To Most Of Those Products Application Form From The Element Phase Multiply Product From Now Considered For Product Positive For Introduction Of Thoughts On Current Element What Will Be The Earth That Artisan You All Seekers Ki Suhaan Wich Backem Maximum Product Features Current Minimum Product All Subscribe Minimum Subscribe And Now Suhaag Find There Current Minimum Product And Can Be Used For Negative Product Positive Number One Number And Two The Election Number Tips To Become History Product Nau And C Multiply Adapter Positive Number dial cancer patient have minimum product otherwise subscribe current elements of greatest number subscribe share subscribe and like comment subscribe to all of you fan porn p name start price i felt tip account hai ko minimum ko nashik is lining first element pims paris Contents Only One Element Minimum Balance Till Sanam Resettlement Selfie And Then Final Subscribe To Novel Tuition Processing The Point Is First One Is Su Strength And Scientific Tomorrow Morning Need To Update Current Minimum And Current Maximum According To The Current Element Name Side Quiet Sudhir Warrant Minimum Can Be Updated On That Started See Multiply To Reason Maximum To Current Element To Maximum Product Details From - To Multiply Product Details From - To Multiply Product Details From - To Multiply Anonymous Said To Tuition Current Element Hospitals Plus To Members Juice - Sexual Harassment Plus To Members Juice - Sexual Harassment Plus To Members Juice - Sexual Harassment Refer Minimum To Turn - 600 - Travis Lesson - 600 Current Will To Turn - 600 - Travis Lesson - 600 Current Will To Turn - 600 - Travis Lesson - 600 Current Will Get Updates Current Max * Name Side Get Updates Current Max * Name Side Get Updates Current Max * Name Side Effects 3D Max Like and Subscribe Minimum Product Subscribe Development This pattern government has given minimum tilawat to very six and resettlement of mind state that took place - 12th Subscribe took place - 12th Subscribe took place - 12th Subscribe Minimum Will Get Updated ons inside that Scenario like this do minimum balance and who isro butter current element subscribe minimum husband and how to find are minimum plants side reaction intruding name number name in the shadow that now these to find the current maximum one to one journey your values of first number This journey your values of first number This journey your values of first number This multiply by positive number 90 arrangements will welcome free of max into account number the satisfaction to do for induction are you very 2012 how to wife is on front minimum positive number and current element gold september 28th potential to the box se mobile you will take Strict adherence to enter isro and current element se quarter inch elements of obscurism hai ka sentiment 250 reasons maths phone pe candy crush open final max hai in that case bell patri update and answer tooth till reason max i apni status one problem in pictures implementation currently Civil Line Number Computer Subscribe [Praise] Subscribe That And Will Multiply That A Number Fateh Minimum From Other Side Reaction Student Time Now That Now Settings Events End Tried To Compile This That Sex Cut Tips Character Moral Evening Till Latest transmit problem hua hai kar do to it's chapter thank you so much for watching the video hua hai
|
Maximum Product Subarray
|
maximum-product-subarray
|
Given an integer array `nums`, find a subarray that has the largest product, and return _the product_.
The test cases are generated so that the answer will fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[2,3,-2,4\]
**Output:** 6
**Explanation:** \[2,3\] has the largest product 6.
**Example 2:**
**Input:** nums = \[-2,0,-1\]
**Output:** 0
**Explanation:** The result cannot be 2, because \[-2,-1\] is not a subarray.
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `-10 <= nums[i] <= 10`
* The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
| null |
Array,Dynamic Programming
|
Medium
|
53,198,238,628,713
|
385 |
Well, I'm going to do problem number 385 of the it code that doesn't bother me even because it's your program that is marked as medium. I think it's a lot of work to do it, that is, because with this one it's recursion and seriously I get this one but it's Quite complex and confusing test, they will get better, it is complete, but if this seemed very confusing to me, what we have is good. First, they give us an app and an interface of the object. In that interest, it is integrated into an object that these bridges were created and the object itself. It is complex because it has two functions, one function here and the two conditions exclusive of each other, that is, if you light for one thing, there is one, press for the other, which is what is confusing, so you can use the object to store an interest or to store a list of objects is not integral that is the complicated part of their job to understand it so what they are going to give us is a chain with certain characteristics and we have to return an inner nes object that meets the characteristics of that chain based on certain rules which are those rules, for example, if we simply have a number in our previous string and it returns s, the pythons integrate and pass in the constructor the integer that we are returning and that's it brad is when we have is with we have parentheses because what we are doing is that we must return a object is to integrate with a list, that is, it is the object that contains a list in which one member of that list is the value 123 and another member of that list is another object that integrates, which in turn has a list with two elements, the first element is a nest inter object which is this is an element is another ernest object and integrates with another list with an element which is site 89 so it is there it appeared quite confusing I didn't really like the problem but here it has a high little sister below but it has many Hands down because it is quite tangled so well here we have 2 possible cases you may have to see my notes where I already solved it because I don't remember this try to solve them and nothing more this and we have this we can have two cases initially we can have two cases If the text box starts with a number or starts with an open parenthesis, it is always with a number. We can assume that we do not have anything nested and that we simply have to return an object. It is not integral with this integer that we have here, so we can start from there it starts wits yes I had that doubt yes it starts with rather if it doesn't start with this then we have to go back and a best seller we are going to put even an internet on it and now the program is obviously with we have something like this so for that first we are going to see two variables the test variables start can social from 1 because let's say that in this part we had the character 0 which is this one we are going to use it from 1 we are going to use another one that is going to be our pointer where we are going to sweep the string that is called and that It's going to be the same start, let's go to one so that we don't lose the stack of this inside, what a fool, kleist the east, and we make the object where we are going to return the result that is going to be in this interest in the networks, we were going to put our object in our stack and that's it. in the cases being as long as it is less than that slow point how to do a series of things here we have let's say two and a half cases there are two and a half possibilities and again well I can modify them because if he gave me the possibility it is that he monet centers and he gave me the possibility would be that the character we're pointing to and it's something like this is a looks open so yeah if that's the case looks open means it's a we have to be a new object inside with whatever is inside of it. those two parentheses then if so we simply make the new object to which we are going to put crazy disintegrate this object mpn disintegrate a we would have to be here we simply go to our state rather in the res object that is inside our state you will know and why you are doing and that is what is now going to be up there well we have to map it there but we also have to put our stand to see if it is going to be the reference we are going to have two references within the start one that is going to be between what towers and another that is going to be that we are going to put up the start to manipulate now that object then and we have to put arts equal and plus one we have to move forward be wherever it is there next and I think that That's all there is to do with this one in my notes. If I can't figure out why, the other possible case is that, but he gave two and a half because they are two cases, but this one can be taken as a middle because the two are very similar. That 's when it's worth it. when it is 's when it's worth it. when it is 's when it's worth it. when it is valid comma is comma what is this then we get to this point what we have to ask first is that stark is minor there if it is minor arts there it means that there we have a numerical value because we have been sweeping and for example if it is afternoon this is already is here so we have a 123 there so we are going to take it out it is equal to that point 30 since this fertilizer is there obviously it will always increase the y an since we have the issue of str we are going to make a new object of these but we are going to pass it and We are going to put it here and we are going to move forward being alone well it is only said in this case it preserves its various decisions we no longer have to be manipulating that it is you have to integrate that let's say that we just used it this one is simply about to pop at the end We should only be in this idea that we have to get out because we are always working with the reference he said and this I'm not sure well what we have to do I'm not sure if we have to put it back because we don't we are manipulating a new nest inter object so I figured let's see what it says here we have the string what is this it doesn't matter of course if it's wrong we have to do it and that's it because I didn't have manipulating a new object so that's basically the The problem is very confusing about his program, very ugly, I hope he never has an interview, I hope it's my turn, Faust, nothing.
|
Mini Parser
|
mini-parser
|
Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return _the deserialized_ `NestedInteger`.
Each element is either an integer or a list whose elements may also be integers or other lists.
**Example 1:**
**Input:** s = "324 "
**Output:** 324
**Explanation:** You should return a NestedInteger object which contains a single integer 324.
**Example 2:**
**Input:** s = "\[123,\[456,\[789\]\]\] "
**Output:** \[123,\[456,\[789\]\]\]
**Explanation:** Return a NestedInteger object containing a nested list with 2 elements:
1. An integer containing value 123.
2. A nested list containing two elements:
i. An integer containing value 456.
ii. A nested list with one element:
a. An integer containing value 789
**Constraints:**
* `1 <= s.length <= 5 * 104`
* `s` consists of digits, square brackets `"[] "`, negative sign `'-'`, and commas `','`.
* `s` is the serialization of valid `NestedInteger`.
* All the values in the input are in the range `[-106, 106]`.
| null |
String,Stack,Depth-First Search
|
Medium
|
341,439,722
|
133 |
today we are going to solve clone graph we are given an undirected graph and we need to return the deep copy of the graph so what does the deep copy mean deep copy means that we are going to return a new graph which is will be exact same copy means it is containing same number of nodes and similar kind of edges everything will be exact same but it will be a different instance of the graph it will not be the same graph so if we see in this example we are given this original graph it is containing four vertex one two three four and edges are undirected so it is four edges one from one to two then two to three then three to four and four to one so this first graph which they have returned is exact same so this is not a acceptable output now this third graph this graph having the same number of vertices but the relationship is not maintained here one is connected to three but in the original graph one is connected to two so this is not also a valid solution now the second graph is having the same number of vertices and it is containing all the relationship in the correct order one is connected to 2 is connected to 3 is connected to 4 and 4 is connected to 1 so we are going to output 2 as a valid solution so how we are going to solve this problem so we are going to solve it using dfs depth first search so firstly what we'll do we will start our traversal from any of the starting nodes let's say suppose we start with one and we try to create a copy of the node so firstly we start our traversal with one so we are going to create a copy for one we created a copy of one now we are going for its neighbor so we will just force the traverse in this direction okay then we go for the other direction so 2 is there so we are going to create a copy for 2 now we explode this direction now 3 is there so we are going to create a copy for 3 so 3 and 3. now we're going to explode this three so there is four so we are going to create a copy for four now four has one so we are not going to create again the node one because we have already created so this means that we need some mechanism which can tell us okay we have already created this node don't create another copy now we need to create or mimic the relationship it's neighboring relationship so we don't need to create the copy again because 4 is having one as its neighbor so we need to just put this relationship here that okay 4 is connected to 1 so we are going to create initially create a hash map okay so we'll create a hash map which are going to tell us which node is copied and which node is not copied so initially one is coming so there is no node we will check in our hash map so whether there one in our hash map there is no one so we are going to create a copy of one now we are going its children so two whether two is there in a hash map no it's not there so we are going to create a two and its copy now we are going for three just we are moving in this direction okay so now we reach three so three is there no three is not there so we are going to create a copy of three now we continued our traversal so we reached four is there no four is not there so we are going to create a 4 here now we will go for 1 one is there yeah one is there so we are going to return this one that okay in 4 neighbor add one so now there will be like if we create our graph initially it will be one two three and four so this thing is already this thing is done now we're traversing this thing so one is already there so we don't need to create one node again so we're just going to put this one node in its adjacent four adjacent node will be one so we create this link now we move to the four other neighbor so we have completed this direction traversal so this direction traversal is completed but before there is another direction possible that is this one because it's an undirected graph so we can go in this direction so 4 has another adjacent node 3 so we'll check whether 3 is there yes 3 is there so we are going to create a link so other adjacent node for 4 is 3 now the traversal of 4 has been completed we traverse both the direction possible this direction and this direction so we are going to return from here so we will go for three so we'll go for three now three one traversal we have done to the four other traversal this direction is still there so we'll go and explore that direction so we'll check whether 2 is there yes 2 is there so we are just going to put 2 in its neighboring node so we copied this relation now 3 traversal has been completed we move to both direction this direction and this direction now we'll go for 2 it's parent function so 2 is there so now for 2 this we already traverse now this is the direction which is left one so we'll check whether one is there yes one is there so we are going to create a neighboring node relation with one so this one traversal is completed so we'll go after completing the traversal of two we are going for one it's parenting so we'll check whether one traversal so when so for one this direction we have already explored but this direction is remaining on so we'll go for this thing so we'll check whether 4 is there yes 4 is there in our hash map so we are going to create adjacent relationship with 4 so now our graph is completed so we are going to return this graph here all the adjacent relationships are created in this graph and we have same number of vertices also and same edges here so this is our valid output we are going to output this graph so what will be the time complexity will be o b plus e because we need to go for each vertices and each edges so it's linear and space complexity will be ov because we need a hash map to store the information with which node is already been created and which node we need to create such a copy node so yeah that's it so we need a hash map so let's create our hash map now we need to write our dfs function so let's create our dfs function dev dfs so the node will be our parameter for which node we are going to explore its neighbors so node is the parameter if the clone of this node is already present in our hash map then we need to return the clone of that particular node so let's check if node in clone then we need to return the clone of this node so clone node otherwise if it's not there we need to create the clone copy is equal to so we created a copy and now we need to keep this copy node in our hash now we need to go for visit for its neighboring nodes so we need to add the neighbors in the copy node also and at last we need to return our copied node so return copy so yeah that's the code we are just traversing each node and going for it's checking whether this node is already copied or not if it's copied we are going to return the copied node and going for traverse its neighboring nodes and creating that links and at last we're going to return that node so let's call it if there is no graph then we need to return a null object so if there is no node present so we are going to return null otherwise we are going to create a copy so this is it let's run our code so it's given its correct thing let's submit our code so yeah it's got submitted efficient and space complexity is not that good because we are using a hashmap to store our vertices and copied vertices information so yeah that's it for today i hope you found this video useful please do like and subscribe thank you for listening see you next time
|
Clone Graph
|
clone-graph
|
Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors.
class Node {
public int val;
public List neighbors;
}
**Test case format:**
For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list.
**An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph.
**Example 1:**
**Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Explanation:** There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
**Example 2:**
**Input:** adjList = \[\[\]\]
**Output:** \[\[\]\]
**Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
**Example 3:**
**Input:** adjList = \[\]
**Output:** \[\]
**Explanation:** This an empty graph, it does not have any nodes.
**Constraints:**
* The number of nodes in the graph is in the range `[0, 100]`.
* `1 <= Node.val <= 100`
* `Node.val` is unique for each node.
* There are no repeated edges and no self-loops in the graph.
* The Graph is connected and all nodes can be visited starting from the given node.
| null |
Hash Table,Depth-First Search,Breadth-First Search,Graph
|
Medium
|
138,1624,1634
|
1,519 |
hey everybody this is Larry this is problem 2 on the recent contest it like went into subscriber enjoyment it is called number of nodes in the subtree with the same neighbor so basically for this problem I just said of recursively I used counters to go do the count you can maybe get away with just using it away or something like that and then count out but basically you do a pre-order traversal of all the nodes and pre-order traversal of all the nodes and pre-order traversal of all the nodes and the idea is that for each of those nodes the recursion wants to return the count of every character from A to Z and once you do that you just sum them up together matching them up and also making sure that you count the current label and that's pretty much it's a little bit tricky to reason and especially depending on your language it may be a little bit tight on time constrain seeing that this is a hundred thousand times twenty six is a little bit tight in certain languages but it worked for me so yeah stay tuned for watching me doing this live and let me know what you think so this is a straight for or like it's a straight for as it gets with respect to the recursion it's a little bit tricky to kind of prove that this is fast enough though so sighs and what oh my god don't tell time
|
Number of Nodes in the Sub-Tree With the Same Label
|
minimum-subsequence-in-non-increasing-order
|
You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` `edges`. The **root** of the tree is the node `0`, and each node of the tree has **a label** which is a lower-case character given in the string `labels` (i.e. The node with the number `i` has the label `labels[i]`).
The `edges` array is given on the form `edges[i] = [ai, bi]`, which means there is an edge between nodes `ai` and `bi` in the tree.
Return _an array of size `n`_ where `ans[i]` is the number of nodes in the subtree of the `ith` node which have the same label as node `i`.
A subtree of a tree `T` is the tree consisting of a node in `T` and all of its descendant nodes.
**Example 1:**
**Input:** n = 7, edges = \[\[0,1\],\[0,2\],\[1,4\],\[1,5\],\[2,3\],\[2,6\]\], labels = "abaedcd "
**Output:** \[2,1,1,1,1,1,1\]
**Explanation:** Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.
Node 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself).
**Example 2:**
**Input:** n = 4, edges = \[\[0,1\],\[1,2\],\[0,3\]\], labels = "bbbb "
**Output:** \[4,2,1,1\]
**Explanation:** The sub-tree of node 2 contains only node 2, so the answer is 1.
The sub-tree of node 3 contains only node 3, so the answer is 1.
The sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.
The sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4.
**Example 3:**
**Input:** n = 5, edges = \[\[0,1\],\[0,2\],\[1,3\],\[0,4\]\], labels = "aabab "
**Output:** \[3,2,1,1,1\]
**Constraints:**
* `1 <= n <= 105`
* `edges.length == n - 1`
* `edges[i].length == 2`
* `0 <= ai, bi < n`
* `ai != bi`
* `labels.length == n`
* `labels` is consisting of only of lowercase English letters.
|
Sort elements and take each element from the largest until accomplish the conditions.
|
Array,Greedy,Sorting
|
Easy
|
2316
|
742 |
Hello Hi Friends Welcome Back Today We Are Going To Solve Its Problems Shift Or Project But 350 Will Look Into The Problem Description And Samay Examples And Solution For This Problem Is Just Want To Mention Back To My Channel Is Dedicated To Help People Who Are Preparing For Code in Interviews and Java Interviews and All My Channel Crack More Than 200 Coding Solved Examples Which Were Previously Last Interview Questions for B Tech Companies Like Amazon Apple Facebook Microsoft Google Yahoo Adventures and Whose Hand Problems Are to Our Important Variety Sperm Coding for Interview Questions for This Dynamic Programming and Questions Binary Search Tree Questions List String Related Interview Questions Benefits Matrix 2ND Grade Optimization Problems So Friends and Different Varieties Very Important From Coding Introspective You Will Find Lots of Soul Pimples Explained With Java Code To A Fever Preparing For Job Interviews More Cool Interviews Please subscribe this Channel Now So Let's Go Through This Description And Close Loop In Binary Problems To Given Not Tree Every Not Have A Unique Values And Target Key K Tree Every Not Have A Unique Values And Target Key K Tree Every Not Have A Unique Values And Target Key K Find The Value Of Nearest Loot Target K Intermediate R Multiple Sclerosis You Should Follow This Priorities Dilip Notice The Left Shift Jindal Factory Of The Knot With K Dalit Nodes In Right Sub Turn Of The Knot With K And Elephant Is Not Enough But Not With K 202 Root Represents Binary Tree With At Least One Month And Don't 108 Every Knot Is Unique Not Believe In The Range Of 12310 1210 Exit Node In The Given Point At River Which Not Person Friendly Leaf 1 Ltr Small Children Died So For Example Viewers One Example Ye Swadeshi Daaba Result And Difficulties Equal To One Has Given To 10 Days Ginger Close Loop This Result Bigg Boss First Priority Will Be Given To The Left Subscribe Screen System Left Side And Tourism The Right Side Effects And 321 Priority Have You Seen This Country Sanskrit Sweater Condition Slip Let's Go Through Which One You Dare Multiple K Smith Multiple K Statement Sirvi To And Three Both Are Equidistant From Both Are Leaves Request Bluetooth They Will Consider And Singapore Shift Consider Lift Day Specific Consider It And If It's President Not In Left And Right Three Do It Consider The Fat Of The Third I Will Discuss With You In The Example So Let's Look Into Being Example That Is Created To Tree With Which Of This Is The Tree And What It's First Discuss About This Three Condition Speakers Battery Saver Important Indoor Implementation Prospective Bride For Example Gift Were Wear Look Into The Matter 2008 Closest Lift 0 Win First Tak Lips 2012 is the classes 145 positive inside left side right now if you were looking late from this point download on whatsapp looking for follow us at home now half sleep for this note 4 rights of clans turned out to be the first priority will give to The Left Software Right And It's Not A Cliff Is Not Found In Lips Afridi Will Go To The Right For The Most Basic Choices They Tried To Find Out In Their Lives At Risk For Giving Like T-Shirt At Risk For Giving Like T-Shirt At Risk For Giving Like T-Shirt Using Edifice And You'll Find Deadlift Team is the classes for life according to the user can give unconditional love that will give priority in height most strongly third key I will show you what the third case minute solid letter to fair suitcase comes when we are trying to find out close just leave for Not to result so s you can see President Sudhir Vinod face involved sir 10-11-2013 Vinod face involved sir 10-11-2013 Vinod face involved sir 10-11-2013 flirting 1516 0 and binocular sleeves are there in figo only devotion and right then subscribe 1234 The Lips 40 11:00 The Lips 40 11:00 The Lips 40 11:00 12345 subscribe you will see Shyam Notes But As You Can See The Question Is Not Denote Subscribe To One And Only To Take Care Subscribe Not Want To 10-11-12 606063 Subscribe Now To Receive New Updates Klariya Tha To Sub Tree And Tanodiya Switch Of Industries And Accurate to the root of the toe and when you have toe found out on the side basically a System The Right Side And It Can Exist Outside Inside Outside Of Distic Collectors Basically The Cover Is Common That Now To Solve This Problem For What We Will Do It Is A Will Lift From And Target Notice Given S To Right Letter For Example The Consider Distic And Did not give nehru per do so with first day of starting from root and will try to find out the target notes and target notification find a website and will just and the value of the node for example and assure you implementation and same time so you will Be aware of this great you don't forget and will popular this but you will find target by using different starting from root and will popular dead target note target here right 100 war more details but this is what we will do and during deficits during the date of Birthday to you are going to be doing right from the root will also create or no different method note current map what is it means and is not will capture develop as it's parent for example wonders not have any parents fail to front this lineage will Have two plus two is active person thirty one is the value rights like this for example no is the year no is the cases this point is not right the thing because after 90 11123 lifting blackboard no specific limited tiger shroff and will not for this me will Prepare in our during or defense operation and day once paid day man trying to find close loop what will give it first to Gonda left side of to right side of pride and at the same time to time will do and bf and they will create YouTube here that and will and this value in to the curious tube will create so let's is from that letter said som rate decision of and because a 100 e will produce value 2015 year 2015 and after that you will also find the talent of Rural Parents 251 Hair Pack 932 Is Out At The Time Will Put All Is Well Are Left Right End Parental VV David One Of 451 And They Will Put Her Left And Right Side Loot 6 7 End 4589 1513 Right It's Right Side Swift Only Three Did Not To Request To His Visit Do You Will Give Will Also Should All The Return Of Switch On To Visit You Already Have Visited 500 Aa Let's Put Into The Give Respect To Show You Will Understand 6 7 8 9 Fix Loot-Loot 789 Become And When They Are Putting Also Cheating Dare Not The Leaves Are Right And A Girl Were Trying To Put This Year They Are Trying To Prove It's Not Even If You Tried And Time Hui Navodaya School Redefined Alif Height Service Will Give Returns And The Answer Is Because They Have Already Riched To Leave and cities now this and will find the classes leaf developed all this always finds close jaswant suthari with answer for this of preventive wear heavy target note to write to atithi hi they are going to the implementation so I will say implementation code no hai to common Nikal With Easy To Understand After 2 2 2 's Patta Is A Zenda Map Which Cold Action 's Patta Is A Zenda Map Which Cold Action 's Patta Is A Zenda Map Which Cold Action Replay Is On Time This Note On Weeravar Starting From The Route Swift Route Video Must Subscribe To Front Part 2 That Hum Disavar May Condition A Routine Request Tomorrow Will Return Right in Devise otherwise parents not equal to none when will put the map root from apparently because they are creating this mapreduce map where creating in a vs not parents map and in it's that person's day v5 and target such target is equal to root basically Like this target war chapter note 100MB accessible from all the best subscribe gift hear or interruption target get proper electronic value message for example valuable west indies value to matches in and targets populated pimples and targets do and after that it's not matching day who have to go On left side and inside right side of the most difficult dows work rights or benefits dot right against corruption route map and the fat of this show awak davidson hair pack tak hui dows deficit target will be updated and our medical superintendent time to forget it is Not moderated and will return minus one should not exist in the given tricks for example this target is ignorant guptarghat is vansh does not exist in the given there right to will return minus one in this is that was doing this why you will create why sirvi chapter notes And because they want to see the notes20 that divide savitri at her top interior and when will offer target note first target lord will offer interview right and you can see your target wearing good clothes and dedicated to visit this site because you have already been stated That target value's quick way to indicate were that [ __ ] after that is the place where our deficits are clear shot actually taylor swift value from the curious swift value from the curious swift value from the curious hand tool first rationalization not be you friend polling productivity relief verma types of duties indian lady From middle of the novels written person Phillips current not benefit is not left din hui have to go to the left side first flight courier doing current chapter note channel and it is not visited already din quizzes offer that current boat lift there why and will lead to avoid Set theory is disputed Waqt din hua America North responsibility and Andhra Right side opposition Attitude is over condition Faizabad Related Issues For this is the condition Types of forest will go to the least three Do you want to right Sub tree and cafe Talking to support you have To break into the you have to take care Thakur Singh's Parental Point Favorite Song Start Hui Ya Damage Hair Sun Which Actor Karan Left Side Degi Are Going to the Right Sub Trick Basically Of The Current Not Like And Drop Erring Left Right Note Intuitive And Way Also adding that initially she tried and not the system will have to also added the parent of too great front to how to take to yaar do it man app contents current rights on current issues one basically suwan is daur surya fit is contest someone and not visited The Movie Will Put Into The Tube President To Visit Set An Tomorrow Morning To The Why Tight Because It's Parent And In Next Time When You Were Going And Win Again Got To The Left Side Life Was Left Between 70 80 Will Go To The Right Side Clearly Stated To Be Converted To Right Suvarchla Right Side Entries Actually Ignore Services Pet Teeth Service Was Improving The Implementation Like Share And Grandfather Was Gifted To Find Anything In Return - Gifted To Find Anything In Return - Gifted To Find Anything In Return - 150 Find The Close Real Fear With Written Test Current Value Cabinet And Sacrifice Will Always Strauss 5th Class Eight One Died Because Its Benefits Yadav God Is That [ __ ] Shishu You Can Solve So Film [ __ ] Shishu You Can Solve So Film [ __ ] Shishu You Can Solve So Film Actress Problem Solve Latest One The Current Example That Will Discuss Digit All Right One That I Created For You Did You Get Done Hurt So Let's Go Ahead And Download Limit Ticket Group Color Sweet Will Be Easier For You To Can See This Tree Na Vikas Slaughter Corner Sardar Na Hai To Ke Sunao Will Take Over Cost Its List Tubelight Show Will Terminate Your Closest Iron At Solid Setting Software Getting Free Leg Dancer Proper Correct Name Lipstick Another Text S They Are Putting Seven Hair 087 Gender To 10th 12th Left Is The Priority Right And Right When Is The Present Chief Color Enemy Again Taste Vacancy 12th Coming Proper Correct This Fool Takes For Instance Of To The Right Left For Dam The Taste With Answers Flats Rang Distic Judge So Let's Put Fourth Year That Encounter Test Hai Tu Yaar Cutting ₹10 Correct Answer Is Left Tu Yaar Cutting ₹10 Correct Answer Is Left Tu Yaar Cutting ₹10 Correct Answer Is Left Side Will Always Check First Part To Era Already Chapter Two Will Give Three And Technology Transfer Placid In This Ek Sutra Is Dacoit Close Nodu Dude Getting Caught On World Records As You Can See 1234 Others Note 3 Test One Two Three Steps Right To This Project Work So Intense Gold And Will Submit Dissolution 116 Moments To Text Do It Is The 98% Of Poster-Banner Submissions Very Good Show This 98% Of Poster-Banner Submissions Very Good Show This 98% Of Poster-Banner Submissions Very Good Show This Is The way you can solve sleep in binary tree problem with the help of deficit and bf sds which is used to find the target road and to prepare them applied parent child map and bs we use to front part closest lifter to the point that is the road. To You Thank You For B.Ed Busy Has is the road. To You Thank You For B.Ed Busy Has is the road. To You Thank You For B.Ed Busy Has Replaced Track Of The President's Notes Do You Celebrate So I Don't Want To Tree With Lemon Juice 919 Amazon Interview Questions Topics Important Interview Questions For Class 10 Questions And Answers For This Questions To Look Into My Channel Play list please go through 98100 examples subscribe that graph problems binary search tree in binary related interview questions a coding questions stringer edifice matrix 2nd grade teacher education problems as well as different telephonic interview questions for java interview certificate for cooling interview Please subscribe this Channel IF YOU FIND THIS VIDEO HELPFUL AND IF YOU LIKE OUR WEBSITE SPLENDOR UNION DAY PLEASE SUBSCRIBE THE CHANNEL AND LIKED THIS VIDEO ALSO YOU ARE SUBSCRIBING WILL BE REALLY IMPORTANT TO SPEAK THAT IS THE VIDEO CAN REACH TO MORE PEOPLE THE CAN ALSO WATCH THIS Video And Conduct And How To Shoulder Coding Problems And How To Approach To Different Varieties Of Problems Which Can Also View Loan From This Video Please Subscribe To Our Channel And You Like Please Share With Your Friends And Colleagues And Thanks For Watching This Video.
|
Closest Leaf in a Binary Tree
|
to-lower-case
|
Given the `root` of a binary tree where every node has **a unique value** and a target integer `k`, return _the value of the **nearest leaf node** to the target_ `k` _in the tree_.
**Nearest to a leaf** means the least number of edges traveled on the binary tree to reach any leaf of the tree. Also, a node is called a leaf if it has no children.
**Example 1:**
**Input:** root = \[1,3,2\], k = 1
**Output:** 2
**Explanation:** Either 2 or 3 is the nearest leaf node to the target of 1.
**Example 2:**
**Input:** root = \[1\], k = 1
**Output:** 1
**Explanation:** The nearest leaf node is the root node itself.
**Example 3:**
**Input:** root = \[1,2,3,4,null,null,null,5,null,6\], k = 2
**Output:** 3
**Explanation:** The leaf node with value 3 (and not the leaf node with value 6) is nearest to the node with value 2.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `1 <= Node.val <= 1000`
* All the values of the tree are **unique**.
* There exist some node in the tree where `Node.val == k`.
|
Most languages support lowercase conversion for a string data type. However, that is certainly not the purpose of the problem. Think about how the implementation of the lowercase function call can be done easily. Think ASCII! Think about the different capital letters and their ASCII codes and how that relates to their lowercase counterparts. Does there seem to be any pattern there? Any mathematical relationship that we can use?
|
String
|
Easy
|
2235
|
393 |
so here we are hello and welcome hello howdy today just give it a moment see yeah all right there we go sweet um yeah so i wanted to i'm gonna go see a friend later today and it's gonna be great and um i want to work on a problem before we go within the hour of time i have before seeing that person so we'll do that um yeah also praise god you know yesterday was easter and really i should kind of treat every day like it's easter i guess right like i recognized that yesterday i was like thinking about god more than i normally would um so praise god i don't know thank god for another day and uh hallelujah um okay anyway so yeah appreciate the finished work of jesus christ on the cross let's appreciate that um but also uh right so the problem that i wanted to look at was utf-8 validation look at was utf-8 validation look at was utf-8 validation i haven't seen it yet we're going to just go for it so yeah see how we do give an integer and try to do this somewhat quickly i have a something of a time limit here uh integer array data representing the data return whether it is a valid utf-8 encoding is a valid utf-8 encoding is a valid utf-8 encoding character in utf-8 can be from one to character in utf-8 can be from one to character in utf-8 can be from one to four bytes long subjected to the following rules one byte character the first bit is a zero followed by its unicode code n bytes character more than one i guess the first n bits are all ones the n plus one bit is a zero followed by n minus one bytes with the most significant two bits being ten what i just read let's get some examples hopefully some examples could make some sense what is going on how it's utf-8 encodings would work okay how it's utf-8 encodings would work okay how it's utf-8 encodings would work okay character number range hexadecimal etf 8 octet sequence binary let's see oh input is an array of integers the least significant eight bits of each integer is used to store the data this means each integer represents only one bit of data here you could use characters by the way you don't need to use ins if you're gonna do that characters usually are one bite i digress i don't know if they're always one bite they might be two bites but anyway okay so um i'm so confused okay 197 131 true represents the octet sequence all right so you can convert these to octet sequences octet why are we doing oh an octet i think is being referred to as eight bits okay i think i understand which is actually two bytes oh i'm sorry card no i take it back uh no it's a bite that's one bite a bite is eight bits yeah knocked it's a bite okay it's a bite all right it's so confusing uh octal is base eight which is different from an octet and octal there's hexadecimal a binary decimal and octal right and then there's an octet which is so confusing because all these words are kind of being thrown around in different uh position points so decimal binary is base two decimal is base ten i don't know binary is base two octal is base eight decimal is base ten hexadecimal is base 16. these are all different ways of representing numbers right so like binary there's representing a number with a bunch of zeros and ones um basically each of those numbering um names represent how many digits are going to be used in that kind of number system so binary only has two right because binary by two octet is not referring to a numbering system but instead referring to a num a collection of eight bits octet meaning an octet of bits eight of those bits a byte usually is what they use to mean that so that was extremely confusing but i think i understand now what they're getting at so what i don't understand though is the utf sequence what is that supposed to mean what so okay here's an example so true data represents the authentic okay so this could be converted to octets basically base two okay that's that i understand got that i'm with you there is a valid utf-8 encoding for a two is a valid utf-8 encoding for a two is a valid utf-8 encoding for a two bytes character followed by a one byte character uh excuse me oh i think i understand so there's actually an arbitrary number of these integers which you convert each integer to binary and then you would have to oh that's so confusing oh no this might be a lot harder it's got a lot of downloads this might be a lot harder than i really have time for i think this what's the restraint 20 000. uh yeah maybe not well if it's 20 000 it's probably not backtracking basically i'm thinking they might have to do some kind of a backtracking question where you say you know can we take the first is you know the first bite or the first number is a single byte yes or no if you can yeah basically like a depth first search like a backtracking question where if you take the first element as a byte then you would have to recurse and say okay well the rest of the um array has to be also a valid utf-8 um array has to be also a valid utf-8 um array has to be also a valid utf-8 encoding if it's not then you need to flip your decision the problem with that though is i guess it's not that bad necessarily i'm not really sure um just thinking technically you could do this if you memoize that like you could do it somewhat recursively where you have you know the value that you're recursing on is uh is um like the index in the data stays the same the index changes you're really just recursing on the index and basically the recursion is going to be like from this index point to the end can that be a valid utf-8 encoding or can that be a valid utf-8 encoding or can that be a valid utf-8 encoding or not yes or no and because you've got four choices right you've got um the first byte using only the first two bytes using the only the first three bytes or using only the first four bytes and if you consume those bytes then in each of those cases you would the rest of the encoding would have to still follow the utf-8 utf-8 utf-8 encoding actually i think this is not too bad this i don't think is as bad this is a kind of a dynamic programming solution i think it's okay um in that regard i think i don't think we hit awkward time bounds i don't think we need to really do too much extra work i'm thinking about it's really just um it's really just like a constant factor of four and it's linear time the tricky thing though is that in each of those cases one two three and four if indeed those are valid encodings which that i don't really understand and we're only considering the first eight bytes of bits by the way which is an integer would have 32 bits so we only really care so we have a mask we could do a mask that's fine so let's do okay auto recurse something like this zero and the mask is going to be you could do a hexadecimal you could do it's going to be all zeros except you can also just calculate the number directly i mean there's a few ways to do this but i think 15 is what you want right yeah 15 should be fine and then we want in x and we have include ordered map memo okay memo let's say base cases um basically return red so it's going to be f of x minus 1 or yeah or f of x minus two or f of x minus three there's actually there are actually three different there's four possibilities really um say cases there are four cases and there's base cases uh we'll just say if memo dot count of x term memo of x if x is less than zero i think you just return false in those cases and then you can say right there's four different cases we're gonna go through each of those i think it's actually really that simple yeah i don't think it's really too involved here too much to do i could be totally wrong too by the way i don't actually know until they really get into it then they'll all have a better sense so each case is four cases so first case we said um it okay for a one byte character the first bit is a zero so let's say bits we're going to say get a phone call don't know who it is don't recognize the number we're going to say it's not really the bits that we want okay first case we're just going to say in bits i'm going to say data of x and the mask right and the first bit is a zero followed by its unicode code okay this i don't entirely understand one bite character um what is a unicode code utf unicode code i think a unicode code getting another phone call do not recognize the number let's see list of unicode characters i don't know what the unicode code is referring to see not technically possible list all these characters in single wikipedia page there's 140 000 of these characters uh i'm really confused i want to say it just needs to start with a zero control codes um how many of them are there seven right so it's two to the eighth minus one like only 255. very confused this is a lot more than 255 this is not extended unicode i guess it's see that's the thing utf-8 that's what see that's the thing utf-8 that's what see that's the thing utf-8 that's what we're looking for utf-8 we're looking for utf-8 we're looking for utf-8 character encoding all valid character code points in unicode using one to four oh okay these code units gotcha and it's backward compatibility with ascii first 128 characters unicode one-on-one with ascii characters unicode one-on-one with ascii characters unicode one-on-one with ascii your cody's in a single bite with the same also not to the eighth it's to the seventh i don't know why i got to the eighth that's wrong um okay i think that makes sense all right huh okay so this is the first case all right so first case one by character is so really we're just checking if the first bit which is a bit all the way to the left so actually really that's just um we'll check it's just gonna be and that with um one bit shifted to the left uh how much eight positions it's really seven positions right if you one and then you should bit shift that once that's actually the s the second well it's the seventh index yeah that's the check and then we'll say check it's gonna be really it's check one our check and then check end equals um our check equals check end now we do recurse or f of x minus one or really we're doing the other way around we're doing this incorrectly right it's really plus one and yeah not minus one plus one and we wanna say not x less than zero but x is greater than or equal to data.size or equal to data.size or equal to data.size that's really what we want and yeah so we would say this check right that's case one case two is n bytes character first n bits are all ones n plus one bit is zero followed by n minus one bytes with the most significant two bits being one zero okay i no idea what that means not a clue what's going on here um they try reading what the etf encoding describes backward compatible with ascii um valid ascii texas value tf8 encoded unit code as well ascii bytes do not occur when encoding non-ascii code points into utf-8 non-ascii code points into utf-8 non-ascii code points into utf-8 etf-8 is safe to use within most etf-8 is safe to use within most etf-8 is safe to use within most programming and document languages that interpret certain ascii characters in a special way such as forward slash and file names backslash escape sequences and um percent in for death so what is percent yeah okay interesting superior alternative to utf-1 proposed superior alternative to utf-1 proposed superior alternative to utf-1 proposed variable with encoding with partial ascii compatibility which lacked some features including self-synchronization self-synchronization self-synchronization and fully ascii compatible handling of characters such as slashes ken thompson rob pike produced the first implementation for the plan 9 operating system in september 1922 1992. i was born one month before that by the way a month before i was born or a month after i was born you know i'm sorry uh i don't know i was born november two months after excuse me yeah two months after i was born two months after this date this month yeah this led to its adoption by x open as its specification for fss etf which would be the first which would first be officially presented at use nix in january 1993 and subsequently adopted by the internet engineering task force ietf in rfc 2277 bcp18 for feature internet standards work replacing single byte character sets such as latin one and older rc's etf-8 is by far the most common encoding etf-8 is by far the most common encoding etf-8 is by far the most common encoding for the world wide web accounting for 97 of all webpages up to 100 for some languages as of 2021 yeah utf-8 super 2021 yeah utf-8 super 2021 yeah utf-8 super like well known well used um i kind of take it for granted ascii and utf both of these are kind of taken for granted but if you open notepad you can save a file as let me just see something before i do anything else um you can see it uh encoding hey there you go yeah you ready for this um this is like in notepad encoding utf-8 this is like in notepad encoding utf-8 this is like in notepad encoding utf-8 right you can go ansi 16 utf-8 is the right you can go ansi 16 utf-8 is the right you can go ansi 16 utf-8 is the common one oh did me to save that did i save it i didn't mean to um yeah anyway that's fun so yeah uh was i doing i need to hurry up i don't have too much time here it's an interview no kidding um all right uh i don't understand the second part of this question though n bytes character the first n bits are all ones the n plus one bit is zero followed by n minus one bytes so the so for a two byte character the first two bits are all ones the n plus one bit the third bit is a zero then there's n minus one bytes two bytes with the most significant two bits being one zero so it's so confusing but i think i understand it so they're saying for a one byte sequence this is it two bytes two bits and then everything else is a one zero and then for three bits three bytes it's three with a zero and then okay i think i understand now i think i get it so we'll have a few different checks check one check two is going to be data of so we have different masks then um really mask one a few different masks do mask one mask two mask three and mask four we probably could do these differently as well also we could just put like three masks on one line put another mask on the other line um so do we really we don't really even care do we actually we really just care we don't even care about the mask do we don't no we don't even need that actually i mean i guess i don't know the first mask really doesn't matter that much because the first mask actually is just the symbol it's really just this and then the negation of that right that's just that's got to be zero um that's true and then the second mask excuse me this secondary kind of a mask thing is just it's really just one bit shift um i'm actually not sure we don't care what's in these other spots we only care that this has to match um yeah it's gotta be uh i'm actually not sure how do you check that both of those bits how do you check that this mask matches using bit manipulation right how do you do that because if you end you don't want to touch these other bits like what are you looking for when you end if you were to end you want these to match all these other bits that we don't care about at all um just thinking here i know we can use i know if it was all ones i would know what to do but uh yeah i mean you could just do you just do them directly i don't think it matters that much don't even need to use a mask uh yeah okay so check two is gonna be dative x is there's another issue here too which is here we go x is less than data size right then x is less than data size minus one there are like a few things we need to check here all right because you're gonna do multiple checks right so data of x has got to have this thing going on so and 1 less than 7 and one less than see that's the thing this has got to be positive thing this is a little confusing i have to admit definitely a little confusing seven so yeah so two so okay so it's gotta be seven it's gotta be six right and you've gotta do a zero at the end there and not now see that's really confusing this is actually i think this is wrong right this is um no see this is wrong what i'm doing this negation incorrect this is so confusing it's so confusing you want that's a zero at that spot and how do you check that there's a zero at that spot and you don't care about the other bits only because that spot to zero um well you could remove all the other bits using a mask and then check that the whole thing is zero that's one way of doing it another way of doing it is i think it's actually the only way to do it if you end that's no it doesn't no i don't know yeah well if you end with this then the whole thing is going to be zero on the right side and then a zero or one right so this is a zero it'll be zero if it's a one it'll be one so actually this is right this is fine it's confusing but it's fine right and you would do that for and actually yeah this works also if you just yeah it works for every okay never mind all right that's i realize it's confusing but yeah that's huh okay seven has got to be yeah this isolates this does this and does isolate that one bit like this is okay this is fine it's confusing but it's fine so these things gotta all be true and then also um i don't really like this is like a wish can we just the thing that's awkward about this is i would like to kind of make this one single binary uh not binary but one single kind of like bit manipulation where we could just end where these are set and everything else is you can't really do that can you all right whatever we'll just do it like this it's fine for now i guess it's okay um i mean i don't know so many things about this that are just kind of awkward three bits okay fine and these are set with um i don't know how else to do this there's probably a better way to do this but i'm gonna do it like this for now i'm going to do it like this for now it's definitely a better way to do this you actually negate this part yeah so one zero and then the next data datum is gonna be one zero okay like so okay this is check two three oops check three two pieces delete that one there two and i did this wrong this is six instead of seven six seven okay and here we have one more piece this goes to four and that's three and now we have four all righty there we go so one two and this is three this goes to three this is deleted here there's got to be a better way to do this is so like i don't like this at all alrighty so um what we end up with is etf encoding would work all right so we end up with these different checks on these different data points this does have five bits so we check one two three four five yeah so we have these one two three four five bits that we check and then two bits at a time right and now what we're going to want to do is say check two maybe check to end f of x plus two and the same thing over here check three x plus three and finally check four x plus four uh yeah i think that's right um yeah and then we'd say ret any of these are true then we memo of quite the doozy see how we did does it compile no of course redefinition of check three check four should be does this compile auto return false um what how did that happen oh it's probably because of this i forgot to do this tendency to forget these things as it goes false nice wrong awesome uh how are we doing we have let me check my phone okay wrong wait what oh okay i guess we do need this somehow this determined to be an integer just decided to become a decided to be an integer i don't know how that type deduction ended up with an integer but it's not so false output false expected true oh um i think actually the default should be true for these yeah actually this should be true i could be wrong about that this actually should be true okay they're looking pretty good um let's see if there are should we just go for it i kind of just want to go for it let's try some stuff see what we get excuse me that's me between 1 and 2 55. i don't know what to do without this case okay that's good probably should test um one byte two byte three byte oh yeah so it's possible to make it not a one byte um how about what about these what do they give us okay that's good we're a two byte look like two byte we said one when the byte is one these are being interpreted i think is as integers right so but they have to be negative this is this 2 byte is fine that's really interesting am i missing something here oh i see right i think that's why that might have been why they used integers instead of characters for the because you'd want to use unsigned characters and i guess that can get a little bit confusing you have like yeah okay well anyway well although actually yeah anyway okay um what are we doing here so all right if we wanted this one right this is so this is basically 128 plus 64. right so 128 plus 64 is what uh i think 197 right yeah 187 and then this is 128 not and they're 129 it's two bit that's two and then we could do three and then four something like this all right let's go for it see how we do oh what excuse me of course why what why would that happen what that just seems bizarre what is that 237 huh why would that happen hello get the old calculator out for this one 237 huh um okay well uh two four eight one two four 8 16 32 64. 128. let's see one two three four five six seven yeah okay um seven minus 128 109. 64. it's 45 it's 32. 13 minus 8 is 5. okay yeah so this is what we get for 237. so this should just return false no it's got heat buffer overflow what happened check one check two check three check four these should all just be false how do we get a buffer overflow on that what happened i was not expecting that at all not even remotely huh what the heck happened there or what happened there um okay when where and why so this should not be true x is zero data size is one we go here x is zero is less than 1 all of these should just be false right 1 0 less than 0. so these are all just false so i don't think these even enter so check 1 so x plus 1 is so when x is one the data size doesn't change we say so this all would be false um this would these would um terminate early too so we don't even enter these code blocks so this should all just be false for this f 2. this ends up being well actually this will return true right f of 2 will return true but yeah so our first check this should be false all right 0 1 seven and this is false this is true this ends up being false these are the ones all before all false why doesn't this just return false and that's the end of it where do we get a heap buffer overflow how does that happen where does that happen that's bizarre i was not expecting that one basically thought we were done i mean i don't know man test gets cold okay how about test two how are we doing on time all right 45 minutes test 2 gets called okay how about test 3 and test 4. test 3 gets cold test 4 does not get called so here seems to be before we run into issues does this need to be um why what why would this cause problems this is just true so this should be an issue um x plus one x plus two we don't really terminate it early so i guess we do call all of these things but these shouldn't they shouldn't even enter these blocks is that why maybe i'm missing something here that'll be really annoying i don't think that matters but i guess maybe it does i don't know this size uh i want to say what number is this yeah that underflowed okay it's wondering it's like what is going on this could i think because this is an unsigned integer yeah you've got to be careful about that yeah that's a tricky thing um that's exactly what's happening yeah okay yep okay though those errors will catch you off guard those will catch off guard definitely doesn't happen to me too often but it happens often enough things related to overflowing and underflowing yeah you'll get these just like out of the blue kind of bizarre errors and you're like what is why is this happening the reason is that you don't expect to hit an under flow or an overflow with your calculations because you don't realize that you're it's happening and then so your calculations are just wrong so like what you expect is just not what's happening and so you're just totally blindsided it's great it's the best all right now let's find it let's find a test case that we fail on oh got him nice sweet done not too bad um not the most efficient or um memory what do you call that not the most efficient or memory what are they called what's the expression um not the most efficient and not the most i guess lean on memory yeah not the most efficient in terms of time and memory usage but okay i think more efficient would be to um so it's about 50 minutes all right we technically failed it too which is awful but i think the idea was correct is just implementing it was a bit of a doozy um a few things we can actually do this with a dynamic programming solution going from the back to the front that's an idea um yeah that's an idea and we also which would probably be more efficient and then we also could that would also be iterative instead of recursive so probably more efficient in that regard too we also probably could um and that was kind of what i was struggling with for a while i spent like a solid 20 minutes trying to figure out how to make excuse me how to make these checks more efficient these things that are going on um these are definitely strange i'll say uh okay it's probably time for me to go let me spend like another like 10 minutes or five minutes two five minutes because i said like i mentioned i'm going to see somebody soon and i don't want to be late so i would want to convert this to a dynamic programming solution that's dynamic programming solution that is it done iteratively and then i also would want to update these different checks to something that um i don't know it's like a little bit more a little bit simpler i guess um um i want to say we could do an xor we could do an and mask and then an xor of what we want to check if they're equal so bx or b kind of a thing um that's equal to zero so we could do that kind of a thing um for the mat we use like a mask that's one two three one two four five one two three four five so the mask we're gonna set those all basically although all those to zero so we would say something like this one we can kind of leave it as it is that's fine so you can't really do much better than one sort of um bit wise check to get two and a half oh man it's a speed run here this one though we could say okay um we're gonna mask data of x and with this mask which is um it's gonna be it's the mask is going to be one bit shifted we want to take one two three how many numbers we want one two three four five numbers right that shift five subtract one if we do that then if we bit shift five subtract one then these all be ones we actually want to negate that to make those all zeros right so we end this with this mask and then we want to xor with this one on one zero with all zeros at the end um that's basically i want to say this is i want to negate that as well it's a little bit confusing but that 1 0 at these two numbers this is 128 plus 64. 192. okay that's what we want instead of these two and this one let's try that see if this is still correct after making that change are we still correct yeah okay it's basically what i want to do i want to update all of these different pieces and this part actually this mask this is should be the same for all of them um this will say oh we're about to be in a tough spot here or an awkward spot so we move this one more bit over to the left and instead of 192 it's actually 128. and that checks that's x plus one we want to say okay we do that see if that's still correct speed run over here end of declaration okay we'll spend like another like three minutes okay now we can update the other ones too oops this is for the other three bits so we have this one two times here so we do that for one two and then we do it three times on the other one two three all right let's try that one see that goes probably don't need those okay and then we can update this as well to set 192. um this is that's the first check the second check is 192 i think plus 32 which is 224 192 plus 32. yeah 224. and then over here we would say and that's the five bits that's one two three four five right this is four bits now this is three bits and add 16 to that it's 40. let's say something like that let's see how do we do okay that's a little bit better i think still correct okay so that's a little bit better now we'd want to do is i don't have the time to do it but what you could do from here is um i'm gonna go what you do from here is you could change this instead of doing a recursive function and then memoizing the results you can actually just write a dynamic programming solution where basically you fill an array of booleans from right to left and um and then these would be array axis instead of function calls each of these and you can do it and it wouldn't have to be recursive at all either you wouldn't need to memoize an unordered map then this would probably be a lot more efficient and it would be more efficient on the memory and the runtime both of those would be a lot more efficient these also i guess this number you could probably um what is it you could probably pre-compute pre-compute pre-compute like this some of these steps too something like that like these are actually numbers each of these um yeah this number each of these numbers you can pre-compute them as well you can pre-compute them as well you can pre-compute them as well um and then just kind of use them in the uh the logic uh yeah so let me go um yeah let me go thank you for watching uh it was fun that was interesting i'm glad we got it that took us oh um basically an hour that was kind of rough i give myself a little bit lower the volume i give myself a little bit of credit because that was definitely challenging um kind of just to understand the question in the first place like what they were asking but yeah definitely interesting um utf-8 there you go interesting um utf-8 there you go interesting um utf-8 there you go that's how it's done seems somewhat arbitrary but it's not really arbitrary it's just wow it seems like the volume is really high it's not arbitrary it's just um just how they did it i guess how they picked it so yeah let me pick the format let me go thank you all for watching talk to you soon have a good rest of your day take care
|
UTF-8 Validation
|
utf-8-validation
|
Given an integer array `data` representing the data, return whether it is a valid **UTF-8** encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).
A character in **UTF8** can be from **1 to 4 bytes** long, subjected to the following rules:
1. For a **1-byte** character, the first bit is a `0`, followed by its Unicode code.
2. For an **n-bytes** character, the first `n` bits are all one's, the `n + 1` bit is `0`, followed by `n - 1` bytes with the most significant `2` bits being `10`.
This is how the UTF-8 encoding would work:
Number of Bytes | UTF-8 Octet Sequence
| (binary)
--------------------+-----------------------------------------
1 | 0xxxxxxx
2 | 110xxxxx 10xxxxxx
3 | 1110xxxx 10xxxxxx 10xxxxxx
4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
`x` denotes a bit in the binary form of a byte that may be either `0` or `1`.
**Note:** The input is an array of integers. Only the **least significant 8 bits** of each integer is used to store the data. This means each integer represents only 1 byte of data.
**Example 1:**
**Input:** data = \[197,130,1\]
**Output:** true
**Explanation:** data represents the octet sequence: 11000101 10000010 00000001.
It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.
**Example 2:**
**Input:** data = \[235,140,4\]
**Output:** false
**Explanation:** data represented the octet sequence: 11101011 10001100 00000100.
The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.
The next byte is a continuation byte which starts with 10 and that's correct.
But the second continuation byte does not start with 10, so it is invalid.
**Constraints:**
* `1 <= data.length <= 2 * 104`
* `0 <= data[i] <= 255`
|
All you have to do is follow the rules. For a given integer, obtain its binary representation in the string form and work with the rules given in the problem. An integer can either represent the start of a UTF-8 character, or a part of an existing UTF-8 character. There are two separate rules for these two scenarios in the problem. If an integer is a part of an existing UTF-8 character, simply check the 2 most significant bits of in the binary representation string. They should be 10. If the integer represents the start of a UTF-8 character, then the first few bits would be 1 followed by a 0. The number of initial bits (most significant) bits determines the length of the UTF-8 character.
Note: The array can contain multiple valid UTF-8 characters. String manipulation will work fine here. But, it is too slow. Can we instead use bit manipulation to do the validations instead of string manipulations? We can use bit masking to check how many initial bits are set for a given number. We only need to work with the 8 least significant bits as mentioned in the problem.
mask = 1 << 7
while mask & num:
n_bytes += 1
mask = mask >> 1
Can you use bit-masking to perform the second validation as well i.e. checking if the most significant bit is 1 and the second most significant bit a 0? To check if the most significant bit is a 1 and the second most significant bit is a 0, we can make use of the following two masks.
mask1 = 1 << 7
mask2 = 1 << 6
if not (num & mask1 and not (num & mask2)):
return False
|
Array,Bit Manipulation
|
Medium
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.