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 |
---|---|---|---|---|---|---|---|---|
510 |
hey how's it going so today we're gonna do record in other successor mbst um two of so this question so given a note in the binary search should you find the in order successor that of that note in the bst if that node has no in order successor return none on the successor of a node is the node with the smallest key greater than node of value you'll have direct access to the node but the roots of the tree each node will have a reference to its parent node below is the definition of the node so basically um this in order successor in bst2 is different from the in order successor of bst one because um we have access to the paranoid so that's actually make uh this thing easier because let's look at this example um what's the in order successor of node one it's two right so what's the in order successor of two is three right it's the smallest number that is greater than the node what is the in order successor of three it's four what's the in order successful of four is five right what's the in order successor five is six what's the in order successor of six it's not because it's done at the last uh last note in the in order traversal right so we can see that if a note has a red tree right it means that it has something larger on the right tree so we just need to explore the right tree so if let's say for if there is something like let's say 4.5 in the left subtree basically if we 4.5 in the left subtree basically if we 4.5 in the left subtree basically if we want to find the node of node 3 successor we have to if it has a right subtree we know that the successor will be somewhere inside the right tree right and if the four has a left sub tree we have to go left because we know that somewhere here in this right subtree it has the successor and we have four here so if there's something smaller on the um on four we have to go left until we reach the leftmost node right and we return that node so that's our first case so if um the node we're looking for has a right subtree let's write it down first so if so the node we're given is the node that we want to find the successor to so if node has array subtree is if it's not known then we basically traverse we go to the right tree right so this is how you traverse from three to four and once we're done here and while note down left so basically we're saying if there's any subtree left subtree of the four we have to go uh go to the leftmost note right oh and all we need to do at this point is return node so if there's a let's say if there is a left sub tree here 4.5 4.5 4.5 then we here we go to the 4 and while it has a left subtree so while it has the left substrate so if there is a 4.5 substrate so if there is a 4.5 substrate so if there is a 4.5 node equal to node.left so we go to node equal to node.left so we go to node equal to node.left so we go to node 4.5 4.5 4.5 and at this time we just need to return node okay that's our first case where uh the indentation is a little bit off that's our first case where node has the right subtree right what if the node doesn't have a right sub tree for example the 161 doesn't have a right subtree so we know that it has to go to the parent right so we know though the uh answer is 2. for 2 the answer is 3 right for 4 it doesn't have a right subtree it answer is not 3 but it's five so basically we want to go to its parent node until the parent is larger the parent's value is larger than the uh the note right so for example here one we go to the parent and parent is greater than uh than the note then we return the parent right so for two it doesn't have a right subtree we go to its parent and we find the parent is greater than itself so we return the parent and for four it doesn't have
|
Inorder Successor in BST II
|
count-subarrays-with-more-ones-than-zeros
|
Given a `node` in a binary search tree, return _the in-order successor of that node in the BST_. If that node has no in-order successor, return `null`.
The successor of a `node` is the node with the smallest key greater than `node.val`.
You will have direct access to the node but not to the root of the tree. Each node will have a reference to its parent node. Below is the definition for `Node`:
class Node {
public int val;
public Node left;
public Node right;
public Node parent;
}
**Example 1:**
**Input:** tree = \[2,1,3\], node = 1
**Output:** 2
**Explanation:** 1's in-order successor node is 2. Note that both the node and the return value is of Node type.
**Example 2:**
**Input:** tree = \[5,3,6,2,4,null,null,1\], node = 6
**Output:** null
**Explanation:** There is no in-order successor of the current node, so the answer is null.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-105 <= Node.val <= 105`
* All Nodes will have unique values.
**Follow up:** Could you solve it without looking up any of the node's values?
|
Change the zeros in nums to -1 and create a prefix sum array prefixSum using the new nums. If prefixSum[i] for any index i in the range 0 <= i < prefixSum.length is positive, that means that there are more ones than zeros in the prefix ending at index i. If prefixSum[j] > prefixSum[i] for two indexes i and j such that 0 <= i < j < prefixSum.length, that means that there are more ones than zeros in nums in the range [i + 1 : j] (inclusive)
|
Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set
|
Medium
|
474,1999,2261
|
1,377 |
Loot hello welcome to this list dot problem holidays subscribe and subscribe the channel questions related to follow subscribe my channel subscribe the one more that and you know the prime president don't forget to subscribe on thursday subscribe the channel Subscribe Must Subscribe To That A Atm Sabse 65 Years To That A Atm Sabse 65 Years To That A Atm Sabse 65 Years Jo Person Time When Screen Nod32 To Find The Road To 9 To Subscribe Our A Properly Dealt With In Order For Date Of Birth Is Properly tf2 Time Date Of Birth Day June 1 k rog job luteya problem pintu time hai proper problem hai the property of withdrawal from youtube now closed subscribe to me stories paste immediately pretty simple things used lubricating Recent Times 12345 What is the problem Question is the time to problem Subscribe now to quality tak to rock will remain in order to avoid no problem Video then subscribe to the Page if you liked The Video then subscribe to subscribe our YouTube Channel and subscribe the Channel Hai Aur Iss Your Time Fearless Man Time gave the reservations to fix from where river good qualities and exit poll Reddy Shiva Reddy Samjh Take It Means the subscribe for you liked The Video then subscribe to the New Delhi Famous Images Will add mixer to intruder facility subscribe for you liked The Video then subscribe to the Page [ the Page [ the Page Torch Light of Petrol Navneet to Make Short Dasha House from is given to right is from this great country not possible subscribe and subscribe the Channel and subscribe the Video then subscribe to that on the graph Ambrose vs. Whatever do you do long to avoid this problem to customers A push back torch light to Ajay is it that person subscribes to his computer that this tax is being imposed from here Radhe Pandit Ji Ki Staff Butter Time Duty Now Our Channel Subscribe Play Kar Do Ki Bigg Boss Louis Right Type To Subscribe Computer Problem Subscribe Hey O Ki Time But Its President Subscribe What Is The Subscribe You Want To Give up this post bol restore day text wear information provided in the mid-day provided in the mid-day provided in the mid-day time in this world a property rights to attend table time lutb scan say composition service commission in this quality this comment subscribe to me here board also you why because in Of The Year That In Nadol Quality Double Tight Understand Your Limits On An Older Female Staff Visible Tube Light Tube Subscribe To A Better Position Due Dates To Avoid Taxes On Twitter Subscribe RSS Feed Subscribe So Did Not Difficult Unless You Are Interested In Front Aaf the 9th that these accused and 5cho a scientist is cute front edition dot print quality time with him and off but you should not be subscribe Video subscribe here come that time inka obscene video and in due time left back and drop servi channel Subscribe to: 202 Strikes August 20121 Comments 2181 Studies Subscribe Button Switch On Thursday In Vitamin Water And Representatives In The Dock Withron Its Great Dane Graph World Plut All Chief Editor Off But SIM Question Suggested Switch To Hands Free Mode Electricity Graph Vibes That's time plus and loot subscribe to 500 1000 for converting into blood that businessman Suresh Lohar upon which the want BSP rule times over 1500 subscribe and subscribe this loo 's responsibility tiffin dual spots for pimples subscribe 's responsibility tiffin dual spots for pimples subscribe 's responsibility tiffin dual spots for pimples subscribe to feel good on one hand Se Uttar Pradesh One More Updates Ok Write Subscribe To The Interactive Vitamin Chup Bay Sakte Hain Ajay Ko Ki Ko Alex Pet Scientist This Only Sudhir Dhawale Ko [ Sudhir Dhawale Ko [ Sudhir Dhawale Ko Jhal Ajay Ko Ki Aapke Shri Krishna Shyam Surface Apne Is Tune Jhal Effective International Singh Secretary Dr is startled OK Come on the other side That's the measurement of inches Now pair of all these stakes but will take on How to be som abroad as well placid on Hello viewers Uski sudhi Silev mistake is left to right to education but Amazon Problem Not Enter Subscribe To Jhal 120 Test And Online Reader Balram Lekin President subscribe and subscirbe Subscribe To Main Secure Access Anand Selectors Very Small Cars Tay Using Double Cylinders And Pimples Se Zid subscribe and subscribe the Video then subscribe to
|
Frog Position After T Seconds
|
number-of-comments-per-post
|
Given an undirected tree consisting of `n` vertices numbered from `1` to `n`. A frog starts jumping from **vertex 1**. In one second, the frog jumps from its current vertex to another **unvisited** vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex.
The edges of the undirected tree are given in the array `edges`, where `edges[i] = [ai, bi]` means that exists an edge connecting the vertices `ai` and `bi`.
_Return the probability that after `t` seconds the frog is on the vertex `target`._ Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** n = 7, edges = \[\[1,2\],\[1,3\],\[1,7\],\[2,4\],\[2,6\],\[3,5\]\], t = 2, target = 4
**Output:** 0.16666666666666666
**Explanation:** The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after **second 1** and then jumping with 1/2 probability to vertex 4 after **second 2**. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 \* 1/2 = 1/6 = 0.16666666666666666.
**Example 2:**
**Input:** n = 7, edges = \[\[1,2\],\[1,3\],\[1,7\],\[2,4\],\[2,6\],\[3,5\]\], t = 1, target = 7
**Output:** 0.3333333333333333
**Explanation:** The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after **second 1**.
**Constraints:**
* `1 <= n <= 100`
* `edges.length == n - 1`
* `edges[i].length == 2`
* `1 <= ai, bi <= n`
* `1 <= t <= 50`
* `1 <= target <= n`
| null |
Database
|
Easy
| null |
113 |
Hello Everyone Welcome to the Video You Will Be Discussing Network Problem 95 Samudra Problems Ek Incident Jeevan Root of Binary Tree and Vitamin Enriched Turn on the Road to Leaf and Steel Workers Subscribe Bhi Problem Aaye Tree subscribe to the Page if you liked The Video then subscribe to the Page व्यापाट सोना विल नॉट पात इस लेस्पूर्ट व्यापाट सोना विल नॉट पात इस लेस्पूर्ट व्यापाट सोना विल नॉट पात इस लेस्पूर्ट MR कल सुभा आप Define Emergency You Can Share All The कल सुभा आप Define Emergency You Can Share All The कल सुभा आप Define Emergency You Can Share All The Elements From This Point To Panch Withdrawal 135 वे Subscribe To-Do List On Withdrawal 135 वे Subscribe To-Do List On Withdrawal 135 वे Subscribe To-Do List On The Parts Of Flower Subscribe To This Serum Other Text Five Four Laga Do A Defined Twenty-20 World Solution Doobie Twenty-20 World Solution Doobie Twenty-20 World Solution Doobie Solving Its Problems Problem Ka Solution Subscribe My Channel Subscribe Solution Work No Problem Hai Ki Sapoch Yoga Departed And Twenty-20 Flats Ki Sapoch Yoga Departed And Twenty-20 Flats Ki Sapoch Yoga Departed And Twenty-20 Flats So let's send how to distributors chocolates that children in the house as one house for rent houses for children books for children in to-do list webs Click children in to-do list webs Click children in to-do list webs Click on the link For subscribe The Amazing in solving come this sample ok take it a noida- based Five White Chocolate Sandwich a noida- based Five White Chocolate Sandwich a noida- based Five White Chocolate Sandwich Chocolate 100MB Left With 17.70 Cricket Chocolate 100MB Left With 17.70 Cricket Chocolate 100MB Left With 17.70 Cricket A Height Come To I Have Two Options Color To Go To The Left To Right Super Spider Left Gifts Chocolates We Attacked 2017 - 1431 Gifts Chocolates We Attacked 2017 - 1431 Gifts Chocolates We Attacked 2017 - 1431 Okay I Don't Have The Right Hair Oil Computer Left That Thirteen - Lagaenge is too good right here That Thirteen - Lagaenge is too good right here That Thirteen - Lagaenge is too good right here first but I hop chocolate bar tarah survey children is not disturbed tak ok r children will get angry with chocolate ice cream the subscribe The Amazing ki hum lapet khusro chocolate after defeating aa tu chocolate par kiss hindi south these forms One of Math Solution Maximum This is Shapath 547 2 and Five Plus 409 Plus Lagna 028 Pass 122 365 Time Response Time Solution Which How Way Can Solve a Problem It Will Oo Ko Sukoon Turtle Bay Discussing the Feeling Using Any Object Oriented Programming Languages Like Ka Java Programming Languages Like Ka Java Programming Languages Like Ka Java Script Python and C Plus In Subscribe Actress Who Believes in the World Tractor 265 Western Media Is Path to To All Elements Which Comes in Current Past and Undone Result Returning to Return Subscribe 21 List and To-Do Subscribe 21 List and To-Do Subscribe 21 List and To-Do List Result The Result Will Look Like 80 Hey Laddu Dictionary App Is Samay Phansi Insult Of Which Cause Not At Least Not Mean That Subscribe Decrement 522 - 578 Half Hai 522 - 578 Half Hai 522 - 578 Half Hai Me Help Vikram Seventeen Years And White Part 2 And Subscribe And The Function Reciprocally Factory 44000 Share And Subscribe - 40 50 And Yash Lakh 30 Pastor Andha Right Farj Select Let's Tree And Not Least Continue Collection Share Looking For * Share Looking For * Share Looking For * Yes Absolutely To 1072 Electric But Its Life Itself But Assam And Samridhi Want Any To - 7 Request - And Samridhi Want Any To - 7 Request - And Samridhi Want Any To - 7 Request - 50 - 500 1000 Members What Dos A This Post I Will Have Added To The Character House History Most Exhaustive Mode Night Sweet Dream To Alert Bright Successful One To Will Be The Password Don't Get Confused If The Single Factor Skin Crossing All The Best Result 2nd Subscribe To Which Or Interest 5.1 120 Vikas Part Which Or Interest 5.1 120 Vikas Part Which Or Interest 5.1 120 Vikas Part Plus 4 Lagna President 22000 And Inserted Into Result Election Special Sexual Remote To Ashok Emo London Dream On Official Remote Jai Hind Same Continue To This Site Ok Sudhanshu Vishal This Problem This Is The Function Definition Of Given In Let Code Explanation Root Of the tree and tagged some and how to return of factors of vectors containing all the 500 it's okay and sorry not emergency deemed limits in emergency given emergency committee target song in such lets artificial per functions paper use question year will need of medicinal parameters In function svaha and the part which contains the current system liquid define the rate of return file not washed function please subscribe please thank you name hindi help function gift current element this root all the best a key and guide a text whatsapp chief producer More Research Chocolate Station Problem In It Chocolate Children Should Be Left With No - Fruitive It Subscribe Left With No - Fruitive It Subscribe Left With No - Fruitive It Subscribe Roots Person Fix Current Past And It's Who Is The Current No Default Note Dhanadya It Targets Hum Isi Chord 2018 201 Is Insult The Path * Result Of The Life Is The Subscribe Please subscribe and subscribe the that in similar manner call pier right side very sick witch state is how to remove what is insulted password min tak entertainment how to remove the correct element I hope you find this video you will not lakshmi so nikal x video
|
Path Sum II
|
path-sum-ii
|
Given the `root` of a binary tree and an integer `targetSum`, return _all **root-to-leaf** paths where the sum of the node values in the path equals_ `targetSum`_. Each path should be returned as a list of the node **values**, not node references_.
A **root-to-leaf** path is a path starting from the root and ending at any leaf node. A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,5,1\], targetSum = 22
**Output:** \[\[5,4,11,2\],\[5,8,4,5\]\]
**Explanation:** There are two paths whose sum equals targetSum:
5 + 4 + 11 + 2 = 22
5 + 8 + 4 + 5 = 22
**Example 2:**
**Input:** root = \[1,2,3\], targetSum = 5
**Output:** \[\]
**Example 3:**
**Input:** root = \[1,2\], targetSum = 0
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5000]`.
* `-1000 <= Node.val <= 1000`
* `-1000 <= targetSum <= 1000`
| null |
Backtracking,Tree,Depth-First Search,Binary Tree
|
Medium
|
112,257,437,666,2217
|
354 |
Hello Everyone Welcome to my YouTube Channel and Question for today is Russian Doll and Electronic Tubelight Ude Re Open Teachers in Vallabh Vya Everywhere you have to go to two states today are short tricks with jam The accident on the Light of and always present at the highest Position with solve Vasundhar them job is bodh with and half rich and position and also this is another and better as they can see this can fit into the solid nature viewers family and wasted in the Olympics involve scan ki heat son of Lord Shiva internal audit so you Can develop likha chahiye person chahiye 500 1000 up example2 80 ki lakshya force episode 723 din aka is and developed and which can do it is that is loot modifications in the mother and the number of mystery and subscribe our channel by making it towards subscribe astu Aankh Dieting Election 2014 B.Tech Course Shybi More Than ₹100 One 2014 B.Tech Course Shybi More Than ₹100 One 2014 B.Tech Course Shybi More Than ₹100 One In The Printing And The Like Top Ten Sports Ministry Approved And Not Lack Electronic System Portal Judgment Wages And They Can Achieve 1000 Of The Statement Display Cardamom The Question Gorgeous Kishore Ab Se Rachid Approach Vertigo * Use hotspot Se Rachid Approach Vertigo * Use hotspot Se Rachid Approach Vertigo * Use hotspot turn on this problem similar to find the longest increase in subsequent already in which will give water synthesis and this proposition third party verification 123 456 long subjects were born in this regard for this is subscribe that is better to forgive you began the Buddhist Problem Similar To Like This Positive Vacancy In Cases Different Dates That Indian Cricket Coach Alan Robert Fixed Person General Knowledge 2012 Police 12345 Shyama Shyam subscribe to the Page if you liked The Video then subscribe to subscribe our Shopping Loot and Everything to Avoid Minimum One More Return of the Day Dangerous Are Great That Superintendent of Police Sudhir Lad Pyaar Hai Website Vya Speedy Swayam Should We Do Hai So Manish Jain Shailesh Bhai So Adv.mr Hai So Manish Jain Shailesh Bhai So Adv.mr Hai So Manish Jain Shailesh Bhai So Adv.mr Handing Over Shopping and Cricketers That Person Setting Battery Guddu Switch agree when you welcome pure this value with value name what is the president account harold 794 12303 420 120 close two i love you will take one because of this element three four milli and they can take medicine want two and three for this dating site verification Suggestion Develop Present at this will be Accounted Updates Index Revenue Growth Send a Maximum of Vacancy in Various Countries 120 days This value will automatically update in 200c quickly Don't you for watching this value will be updated And Saturn will have value and activists were supposed Disadvantages of To Have A Light Off Sudarshan Fit And With No Khetaram Se Lootere Soe Ho I Thing After It's Very Simple Obstacles Long Since And Subsequent Android Users That Were From Starting With In NIOS Science And Technology Development Vineet The Share Index Of A Grid Solar Panels Different from others but in this case is dangerous to eliminate account select back here every else halwa first target turn on this question in the were between mother carried you still can get up to light and golden shakoor just have written hokar have any relationship dam ok Exotic Is Resort Shift Heart Beauty Are Investing In Increasing Author Ashok Sleep 0981 Andar Length Is One Treatment Table Clear Bach Story Of Infield Olympian 151 Life Even In Time Course 204 Two Table Spoons Of This Area And Always Seen From 024 Position His Mother In One President Area Will See Delhi President Maximum Full Of Present Below Lia Dashrath And Two From Scientists Great Leaders Greater Than 150 Who Do n't Were Not Read Don't Share Please For The Volume To 9 10 Vyati I Love You Are The Different Aspects Of Life Easier Motherland Will Change for the end up to this day will be set in the defense and it's done in this for lungi three Atul settings Maxwell Uther Calculator simply Dhamak or otherwise will happen again travels rate in one time and calculate the volume to BHK flat in every step and Vijay Speech On The Best Regards And Certainly Not Its Tattoo Committee Chairman See From Here Who Can See This Software Install Recording This Question But Existing Comment Section Was Exist Complexity Video Fans Reverse Sweep Channel Flat To Followers And Stories For Kids Beef And Events Today Were Already Please Like This Video Update 104 and subscribe To My YouTube Channel thanks for watching Up
|
Russian Doll Envelopes
|
russian-doll-envelopes
|
You are given a 2D array of integers `envelopes` where `envelopes[i] = [wi, hi]` represents the width and the height of an envelope.
One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.
Return _the maximum number of envelopes you can Russian doll (i.e., put one inside the other)_.
**Note:** You cannot rotate an envelope.
**Example 1:**
**Input:** envelopes = \[\[5,4\],\[6,4\],\[6,7\],\[2,3\]\]
**Output:** 3
**Explanation:** The maximum number of envelopes you can Russian doll is `3` (\[2,3\] => \[5,4\] => \[6,7\]).
**Example 2:**
**Input:** envelopes = \[\[1,1\],\[1,1\],\[1,1\]\]
**Output:** 1
**Constraints:**
* `1 <= envelopes.length <= 105`
* `envelopes[i].length == 2`
* `1 <= wi, hi <= 105`
| null |
Array,Binary Search,Dynamic Programming,Sorting
|
Hard
|
300,2123
|
209 |
hello everyone welcome to another lit code so today we'll be doing a medium question which is the minimum size sub-array sum sub-array sum sub-array sum so given an array of positive integers and a positive integer which is called target we have to return the minimal length of a contiguous subarray so that means that there are no breaks in between of which your sum is greater than or equal to the target and if there is no such sub array we return 0 instead so taking a look at example one you see that we have a target of seven and there are indeed many values that can form this target so for example the whole array right here when you sum it up is at least greater than or equal to the target so there's also a possible answer however what we want to do is to return the minima so as such in this array right here you see that the minimum is this one right here which has four and three since it's at least greater than or equal to seven and as such we will written up of two which is the length of this caliber subarray likewise for example two we see that solely just one element can already help us to form the target minimally and thus we output one however for example three we see that it's not possible for us to hit that target because even if we sum up this whole array it still is still less than the target value right here and as such return zero so that is how the problem sounds like so off the top of my head one can think of is a good first solution but you are running 4 of n square which is not the most efficient so what we need to do is just simply have a counter and we set it to the first index right here of two and then we just continue to look through the array and increment the counter by the back by the values right here as well once we see that we have already hit the target then all we have to do is to just return the length of this array so that will mean that the length of this array will be the continuous sub array that can help us to form the target or value of 7 when we begin at this index and then we just have to iterate through this same algorithm for the rest of the sub arrays so we start at 3 then go through the rest style 1 then go to the rest and etc so this will be how we can get the answer by the root force method however an algorithm that we can use is a sliding window pattern approach which will help us to run the algorithm at on time which is more efficient so this is how the algorithm will sound like so initially we have a start position and the end position and what i will do is that at every iteration i will check whether the subarray which is in between the start and the n inclusive can help me to hit the target which is seven so in this case right here i say that the sum of these two values is five and that is still lesser than my target so what i will do is to shift the n by one and now i'll take a look at this whole sub-array instead so i see that the current sum is actually 6 which is still lesser than my target and so i'll keep moving my n-index n-index n-index so right now we see that the sum is actually 8. it at least meets my target now so that'll mean that this right here is a very sub array that can be written with a length of four however what we want to do now is to slowly move our stack index to the right so that we can check for the smaller length that still satisfies this target value so for example since this country satisfies i will already record down the length of 4 right here which is at least one of the valid answers to be written and now i'll move the start index so as i hit 3 right here i see that it no longer meets the appropriate value because now the total sum of these three string integers right here is 6 which is lesser than a target so this would mean that i have to shift my n again so at this juncture right here i have a sub rate of length 4 again and i see that it still fulfills the target requirement however since the minimum one that i have already recorded is ready for i will not update the new one and right now since this sub array already meets the target i can shift my start to the right again so i'll shift it right here and i see that it still fulfills my target of at least seven so tell me that this is actually a shorter answer since it has a length of three and that's how i need to update it right here to become three and then i continue to shift my start to the right because it's valid so at this juncture 2 right here i see that it's in value again so now i'll shift my n and then now it becomes value again and now i'll check whether the current length right here is less than or equal it's less than my current length that i've recorded so anyway it's the same so i want to update it and then now i'll shift my two to the right so as you control in time it still satisfies my target and now he has a size of 2 which is lesser than the length right here so likewise i need to update this to become 2. and now i have already come to the end of the array so this will be the answer that i'll be returning so this approach right here is called the sliding window approach because we initially have two pointers that start at approximately the same point and we will just like then slide that across the right towards the whole array and as such since by the work case scenario either pointers will take on time to reach the end we have overall time velocity of o n which is faster than the brute force method right here and for the space complexity is going to be a constant because we are just taking a look at pointers of the e of the array so as such this will be how the general algorithm will flow and now let's move on to the coding part of the solution okay so now let's move on to the kodi part of the solution so as always let's talk about sudo code first firstly we are going to be utilizing the starting window approach so let us do some uh initial validation checks first so you are going to have uh empty nums array yeah i can just return 0 also or if the sum of my nums is already less than the target i can return 0 as well since there's no way there can be such a sub array so if nums is empty or some of my nums is less than target they'll just return zero another thing that we can check is whether the first number present is already greater than or equal to the target so if so we can just return one so just a very simple check actually first number already meets target if so i can return one else this is where we'll begin our sliding window approach initialize the start and end and while my sub array in between start and end is less than my target keep increasing my n so that you can look at the new range else i will move my start and keep checking if it is still valid and if so take the minimum of the size as my answer so this will be how the general algorithm will flow so let's initialize our variables now so i just have a start at zero and end that starts that one first and i have a accumulating value to help me check the total value which i'll initialize it to be at the start as well so right now i'm looking at the first index so you'll just register two for example right here and you'll slowly move beyond from here so for the size initially i'll just assign it to be an infinite value because i want to take the minimum of it if there's an answer so now we will do the study window so while my n is still less than my num length of nums so name so that means that it's still valid i'll add it to my total and when i edit to my total what i will do is to check if i've already reached a valid sub array so if so then what i will do is to update the size now what i will do is to iterate through while the total is still valid so while my total is greater than is at least greater than or equal to the target doesn't mean that the sub array is too valid what i'll do is update my size take the minimum between the current size and the length of my sub array so there'll be a minimum between size and n minus 5 plus 1 and this will be the length of the sub array and when i do that what i want to do is to shift my nums to the right but take note that we have to subtract away this value right here so that we can update the new subarray so for the total we have to minus off from the nums and the start so that we can take away this value and continue to check whether the subsequent subarrays are valid so once i have subjected it i can increment my start value so once this is done at the end of the day if this if loop doesn't execute no matter what we still have to increment our n this is so that we can take a look at the subsequent values to see whether they will eventually satisfy the total right here and after we have finished this algorithm running then we can just simply return size and that will be the updated value so as i mentioned just now the time g will be of o n simply because we are just using a 2.0 simply because we are just using a 2.0 simply because we are just using a 2.0 approach that will put just right in the same direction and therefore the space capacity will just be o1 because we are just directly assessing the index which takes constant time so as such this will be the answer right here so actually i made a kind of a rookie mistake he said i forgot to code out these parts right here or the validation checks so let's just do it right now so if my announce is empty it's just empty array for the sum my number is less than the target i can just return zero this will not be possible and let's do this simple check as well so if my first d first number is really greater than or equal to the target i can just return one and i believe the solution should work so and as always if you have any questions then feel free to leave in the comments down below and i'll do my best to help so yeah thanks for watching
|
Minimum Size Subarray Sum
|
minimum-size-subarray-sum
|
Given an array of positive integers `nums` and a positive integer `target`, return _the **minimal length** of a_ _subarray_ _whose sum is greater than or equal to_ `target`. If there is no such subarray, return `0` instead.
**Example 1:**
**Input:** target = 7, nums = \[2,3,1,2,4,3\]
**Output:** 2
**Explanation:** The subarray \[4,3\] has the minimal length under the problem constraint.
**Example 2:**
**Input:** target = 4, nums = \[1,4,4\]
**Output:** 1
**Example 3:**
**Input:** target = 11, nums = \[1,1,1,1,1,1,1,1\]
**Output:** 0
**Constraints:**
* `1 <= target <= 109`
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 104`
**Follow up:** If you have figured out the `O(n)` solution, try coding another solution of which the time complexity is `O(n log(n))`.
| null |
Array,Binary Search,Sliding Window,Prefix Sum
|
Medium
|
76,325,718,1776,2211,2329
|
384 |
hello friends so today we're gonna discuss this question on the it code problem number 384 shuffle and hairy so in this question you are given inputted and edit and you have to make three two functions actually the first function should return the original edit and the second function should return a shuffle form of the area which is inputted okay so how do we shuffle this edit there's a different algorithms but the most simple one is the fishery it's shuffle or the cannot the shuffle so let me describe here how to do the shuffle so let's assume this is there in so we'll move from right to left and first we fix this the last element and then we choose our random number from this range this here to here and let's assume this number is chosen so we swap these two numbers this number the swap and the new array will be like 2 5 3 seven and one and now because one has been suffered we put a marker and now we move on to zero now we choose a random number from this subsection and let's hope this number is Susan so we shuffle this with this so now the next array will be two seven three four five well now because these two elements are separate now I remain this symbol to here and this is how I got them will proceed we'll just shorten our array and choose the any random number between these the remaining subsection the severity and then zap that element the randomly selected element with the chosen element and this algorithm will run in O n time because we are just moving from right to left I hope you understand the algorithm so this is what we're done in the core as you can see we first initiated these two areas and the solution thus we have what we have done is we initiated these two arrays with the original num array which is inputted then for the reset function we just return the original area because we do not have to shuffle anything but in the shuffle when you call the shuffle function if the random array is empty random area also contains an array is actually the random array is just a random formation of the actual airing so we have copied the original array into random so if the random array is empty return random or else will be what can do is remove some right to left and we just have the element on which we are with a random number which is choosen and we move somewhere to left it is an O of n time and this return the random I hope you understand this logic because when we are choosing each element it is done by this function only random function and you can easily understand the logic if you don't you can watch this video I hope you understand the logic and thank you for watching and I'll see you in the next video
|
Shuffle an Array
|
shuffle-an-array
|
Given an integer array `nums`, design an algorithm to randomly shuffle the array. All permutations of the array should be **equally likely** as a result of the shuffling.
Implement the `Solution` class:
* `Solution(int[] nums)` Initializes the object with the integer array `nums`.
* `int[] reset()` Resets the array to its original configuration and returns it.
* `int[] shuffle()` Returns a random shuffling of the array.
**Example 1:**
**Input**
\[ "Solution ", "shuffle ", "reset ", "shuffle "\]
\[\[\[1, 2, 3\]\], \[\], \[\], \[\]\]
**Output**
\[null, \[3, 1, 2\], \[1, 2, 3\], \[1, 3, 2\]\]
**Explanation**
Solution solution = new Solution(\[1, 2, 3\]);
solution.shuffle(); // Shuffle the array \[1,2,3\] and return its result.
// Any permutation of \[1,2,3\] must be equally likely to be returned.
// Example: return \[3, 1, 2\]
solution.reset(); // Resets the array back to its original configuration \[1,2,3\]. Return \[1, 2, 3\]
solution.shuffle(); // Returns the random shuffling of array \[1,2,3\]. Example: return \[1, 3, 2\]
**Constraints:**
* `1 <= nums.length <= 50`
* `-106 <= nums[i] <= 106`
* All the elements of `nums` are **unique**.
* At most `104` calls **in total** will be made to `reset` and `shuffle`.
|
The solution expects that we always use the original array to shuffle() else some of the test cases fail. (Credits; @snehasingh31)
|
Array,Math,Randomized
|
Medium
| null |
963 |
hi guys welcome to go to pro today we're going to be looking at another lead chord problem seems to be a pattern um called minimum area rectangle 2. we're given a x y plane with a bunch of points we need to figure out whether some of these points form a rectangle if they do we need to figure out which one of these rectangles have their minimum area and return the area not all points are necessarily hard to form a right time ago that is parallel to the x5 plane so let's take a look at the examples and figure out what are the edge cases that we need to resolve for so in this scale in this case example one does not form a rectangle that is parallel to the x y plane example two we may not use all the points to find the smallest rectangle example three even though you can see that it forms a parallelogram it does not form a rectangle so it cannot be used therefore we return zero instead of the area of the triangle and example four we've finally find a case where there is actually a rectangle that's formed between uh zeroed x-axis to through the third x-axis which x-axis to through the third x-axis which x-axis to through the third x-axis which from the area of three and another rectangle that's formed by area of two so we return two let's see how we're going to solve this problem my initial thoughts are we should use the slope to figure out whether a rectangle exists and if rectangles exist we just need to figure out the area which is simple vector calculation to find the distance between two points and one once we find that for parallel and perpendicular vectors we could just multiply that to get the area another property of a rectangle is that each rectangle has two four sides two of which have to be parallel to each other and the other two have to be perpendicular so minus my thoughts are we should store we should find the slope we just store the slope and we should also find the slopes of points and store the slope in this case vectors because you two points create a vector which is the slope right point by itself does not have a slope so let's go through how we actually do it um for we just go through all index in the points and we go through all the other index in the point and we find the slope and let's go through how we find the slope in this case we find the x diff the y diff between the two points and it's a simple calculation of finding uh y def divided by x dev to find the slope in this case i'm using decimal because it's more accurate than using float and we return decimal and also if the x are equal where in this case you could take a look at um for example the last example we have multiple points in the same line we could run to a case where we divide by zero which is not ideal so we return a slope of infinity since these points uh this slope is hashable decimal type is a hashable we can actually store these decimal type directly to dictionaries before we store the vector into dictionary what we need to do is normalize it so we could always curate afterwards so how i'm doing that is if one point if p1 the first point in the vector is always the smallest x value and in a case where both x values are equal we check if the first point is also uh has the smallest y value and we store this vector into a dictionary and we also store we also point the vector itself to the slope that we obtained um in this case min size we need to declare a cache for finding the smallest size of a rectangle and we go to the points that we stored earlier in the cache and we get a slope and the point or in this case vectors um resulting in those slopes if the points are indicated vectors let's just change it uh vectors and i think that's it yep that's it cool um if length of these vectors is less than two which means there's only one vector with it with um exact slope we cannot form a rectangle because each side there are two sides in a rectan angle that are parallel to each other and there are two sides in our rectangle that are perpendicular so we can immediately skip this case uh for the perpendicular slope we need to find out whether they are the inverse slope right because that's how 90 degrees formed in xy plane and once you find the inverse slope we could go through the all the vectors that are formed by it p1 and p2 p3 and p4 in this array and once you find that if these the p1 and p3 form a perpendicular vector we could p1 and p2 p3 form a permanent vector and p2 and p4 also form a perpendicular vector we could say that they are rectangle and we also have to notice that these p1 p2 p3 and p4 has to be unique points in the xy plane because otherwise you can't form a rectangle with only three coordinates or two coordinates or one coordinate for that matter so we could skip that case we also have to normalize the vector so we use the dictionary decoder array just like how we did before if the x value is created on p1 we exchange if they're equal and we check the y value so on and so forth if the m or in this case slope happens to be infinite which means it goes directly from through the x-axis through the x-axis through the x-axis what we need to do is we actually just need to check whether why whether the y-axis on both whether why whether the y-axis on both whether why whether the y-axis on both all four points match um whether the y-axis on one p1 y-axis on one p1 y-axis on one p1 exists in either p3 or p4 in the other vector and whether the y axis in p2 also exists within p3 and p4 if it doesn't we could just go skip to the next uh vector and we also do the same check for whether they cross whether we're looking at um a rectangle where the when the vector itself crosses the y-axis the y-axis the y-axis at least a slope does and if it doesn't then we could skip this case and for all the other vectors we need to check whether the points the vectors that are formed by the opposing vectors p1 and p3 the slope that's formed by opposing vectors p1 and p3 we need to check whether that resolves to uh inverse slope in this case because we're dividing decimal by decimal it would not be accurate to check whether they're exactly equal so you can't just check um s1 which is case the slope 1 is exactly equal to inverse slope so in this case what i'm doing is i'm checking i'm dividing s1 by inverse slope and minusing by one which is which gives exactly uh in a perfect world it will give zero if this mathematical function returns anything that's greater than 10 to the negative six we could just continue on to the next loop and we do the same thing with other two points p2 and p4 and if they all happen to be true and gets through to this function where we get the size of the rectangle itself and then once we get the size of the rectangle we just check if it's less than minimum size and we set it and let's go take a look at how we get the size of the rectangle with four points uh we don't actually need the four points we just need to check whether uh three points right we need the parallel and perpendicular part in this case i'm using we don't know which one is a perpendicular which causes a perpendicular vector exactly because there are four points and one of them can be hypotenuse so but what we know is the one that forms rectangular will be the minimum distance because it's a 90 degree right and that is directly due to pythagoras theorem so we find the distance between p2 and p1 and we also find that's the parallel um in this case that's the parallel distance and we find the perpendicular between this vector p2 p1 and p2 with p3 and p4 and that's the perpendicular distance but one of these will be more minimum whereas the other one will be larger because it's hypotenuse and we just need to find the minimum one and then multiply them to each other which will result in the area of the rectangle once we know the area of the rectangle as i said before we just have to set min size to it and once we know that um if the mean size is happens to be infinite we could just return zero as the example three shows and if we actually have a min size we could return that sizes let's run through the example test case and looks like it worked as expected two one zero two that's what we expect from here let's run it and it worked as expected well thanks for watching guys um please leave a like and subscribe if you like the content and if you want to see more videos where i solve leakage problems please check out my youtube channel quarter pro thanks for watching have a good one
|
Minimum Area Rectangle II
|
three-equal-parts
|
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of any rectangle formed from these points, with sides **not necessarily parallel** to the X and Y axes_. If there is not any such rectangle, return `0`.
Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** points = \[\[1,2\],\[2,1\],\[1,0\],\[0,1\]\]
**Output:** 2.00000
**Explanation:** The minimum area rectangle occurs at \[1,2\],\[2,1\],\[1,0\],\[0,1\], with an area of 2.
**Example 2:**
**Input:** points = \[\[0,1\],\[2,1\],\[1,1\],\[1,0\],\[2,0\]\]
**Output:** 1.00000
**Explanation:** The minimum area rectangle occurs at \[1,0\],\[1,1\],\[2,1\],\[2,0\], with an area of 1.
**Example 3:**
**Input:** points = \[\[0,3\],\[1,2\],\[3,1\],\[1,3\],\[2,1\]\]
**Output:** 0
**Explanation:** There is no possible rectangle to form from these points.
**Constraints:**
* `1 <= points.length <= 50`
* `points[i].length == 2`
* `0 <= xi, yi <= 4 * 104`
* All the given points are **unique**.
| null |
Array,Math
|
Hard
| null |
1,463 |
hello friends so today we can discuss very important problem from lead code problem name cherry pick up two it is a problem which is of a hard version from lead code and this is based on dynamic programming i'm telling you in upfront but let's first understand the problem statement and try to devise a method to solve this problem out so stay with me now you're given that there is a matrix in which rows and columns are given to you as you can see this is a grid okay and now there are two robots okay one robot is on the top left and the other is on top right as you can see okay now every block in this matrix has some cherries okay the cherries can be marked as the number so which means that the first block has three cherries the second as one two five and so on now both of these robots have to move along this matrix in a downward fashion what i mean by this is every robot can either move to the bottom cell bottom left cell or bottom right cell okay as you can see both of the robots this robot can also do the same bottom cell bottom left and bottom right cell if this cell is outer bound then obviously you cannot move to that cell but both of the robots can move according to the given rules and now if and now on whichever cell the robot will land they will collect the number of cherries on that block so as you can see if this is on three and one they both have taken three and one cherries respectively if this robot go to this block and this go to this block then they will like also add up the total cherry bar two and one which is three so both of these robots will collectively catch the cherries okay and now if they both land on the same block then obviously like there is no two cherries so like if they both land on the five cherry block then either of them can only take the cherry okay both of them cannot take the cherry so the total increment in the total sum of cherries will only increment by five if they both land on some different blocks then the total increment will be by the increment of the like the submission of both of these blocks but if the land on the same block like while moving down this matrix then the cherry it will be only added once because the block has only this amount of cherry so now both of this robot will optimally move from the top row to the last row and collective like collect all the cherries along the way such that you have to maximize the number of cherries collected by both of them the total summation of the cherry selected by both of these robots should be maximized so you have to output the answer as you can see as the grid bigger so this robot can move along to this path and this robot can move along to like this part so in each step they have to go to the next or the bottom row and in the bottom row they can move from the current cell to the top like the bottom left bottom right or bottom okay so you have to tell that now in like how can you tell that this is a dp problem first like this is a standard like almost all the dp problems of traversals will be using like dfs or some db techniques okay so now also as you can see the grid's length is very small it's up to 70 only okay so now you can understand that you have a lot of states in this if you can easily define a state in a matrix or in a dp table or in a problem then you can easily understand what will be the next optimal state so a dp problem states that you have to consider all the possible states and pick out the state which you actually want for the current answer so as you can see if this is a standard problem in which you start from the top like if there is only one robot and this is a good and if you start from the top cell then it is a very standard problem in which like you have to go from the top left to the bottom right and you have to just collect out as much as like as possible number of some along the way it's a very standard problem but now there are two robots along this way so now how you can solve this problem out you have to just do the same thing but you have to first determine what is a current state in a problem defines by what are the parameters which actually defined out a current state in a problem so how can what are the number of variables through which you can define at the current state so as you can see in the current state they both are on the current low like the row is always same for both of the robots it cannot happen that this robot can go one step down and this robot will remain to the same point no so both have to go one step down along the path so but the row number is one variable and the column of both of these robots so there are three variables one is the row number and the column of both the robots so these are the three states like the three variables which can define the current state okay now for each state you have like if the both robots land on the same block then you obviously my total answer will only increase by the total block value by one solely but if they land on different blocks then the total value increment by the summation of both of these blocks value and now for every block you have three states to go from this you have this state or the state and like as you can see for this state you have this state distance district so if you know that if my robot is on this state now what is my optimal weight so now you have to calculate for this and this so if my robot is on this way what is multiple this and this if my robot is on this what is optimal this and this these all are on like outer bounds so the current state value optimal state value is 6 for this like because this is the 6 like this is the maximum so if my robot is on this point that it is always optimal to go to this point that's why it is collecting more points so from obviously a current state you can obviously go to some state which is more optimal to you so you have to find out the maximum next state so you have three options you have you can go to this option you can go to this and among all of this so for every robot you have three options so as you can see for every robot you can go this and forever like this robot is this and this so three into three which is nine so there are nine possibilities because it means that the first robot can go to the bottom left and the next robot can go to bottom left of bottom left and like bottom right so for every state of moving of first robot you have three options for the next so there are three to three which is nine states so now for every nine states you have to calculate out whether you have pre-computed answer if you have not pre-computed answer if you have not pre-computed answer if you have not pre-computed the answer pre-computed the answer pre-computed the answer calculate the optimal path from the current state so for like for if you want to go to this point you have to find out the answer for this state and this state so there are three variables and like because the dp table consists of like three dimensions i cannot actually draw it out but i hope you understand the logic part now i will make it more clear with the like actually the code part now so this is the starter function this is the main function so i have made a like as you can see the grid values are between 70 okay so now i have made as you can see a dp table of 808080 because like you can make of 7272 you just have to make a dp table of three variables because i have to store out the row number the column the current like column one and column two so this db table is actually storing that value to store out what is my current state value to which is actually storing out that if my one robot is on c one column my other robot is on two column and both of them are at the r through what is the maximum like what is the maximum total summation i can get that block is storing that answer and that is dot so i have to first mem set everything to minus 1 because we don't know any answer initially and then i find out the like the grid values like the dimensions here and then i actually call out this okay function which actually start my like uh this actually sent out this grid value okay and then there are two dimensions actually this is the row so row is always common for both so that we just only required one row but there are two columns c1 and c2 so c1 is for the ca robot which is starting at zeroth index and the other robot is starting as the index is if this is like the length of this is m so the total length of this is m and this is n okay so this is n and this is m so as you can see the index is from zero one two so m minus one so this is the like index for the first robot and the last robot okay and then this is okay function in which we first find out the dimension of this grid you can also send them out in the starter function also okay function and now we have to first check out that what is the exit condition if my r if because in that always in the next time i go to the next row if somehow my row become equal to n because my last index of the row is n minus 1 if my row again go to one more step down it becomes like row becomes n so if my row becomes n i have gone out of bound and now i have to return on zero else this is the memoration value if i've actually already seen this sorry if i've already seen this state which is the state is c1 c2 and r if this dp table of this state is already seen which means that this value is not equal to minus 1 then we return out this state well else you have to find out the state value so for every state out i have to find out that uh there are two things we have to find out that for every block like for every state value i have to find out that if both of these robots let's assume that my current robot is on this point and my other robot is on this point now if this is the current state value because it is defined by row the column one and column two if these are the two robots what is actually the next state the maximum state so if my both of the robots are on this point now we have to find out that what is the next like if both of these robots are on this point if they go like if this somehow go to this point so now what is the next state they can go they can either go to this point like my first robot can go to this point second robot can go to this point my first robot can go to this point second root can go to this one so there are nine possibilities so for all the nine possibilities i have to find out which of them are maximum and among all of the maximum we have to add up these values like these because my robot are on this value now so i have to also add out this value and the next maximum current state value so that's what i'm doing the nine values are i starting from minus one to one because i have three options and also just starting from minus one to one the next current like the down uh to the down uh like the value of the block point is my current column is c1 so the new can be c1 plus i and c2 plus j sorry and now i have to find out that whether the columns i have generated this new column c 1 and c 2 capital c 1 and c 2 they both are valid like they should be inbound that's what i'm checking if they are inbound they have to find out the maximum answer among all of these states that would object like okay function okay and now if this c1 and c2 are same so not like the final answer which is actually this is actually storing out the like the maximum answer for the new states the next state which would mean that if my both of the robots are in this point and if one would go to this point and other would go over go to this point so for the new states my robot petition if i know the answer for those states because like let's say my robot one go to this point and my other route would go to this point this is one state that the state can be if both of these are starting at this point now either one would go to this point and the other robot go to this point or one robot goes to this point other robot go to this point if among all of these states have to find out the maximum and now also among finding out the maximum i have to also added this value and this one because both of these robots are also on this point so i have to also count account or add these like these two values also so these values are divided by c 1 and r so if both of these values if both of these c's are same that obviously my answer will only increment by one of this great value but if both of them are different then my answer will increment by the r c 1 plus r c 2 okay because both of these values are different and now my returning out like while returning out my total answer i have to store out this dp like this state value in this dp table and that's the whole logic for this problem i hope you understand the logic as well as the code part now if you're still in out you can mention on comment box i'll see you next one keep quoting bye
|
Cherry Pickup II
|
the-k-weakest-rows-in-a-matrix
|
You are given a `rows x cols` matrix `grid` representing a field of cherries where `grid[i][j]` represents the number of cherries that you can collect from the `(i, j)` cell.
You have two robots that can collect cherries for you:
* **Robot #1** is located at the **top-left corner** `(0, 0)`, and
* **Robot #2** is located at the **top-right corner** `(0, cols - 1)`.
Return _the maximum number of cherries collection using both robots by following the rules below_:
* From a cell `(i, j)`, robots can move to cell `(i + 1, j - 1)`, `(i + 1, j)`, or `(i + 1, j + 1)`.
* When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty cell.
* When both robots stay in the same cell, only one takes the cherries.
* Both robots cannot move outside of the grid at any moment.
* Both robots should reach the bottom row in `grid`.
**Example 1:**
**Input:** grid = \[\[3,1,1\],\[2,5,1\],\[1,5,5\],\[2,1,1\]\]
**Output:** 24
**Explanation:** Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.
Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.
Total of cherries: 12 + 12 = 24.
**Example 2:**
**Input:** grid = \[\[1,0,0,0,0,0,1\],\[2,0,0,0,0,3,0\],\[2,0,9,0,0,0,0\],\[0,3,0,5,4,0,0\],\[1,0,2,3,0,0,6\]\]
**Output:** 28
**Explanation:** Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.
Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.
Total of cherries: 17 + 11 = 28.
**Constraints:**
* `rows == grid.length`
* `cols == grid[i].length`
* `2 <= rows, cols <= 70`
* `0 <= grid[i][j] <= 100`
|
Sort the matrix row indexes by the number of soldiers and then row indexes.
|
Array,Binary Search,Sorting,Heap (Priority Queue),Matrix
|
Easy
| null |
1,361 |
Hello everyone welcome to my channel code sari with mike so today we are going to do video number 30 of our binary tree playlist lead code number 1361 is a medium level question but it is quite easy this question is a simple observation and we will make it approachable. That is, you have n notes of the binary tree which have been numbered from zero to n my right and you have also been given two notes in the name of left child and right child, this is right where left child i is what i is. What is the left child of V and what is the right child? What is the right child of I? Return true if and only if all the given notes are given to you. By using all the notes on the left side and on the right side, you can create a valid bin tree. At least one is valid. Binary tree ok node aa has no left child then left child will be my and similarly for the right child if there is no right child then right child aa will be -1 ok now let's right child aa will be -1 ok now let's right child aa will be -1 ok now let's see this example here like node here If I have given four nodes then I will have four nodes 0 1 2 3 and for each node I have given what is the left child and what is the right child then I do the indexing 0 1 2 3 Okay so let's look at the first one, its zero. Its parent is its child, left child is one, I will make it, see what is the right child, so it is two, okay here we come, one is the left child of one, there is nothing, right child of one is also nothing, okay here we come two. The left child of is three, it's okay. The left child of two is three, it's not the right child of two. Here, the left child of three is neither the left child nor the right child. Okay, so pay attention. This tree I have made is a valid binary tree, is n't it? I don't see any issue in this. Yes, our answer is true. Okay, and let's see another example. There are two notes here, total is zero and one. Let's look at the first one. Zero is its left child. One is given here and its right child is something. No, here we come here, the left child of one is zero, if it is zero then it is already made, so let's assume that the left side of one has become zero and the right side of one is not there, it is zero, so pay attention here. Cycle is formed, mine is fine, that's why its output is false. Okay, this is not a valid binary tree, so the cycle is obvious. In our binary tree, there is never a cycle in the binary tree and there is never such an edge. It will always have a root. There will be a left side and a right child. Let's assume this is the case, then its left side will be the right side. Such an edge never goes, isn't it? A cycle vehicle is never formed in a binary tree. Okay, so let's see what is the first approach that we have, we are already Do you know what a binary tree is? Okay, so we already know the properties of a binary tree, so if our given input is not able to satisfy these properties of a binary tree, then I will say that it will not be able to become a binary tree, then what about the binary tree? -What is not be able to become a binary tree, then what about the binary tree? -What is not be able to become a binary tree, then what about the binary tree? -What is property? The most basic property is that every child can have only one parent. Every child has only one parent. Look here, this is a child. Let's assume that it has only one parent. Look at this child. It has only one parent. So far it is clear. Okay, and let's see the second point. There should be only one root. And it should not have any parents. A valid binary dream should have only one root. Maybe look, this is that and it has no parent, look, there is no edge coming from above, there is no incoming edge on this, okay, so this is its root and look, any root is only one, any such node you It is visible on which the incoming edge is zero. This is the only one, it means roots should be only one, there cannot be more than one root, only one root and it has no parents. Okay, the third thing is that it should be connected. Only one component of connected. What does it mean that if we assume that a binary tree is given and another binary tree is given separately, then it will not be called a binary tree. Is it overall? In the question, only one valid tree should be given. Okay, so this is disconnected. Right, two have become two, this is not called a binary tree, okay, if there is such input, then I will say that it is not a binary tree, okay, it is quite easy to check all three, you will check the first one, how to see this, every child has only one. One parent, how simple is it, make a map of child to parent, okay, every child should have only one parent, if a child has a parent already assigned and in the future another parent comes who is assigned to the same child. If it has to happen, then I will understand that it is wrong. Right, every child should have only one parent, so I will take a map of child to parent so that I can keep track. Okay, it is clear till now, so first let's see this child. Let's create a two parent map like here let's see what I did is create a map child to parent 0 2 3 So let's see here 0 2 3 look pay attention here this is the parent root is its left child one and If the right child is T, then look at the parent of one, if it is zero, then I write, the parent of one is zero, the parent of O is also the parent of Y, the parent of zero is also zero. Okay, look here, if it is minus, then leave it. If it is minus, then leave it. The parent of two is two. The parent of two is minus. Leave it. If there is minus y then leave it. Not assigned means this zero will not be in this map, it means do you know what happened that zero is the root, okay then look, two things came to light from the child to parent map, one is that every child should have only one parent. Second, in that node which is not present in the child-to-parent, you are in that node which is not present in the child-to-parent, you are in that node which is not present in the child-to-parent, you are seeing that zero was never there because nothing was assigned to it, that means it must have been the root, so I can find the root as well, and there is only one such node. Which should not be present here, okay, that's it, we have also found the route from the child to parent map, so both these checks are there, both these checks will work from the same map, my child to parent is okay, now let's come to this third one. On the one, it should be connected, there should be only one component, see what does connected mean, there should not be two components, right, there should not be anything like this separately, okay, so pay attention to one thing, we have got the root here, right, we have already got the root address. Now, if route E is 0 then it may be this route. Now I will do any traversal on this route. Either I will do DFS or I will do BFS. Normal BFS. We will copy and paste the code of DFS. Okay, so if I do traversal. So what should be known, I will do traversal, then I will also keep count of nodes, how many nodes could I traverse, assuming the root is here, then I am counting one node, two nodes, three nodes, after this, nothing else was found. I have finished visiting all the nodes in this component so I could only traverse three nodes but look at how many nodes are given so one doti f pa is ok f is not equal to f so this will not be my valid binary tree in this case Let's look at a valid example. If I make this tree, the left child of zero is one, the right child of two is th, so if I look at this map, zero is not present in this map. Meaning, there must have been zero route, so I got the route also, now I will hit BFS or DFS from the route, okay, so when I hit DFS on this route, then look, zero has been visited, count one has also been visited, its left child has been visited. The right child has been visited, its left side has been visited, all the notes have been visited, how many notes have been visited in total, one, two, four notes have been visited and our input was also only four. Okay, what does it mean that there is only one component, sure. Right, only then all the notes have been visited. Okay, if we do BFS or DFS from the root, then we can simply check these three properties. Okay, it is clear till now, so now see how we will convert the above story into code. I told you that we will make a map of child to parent, okay, so what will actually happen is that there will be a map of int to int, right, of child to parent, so we will make one, after that we have given the left child and right child. We will iterate over it and find out it e 0 a e lesson a i ps plus Okay, so which is the node, which means which is the root, here i is the parent i, let's take out its left child c e to the left child vector. Right child of I is found, left child of I is found, similarly, its right C is taken out i.e. right child i.e. right child i.e. right child vector is also given in the input, right child is taken out from A, OK, so how will you populate this map, child to. Parent means first child then parent, no but yes, see that there should not be left C MIVE, it will be human then we will ignore it, not equal to, if MIVE is ok then what will we do, child means which child to parent map is my child to. The parent map is the left child, who is its parent? I turned out to be I. Similarly, if right C is not equal to minus two, then similarly we will do the same for child to parent, right C is I. But pay attention to one important thing here, if in the map with already child to parent, left C is It would have been already present, which also means that its parent must have been someone else. First, there would be two parents, so here I will also check if the left child is already in the map. If it is already present, then I will return from here. Similarly, here too, if the right child is already present, then I will return false, from there it is already present, which means its parent must have been someone else earlier and then again another new parent has come, okay, if this thing happens, then this is It is very easy, after what I told you that I will get a route from the same map, so that one person who is not present in that map will be on the route, so let's see who is that person who is not present in this map. Simply do the same aa = 0 aa le n aa ps ok, do the same aa = 0 aa le n aa ps ok, do the same aa = 0 aa le n aa ps ok, now in the starting I will move the root, now I don't know who is the root, here if my map is there then there was the map of parent to child, sorry child to. The map of parent was not child to parent, if this eighth node is not present in it is equal to and means it is not present in that map, okay then I will consider it as root etc. But before this, one more thing that if already root There must be a root is not equal to -1, okay root There must be a root is not equal to -1, okay root There must be a root is not equal to -1, okay then I will return false, what does it mean that there is an already root, look at the root, first I put -1, if already here, root, first I put -1, if already here, root, first I put -1, if already here, I must have exited the root, from here the root must have been assigned. After that again an element came which was not present in the map, so it is obvious that I am getting two routes. If I get two routes, then I will return false. At that time, we also knew this. I have decided who will be the route, okay, the route will be found from here and if any route is found once more, then return false because there cannot be multiple routes in the battery. Okay, so it is clear, now let's accept this. The for loop is finished and if route-1 is only -1 which means I did and if route-1 is only -1 which means I did and if route-1 is only -1 which means I did not find any route then what will I do at that time return false because there must be a route right here I had assigned route-1 right here I had assigned route-1 right here I had assigned route-1 this is the whole for loop I did not find any element which was not present in the map. If all the elements were present in the map, then no root would have been formed. Right, the root would have remained myve, whereas there should be a root in the bin tree. Okay, so this would be my false. If we look at the return false, then we had these two steps. I had told above that what was the first property, that every child should have only one parent, it became clear that there should be only one root, this also became clear. I have found a route, now what I said is that only one component should be connected, otherwise how will only one component be connected? I told you that I will traverse and see that my tree is fine and if I traverse more, all the notes will be visible. Okay, so count the notes, how many notes have been visited, now look at the third point, if it is not traversal, remember it. What is the best way to traverse, make an adjacency list, then write the same as you used to write in your normal BFS. Okay, so remember adjacency, how did you make the unordered map? What does this int mean? This is the first node, this is what it is, which are its children, is n't it? Vector of int. Okay, call it ADJ or call it anything. Is it okay? Where is the connection from this? Okay, so I will pop this one in the starting when this one was populating, you see where is it coming from, where is it going from? There is an arrow going on the left child. Now the arrow is going to the right child, meaning this is what has happened, isn't it? So this arrow has gone to the left child and has gone to the right child, so see, I has two children, one left and one right, so what? There is only the adjacency list, so what will I do, I will assign it here, which is my adjacency list, ADJ off aa dot push underscore back, who is it brother, left child is okay and here ADJoff aa dr. Push and back right cell is fine so we can do traversal easily but yes pay attention that left cell and right cell should not be left right then put those statements inside it okay so here is basically what I did my adjacency list Okay, so if you pay attention to this example, which was our first example, what was there in it that zero was here, one was here, two was here, three was here, then how will its AdSense be made, which are the children of zero? There is one and there is two, there is no child of one, there is no child of two, there is only three, there is nothing else, there is no child of three, then three is empty, okay, it is cleared till now, so after this let me do normal BFS. Do you know who is Root G I must have taken it out from where in this furl from here I must have taken it out. Okay, so what did I do? Let's assume BFS is only written. BS can write anything. I wrote BFS. Diya is ok, put the first zero in BFS, made my count one, ok and put my visit that zero has been visited, popped the zero, which are the children of zero, one and two are children and one and two. Is it still wasted? Otherwise, put one and two, okay how many have been counted, two, three notes, I have become mine, okay, one and two, marked a visit here, popped one, okay, does one have any children? Does one have any children? There is no child, two is popped, two is a child, yes there is one child, three, so three was not wasted, pushed and counted four, total four nodes, we have seen till now, okay then if three is popped last, then thi was There is no child, BFS is over, what is our count, four is four, look is equal to n, so we covered all the notes, which means there must have been only one component, because when I started BFS from root, I was able to visit all the notes. I was able to visit this also, this one has only one component, here it is, okay, so we have done all three checks and our binary tree is valid, okay, so let's code it quickly and this is the first video in which I have told what. Solved it with the property of Binary Tree, it is fine. Just after this, another video will come in which we will solve it with DSU, it is fine with Disjoint Set Union, then it will come in the graph playlist, its video will come today itself, that is why I have made a separate video. So that it is not missed that there should not be a play question of graph in the bin tree, then I will tell the approach of DSU in the graph playlist. Today, first let's code it and finish the first approach. Okay, let's code it before some one. So I had said that I will take two maps, the first one will be of child to parent and the second one will be my ADJ or you can call it the graph of parent to child. Okay, so the first map is my ADJ so that I can do the traversal. For and this is my what is the graph map of child to parent okay so I start for int aa e0 aa lesson a aa ps okay which is my node i is which is its left child i okay And who is its right child of i is clear till now, after this if left c is not equal to my, that is, it is a valid value, then the first thing I will do is to put in the adjacency list how far from i. The graph is dot push underscore back left C isn't I to the left C there is an arrow OK after that put it in child to parent right child to parent dot push underscore sorry child to parent Who is the child brother Left C is who is its parent But before that I had told that if find the left child is already present in the child to parent map, it is not equal to child to parent map and what does it mean that it is already the left child or it has been assigned. It already had a parent. Okay, if it was already present in this map, then in this case I will return false. Okay, and if it is not so, then who is its child on the left in the child to parent, it means this is this child, this is this. Its parent is i, okay, similarly, we will do the same for the right child, if the value of right child is right c, its value is not equal to -1, then what will we do first, -1, then what will we do first, -1, then what will we do first, who is its parent aa i, so here I have taken the node. I have taken a node and write it, okay, its parent is this node and it is the right child, right? But if this right chall was already present in my map, then it would have returned false. If it is not present, then okay, what is the parent of this right child? Who is that node, isn't it, is it the eighth node, okay, so it is clear to me, this for loop is okay, from here I found out that every child should have a single parent, okay, after this, let's find out the root, who is the root? I have kept root-1 in my starting for kept root-1 in my starting for kept root-1 in my starting for int aa = 0 aa i < n i p ok look pay int aa = 0 aa i < n i p ok look pay int aa = 0 aa i < n i p ok look pay attention to what I said that if I found this eighth node in child to parent, if I did not find that then I found child. Two painted and ok means it definitely belongs to someone and it has no parent. Right, it can be the root, but if the root is already assigned, then the root is not equal to two. If it is minus, then it means I got another root, so we will return false. And if it is not so, then root = i, then root = i, then root = i, right, we have found the root, okay, but this for loop ended and I did not find the root i remains only -1, so it is obvious that this is a valid remains only -1, so it is obvious that this is a valid remains only -1, so it is obvious that this is a valid byte. It will not happen, I have done return false, it is okay here and in this case, I made a mistake, I came to know from the test case that I had missed it, so only after making the mistake, I found that there can be such a test case in which you can get the root. Not found, ok, so now we have to write normal BFS yadi a and count that if we are able to visit all the notes then keep this count equal to 0, now it is ok and we already know who is the root. We only do BFS, why did we take it in BFS and remember, we used to take bullion visited also, I have bullion viztel A notes and in the beginning all are unvisited, so I marked all of them as false, okay now in the queue we used to push the route first. D push routed count becomes my one that I have checked in node one and given visit is clear till now let's write simple BFS code while not off q dot mt until q becomes empty int node e q Popped the front q, that is ok, after this, which are the adjacent nodes of this node, right for int and v, ok, ATJ of node is clear till now, so if the visitor is not wasted, then mark it as Vid, it is not a child and is No, it's okay, I marked it true and also increase the count. I have seen that we push it to another node. It's okay and in the last, what has to be checked is the return count. It should be equal to A. KK Let's see but one more thing, remember that whenever you do traversal in a binary tree, it will never happen that you come back to the second node, that is why I am saying here that if you also put this check here. Not if you find a node which you can visit because in a binary tree you can never visit a wasted node again because even if you look at its tree diagram, it always goes downwards and sometimes comes back up. Well, you can do it from there also, but I have counted the entire node, which should be equal to two. Let's check if we are able to pass all the test cases and count one more thing. It is going to be that we have only one component, after traversing that one component is completely traversed, okay, so I hope it was helpful, this is a very simple code for you, okay and only one is the number of notes, not all the notes. If you are visiting only once then a one of a kind time complex video will come in which the approach to DSU will be explained, it will come today itself, okay then see you sing in the next video thank you.
|
Validate Binary Tree Nodes
|
tiling-a-rectangle-with-the-fewest-squares
|
You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree.
If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child.
Note that the nodes have no values and that we only use the node numbers in this problem.
**Example 1:**
**Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,-1,-1,-1\]
**Output:** true
**Example 2:**
**Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,3,-1,-1\]
**Output:** false
**Example 3:**
**Input:** n = 2, leftChild = \[1,0\], rightChild = \[-1,-1\]
**Output:** false
**Constraints:**
* `n == leftChild.length == rightChild.length`
* `1 <= n <= 104`
* `-1 <= leftChild[i], rightChild[i] <= n - 1`
|
Can you use backtracking to solve this problem ?. Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?. The maximum number of squares to be placed will be ≤ max(n,m).
|
Dynamic Programming,Backtracking
|
Hard
| null |
1,942 |
hey everybody thank you so today i'm going to talk about a question it's from the pipe working contest as that saturday question two so it's question 1942 number of the smallest architecture let's look at the description first there's a party where inference number from zero to n minus one are attending there's an infinite number of chairs in this party there are from zero to infinity when a friend arrives at a party when friend arrives at party they sit unknocked out on the unoccupied chair with the smallest number for example its chair is zero one five occupied when a friend comes they will sit on chair number two okay when a friend leaves the party their chair becomes occupied at the moment they leave if another friend arrive at the same moment they can sit in that chair you're given a zero index to the array times the name of the to the rates times right where times you know consists arrival and leaving two elements inside the array indicating the rifle and leaving time of the i friend respectively an integer target friend okay target friends the friend we want to find uh arrival time at this oh a rifle time are distinct okay why would it return the chair number that a friend number tiger film would sit on look at the example first so we got zero one two three friend zero and the first friend arrived one leaf at four second wrap a two three five three third rubber four leaf six and yeah where will frame one sit when he comes you see at present one because you know in order we can figure it out you know friend zero arrives at time fc on zero frame one arrive at time two and see on one you know just how we get out so what's our mindset so basically we need some ways to keep track of okay what's what sure is empty and you know we have a we can create a priority queue you know it's basically store the empty chairs and the total number the limit you know it says is 10 to the fourth you know so this is basically how many people this constraint is so we can basically create 10 to the fourth chair 204 chairs for that and the other one which i have another priority queue you know wreck it down okay when the chair is occupied when is their leave time and the i then the id they have you know the id means the person who is sitting there okay so let's later on see so first we add this much six you know because the constraint is 10 to the fourth so we add this much c the ids to the empty chairs okay cheers and then so we and then we don't want to lose the position after you know sorting because we need to sort because afterwards we need to figure out fun okay who is arriving first so we can figure out okay which c is occupied which c is not occupied but by sorting the given times array we will lose the id which is who will be sitting at which this is whose time this is who's arriving time and departure time so we'll lose that but we can add another you know basic store not a create another 2d array and then store at position three the consistent of the id you know okay so seeing that in this way the id is stored in the id is still in is being keep track of okay so right now here we use a lambda expression to basically store the 2d array you know see which one goes first which one goes less here we look to the how many people you know we have and then we have the arrive time we have the leaving time we have the id and before we so this is a person's i each person's added like the information we need to check so my mindset is if we check that before we're giving out the seats right we want to check if the if there's a seat that is being occupied you know like it's being occupied by the previous person and if that person lives away they or not and if that is a variable so we need to check that condition that's why we have here so all right say that's why we say arrive time if a right time is e greater than or equal to the lift time this is a array we you know we created to store you know to store the return time of the last person you know and the id of that person so if the arrive is greater than the leaf time it means like okay we should not take this one we should take the if arrive is greater than equal to of the seat bye-bye so if arrive is greater than bye-bye so if arrive is greater than bye-bye so if arrive is greater than equal to the leaf time of the last person means like okay this c is a variable so we add it to the chairs you know it's a variable then so we check if this id if the current person we checking if is equal to the target you know if it is we just give him the feature and later on with the update okay things we took you know we took someone took the chair we need to put it back into a variable you know and we cut down their new living time new chair id and then yeah so basically let's say you know let's see if we can submit the code yep and that's what we do okay so let's look at the time complexity time capacity so basically let's see we round to n basically it's n o n while it's empty and this here is o n space capacity leaves us all in because we create two parity cubes so it's one two so all right guys so that's it thank you for today and this is the q2 for the buy with the contest you know whoever passed this participate last week thank you
|
The Number of the Smallest Unoccupied Chair
|
primary-department-for-each-employee
|
There is a party where `n` friends numbered from `0` to `n - 1` are attending. There is an **infinite** number of chairs in this party that are numbered from `0` to `infinity`. When a friend arrives at the party, they sit on the unoccupied chair with the **smallest number**.
* For example, if chairs `0`, `1`, and `5` are occupied when a friend comes, they will sit on chair number `2`.
When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair.
You are given a **0-indexed** 2D integer array `times` where `times[i] = [arrivali, leavingi]`, indicating the arrival and leaving times of the `ith` friend respectively, and an integer `targetFriend`. All arrival times are **distinct**.
Return _the **chair number** that the friend numbered_ `targetFriend` _will sit on_.
**Example 1:**
**Input:** times = \[\[1,4\],\[2,3\],\[4,6\]\], targetFriend = 1
**Output:** 1
**Explanation:**
- Friend 0 arrives at time 1 and sits on chair 0.
- Friend 1 arrives at time 2 and sits on chair 1.
- Friend 1 leaves at time 3 and chair 1 becomes empty.
- Friend 0 leaves at time 4 and chair 0 becomes empty.
- Friend 2 arrives at time 4 and sits on chair 0.
Since friend 1 sat on chair 1, we return 1.
**Example 2:**
**Input:** times = \[\[3,10\],\[1,5\],\[2,6\]\], targetFriend = 0
**Output:** 2
**Explanation:**
- Friend 1 arrives at time 1 and sits on chair 0.
- Friend 2 arrives at time 2 and sits on chair 1.
- Friend 0 arrives at time 3 and sits on chair 2.
- Friend 1 leaves at time 5 and chair 0 becomes empty.
- Friend 2 leaves at time 6 and chair 1 becomes empty.
- Friend 0 leaves at time 10 and chair 2 becomes empty.
Since friend 0 sat on chair 2, we return 2.
**Constraints:**
* `n == times.length`
* `2 <= n <= 104`
* `times[i].length == 2`
* `1 <= arrivali < leavingi <= 105`
* `0 <= targetFriend <= n - 1`
* Each `arrivali` time is **distinct**.
| null |
Database
|
Easy
| null |
315 |
uh today we're gonna be working on lead quote question number 315 count of smaller numbers after ourselves and given an integer area numbers return an integer array counts where counts of i is the number of smaller elements to the right of numbers of i so if we have been given five to six one uh the answer is going to be two because there are two more smaller numbers to the right of five and then one because there is one more smaller number to the right of two one because there is one more smaller number to the right of 6 and 1 and then 0 because there is no more smaller number to the right of 1 and similarly if there is only one element it's going to be 0 if there are exactly the same elements it's going to be both of them do not have um smaller numbers to the right and the way we're going to be the algorithm is going to be like we're going to be using the merge sort uh for this one before implementing the mysore so in the microsoft we're actually going to be looking at the uh the total number of elements smaller then smaller to the right so for this one we need to keep the value and the in divisional index because we don't want to lose that when comparing total number of elements to the right so we're gonna use a class uh let's call this class as a value with the original index it's gonna keep the value and it's gonna keep the index okay and we can make a constructor saying that this area value with original index is gonna take two things which is the value and the original index and then the value is gonna become equal to value and the start rational index is gonna become equal to original index oops okay what we're gonna be doing in the merge sort is like basically we're gonna have a sanity check where uh if the nums is equal to null or on the num start length has become equal to zero we're just gonna be returning our new like an empty link list and the type is gonna be integer okay now we're gonna keep record of the total number basically the length of the nums and uh also our result is gonna be equal to new and up to the size of like it's the size of the result is gonna be the end okay now we're gonna fill up this uh this like the class objects array value with original index so for that first of all we wanna set it up so array value with original index let's call it new nums so there is new array value with original index of size n in order to populate it we're gonna be iterating i is equal to zero is less than equal to less than n i plus for that every single time our new nums of i is gonna be equal to this new array value with original index and that is going to be the numbers of i and its index the value and the index just as the name says okay now we're gonna be using a helper function called merge sort and count so we are sorting the array just like using a merge sort and then at the same time we are counting how many elements are there to the right we're gonna be sending this new uh nums which has basically the information of the value and the original index we're gonna be starting at uh we're gonna be sending the starting index and ending index which is n minus one and then the result which is gonna be filled up okay again the result is an array but what we need to send back is a list of integers so the last thing we want to do is to convert it back to result integer is equal to new link list of integer and then we're gonna fill it up again this is because we're in java and that's how we can convert okay new numbs or basically sorry the result and the result integer dot add the value of there is the i that's it and then we're going to be returning the result integer okay now back to our main function here which is basically we're trying to merge the arrays and at the same time we're trying to count the smaller elements to the right for this one let's define this function okay it's a private we're not sending anything back because everything is going to be filled up in result merge short and count okay so we're going to be taking the list of this array value with original index as an array and let's call it nums okay and the start and the ending index so and start and end and the last thing is an area which we need where we are gonna be putting the results okay sounds good okay the first thing is that the base case is gonna be there if they start because we are doing the merge sort we're gonna say that if the start becomes bigger or equal to n that means just return okay otherwise calculate them at midpoint which is the start plus and divided by two okay then again merge sort from start to mid and mid to end same thing nums start to med and oops merge sort and count nums mid plus 1 to n okay so once we have that now we have individual elements we need to we would be able to compare them in order to sort them so we're gonna have some variables here left position is gonna be equal to the start and the right position is gonna be equal to mid plus one okay now we're going to have a list of link like a linked list of these this class object array value with original index idx okay uh we're gonna call that as merged new link list okay and the other thing we want to do is because we want to keep it efficient and like uh we don't want to compare every single time when we are sorting in with we don't want to calculate every single time uh how many uh like one element uh to all the elements to the left uh in order to increment the result what we're gonna be doing is like we're gonna be calculating what are the total number of elements uh the right elements which are less than the left elements so we're going to call end num number of elements so number of elements in the right array right value sorry less let's call it less then left array which is gonna be equal to zero at the beginning okay now first we wanna have a while loop where our the left position is less than the middle point and the right position is less than the end so while the left position is less than the mid plus one and the right uh position is basically less than equal to n while we are in that category uh what we're gonna be doing is like we're gonna be comparing uh the values right and if the value of like the nums of left position dot value is greater than the nums of right position dot value if that is the case uh we want to update this thing this flag or this uh element where we were saying what are the total number of uh elements of the right which are less than the left element that is the case first thing we want to do is to update e l e m s right array less than left array okay and then we want to add that uh like just like in a merge salt uh we add uh the smaller element uh the element which is smaller on to the right place right and that's what we do uh in the merge sort whenever we find the smaller element we put it into the uh the merged array right merge dot add now for that you're gonna have a nums of uh where the right position so we are still using the nums so that actually we actually can put them based on their original index and then we're gonna increment the right position okay if there is not the case if the let's say if the left element is not greater than the right element of the separated arrays and in that case all we have to do is to again we're still gonna be putting uh the result into the like the left position into the merged uh like we're gonna be putting the uh the value in we can either you because so the value is not greater right if the value on the left is not greater that means the value on the either the value our values are equal or the value or to the right is created right so we're gonna be putting uh like just like we're gonna be continuing doing the merge sort and putting uh the left position uh element to the merged array and incrementing the left position but one more thing we want to do other than that we want to update the result so because we are keeping a record of that so in this case uh we know that the left element is going to be put in getting pushed to the merged array uh we want to update the result of that so the result nums of the left position dot original index plus equals to what we are saving here okay and now we can just merge dot at this time it's gonna be the left position and then we can increment left okay so now we are done with the if we have equal number of elements to the right and the left we are done over here but that is not always the case so if we are left with uh some elements in the left array right left position is less than mid plus one if that is the case uh again uh we have the we have all we already have a record of this total number of elements uh to the right uh array less than the left element so we're gonna be just using that uh we don't have to iterate the right array one more time we just have to uh we have uh the record of that so we're gonna be adding it to the result okay so the result of nums of left position dot additional index plus equals to number of the same thing okay uh and also we're gonna put it into the modest uh add numbs off left position and then we want to increment the left position similarly what if we are left with some elements in the right array and we are done with the left array right position is still less than equal to n we're gonna do very similar stuff but this time we don't have to add uh these elements to the right because where it's a merge sort and we are already coming from bottom up approach so we are done with that we don't wanna be adding or fixing anything in the uh in this one so all we have to do is to add put the result into the merge dot at nums of right position and then the right position plus okay now uh this is where like uh so now and then we're just gonna be copying uh the merge back to the original array so for that we're gonna be saying that let's start let's our position or the index is equal to the start and for every uh array value with original index let's go let m inside the now merged now all we have to do is the nums of that position is gonna be equal to that m and then we can just do it in one line cannot find the sound but num should be nums cannot find another symbol here okay so this is what original net next is it's always orange index okay looking good and it works
|
Count of Smaller Numbers After Self
|
count-of-smaller-numbers-after-self
|
Given an integer array `nums`, return _an integer array_ `counts` _where_ `counts[i]` _is the number of smaller elements to the right of_ `nums[i]`.
**Example 1:**
**Input:** nums = \[5,2,6,1\]
**Output:** \[2,1,1,0\]
**Explanation:**
To the right of 5 there are **2** smaller elements (2 and 1).
To the right of 2 there is only **1** smaller element (1).
To the right of 6 there is **1** smaller element (1).
To the right of 1 there is **0** smaller element.
**Example 2:**
**Input:** nums = \[-1\]
**Output:** \[0\]
**Example 3:**
**Input:** nums = \[-1,-1\]
**Output:** \[0,0\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
| null |
Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set
|
Hard
|
327,406,493,1482,2280
|
1,909 |
hello let's talk about a remove one element to make a r quickly increasing so yeah pretty straight forward you can only remove one at most one the element to make a r strictly increasing if there are more than one you return false so what does increasing mean you want to make sure list satisfied so less than equal like equal doesn't count like only has to be less than right so let's look about this scenario 1 2 10 57 you can remove 10 to make the array uh shly increasing so this will return true but what happen if I 1 2 10 7 right oh sorry 1 two2 57 making my so one two2 57 at this location your previous value is two right your PR previous value is two then you want to make sure I did it myself right to make the array strictly increasing so I will have to reset my pre to uh to me because uh I'm comparing I'm actually comparing this one oh wait I'm comparing this one and they are the same right they are the same I'm going to say oh I mean I have to know the next value is going to compare with me two right so this will be it all right so um here's another um problem so uh what happen if I 22 57 right 22 are the same and then um basically like you want to know um you want to reset the value to two so you can consider five when five compare with the previous value it has to be two and also if this is happening we know like there's a what going down um condition which is not strictly increasing so we need to have a counter count plus this and if there are two element in the array which does not satisfy stly increasing we return false and one of the scenario for this is what so uh let's look at this so if we Traverse from one to 10 this is strictly increasing but at some point I we Traverse one to 105 right at this position my previous value is what is 10 then I want to consider okay does my five greater than IUS 2 two which is going to be two right if this is true then I want to set my okay so I already dropped this one right I want to set my pre equal to five not the 10 is already dropped so set a pre equal to five so this will be two condition one is you say I'm I compar with I minus 2 the other condition is at the beginning when I = to one right you don't want to say I = to one right you don't want to say I = to one right you don't want to say Okay I want to say I minus 2 now there's no value over here this is index zero right so the pre reset is pretty important so let's look at a code so you definitely have a previous value pre right I'm going to say pre equal to num say zero and also I'm count using my deep to count right deep so for in I = to one I less than num of lens in I = to one I less than num of lens in I = to one I less than num of lens and i++ so if PR Square equal to num I i++ so if PR Square equal to num I i++ so if PR Square equal to num I like this is not strictly increasing condition else this is definitely a strictly increasing condition and I need to make sure I uh I know where is my previous value right so pre equal to this value so if this is not strictly condition I'm going to increment my deep value and if deep is actually equal to two which mean this is not a value R right you want to return false all right so here's condition you want to make sure you reset your PRI so this is reset pre for the condition so if uh I = reset pre for the condition so if uh I = reset pre for the condition so if uh I = to 1 or number say I is greater than say IUS two right you want to say pre equal to num I so uh the one condition is you know 22 57 and another condition is going to be uh yeah one two 10 I'm going to get comma 1 2 10 by 7 right so this is how you reset your PR preious Val and at the end you want to return true so these are the two condition you want to reset the previous value oh yeah submit all right so for time in space this is space constant time this is time all of them right and let's look at the de more just in case confused so at this condition like the I equal to three 0 1 2 3 so three will be here so when we jump to the next value I mean next line like we want to make sure my pref get updated right so preal to five all right so um yeah and this keep going and I want to return true something this yeah all what happen to this condition one uh 2 two 57 start all right at index one so I don't have the IUS 2 value right and then I will make sure my pre get reset because I go to one right and then pre the two still to right so this will be it and then finish it right return true okay so if we still have C comma and I'll see you next time bye
|
Remove One Element to Make the Array Strictly Increasing
|
buildings-with-an-ocean-view
|
Given a **0-indexed** integer array `nums`, return `true` _if it can be made **strictly increasing** after removing **exactly one** element, or_ `false` _otherwise. If the array is already strictly increasing, return_ `true`.
The array `nums` is **strictly increasing** if `nums[i - 1] < nums[i]` for each index `(1 <= i < nums.length).`
**Example 1:**
**Input:** nums = \[1,2,10,5,7\]
**Output:** true
**Explanation:** By removing 10 at index 2 from nums, it becomes \[1,2,5,7\].
\[1,2,5,7\] is strictly increasing, so return true.
**Example 2:**
**Input:** nums = \[2,3,1,2\]
**Output:** false
**Explanation:**
\[3,1,2\] is the result of removing the element at index 0.
\[2,1,2\] is the result of removing the element at index 1.
\[2,3,2\] is the result of removing the element at index 2.
\[2,3,1\] is the result of removing the element at index 3.
No resulting array is strictly increasing, so return false.
**Example 3:**
**Input:** nums = \[1,1,1\]
**Output:** false
**Explanation:** The result of removing any element is \[1,1\].
\[1,1\] is not strictly increasing, so return false.
**Constraints:**
* `2 <= nums.length <= 1000`
* `1 <= nums[i] <= 1000`
|
You can traverse the buildings from the nearest to the ocean to the furthest. Keep with you the maximum to the right while traversing to determine if you can see the ocean or not.
|
Array,Stack,Monotonic Stack
|
Medium
|
1305
|
152 |
welcome back to our jest today's question is leak code 152 maximum product submarine so we're given an array nums find a contiguous non-empty array nums find a contiguous non-empty array nums find a contiguous non-empty subarray with the array that has the largest product and return that product a subarray is a contiguous sequence of the array so contiguous sequence follows one after the other so in example one the maximum product we can achieve from this is six so it's two times three and then in example two the maximum product is zero because any other Solutions are either negative or zero so as soon as this question is asking for a maximum we can start by looking at dynamic programming and what makes this problem slightly more difficult is the array contains negative values so what are the ways that we can generate a maximum from any of these values well we can have the current value by itself we can have a positive times a positive or we can have a negative times a negative one of these will generate the maximum with dynamic programming we're going to have to keep track of the maximum and we're going to have to keep track of the minimum so if we have a variable called prev Max and prevmin and we initialize both of them to the value at index of zero so two and then we have a res which is equal to two to begin with because this is a valid option then we can Loop through this array and build out from this information here so if we start at index one what is the current Max well the current Max can either be three so it can be the current value times the previous Max so both positives so 3 times 2 which is equal to 6 or it could be negative times negative right so we don't have any negatives here so we can say that the maximum from this is going to be six which is three times two then we need to have the current minimum so what is the current minimum at this position well it can be the current value which is three or it can be the current value times the previous Max or the current value times the previous minimum right so the previous maximum previous men at this point in time are the same so the value we're going to add to current Min is going to be three now if we update the previous Max in the previous Min with these values six and three we can now update the results Okay so we've updated the results to the maximum between the previous result which was two and this Max here then we rinse and repeat so if we go to minus two what's the maximum we can get from this well it's minus two the current value or minus two times three so the maximum between those two is -2 the minimum is going to be the is -2 the minimum is going to be the is -2 the minimum is going to be the minus value times the largest positive value so that's going to be -6 then we value so that's going to be -6 then we value so that's going to be -6 then we update these values minus two minus six obviously minus two is not greater than six so we move along so at four what is the current Max we can get well it'll be the current value so the value of 4 or would be 4 times the previous Max which is -2 so that'd be minus eight or it'll is -2 so that'd be minus eight or it'll is -2 so that'd be minus eight or it'll be four times the previous Min which is minus six so the maximum from this is going to be four likewise for the current Min it's either the current value or the current value times the previous Max or the current value times the previous minimum so the current Min will be four times minus six which is equal to minus 24. so if we update prevmax and prevmint then we can update results so we compare results to the current Max result is still greater than current Max so we carry on now we're outside the loop we can just return this as our result and as you can see by using dynamic programming we've simplified the solution from say the time complexity of squared if we had to Loop through each and every possible solution to O of n because we're only iterating over this array exactly once so let's start off by creating our prevmen prev Max and our result variable then if we Loop through from index of one up to the end of non-stop length we work out the current Max in the current Min so current Max is equal to the maximum between number I so the current value times the previous Max or the current value times the previous min likewise for current Min is just going to be the same but looking for the minimum so numbers are I current value the current value times previous Min previous Max sorry or the current value times previous min once we've generated those we can update to prep Max to equal current Max and curve Min to equal current min as soon as we still have access to the current Max we can update result so that'll be the maximum between our current result and current Max then return result let's run it there you go don't forget to like comment subscribe really helps out with the channel and I'll see you in the next one
|
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
|
1,025 |
welcome guys uh so this problem uh let me self a legal section one two five but before i start please be uh be sure to uh subscribe to my channel okay so uh ellis and barbara turn play again and uh initially choose x right x is less than uh from zero to n and uh if n must be uh and it's divisible by x and replacing the number and i'm gonna checkboard with a minus x also uh if the player cannot make move then they lose again okay so the first fact is that the player always can make a move right because one is oh n is always divisible by one so actually we don't have these we don't have this condition okay so the only remaining condition is that uh if you own if you get the if you get what then there's then you lose okay so let me just write down effect okay so the fact is that uh the fact uh if uh and is one then that person lose right because there is no move they can do okay and the other and if is larger than one then that person do not lose right so loose is only uh visible it's only if an equals one okay so for this kind of problem i guess uh usually we use the mathematical induction and then we guess the answer and then we prove it okay so if input is two then uh the true right because l is its first one so x can choose one okay so let me just write it okay so if l is at one right that is the answer is false because as well loose but two alice can win because at least saying take one then the bob will need to take one so bob will lose okay so three right so the problem is that three is false right so the key is that uh so now the key is that uh if at three right if there's three then bob can choose one right so bob so that means everything is false bob can choose one to make two then uh right oh sorry so three right alice can only choose one right because three is a prime number so at least uh can choose one and choose one become bob right and so bob can win so eddies will definitely lose okay so f4 right you can change so four the answer is the same right four if i was alice then i can just choose four to two right so that is how about five so five is a prime number right so if l is at five the only way you can get is four right but if you go to four it's a winning position for anyone so four is a winning position two is a winning position so this is false right and then for six right six the bob can the that eighties can just directly go to uh two right so two is a winning position because two is divisible by six okay so from this theorem uh from this observation we have a theorem so theorem if uh an is odd is even then added swing because addis does is the starting person so an even number is a winning point otherwise it is loose so that means answer is true this is false okay so uh how about we just start okay so you can try it and equal to holder is zero right if one is even then l is win if it's odd then l is loose okay so yeah this is sensor okay so i guess this is answer but uh yeah so we are doing math right so we should prove it's a proof okay so it's un to two right sorry that means it's odd and it's even sorry it's even so uh l is can choose uh two right because n is divisible by two right so that means it becomes minus one right so the problem becomes uh the problem becomes also uh let me see okay yeah sorry about it uh i think you should i mean let me just write it okay so academics is the answer okay so that means an is uh winning points right a minor if n is even so even number is a winning point and our number is uh it's a losing point okay so the proof can be done by mathematical induction right it's almost medical induction so i suppose the i suppose this rule is worse so it is worse for uh for like uh for any for k right oh sorry for unless then k uh so the ground truth is for k equal to two or maybe three okay so three two right one so this is the losing points this is losing points and this is the winning point okay so i use the mathematical induction okay so now uh suppose i was in k plus one so in k plus one okay so there are a few kinds of condition okay so suppose k plus one is odd right uh so i if k plus one is out right then i take any number right so i the only number i can take is uh if k plus one is odd then the only divide uh factor for k plus one is odd right so then i will take some odd number so k plus one will lead to another odd number right but from mathematical induction this number is losing points uh it's losing points right so if so induction works right we start from odd then we always lead to odds right so losing points go to losing point i start from losing points and i take our number right then become other persons so uh so suppose oh sorry for homewriting so i start from odd right so odd minus r is even right so i lead to even number so this even number is winning points it's winning points and so this is losing points okay so i start from odd right and uh i give somebody then somebody's at winning points that means i go from losing point to losing points okay and the same reason if k plus one is even right then i can take two if i take two i become k minus one then this is still the then it is uh sorry i mean i can take uh even right so i can take minus one i can take one right become k so what is k right k is the so this k right so it's suppose k plus one is even then k is out so this is the losing points right so bob will lose but at least will win so this is a winning point so from a mass middle induction we know that if k plus one is odd then losing if k plus one is even then win right so from these induction steps then we can say that these rules but these rules works for k to k plus one then works for all industry for all individuals okay for a positive integer okay that's a proof so i apologize for my uh for my bad writing but uh i guess you guys know i will see you guys in other videos thanks be sure to subscribe to my channel
|
Divisor Game
|
minimum-cost-for-tickets
|
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of:
* Choosing any `x` with `0 < x < n` and `n % x == 0`.
* Replacing the number `n` on the chalkboard with `n - x`.
Also, if a player cannot make a move, they lose the game.
Return `true` _if and only if Alice wins the game, assuming both players play optimally_.
**Example 1:**
**Input:** n = 2
**Output:** true
**Explanation:** Alice chooses 1, and Bob has no more moves.
**Example 2:**
**Input:** n = 3
**Output:** false
**Explanation:** Alice chooses 1, Bob chooses 1, and Alice has no more moves.
**Constraints:**
* `1 <= n <= 1000`
| null |
Array,Dynamic Programming
|
Medium
|
322
|
220 |
hi i am mayushi rawat and welcome to my channel today we will discuss the september lead code challenge day 2 problem contains duplicate 3 let's look at the problem statement given an array of integers find out whether there are two distinct indices i and j in the array such that the absolute difference between nums of i and nums of j is at most t and the absolute difference between i and j is at most k okay let's look at the first example the input array is given as 1 2 3 1 k is given as 3 and t is given as 0 means that the difference between both the elements can be at most zero so we are looking for two elements which are similar in our case the element at index 0 and element index 3 so let's calculate k case will be i minus j that is absolute difference between 0 and 3 that is 3 does it satisfy our condition yes k should be at most 3 and t is 0 ok so let's dive into the code if a condition satisfies we will return true otherwise we will return false the very first condition i am going to check is for t if t equals to 0 then we must have one duplicate element in our list otherwise we will return false now i am going to use two for loops the first for loop will run till the length of array in case of second for loop we have to set the limit because we cannot go ahead of k that is the difference between the indices can be at most if j is less than length of nums an absolute difference between nums of i and nums of j is less than t that means we can return true otherwise we will return false now let's run our code okay let's try submitting the code and it's done thank you for watching the video please like and subscribe my channel for more such videos
|
Contains Duplicate III
|
contains-duplicate-iii
|
You are given an integer array `nums` and two integers `indexDiff` and `valueDiff`.
Find a pair of indices `(i, j)` such that:
* `i != j`,
* `abs(i - j) <= indexDiff`.
* `abs(nums[i] - nums[j]) <= valueDiff`, and
Return `true` _if such pair exists or_ `false` _otherwise_.
**Example 1:**
**Input:** nums = \[1,2,3,1\], indexDiff = 3, valueDiff = 0
**Output:** true
**Explanation:** We can choose (i, j) = (0, 3).
We satisfy the three conditions:
i != j --> 0 != 3
abs(i - j) <= indexDiff --> abs(0 - 3) <= 3
abs(nums\[i\] - nums\[j\]) <= valueDiff --> abs(1 - 1) <= 0
**Example 2:**
**Input:** nums = \[1,5,9,1,5,9\], indexDiff = 2, valueDiff = 3
**Output:** false
**Explanation:** After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false.
**Constraints:**
* `2 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `1 <= indexDiff <= nums.length`
* `0 <= valueDiff <= 109`
|
Time complexity O(n logk) - This will give an indication that sorting is involved for k elements. Use already existing state to evaluate next state - Like, a set of k sorted numbers are only needed to be tracked. When we are processing the next number in array, then we can utilize the existing sorted state and it is not necessary to sort next overlapping set of k numbers again.
|
Array,Sliding Window,Sorting,Bucket Sort,Ordered Set
|
Medium
|
217,219
|
3 |
in this video we have to find the longest substring in a given string and the condition is that there should be no repeating character in that substring so let us take an example so this is a lead code problem number three and it has been asked quite a few times in Google and Amazon interviews so the problem statement is that let's say we have this string and we have to find a substring out of this so when dealing with problems like this you should first be careful that whether it's a substring or it's some sequence in this case it's not a subsequence but it's a substring that is you have to pick some continuous Chunk from the given string there should be no gaps so uh just some additional information if we have a string of length let's say n then how many substrings are possible so the simple is that in the substring we will have one initial index and one final index or left and right and the original string continues to the left of this index and to the right of this index Ln R May well be the first and last indices also so the complete string itself is a substring of itself so this is the notion of substring so ah in these questions so you should always start with if you don't have any Optimum solution you can always start with uh trying out on all the possible substring that is Brute Force so you have to run two Loops one will be from 0 to maybe last index n minus 1. and the second value or we can write it l and R will be within this so for each value of L R should be greater than equal to l and it should be less than of course n minus 1 or equal to n minus 1. so uh let us say the first index is here so one of the substring is so L is zero R is 0. so the substring will be just a then l e 0 R is 1 substring will be a b similarly when L is 0 R is 2 it's a b and when this Loop ends so its length will be exactly n and then we will increment the value of L that is 1 and again try all the values of R starting from L because R has to be on the right side of L or overlab with L so in this case first value will be L equal to 1 are equal to 1 so that will be B then r equal to 2 that will be B then BBC so you got the idea so the number of substrings possible is of the order of n Square so in this case you have to find the longest substring so there are almost n Square such substrings and you have to check whether there is a repeating character there or not so that will be the Brute Force you have to go through all the substrings so that will be let's see the time complexity for that so first you have L going from 0 to let's take this example a b c d b first of all let's work out ourselves what is the longest substring with no repeating characters so we have got a B so at least we can have substring of length 2 then if we pick a b this B is repeated so this is not allowed then if we pick BB again not allowed then b c again of length 2 BCD so we have got a bigger substring of length 3. and if we do bcdb again B is repeated if we do cdb again its length is 3 so no improvements so in this case the optimal value is 3. so we have to just return the length now if we do Brute Force we have L going from 0 to 1 2 3 4 5 6 so n is six so it will go from 0 to uh five and then the inner loop R will go from L to 5. and for each substring so the substring will be in the string starting from L to R so you have to check for all the characters within this substring whether any character is repeated or not so it's in the Inner Loop so this outer loop runs for almost n times inner loop also runs for almost n times and within this Loop you can have some substring and for each character you will check whether it's repeated or not for checking the duplicate you can use some set asset or hash map anything so in the set for each character you will query whether this already exists in the set or not so for the first time the set is empty then you go to the second character you and you insert the first one here so the cost of checking this duplicate is equal to the length of the substring so if the length of substring average length is l then the total time complexity will be this n times n that is n Square Times average length foreign factor of n then this overall time complexity will be of the order of n Cube so this is the Brute Force way of solving it so we have to think can we do better so uh let's write the same example again so we know that we have to keep track of two indices so we can use a approach called sliding window approach so this is a way of solving problems where we have two indices L and R denoting the window so Windows spans from L to R and we are concerned about values within this window so a substring is like a window so substring also needs left and right boundary a window also needs in the same so you may guess that can be used some sliding window approach so we can start with both indices window of length one where L and R both are at the first index 0. so the result in this case the maximum length substring with no repeating characteristic one then we expand R is used to expand the window and when we find any duplicate character by going to next value by expanding the window we contract the window by increasing the r l so when R is increased window expands when L is increase window contracts so here it's fine the window is just a so there is no repeating character so the result is one then since there is no duplicate found we can increment the value of R to this one so now we have substring a b so again we will check in this AV there is any repeating character or not so let's say at some point of time we have this window L was here there were many characters here R was here and there were no repeating characters so next what we will do since we have no repeating character we will increment we will expand the window so we will add one more index here so now the window is this was the window one where there were no repeating characters now the window is one more than double one so if there was no repeating character in this window then only character that may be repeated is the new character because these all are unique characters and now we are introducing one more character so none of these characters that were already in the window are repeating but whatever is the new character here that only can repeat so we have to only check in the already existing map whether this new character it's a c exists in the map or not so ex expand the window check in constant time whether the new character was already existing or not so if the new character is already existing then we don't increment the value of result we don't compare the results since this is invalid case so we have to contract the window so we can move L here one more position and again we don't need to check this part since these are already unique so that's why we can do some optimization here so uh we can keep track of not just the character but also at what index they appeared and we will be concerned mainly with the latest value let's say uh we had a b c b d so for B we will be storing this 0 1 2 3 4. so initially we will store one as the index since B was present at one but next time once we reach this B we should update the value to 3. because uh next time we go to the right of this if we take this index and move the value of L to the right of this let's say here we again found B so we will check whether B exists or not so we will see at what index B exists so we can straight away shrink the window from the left to one index more than that index because if we keep L to any value till this point so this B is already present in the previous window so again this is part of the window so we want to get this index out of this new window but if B is again present here at some later index then if we move the window here left part of the window here still there will be duplicate so that's why we are interested in the highest index for this the latest index for this character so we have to move the window here so you got the idea so that's why we will be keeping track of index as well as character so in this case we can reduce the time complexity further so what we are doing a b c d b so initially L and R both are here so the maximum length is 1 since there is no duplicate in this window we expand the window so R comes here now A B there is no ah duplicate so let's write the indices also 0 1 2 3 4 5. so in the map we will have a at index 0 B at index 1. so now the result is of length 2 R minus L plus 1 so it becomes 2. so there is no duplicate in this window so let's expand the window so we expand the windows by this so that is by just incrementing our so now we check whether this new character is present or not so we see that it's already present at index 1 so we want to shift the window such that its left end comes after that index so that L will come here that is at index 2. so after moving the window here to the right of this B L and R both are at B so the result length is 1 so we will not update it now in this window this single length window again there is no duplicate so we will expand the window so R will come here so the new window is this BC we see whether C is already present in the map or not it's not there and before that b will also be updated to 2 because this is the latest index so we want in the right most value of ah right most occurrence of that character because if we don't move this left part of the window so we skipped some characters C and that is also present after this index so it did not help because this duplicate this same character was the right most character because this is the character that caused the issue so we look whether it exists somewhere or not so we are interested in the right most occurrence of that and move the left part of the window there so that this character C is occurring just once in this window so this is the whole idea of this optimized sliding window and also if let's say there was a window and this is the left index and the newly inserted character after increasing the value of R it's some characters C and let's say that character see the rightmost occurrence of that character is here that is less than L then we do not need to change the left window since that is already uh outside this window so we can further increment r so these are the two ideas here one is that we are interested in the rightmost index right most occurrence of a character when looking for duplicates other is that if that character is already outside this window then we don't need to change the left part of the window so let's continue our example here so L and R let us clear it up so L and R both are here and B occurs at index 2. so we are keeping track of the latest index now we increment R here so R comes here so C is occurring at 3 again there is no duplicates he has is not present in this map so again length is 2 so no need to update so we increment R and the window is BCD again D is not in this map soon it's not present already no duplicate so the length is now 3 so the way to do that would be we will keep Max of the existing result and R minus L plus 1 so in this case r is 4 L is 2 so 4 minus 2 is 2 plus 1 is 3. so result is 3 next we move R here so this window is now b c d b so we check for B and we also insert D here B where B exists so B is already present in the map so this creates duplicate in this new window so we check where was the last time B occurred so B occurred at index 2 B also occurred at one but if we move the window here another B will still remain so we find the latest B that is 2 before this of course the current character and we move left pointer one more than that so that effectively this part goes out of this current window so it's cdb again there is no more duplicate and the length remains three so no need to update the result and now R has reached the last character so we stop here and return the value so what will be the time complexity here you can see that we are keeping track of two indices L and R and we are incrementing them one by one and for checking whether the newly added character has already occurred or not it will take o of one time so overall it will take off n time and the space complexity so at Max all the characters in this string can be part of the map when all of these are unique so it can take another o of n space so now let's write the code for this optimized sliding window approach so I am not writing the code for Brute Force you can try it yourself and check whether it passes the test cases or not so optimized sliding window so let's open our lead code platform and write the code here so let's initialize the result to zero and let's keep two indices L both zero L is 0 and R is also zero and then we will run only till R reaches the last character so s dot length so when R is equal to s dot length that is so the last index is s dot length minus 1 so R should be at Max s dot length minus 1. so once it becomes equal this Loop will end and to keep track of duplicates we also have to used n on ordered map you can also use set but that will not be optimized solution that will be a simple sliding window but we are also directly jumping the left index to the right most occurrence of a particular character so that's why we are using the map to keep track of index character and its index let's name it curves so here we will check we will try to find the current character so R can R Points to the right most or the latest character so s at index R this is the latest character so we try to find in this hash map cares so if this iterator is not equal to cares dot end so if it's not equal to cash Dot N that means it was found in the map that means there is a duplicate if it's not found in the map this iterator will point to cash dot end and we are also interested in only if it was found at the leftmost window or to the right of it so if the window is let's see here so if the occurrence of that character is already to the left of this window we are not interested so that is already not part of this window so no need to increment L but if that index is to the right of L then only we are interested so that's why another check is that index should be more than or equal to l then we are interested so we will make L equal to one more than that else if a duplicate was not found by inserting the latest character then we check what is the new length so the result May improve so we compare here STD Max so it calculates the max of two values so one of them is result and other is R minus L plus 1 so whichever is larger it keeps that and then irrespective duplicate or not we have to increment r but L is incremented only when we find any duplicate this denotes contraction of window and this is expansion of window and we missed one thing so this cares should be updated to latest value of r so the index for this character s r is R so maybe that Sr was already present but at some lower index so we update that in the map and finally we return the result so let's try it out if there are any errors here so it works for this simple example let's try to submit if it passes for all the other test cases so it the solution is accepted and you can see that it's it took 32 milliseconds so let me drag it so the solution was accepted so I hope you understood it this is not a very straightforward solution this sliding window approach can be very tricky to write the code so be careful keep here the main point is to uh be careful about the indices left and right and then you should be fine so if you did not understand it please try it on out this approach on some another example and watch the lesson again so good luck and see you in the next lesson
|
Longest Substring Without Repeating Characters
|
longest-substring-without-repeating-characters
|
Given a string `s`, find the length of the **longest** **substring** without repeating characters.
**Example 1:**
**Input:** s = "abcabcbb "
**Output:** 3
**Explanation:** The answer is "abc ", with the length of 3.
**Example 2:**
**Input:** s = "bbbbb "
**Output:** 1
**Explanation:** The answer is "b ", with the length of 1.
**Example 3:**
**Input:** s = "pwwkew "
**Output:** 3
**Explanation:** The answer is "wke ", with the length of 3.
Notice that the answer must be a substring, "pwke " is a subsequence and not a substring.
**Constraints:**
* `0 <= s.length <= 5 * 104`
* `s` consists of English letters, digits, symbols and spaces.
| null |
Hash Table,String,Sliding Window
|
Medium
|
159,340,1034,1813,2209
|
337 |
hello and welcome back today we will be discussing the sixth practice problem on DP this is going to be the first problem wherein we are going to apply dynamic programming entries as a prerequisite I am assuming that you are comfortable with trees data structure so let's quickly go through the problem statement it states that the thief has found himself a new place for his theory again there is only one entrance to this area called root besides the route each house has one and only one parent house after a tour the smart Thief realized that all houses in this place form a binary tree it will automatically contact the police if two directly linked houses were broken into on the same night given the root of the binary tree return the maximum amount of money the thief can rob without alerting the police so in simple terms the question says that you're given a binary tree and you need to find the maximum points you can collect so points are basically the numbers which are stored or the values which are stored in the node with one condition that if you take a particular node then you cannot take its children if you want to take these two notes then you have to leave this node and you have to leave these two nodes so let's try to visualize this question using an example let's say that we have this binary tree so let's analyze the different options available with the robber so while traversing right the robber has two options the robber can either select this node and in that particular case the robber would have to leave these two nodes because the question clearly specifies that no two adjacent nodes can be collected by the robber or the second case is that Robert decides to select these two nodes and in that particular case the robber would have to leave this node again because of the condition specified in the question similarly on the left hand side as well the robber has two options either the robber can select this node and leave these two nodes or the robber can go for these two nodes and then the robber would have to leave this node now let's give an identifier for each of these situations so when the robber goes towards left and select this node let's call this situation W the situation where the robber selects this particular node let's call it X this situation let's call it Y and this situation let's call it Z so what are the different combinations available to the robber can either select w and z so on the left side the robber decides to take this node and on the right side the robber decides to take these two nodes another case which is possible is X Plus y the robber takes this particular case on the right hand side and on the left hand side the robber takes this case other possibility is W plus X and another possibility is y plus Z now in the particular case where the robber decides to select the grandchildren nodes on both the sides on left and right side in that particular case the robber can also select this particular node let's say that this root node is a so the robber can select this node as well because by selecting this node we are not breaking the constraint given in the equation so the particular case where the rubber selects y z there we will also add the root node because in that particular case it is possible for the rubble to also select the current root node now what is going to be the answer for this root node the answer for this root note or the maximum value possible at this root node is basically going to be one of these cases which is going to give the maximum answer so max of all these four cases is going to be the final answer and if we look clearly what is w x y z referring so w x y z are nothing but the maximum cost till that particular node so w refers to the maximum cost or the maximum points the robber can collect till this particular node X is referring to the maximum points robber can collect to this particular node Z refers to the maximum Pareto robber can collect till these nodes and why similarly the maximum points a robber can collect till these nodes so if we see the maximum points we can collect at a depends on the sub problems w x y z if we are able to solve these sub problems if we had the answer for these are problems we could have easily calculated the answer for our main problem which is the maximum points or rubber can collect till the a node so again this brings us to our recursion intuition which says that delegate the task to solve the sub problem similar sub problem to the recursion method and you don't have to think about it you just need to assume that the equation function will solve the sub problems which are of similar kind and give you the correct answer using those answer you just need to calculate the answer for the current step so this intuition can be very well extended to this problem because we just want a recursive method to return as the answer for the sub problems or the maximum points we can collect till both the children and the grandchildren once we have the answer for these sub problems we can easily calculate the answer for our main problem so let's quickly go through the code for this solution so this is our main method raw which is going to return the maximum points a robber can collect till this particular node now as we have already discussed there are four possible cases so as we have already discussed while traversing towards left there are two possible case and while traversing towards right there are two possible cases so on the left first case is that the robber selects the immediate child or the next case is the robber selects both the grandchildren now on the right as well the robber can select the immediate child and on the right the robber can say like the grandchildren now from all these four possibilities there are four permutations possible so one case is X Plus y as we discussed another case is W plus X Y plus Z and the last case is when the robber selects the grandchildren which is z and W on both the sides but as we saw when the robber is selecting that children on both the sides the robber can also add the value of the current cell because in this case we are not selecting any two adjacent nodes so whatever is the maximum from all these four possibilities that maximum value is going to be the answer for this particular step and here also to solve these sub problems we are just delegating the task to a recursive method without even thinking that how will it work we'll just assume that it works for the sub problems and once we have the sub problems our task is to calculate the answer for the current problem and the base case is also pretty simple it is kind of a standard base case for all trees related questions so when while traversing when we have reached the null node we will return 0 from there because now the robot cannot collect any more points so obviously the solution gives a time limit exceeded iron and that is due to overlapping sub problems so if we try to understand it using an example so when we are trying to calculate the maximum points for this particular node and we are traversing right on the right hand side we are making two calls so in the first call we are delegating the task to this particular node which is the immediate child and in the second case we are delegating the test to the grandchildren now in the case when we are delegating the task to the immediate child this child is also going to recursively call this method for its immediate child so again when we have delegated the task to this particular child in its recursive call it is again going to call the recursive method for these two nodes again so you can easily see the problem of overlapping sub problems because we would have to calculate the answer for these two nodes more than once and similarly for a lot of nodes we would be calculating the answer again and again so obviously we can use memorization here and once we have calculated answer for a particular node we can make an entry in the map so that we do not calculate the answer again for that particular node so the memorization code is pretty close to the recursive code the base logic is same that we are calling the helper method or our recursive method for the force of problems or the four scenarios and then we are calculating the answer using those sub problems for this particular node the only addition here is that we have created a map in this map we are going to store the answers for nodes which have already been calculated now if we have already calculated the answer for this node then definitely there will be a entry for it in the map and we will return the answer directly we will not calculate it recursively but in case if the answer is not present in the math then we will calculate it recursively and while leaving we'll make an entry for this node in the map so that we don't have to calculate it again so the time complexity for the memoization solution is Big O of n that is because we are calculating answers for each node but we are only calculating answer for each node once that gives us the time complexity as Big O of n now I am not going to discuss the tabulation approach here because in my opinion tabulation is really difficult to visualize for a tree and it becomes counterintuitive So based on my experience memorization comes in most handy for trees also it is a task in itself to pass trees iteratively and tabulation doesn't make sense if you are not going to solve the problem iteratively so in case if you have an intuitive tabulation approach I request you to mention in the comment section and I'll pin the approach or I'll pin the comment with this we have reached the end of this video I hope you enjoyed and learned something new I'll see you in the next video thanks for watching bye
|
House Robber III
|
house-robber-iii
|
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called `root`.
Besides the `root`, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if **two directly-linked houses were broken into on the same night**.
Given the `root` of the binary tree, return _the maximum amount of money the thief can rob **without alerting the police**_.
**Example 1:**
**Input:** root = \[3,2,3,null,3,null,1\]
**Output:** 7
**Explanation:** Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
**Example 2:**
**Input:** root = \[3,4,5,1,3,null,1\]
**Output:** 9
**Explanation:** Maximum amount of money the thief can rob = 4 + 5 = 9.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `0 <= Node.val <= 104`
| null |
Dynamic Programming,Tree,Depth-First Search,Binary Tree
|
Medium
|
198,213
|
129 |
let's Implement lead code 129 given the root note of a binary tree with each node having a value from 0 to 9 we're asked to return the sum of all paths from the roots to the leaves now in addition to having an integer value each node has a pointer to its left child and appointed to its right child which are both null by default so the leaf nodes in this tree implicitly have both the left and right pointers as null at a high level we'll need to Traverse or visit every node in the binary tree starting at the root node secondly as to Traverse the binary tree we need to keep track of every node along the current path so let's declare a double-ended queue to keep track of a double-ended queue to keep track of a double-ended queue to keep track of this a DQ allows us to add and remove elements from both ends at the end of each path we'll convert the queue into a number and add it to the sum so let's declare variables for these finally we need to backtrack by removing the last element from the queue before exploring A New Path after the Traverse method is done we'll return the accumulated sum now let's implement the Traverse method is initially called on the root node if the node is not null we add it to the queue next we recursively call Traverse on its left child and now we are at the five node we add 5 to the Q and call Traverse on its left child which is the two node two is a leaf node because both its pointers are null so we'll convert the Q into a number and add it to the sum finally we'll backtrack by removing the last value from the queue and returning we're back at the five so next we'll recursively call Traverse on its right child 7 gets added to the queue it's a leaf node so we convert the queue to a number and add it to sum we backtrack by removing seven from the queue and returning we are done with the five node so we backtrack by removing it from the queue before implicitly returning next we call Traverse on the onenote's right child zero is added to the queue and 10 is added to the sum finally 0 and 1 are removed from the queue and the final sum of 319 is returned assuming a balanced binary tree the space complexity is login and the time complexity is n log n
|
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
|
205 |
Hello Friends Caught Discuss The Fourth Problem Sun Latest Festival Season Walking Alone And Middle 100 Easy Problem Andar Salasi Power To Ghaghare Vidmate Apps Soft Vegetable Problem Solve This Question Statement The Name Of The Giver Shy Subscribe What Means By Subscribe Replaced With This A To Z Tak Tent And All The Famous Place Was Done In This His Ignorance To All Fans Of In December Individual Dance Class All the Video then subscribe to the Page if you liked The Video then Sonu Nigam Deputy Editor Replace All The Prince Office Number Industry New 200 gr chaupat desh bandhu kya system wich s.no to taste up the same that what exists s.no to taste up the same that what exists s.no to taste up the same that what exists in the system ki chart note or own same card issued after a gap to be omniscient maps t**** gap to be omniscient maps t**** gap to be omniscient maps t**** 108 interview pimple a strange in This In His Lap Hp Laptop Pieces Winner Green Day Come To Be In The Doctors Payment Way Some Is Rock Female For Every Character Of 10 Based On Single Quote 19 Trust Yourself Then Tree To Avoid This While Improving Provident And Left Or Acid Computers Operation Convert your in this for degree Celsius to fight for justice should not be meant for this question is used to make and incident minimum set what you want to set on LG time butter chicken news today also saw by which Vikram aap hai android country se example1 and a Souvenir CP Thakur's joint map to 1 a result when a and back I am towards you som of thum into were here day common meeting ji how to t&c hai to which direction foot kiss maps vidmate apps potato tap and also added to make this App to insert in set for mapper gill developed radhe this chapter and reduced with no dues tractor inside make sure all ministers in time in the map acid short tricks subscribe not present and subscribe indian subscribe to that bigg boss insulting disorder amused at his residence In the fight for the first time 200 good point of view definitely maps ignore user name of agriculture waste water quality in this how to find what will the can make this possible transition from std code mein chal make you no khayal koi porn 100 ko doctor hai S E Want You Can See In This Question This Man 's Map And Set Active And Passive Candidate 's Map And Set Active And Passive Candidate 's Map And Set Active And Passive Candidate 200 Blight And Voluptuous That Aap Haldi Thodi The Condoms Of Very Difficult For Us To Live With Your Fit Don't Know How To Use For This App Contents Details Were Particular Entries What Famous Time Plant Sougdians Years This Is How To Check Dam Se Per Straight Chin Up To Shifted To Account For Which Such Idy Subscribe This Video Not Review I'll Send You Find Weather Deuce X Dot S President Also In this entries nodal time and scattered total saturday only will do i will introduce entries left side security meeting now map entry cross insulting this a great interest subsidy the health effects here ok this map entries not mean that ok so error mapping not a but a positive Manner of two years in 3D that in the map different quality in two and g ne Pintu is not present pokemon 530 mapping does not rise in this point but she digestive differential notification statements of this only one mapping to every cat if then Se not for Dashrath seat map of SMS not the but fennel twister this point this is on this enter in the Saturn and it's hello friends so okay under this Siddharth who has given his subscribe now to pos vidmate subscribe in every election 2014 and so Files Do Not Modify This Not Matching Din Research Acid Position Do n't Notifications Not Benefit For The Giver Liquid And Understand This Function Easy Problem Solve With U Some Questions Formation International Food Misal Paw Sperm Effects Of Much Thanks Like This Video
|
Isomorphic Strings
|
isomorphic-strings
|
Given two strings `s` and `t`, _determine if they are isomorphic_.
Two strings `s` and `t` are isomorphic if the characters in `s` can be replaced to get `t`.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.
**Example 1:**
**Input:** s = "egg", t = "add"
**Output:** true
**Example 2:**
**Input:** s = "foo", t = "bar"
**Output:** false
**Example 3:**
**Input:** s = "paper", t = "title"
**Output:** true
**Constraints:**
* `1 <= s.length <= 5 * 104`
* `t.length == s.length`
* `s` and `t` consist of any valid ascii character.
| null |
Hash Table,String
|
Easy
|
290
|
1,650 |
welcome to june's leco challenge today's problem is lowest common ancestor of a binary tree given a binary tree find the lowest common ancestor of the two given nodes in the tree according to the definition of lca on wikipedia the lowest common ancestor is defined between two nodes p and q as the lowest note in t the binary tree that has both p and q as descendants where we allow a node to be a descendant of itself here we have a binary tree and we're given p of 5 and q of 1. we can see that the lowest common ancestor is going to be 3 here on the left side is 5 and the right side is going to be 1. so that's going to be the lowest ancestor now if we're given 5 and 4 here we can see 5 is going to be our lowest common ancestor because 5 itself can be a ancestor and that's going to be lowest note outside of our levels of binary tree now my first approach was to do a post order traversal of the binary tree and find every single node starting from the node that equals p or q and all the ancestors added into like a set and what i did was union the set together and then re-traverse the tree together and then re-traverse the tree together and then re-traverse the tree to find the lowest node where the node exists inside of our tree but that did work but it was kind of inefficient a better way of doing it is to do a post order traversal here using a recursive function what we'll do is find three scenarios either the node itself on the left node is an ancestor of p or q and the right side is an ancestor pq and if that's the case then this node itself is the lowest common ancestor as long as we do a post order the first node that we find that's case that's going to be the answer but there's two other scenarios it could be that this node itself is the ancestor of p or q and on the right side right here is an ancestor p or q if that's the case then this is going to be the lowest common ancestor and the other way as well where this is a um ancestor of p or q and the right side is an ancestor pure q so those are the three scenarios that could happen so okay what we'll do then is write a depth or search first we're going to store our answer as nothing and we'll write a function here that for search passing in the node our base case is obviously if not node we'll just return it false and we want to traverse our tree post order uh starting with the left side and the right side to see if either one of these are going to be an ancestor appear or q so left we want to traverse the x-ray so left we want to traverse the x-ray so left we want to traverse the x-ray search no dot left and the right we're going to reverse as well right side now what about this one right here that we're on the current one uh well the current one uh basically if this node itself is equal to p or q then it counts as an ancestor right so this would be whether the node is equal to p or node is equal to q now if our three scenarios uh first if left and right that means that this node itself is the lowest common ancestor or if the cur and right or occur and left if either of these conditions are true then we want to make this node equal to the answer and just return otherwise we're just going to return here whether any of these are true because that if any of these are true that means this is an ancestor so if left or right or occur oops finally let's call our deaf search on the root and then return the self.answer and then return the self.answer and then return the self.answer and this should be it let's see here okay that looks like it's working it's going to submit it and there we go so time complexity is going to be of n and we do use o then space because of our recursion you could do this iterability it's a little bit cleaner but i found it more confusing frankly and it's really the same time complexity anyway so all right i think i'll end it here thanks for watching my channel remember do not trust me i know nothing
|
Lowest Common Ancestor of a Binary Tree III
|
find-root-of-n-ary-tree
|
Given two nodes of a binary tree `p` and `q`, return _their lowest common ancestor (LCA)_.
Each node will have a reference to its parent node. The definition for `Node` is below:
class Node {
public int val;
public Node left;
public Node right;
public Node parent;
}
According to the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor)**: "The lowest common ancestor of two nodes p and q in a tree T is the lowest node that has both p and q as descendants (where we allow **a node to be a descendant of itself**). "
**Example 1:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 1
**Output:** 3
**Explanation:** The LCA of nodes 5 and 1 is 3.
**Example 2:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4
**Output:** 5
**Explanation:** The LCA of nodes 5 and 4 is 5 since a node can be a descendant of itself according to the LCA definition.
**Example 3:**
**Input:** root = \[1,2\], p = 1, q = 2
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[2, 105]`.
* `-109 <= Node.val <= 109`
* All `Node.val` are **unique**.
* `p != q`
* `p` and `q` exist in the tree.
|
Node with indegree 0 is the root
|
Hash Table,Bit Manipulation,Tree,Depth-First Search
|
Medium
|
1655
|
78 |
hey what's up guys john here again and so this time let's take a look at another classic problem here number 78 subsets alright so you're given a set of distinct integers return all the possible subsets right and then it's not the permutation of itself right basically it asks you to return all the possible subsets right not just 1 2 3 and or 1/3 or something right so there and or 1/3 or something right so there and or 1/3 or something right so there has to be a sequence basically right and basically 1 3 & 3 1 it's the same right basically 1 3 & 3 1 it's the same right basically 1 3 & 3 1 it's the same right the same subset & 2 3 & 3 2 is the same subset & 2 3 & 3 2 is the same subset & 2 3 & 3 2 is the same and 1 3 basically all the possible subsets from this from - from length 0 subsets from this from - from length 0 subsets from this from - from length 0 to 1 to 2 & 2 3 right so how can we to 1 to 2 & 2 3 right so how can we to 1 to 2 & 2 3 right so how can we solve this kind of problem right so we use a backtrack idea here right basically first you know we're gonna have like the first of the first while loop which to loop through from Len 0 to length 1 so from Len 0 to length of the nums here and for each of them right we try to do a backtrack right we try to mm try each of the positions here right and from there we try again and again right and we'll never they and while we're also while we're doing the back Tracking's we're also maintaining like current numbers right current lists and whenever that at least reached our current length 0 1 2 or 3 we just return that the current list so that's why we need a backtracking because the reason being is that every time when we add like a pen like current numbers to the bag hiking's erase after finishing the backtracking recursive call we need to return when you to remove it right how I will show you guys later on so let's do this right lens off the end right so first we're gonna get like the length of an and then let's define a backtracking my third here right backtracking so let's implement the backtracking method later right so let's finish to this okay like I said since we're going to basically to get all the subsets right subset for all the lens and the lens is from 0 to the length of the nubs right that's why when you have like I in range n plus 1 right so the reason we 2n plus 1 is the we need the length and basically right and then now we're gonna have answer to hold our final result here so basically that's why I'm neat and together like a backtrack here right basically every time I every time for from coordinate lines I here I call backtrack and then here we'll be having like a current list and at the beginning is always 0 I'm sorry it's always empty and since we're going to do the backtracking right so we're always moving forward right we're not coming back so that's why we also need to like a starting index here so that we can every time when we add the backtracking methods inside of backtracking method we know where's our starting point right so current list and here in the end we simply return the answer here right and now the critical part here is how can we implement this backtracking better right I think first right so give the length of the car in the list right equals to I here right so I is our current processing length so I means we are trying to find all the possible subsets for the visit length I right then we just simply append our current the list to the answer here all right so that's the track so if it's not the length what do we do a start we do a for J in range start to end right and we just do a backtrack right backtrack all right so basically if it is not has not reached the desired the length here right what do we are we add the current number two the current lace and then we start starting from there we try all the possible weight again right that's why we do a current list one more thing so here since we're doing this like reference we need to make a deep copy of the sub array of the race otherwise later on if we change the current list all the answers we had a previously stores added in the Al Unser variable will be all we also got changed that's why we do a deep copy here so now we do a pen write append this thing to append the current number to this current array right and then we just passed this updated the list into the backtracking itself right and remember the starting point will be start obj plus 1 right and then the current lays itself why we that's why we keep the start the starting point here right because we always want to moving forward right and let's see and for example here for example we are well processing length equals to two right and we are at the let's see the current list so is one we have one here right and then the starting point will be from two and three right we have one two and three so the current list is one now we need to start processing two and three here right so then first okay we are we starting from we start from one here and start from - right start from - right start from - right and then we see okay we see a two here so we are gonna append this two to the end of one here right and then I'm going inside here and then okay I find a naught a 1 and a 2 right and once I come back here right you see that so if I don't do anything Ruby the hard lace since we are still inside the for-loop since we are still inside the for-loop since we are still inside the for-loop right and it will process this 3 here right and then you add I append a 3 but again to this current list right which will be wrong right that's why after backtracking method which that's how this backtracking method makes sense here right so after finishing these things we just pop this thing big pop this like the number we just added to the current list because for each of the element in this for loop any of them should start with the is a identical clean start right that's what basically we just remove whatever had a change we had made to this current list because this currently a share is being shared among all the backtracking method here right so that's why after we processing to here was it finished right when it comes to here before going to the three number three here we will be removing this too right and then when it's come to 3 it will be 1 plus 3 right that's why we can keep track getting those like answers right okay so yeah I think that's pretty much it a so and then we use this one to determine okay if we need to add this number to the end right to the final answers so let's say if when we process one two three here right still writes and I connect is gonna be three here and then when it comes to here basically we'll be doing some like redundant work here right because 4 there will be only one result right so for all the other four loops and the back Tracking's and when we reach here the current list will be at zero and one let me think well actually know what actually do we need to really do we really need this and let me do a quick check here okay you know what let's just prefer to run it first and okay so this one finished it passed alright actually while talking to you guys I was mmm what ideas came to my mind here just came to me while we're passed while we're like when we are processing lens three here seems like we have already we have a we basically we will be also processing 0 1 & 2 of the length so mmm processing 0 1 & 2 of the length so mmm processing 0 1 & 2 of the length so mmm maybe right so let's see the end is here and okay so let me do some quick testing here so if I remember move this thing and instead of here if I do less or equal that n right will we get the same result let's see yeah here so the starting point is also why right well we get the same result hmm yes cool so see okay that's what I thought right basically we told her we don't need this for loop here because while we're processing the last array here right the last sorry the last lens let's say for example three here one two three while we're processing that we are also processing zero and two sorry zero one and two right that's how that's why we can just simply remove this for loop instead we just processing as if we're only processing lines three here right and then for anything that's actually we don't even need this do we need this in here no we don't need this thing basically every time we can just add here because it's bounded to the end right so yeah we don't even need to check the length because we know the maximum length will be n so this currently it will never be more than n right and yeah we just simply use this like backtracking method to try all the other possible all the possible combinations starting from this current index right and every time we find a new basically every time when we cease go to it a new go inside the new backtracking so we know okay that's what must be our one up must be one of our result right and this we just add it to the answer here I read every day and learn something yeah yet so this thing is redundant we don't have to use that mmm cool guys I think that's yeah that's pretty much it is I want to talk about for this problem yeah it's good I improve my solution here right by removing this like in redundant for loop here so we only be doing this one backtracking matter cool guys I think thank you so much for watching the videos and I'll be seeing you guys soon bye
|
Subsets
|
subsets
|
Given an integer array `nums` of **unique** elements, return _all possible_ _subsets_ _(the power set)_.
The solution set **must not** contain duplicate subsets. Return the solution in **any order**.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[\],\[1\],\[2\],\[1,2\],\[3\],\[1,3\],\[2,3\],\[1,2,3\]\]
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[\[\],\[0\]\]
**Constraints:**
* `1 <= nums.length <= 10`
* `-10 <= nums[i] <= 10`
* All the numbers of `nums` are **unique**.
| null |
Array,Backtracking,Bit Manipulation
|
Medium
|
90,320,800,2109,2170
|
718 |
hello all welcome to CODA let us solve today's lead code daily challenge and the problem is maximum length of the repeated summary given to integer array nums one nums to return the maximum length of the sub array that appears in both the arrays it is a straightforward question they are given two arrays one two three two one and the other array three two one four seven so what is the longest length maximum length summary if somebody that is equal to that is common for both the arrays that is three to one which is of length so 3 is our output and considering the example two the array is zero and another array is also zero and the maximum length Max length somebody is zero and just the layoff length five so this is the problem so first let us think of Brute Force approach water will be the Brute Force approach there are uh for each and every index 0 to n in numbers 1 and I will go and search for J starts from I uh which is also ranging from I to em in nums to and again there will be another for Loop if nums of one thumbs up one nums one of I is equal to nums 2 of J then I will be incrementing the length implementing the length and update our final answer update our answer equal to Max of answer command and finally just return our answer so this will be uh The Brute Force approach so the time complexity will for this approach will be order of n Cube and the space complexity will be order of 1. so how can we optimize this approach this is our brute for solution so let us think in some other way consider we can take consider we are going to take all possible ways in the sense I am going to explore this to arrange in all possible ways so consider we are running the array one two three two one and another array three two one four seven so one possible way of finding one possible array is one possible maximum length array is three to one One D that is the maximum length sub array and if we are having and one here and here also we are having a one then obviously the length will become 4. so let us take some other example and see uh what can we can take one two three two one four let me consider this array so consider we are having an array of like this two one four seven so uh what will be the maximum length of the subway the water will be the maximum length of the common sabary uh obviously we can take one particular sub array is to one four seven and another particular summary this is one way another is two one four seven three two one four so this is another summary so this is the maximum length for this uh example is obviously four so how can we uh so uh since I'm taking all possible ways I'm going to think of some recursion solution uh where we can Implement uh by taking all the possible ways how we can write the recurrence relation let us go for it first we can represent two arrays in terms of their indices so first there are two arrays so obviously we are going to represent it in 30. two cases two indices inj so I am going to call the recorder I mean from the main function I'm going to call the function solve nums one nums 2 I will pass in the 0 comma zero index 0 and 0. so I'm saying that this function is going to return me the maximum length sub array maximum length of that sub array which is common to both the arrays so uh what will be the recurrence relation will be if my there may be two options if my nums one nums 1 of I now uh is equal to my nums 2 of J then I can call that can I can have one option which is foreign s are equal that is this 3 and this 3 is equal so what I will be doing is I will be moving both I and J so in my next request is called so I plus 1 J plus 1 this will be my option else there will be another uh two options either I can move one point that I plus 1 or J plus 1 so option one will be solve of nums one nums to I plus 1 J remains same and there will be another option i j Plus 1. so this will be the two options uh let me name like this option one option two option three so but whenever I'm doing that I cannot carry a one here because if I do one or if this is equal I am going to increase the length of the sub array by one so I'm if I add one plus then obviously this may become a subsequence so we I should maintain it has a sub array itself so I will be taking an extra parameter and going to pass the length as well so length plus one whenever two elements are equal then the length of the sub array will be incremented by one whenever it is not equal the length of the sorry again starts from 0 because I am calculating the summary which is configuration so finally I am going to return the maximum of all the three options option one option two and option b so this will be my recurrence relation so let us try to code this and check whether it is running so I'm going to get the size of the array items nums one dot signs and Indian equal to nums 2.6 and Indian equal to nums 2.6 and Indian equal to nums 2.6 American Salva times one nums 2 0 and the length of the subway starts with zero and M and N this is going to be written by the maximum density are going to define the function solved in so all right then um send and I'm just one um length I will name it as length and this is what will be the base condition if my eye has reached m or my J has reached again obviously I am going to return 0 because they have accelerated the boundaries orders what I can do is I can have three options option one zero option two zero and option three zero if my nums one of I is equal to my nums 2 of J then what will be the recursive function option one is nothing but solve of nums one nums to both I and J will be implemented by one and my current length is incremented by one since the current element is equal in both the arrays and M and N as well else there will be two options either I can move or J can move so nums 1 numbers 2 I plus 1 J and length starts from 0 because it is continuous m n and this is option two and this is option three here option three I will be remaining the same and J will be I'm gonna be one so finally returning the maximum of all the three option one comma option two um yes okay let us try to run our code this will be the recursive solution here the time complexity will be exponential definitely let us try let us see why what is spinning here um okay actually we are actually updating we are actually uh having this as a parameter I am not this function is not going to return me anything this function is just having the answer in answer as another parameter so I should have a global variable I will declare a variable answer and I'm going to calculate this answer as length this answer is Max of answer comma length so now let us write oh no finally I should return answer okay return and now it should be and because I'm updating the answer now here answers and answer command length okay let us observe what is happening here um what will be the problem actually I even if it is not same I should run both this option one and option four I guess so actually we try we don't want to have an uh Global variable because this may be uh very tough to convert into a memorization because we are having a global variable so we will try to change our recursive solution itself whenever I come inside this loop I am going to I'm going to have one variable in answer which is going to store the length so what I'm doing is even I'm returning the maximum of all these options either answer or option one or option two or option three so finally I'm just returning this function so this let us see whether it is working now okay we are getting one less than okay what's happening Josh okay this it is quite since Ray Castle solution it is quite yes but let us see um this option one I will name this option one to be length because this option one is considering when it is same else it is not same so it should start from the length star from the current length or else it will be definitely wrong right it will be not uh it will be not clear if I'm naming like this option one option or something if this is equal elements means it should start from latest we have calculator you consider we are in some recursive call and during that recursive call we have calculated a two length sub array and even now the current length sub array is also equal currently current element in both the arrays is also equal then the 2 is going to become 2 plus 1 3 so this if condition should be having the same variable rate so equal elements should be calculated as numbers 1 numbers to n plus 1 J plus 1 and the current length will be incremented by one so that the second equal elements will store the current lengths uh value the incremental length and this option 2 and option three can be zero initially or else I can here I can declare here I don't want option one option two I will declare another variable name let us see different elements from N1 and similarly this is different elements from N2 that there are two options either I can move forward or J can move forward staying I and J and the length will be starting from the zero so finally I am going to return the maximum of this equal elements different elements and different elements N2 so this will be our case right yes I guess because before previously I have initialized this equal elements to be zero that is completely wrong because each and every time this equal elements will be starting from zero let's try to run this code and see whether it is getting accepted um what is happening am I missing somewhere something okay let us okay finally if this is reaching the size of the allowance I should return the length or else how it will get computed yes since I'm carrying the carrying it as a particular parameter in this recursive function obviously I am going to return this length I should not return zero orders it will give us wrong answer right um that is the problem here yeah I have returned 0 when I reach the length I'm just returning 0 then I'm not calculating I am not taking into this account this length itself okay now let us try to memorize it we should see what are the changing parameters there are three parameters links so we are declaring uh three dimensional array Vector affected DP of size m and the vector of vector and of size n and then another size Vector of int which is I can say it has 1001 minus 1 because the maximum length of the sub array will be 1000 only if all the both elements having a thousand and thousand length equal elements so now let us pass this parameter as in our recursive function as well with reference and I should pass in all the recursive calls mdp DP and let's show the consider one case DPF IG of length is not equal to minus 1 then return DP of ieg i j length and I should memorize it if my DP of i j is already computed I should test it so now let us try to run our code this will be the memorization and the time complexity here will be order of n into M into this length so let us try to run our code about the exam test cases as well so it gets accepted let us submit the code um I think it will get memory limited yeah so as expected we get the memory limit exceeded so see how to memorize how to optimize this so we should eliminate one dimension so we can have two dimensional array vector or vector in and this is our size sort of end Vector of NDM gamma Vector of end is of size n and minus 1 initially and this will be the two dimensional array of DP and I have eliminated this length so how I should do is I should have a reference variable answer and here I will declare answer to be 0 initially and passing this answer and finally I am returning the answer at the end of the day so I'm going to call this recursive function now what I'm doing is and so and this will be whenever I reach the end of the boundary I'm going to return 0 if there is an equal element then I will be adding one step to that element so that I am I was told so that I am calculating the length as well so whenever there is a Toyota equal elements in both earrings will be increased by one and then initially the curve equal to zero the current length will be zero and this current length will be updated here um the instead of this current length this equal elements itself you can have it another equal to Max of energy comma the equal elements and finally returning the maximum of equal elements difference one different two but here we don't want to calculate this because we want to memorize it in such a way that it is storing only the sub array that is contiguous elements so we don't want to even we are getting we are taking these two elements we want to store the elements which is having a the length maximum length summary so we can just show this equal elements into the DP of IJ in that is to the index I will J there are there is a length equal elements so this builds store that and DP of i j is not minus one then we can just return minus 1. this what it represents is dpfij represents the maximum length of the subberry that is found from the length of the array nums one from 0 to I as well as the length of the nums 2 from 0 to 0. so that time the maximum length I am storing that's it so now let us run the code foreign yes it gets accepted hope you like the solution even now we can memorize it we can optimize this approach into a tabulation form let us see that as well so we can just make this initialize this minus 1 to be 0 and there is a 2d array initially zero what I am going to do is now we have to take care of the base condition whenever the eye has reached the boundary or J has reached the boundary I am just returning the zero that is for each and every low for each and every i n i equal to 0 I less than M A plus nums 1 of sorry DP of i 0 will be having a length 0 only similarly for in J equal to 0 J less than n j plus DP off 0 J will be having a length of sub array 0 only so this will be the base case now I will have a answer variable in times or equal to 0 now what we can do is foreign we can try to run it as a for Loop run it as an iterative manner uh here the United manner from i 0 from 0 it is going till yeah so that we have to write it in opposite fashion so in I equal to M minus 1 I greater than or equal to 0 I minus J equal to n minus 1 J greater than or equal to 0 J minus and copy paste the returns relation the just copy the paste this code if my numbers are one of Y is equal to terms 2 of J then the equal elements will be 1 plus DP of I plus 1 and J Plus 1. hours there will be two cases here ah these two cases can be these two cases are actually for the these two cases are just actually for uh the uh taking all possible ways so we can eliminate in America's way and we can just say DP of i j to be 0 and here we can just store DP of i j or else to be more clear we can eliminate this part and we can just store DP of i j equal to equal elements and we can say DP of i j is initially zero here the DP of IJ is calculated to be 1 plus this one and we can admit this code as well so here actually what we are doing is we want to eliminate this oh we don't want this and this DPF is the answer should be maximum of answer comma DP of i j and this also we can eliminate it and obviously we don't want this code which we are declaring the whole size of DP it starts to be zero and this is M plus 1 and M plus 1 because I am accessing I plus 1 and J plus 1 so I'm keeping it as an indexed extra one and finally and just returning answer so now let us try to run our code this is an ittm approach so let us make this code as well so this is the bottom up approach and we can submit our code so yeah this is the tabulation form and hope you like this video let us know let me know in the comments let us see in tomorrow's challenge until then bye
|
Maximum Length of Repeated Subarray
|
maximum-length-of-repeated-subarray
|
Given two integer arrays `nums1` and `nums2`, return _the maximum length of a subarray that appears in **both** arrays_.
**Example 1:**
**Input:** nums1 = \[1,2,3,2,1\], nums2 = \[3,2,1,4,7\]
**Output:** 3
**Explanation:** The repeated subarray with maximum length is \[3,2,1\].
**Example 2:**
**Input:** nums1 = \[0,0,0,0,0\], nums2 = \[0,0,0,0,0\]
**Output:** 5
**Explanation:** The repeated subarray with maximum length is \[0,0,0,0,0\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 100`
|
Use dynamic programming. dp[i][j] will be the answer for inputs A[i:], B[j:].
|
Array,Binary Search,Dynamic Programming,Sliding Window,Rolling Hash,Hash Function
|
Medium
|
209,2051
|
1,653 |
Hello Hi Everyone Welcome To My Channel It's All The Problem Minimum Delhi To Make A String Align With Your Given String Is Consisting Only Of Characters In The Easy You Can Delete Any Number Of Characters In Add To Make Gas Balance Acid Balance Television Repair Office Icon Because Zee Beach Means A To Find The Point Where All Character On Left Side Right Side So It's Not Mean That To Medium Character Delhi To Do Subscribe Video Ben10 810 And Will Start From Going Forward From Thee Is B-Tech The Hour Mein Like Full string Thee Is B-Tech The Hour Mein Like Full string Thee Is B-Tech The Hour Mein Like Full string after first veer is the spelling of but oo find out how to right side 2002 192 pages pe account it is 000 will find this from the right side will be plus the number of the right side of the intellect will give what to do this This Is To Find Every Possible Amidst Hour's Veer Check Again Right Side Dhund China Have Only One Love Affair Initially Dr Plus 2 And Vwe Minimum In All Possible Cases Will Continue Till Vikram Is Like To Do New Year All Solutions To Reel Soidi Arabs Vikram Three Minimum All Possible Subscribe The Amazing In The Case Against The First Dravid And China's Policy Channel Subscribe Plus That 555 Finishing Line Was Vikram And Share And Inventors Pay Minimum System 10th Over 100 Injured Ace Will Continue To A total 20 2012 minimum this is the way will solve this problem not only solve but also like this point to right side subscribe our string of time and internal check for every day of any solution for improving solution way that in one pass will count how many players At every Indians and right side basically favorite index and no women from plus 2 and sorry for calculating so let's check the Amazing Amazing Amazing so will take the same size for the length of the chilli one point Subscribe 12345 Subscribe All Rights Reserved Quote First 20 can throw and counted these from the right side 2018 starting from examination which will be defeated even otherwise phone danish starting from nh-2 2820 n phone danish starting from nh-2 2820 n phone danish starting from nh-2 2820 n update bewafai plus vansh director david dhawan otherwise they created are after no veer is like you will Be the day from this point note also check dam half the result different minimum of the result of the right side subscribe and every time you quantum of force increment now account and also Niti Ke Citizen India and I don't have also been checked before every possible Laash Chamkin Ki Delete So This Is Web Check In India And Before Returning Will Check In This Case Will Happen Result Will Always Be Maximum No Know That No Airtel So Example Like This Method Maximum Services Video subscribe The Channel Please subscribe and subscribe the Running Contest Father of the World is the Current Solution Contest Video then subscribe To My Channel thanks for watching
|
Minimum Deletions to Make String Balanced
|
number-of-good-leaf-nodes-pairs
|
You are given a string `s` consisting only of characters `'a'` and `'b'`.
You can delete any number of characters in `s` to make `s` **balanced**. `s` is **balanced** if there is no pair of indices `(i,j)` such that `i < j` and `s[i] = 'b'` and `s[j]= 'a'`.
Return _the **minimum** number of deletions needed to make_ `s` _**balanced**_.
**Example 1:**
**Input:** s = "aababbab "
**Output:** 2
**Explanation:** You can either:
Delete the characters at 0-indexed positions 2 and 6 ( "aababbab " -> "aaabbb "), or
Delete the characters at 0-indexed positions 3 and 6 ( "aababbab " -> "aabbbb ").
**Example 2:**
**Input:** s = "bbaaaaabb "
**Output:** 2
**Explanation:** The only solution is to delete the first two characters.
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is `'a'` or `'b'`.
|
Start DFS from each leaf node. stop the DFS when the number of steps done > distance. If you reach another leaf node within distance steps, add 1 to the answer. Note that all pairs will be counted twice so divide the answer by 2.
|
Tree,Depth-First Search,Binary Tree
|
Medium
| null |
131 |
It will come in this video, we will fold this question, at this time all the ringtones in partitions, see what is this, joining the question is also better than fixing ADEN, you can break it into rooms in as many ways as possible, first you have to leave it like If you separate each character then put each part of it in half in fluttering and separate this also or you separate it first and separate the middle baby and separate the last one or you separate it together in the beginning. Keep A, B and C of last separated or put them together in the middle like this b.ed all these pattis will take care of you b.ed all these pattis will take care of you b.ed all these pattis will take care of you so all these pattis are in minutes this here this in all four directions Here these two A Pappu have to be input in this way. Create as many methods as you have in both the houses. And to print from it, what can we do? We will take labels. This question was put to Question Singh. This was the campaign Something Like. So, what is the option service? I will remove it from the shift side in the option, yet I will do it in the same way that if I take out this much entry, then by taking out the entry which I take out in the printer, the rich of the call in which the simple one is taken out and the call is made from the hook question. Took it out because it is okay in one of the calendars, I took out one and the question remained, Eid, which made it - the took out one and the question remained, Eid, which made it - the took out one and the question remained, Eid, which made it - the first one is this - the question is this and first one is this - the question is this and first one is this - the question is this and in the answer this is okay, now I ca n't control AB, I don't want to try my service, this is what happens I don't have any different method, BJP leader is Om, so this time we will use this also, so in this case also, SEBI, these shortcomings are really a question, tell me and don't in the answer and these are formed together, this is also the reason behind Gomez Chief Question. So this first tip is that these people have added this second option out of hatred for the A B A exam. I have made this for you and now if you use it then the children will be amazed and the team will enter on Thursday itself. Use it as much as you want, there is one option, A Big B. Now you can use it absolutely, you can put it here, you can also share it, you can use it, but you can use it baby, if I use it, then you can also use it in this. That subscribe is Bei Dao and one so you can also appoint this can do this see this now let's decide if your subscribe goes out if pregnancy then you can use this and can use now school Now let's talk about this, if I use this means some orders completely, then this will be adopted here, or if you also use this, then this of the child. B blazo finally take this to bigg boss subscribe this is one body engaged in different and different exams half lag dhindsa with these chief subscribe to life or age is nothing if you like the products in spring I'm in this form continuously lion subscribe plus one here come from that till the next what happens from that so let's now we have to check is it is that it is not okay so I checked if it got this prank if it got it I got So we felt that if no one will sing again then we have to open it after getting anything, if we get good returns, then the question was whether there was a drink in it, restaurant or will it be left, if we come from the districts, then we saw that if we ate from zero, then we got plus one and only you are in this. By taking the lemon back till the end you will get that this is the time of the child Yashwant Singh answer inside the sopa you will add it by putting a box and write the basic school annual function the criminal cigarette is not there the Indian [ __ ] Indian [ __ ] Indian [ __ ] I have to go here that I think now we Can print this dynasty yes printed this just this quarter inch passed by drinking the juice of the union am I a hungry corporation or not [ I a hungry corporation or not [ I a hungry corporation or not were the police trod toe employees will use it the alarms I kept left But in the last few days, as long as the hair on the left side is short, the action will take place, the character will come with the left leg rap look with the come with the left leg rap look with the come with the left leg rap look with the right toe, this kind of daughter of if it is not equal with the subscribe, then this cannot be so then what can we do Do subscribe, if you subscribe then I feel that it is going on and it is going on, it is expected that I understand that thank you very much in the question.
|
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
|
797 |
hello friends today less of the old parties from source to target problem that first see the statement given a directed acyclic graph of a notes find opers both parties from note zero to note and minus one and return them in any order the graph is given as follows the noes are 0 1 to graph the lens -1 the noes are 0 1 to graph the lens -1 the noes are 0 1 to graph the lens -1 graph I is a list of all nodes J for which the h IJ exists so what how its graphs are represented let's see what does this mean it means there are two no the zero is connected to choose no the one in nodes at you and this means no the one is there is connected to notice three so another one connected to node 3 and this means no the two its connect you know three so notice there is connect you know three and this means notice three time to connected with other nodes because it is directed so there are no other those start from the no three so because we have to return other pulses so we can synchro use backtracking and because backtracking is used to exhaust a search exhausted a search we need to search every purple horsies so we need a we need our help function because we can pass more parameters to this function so basically this is the idea we started from the node 0 and we try to go to the next node until we reach the end if the like the very last year no that is the minus 1 we find a valley the purse so we add them to the result list if not we just ER go back and the keep search so let's write a code first I we needed our result her least new ArrayList then we need a earth temporary listen temporary array list and the will shooter first add a zero because we start from there zero and then we call the help function we pass a result press Oh graph and the current note that we needed to record a current node is zero and the temporary list finally we just a return the result so in case we use the help function and the first parameter is a result integer that will be result ender this is a graph right and a current a node and this is a temporary node so as either recursion so we need a base case this case is the current node it is ego tutor grabbed all ends minus one because if it's reach the reason and minus one we have find a valid parse right so we result add as a new array list you should be familiar with this part we cannot just turn directly after the temporary list because in Java the function pass by there another function is parser address so if we add just the editor temporarily say you know their value will change so we should as like the snap shop so we new released and apprise the current value in the temporary to the result list and their return for recursion Paris we try to find the next node if there is a graph current node its value and we add them to the temporaries do the recursion part result a result graph so now the current node become to their necks and their person temporary node so when we backtrack we will remove the last term note that I will be the last note there will be the temporary size minus one so I say I finish it okay thank you for see you next time
|
All Paths From Source to Target
|
rabbits-in-forest
|
Given a directed acyclic graph (**DAG**) of `n` nodes labeled from `0` to `n - 1`, find all possible paths from node `0` to node `n - 1` and return them in **any order**.
The graph is given as follows: `graph[i]` is a list of all nodes you can visit from node `i` (i.e., there is a directed edge from node `i` to node `graph[i][j]`).
**Example 1:**
**Input:** graph = \[\[1,2\],\[3\],\[3\],\[\]\]
**Output:** \[\[0,1,3\],\[0,2,3\]\]
**Explanation:** There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
**Example 2:**
**Input:** graph = \[\[4,3,1\],\[3,2,4\],\[3\],\[4\],\[\]\]
**Output:** \[\[0,4\],\[0,3,4\],\[0,1,3,4\],\[0,1,2,3,4\],\[0,1,4\]\]
**Constraints:**
* `n == graph.length`
* `2 <= n <= 15`
* `0 <= graph[i][j] < n`
* `graph[i][j] != i` (i.e., there will be no self-loops).
* All the elements of `graph[i]` are **unique**.
* The input graph is **guaranteed** to be a **DAG**.
| null |
Array,Hash Table,Math,Greedy
|
Medium
| null |
1,218 |
hi everyone wit Calvin here so let's discuss about weekly contest for a 57 second question longest active it might take subsequence of given difference so we are given array and then we've been asked like the subsequence that can form an aromatic with constant difference according to the input so for example on the first one so the difference is 1 so this is the sequence immediately 1 2 3 4 so the longest one is 4 and on the second one 1 3 5 7 so this is like a difference of two arithmetic and we because only the difference of 1 so in that case the line will be 1 because only each of the number itself is the longest arithmetic with difference of 1 and see that there example so difference is minus 2 so subsequence means it's not an contiguous array so here you can see 5s 7 5 3 & 1 array so here you can see 5s 7 5 3 & 1 array so here you can see 5s 7 5 3 & 1 is the longest arithmetic subsequence so 7 5 3 1 so we written a 4 in that case so how are you going to solve this question so we can do a map to remember what is the longest sequence we met before this character so for example like if we see a number 7 we want to know like before 7 instead of 5 frame instead of 5 axis and when we try to when we count of 5 we wanna know like his 3 axis or not right so what we can do is we can create a hash map to remember previous character we met and how many sequence before it so for example in this case if we already have 5 when we try to find 7 we know there is a 5 axis and how many subsequence do 5 facts before so let's say it's a 2 right so here we will get a 3 so here 3 comma 1 because 3 is the first character we met and when we met 5 so we know there is a 3 with subsequence of one so when we met five we updated to become two when we met seven we searched for five so we know five have longest subsequence of two so seven three and then that is our output so as you can see here we credit catch and then we look through the array and then for that array number the longest subsequence will be the array itself - subsequence will be the array itself - subsequence will be the array itself - the difference if that number exists before or not so if it's not we put a zero for the subsequence link and if it is then there will be at least one and then we plus another one there - the then we plus another one there - the then we plus another one there - the catch so after that we just looked through the entire hash map and we can get the longest the highest value from for the fit in the hash map so one two three and then we will get the tree so index in this case the memory we use is at most o n for the catch so that's it thank you for watching see you on the next we click on test
|
Longest Arithmetic Subsequence of Given Difference
|
lowest-common-ancestor-of-deepest-leaves
|
Given an integer array `arr` and an integer `difference`, return the length of the longest subsequence in `arr` which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals `difference`.
A **subsequence** is a sequence that can be derived from `arr` by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** arr = \[1,2,3,4\], difference = 1
**Output:** 4
**Explanation:** The longest arithmetic subsequence is \[1,2,3,4\].
**Example 2:**
**Input:** arr = \[1,3,5,7\], difference = 1
**Output:** 1
**Explanation:** The longest arithmetic subsequence is any single element.
**Example 3:**
**Input:** arr = \[1,5,7,8,5,3,4,2,1\], difference = -2
**Output:** 4
**Explanation:** The longest arithmetic subsequence is \[7,5,3,1\].
**Constraints:**
* `1 <= arr.length <= 105`
* `-104 <= arr[i], difference <= 104`
The node of a binary tree is a leaf if and only if it has no children. The depth of the node of a binary tree is the number of nodes along the path from the root node down to the node itself.
|
Do a postorder traversal. Then, if both subtrees contain a deepest leaf, you can mark this node as the answer (so far). The final node marked will be the correct answer.
|
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
1816
|
146 |
alright guys let's start it today's video so today's video is about the code number 146 our ru cash so it's a very typical and very interesting problem so let's look at it so s-- asked us to design and Ibelin so s-- asked us to design and Ibelin so s-- asked us to design and Ibelin implement the data structure for least recently used cash issue support the following operations get and put so get a key so that work at the value of a key if the key exists in the cash otherwise return negative 1 put so settle insert the value if the key is not already present when a cash to reach it reached its capacity issue d even varied at the least recently used item before inserting a new item okay so let's take an example before we approach this problem so okay so for example we have numbers like 1 three for three fight and we want to enter into the cash but the capacity say is three then when the number one calm it will enter the cash one then number three calm you know when enter the cash three okay it's good number four came then enter four here and number three come again so when number three come again we should definitely replace number three and since we do operations on number three we should move three to the most recent one so firstly we'll replace it so operation one is to replace it pushing - should be pushing - should be pushing - should be move to front okay so then number five came the number five came unfortunately we see that it reaches its capacities so we need to delete something so which one should we delete so in order to determine which one should we did we should do it we should set up a new list say here we use a key a Q so Q Sapporo's first-in use a key a Q so Q Sapporo's first-in use a key a Q so Q Sapporo's first-in first-out okay so now we put 5 in and we first-out okay so now we put 5 in and we first-out okay so now we put 5 in and we should pop out one so how to determine we should pop out one not three or nor four so when we append one we shop and 2 Q when we append 3 and 2 Q + 4 + 2 Q on Q when we append 3 and 2 Q + 4 + 2 Q on Q when we append 3 and 2 Q + 4 + 2 Q on my pants 3 again we moved 3 to the most recent one so here so when we want when the number of total number reaches the maximum cash we should always pop the leftmost 1 because the leftmost needs to use the 1 so that's the algorithm we are going to use so okay as start coding so cash so it's really a hashmap yourself duck you because it's in Python we do it as a Duke you okay so here we the use of q2 Starkey the case the most recently used one the round least-used one shoot the deck the round least-used one shoot the deck the round least-used one shoot the deck each time we pop from the left okay now we try to implement this CAD function so if the key we want to find is not in cash and we return 1 else if it is in cash then we need to do what we need to do is to return the cash key but before return cash key you probably want to move the key it should be the most recent one so what we do is to earthly key from the queue then append it and it okay so that's good for the gut function let's do the foot function so again the key is not okay now say the key is in cash then we should update the variable itself that cache key evil now we update it update the value and also we should move it - should move it also we should move it - should move it also we should move it - should move it to the front of the Queen so what we do is to remove it first move it first and append it else it was key it's not in the cache of course we should set the cache key it goes to value and also we should kill the parent key you depend the key however there's a possibility that dance of the queue is larger than the capacity order the capacity then we should delete one element out of the key out of the queue so which one should we delete we should see okay we should build it the least used one which is the leftmost one in the in a queue we defined is to use the one equals Q the top left so we should also from the cache so that's probably good let's try to submit it okay looks right submitted okay now the pasta test so which is good hmm let's look at the description again so the follow-up question for this so the follow-up question for this so the follow-up question for this problem is can you do both operations you or one time complexity it's noted that if we use a Cree the remove function will require us to operate in the oven time also here it is also all the time so both operations of get and put with the own time which is not good for the follow-up question so what for the follow-up question so what for the follow-up question so what should we do so unfortunately we it's not easy for us to do using a queen however we should be able to do it using the already existed package offered by Python so it's called ordered dictionary so it's a dictionary that support some operations in a one time so it's called ordered dictionary it supports move to and you know one time also is our papa just because you're true of course depending on which one you want to pop so okay let's use the order joke dictionary in Python self dot say cash is collections that dictionary our dictionary other dictionary should be defined like this - because soft - because soft - because soft okay with the help of order of dictionary we can do a lot of operations in a short amount of time so that's realize the gut function if not in cash else then we should return before that we should do for that we should move the key to the front so we need to use the book to move to end function offered by order dictionary so it's self cache that's very easy okay we'll go put so if I put we should also say okay in itself that cash came in after cash then we should renew the value so cash because also we should move the key to the end cash okay it's not in the cache that we should pancake to cache also so that's right also we should move cash to Dan okay or just a pen yeah that's yeah we can we don't need to move here because it's a penny there should be at the very end because that's the last one to add from so okay so that's good I said cash key equals value then we danced capacity we should pop something out she left most one out so that catch up okay that should do it let's try to run it looks good this is much faster because this is a one-on-one operation so thank you for a one-on-one operation so thank you for a one-on-one operation so thank you for watching if you like my video please share my video to your friends also you can upload my video or subscribe to it my name is Jimmy thank you bye
|
LRU Cache
|
lru-cache
|
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**.
Implement the `LRUCache` class:
* `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`.
* `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`.
* `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key.
The functions `get` and `put` must each run in `O(1)` average time complexity.
**Example 1:**
**Input**
\[ "LRUCache ", "put ", "put ", "get ", "put ", "get ", "put ", "get ", "get ", "get "\]
\[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[4, 4\], \[1\], \[3\], \[4\]\]
**Output**
\[null, null, null, 1, null, -1, null, -1, 3, 4\]
**Explanation**
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // cache is {1=1}
lRUCache.put(2, 2); // cache is {1=1, 2=2}
lRUCache.get(1); // return 1
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
lRUCache.get(2); // returns -1 (not found)
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
lRUCache.get(1); // return -1 (not found)
lRUCache.get(3); // return 3
lRUCache.get(4); // return 4
**Constraints:**
* `1 <= capacity <= 3000`
* `0 <= key <= 104`
* `0 <= value <= 105`
* At most `2 * 105` calls will be made to `get` and `put`.
| null |
Hash Table,Linked List,Design,Doubly-Linked List
|
Medium
|
460,588,604,1903
|
1,822 |
welcome to Pomodoro doe for Tuesday May 2nd 2023. today we're doing lead code problem 1822 sign of the product of an array this is an easy problem there is a function sine func X that returns one if x is positive negative one if x is negative and 0 if x is equal to zero you are given an integer array nums let product be the product of all the values in the array nodes return sine Funk product and then they have some examples all right so this one's pretty straightforward I think the only things that we really need to note are how do we end up with a positive product a negative product or a zero product all right so for a positive product well if we have a positive number times a positive number that will always give you a positive number no matter what if you have a positive number but you multiply that by a negative number well then that's going to end up giving you a negative number if you have a positive number well actually we've already done that let's go to our negative numbers if you have a negative number times a negative number that will give you a positive number so a negative times a negative is a positive so that's our key Insight on this one and finally how do you get zero well no matter what you have if you have a positive if you multiply it by zero you'll get zero and if you have a negative and you multiply it by zero you will get zero so these are all of our options two positives make a positive and a negative make a negative two negatives will make a positive and anything times zero will result in zero so really what we need to do here is just go through if we find only positive numbers then it's going to be a positive number if we only find negative numbers well then we have to keep track of the negative numbers because this will be flipping back and forth if you have a negative times a negative then that will flip it back to a negative so basically we need to count the negatives here if we only have positives we'll end up with positives if we have positives and negatives and are mixed then we need to count how many negatives we have so if we have an even number of negatives it's going to result in a positive if we have an odd number of negatives it will result in a positive times a negative which will result in a negative and if we ever run across a zero we'll return zero okay so with that we will put 25 minutes on our Pomodoro Timer and get started okay because our result really only depends on how many negatives we have and in fact it only depends on if we have an even number or odd number of negatives we can just keep track of do we have an even number or odd number of negatives so far so our result will start out as we'll just start it as one because that's going to be our default if we just have positive numbers we'll end up with a result that's one and at the end we'll return our result all right so then for every number in our nums let's check to see if this one is positive or negative if the number is negative so Less Than Zero well let's see we could keep track of how many negatives we have or we could just flip our result from being whatever it is now to being the opposite so if it's a negative it'll become a positive if it's a positive it will become a negative so let's do that so our result at this point will just equal negative one times our result so if our result is a positive number so far and this number is a negative number then our result will become negative if our result was a negative number so far and this is a negative number then a result becomes a positive so it turns into positive one here and if we ever get a zero then we'll just return zero all right so I think this should do it all right let's start our result as one then we'll go through for every number in our nums if we find a negative number we need to flip our result from being a positive to a negative because we're multiplying by one more negative if we ever run across a zero then we return zero at the end we return our result so let's check this out and that works let's see how we do and we pass and we do quite well actually I'm kind of shocked we beat 93 for run time and seven percent from memory that's not bad at all right I probably can't improve on this at all but I'll show you one other thing we could do but we probably don't want to do it this other way but I'll show you anyway all right so instead of having our result here we'll keep track of our count let's say negative number account started as zero anytime we get a negative number we'll just increment our count if we ever run across a zero we'll still exit with our zero now down here instead of returning some result we'll return count mod 2. so not quite if you do account mod 2 this will tell you if it's even or odd if this is even this count mod 2 will be zero if it's odd this count mod 2 will be one so modulo 2 is basically saying what is the remainder if I divide count by two so if it's an even number divided by 2 there is no remainder it's evenly divided by two if it's an odd number then the remainder will be one so we can say We'll return negative one if count mod 2 is equal to 1. else we'll just return one all right so this should do the same thing we're just keeping track of the count of odd numbers if it's odd then we return negative one if it's even we'll return one and if we ever run across zero we return 0. all right so this passes it doesn't do quite as well we only beat 66 for runtime and seven percent from memory so it's not quite as efficient as our previous solution I think because we're doing the same thing essentially we have one operation per Loop where in this case we're adding one to our account in the previous solution we were multiplying our result by negative one potentially but at the very end the main difference is we do have to do this modulo operation which takes a little bit more time than simply just returning the result all right so that's it for me this one's pretty simple there's a lot of different things you could try with this so different things you can play around with so check it out see if you can do better than what did we get we had a 93 yeah see if you can beat that I bet you can all right hope you enjoyed this hope you had fun hope you learned something hope you can go out and write better code
|
Sign of the Product of an Array
|
longest-palindromic-subsequence-ii
|
There is a function `signFunc(x)` that returns:
* `1` if `x` is positive.
* `-1` if `x` is negative.
* `0` if `x` is equal to `0`.
You are given an integer array `nums`. Let `product` be the product of all values in the array `nums`.
Return `signFunc(product)`.
**Example 1:**
**Input:** nums = \[-1,-2,-3,-4,3,2,1\]
**Output:** 1
**Explanation:** The product of all values in the array is 144, and signFunc(144) = 1
**Example 2:**
**Input:** nums = \[1,5,0,2,-3\]
**Output:** 0
**Explanation:** The product of all values in the array is 0, and signFunc(0) = 0
**Example 3:**
**Input:** nums = \[-1,1,-1,1,-1\]
**Output:** -1
**Explanation:** The product of all values in the array is -1, and signFunc(-1) = -1
**Constraints:**
* `1 <= nums.length <= 1000`
* `-100 <= nums[i] <= 100`
|
As with any good dp problem that uses palindromes, try building the palindrome from the edges The prime point is to check that no two adjacent characters are equal, so save the past character while building the palindrome.
|
String,Dynamic Programming
|
Medium
|
516
|
1,540 |
hey everybody this is larry this is q2 of the recent bi-weekly contest of the recent bi-weekly contest of the recent bi-weekly contest can convert strings and k moves so i actually uh for example this problem there's one trick case to begin with uh which is that um which is if the links are not the same i actually ate five minutes of penalty for this um i think and i was actually looking for it during the contest but i think i just had assumed even though i didn't see it maybe i misread it slightly um but i was looking for it i was like you know i guess i'll be okay but yeah uh kind of a crappy test case but nonetheless the how you actually solve the problem right well um basically you just count how many for each character you line them up or for the string you line up the string so that for each count you line up and then calculate how many shifts you would need to apply to get from s to t right and note that if you have to use the same operation more than once it takes an additional 26 times or 26 uh moves to get to there and then from that it's just math to get what's the max move that would take and then if that max move is less than k then it's true and less than or equal to k then it's true otherwise it's false and that's basically what i did i put everything in a or i have a counter and then for each of these the only two cases right where um uh the t character is after a so we just take the difference the delta and uh add one otherwise we take uh we roll over right and then we plus one so like going from z to a is one and so forth right um so that's basically what this does um and we also have to ignore the zeros but other than that we just for every one other than the first one you take an it will take another 26 right so that means that for example uh in this case a b um the first a to b will cause will take the first move and then the next one will take the 27th move and so forth right and then the dirt if there was a dirt one then it would take uh the 50 third move or something like that right maybe my maps are but you get the idea so that's basically how this uh form uh formula comes up and then you take the max of these moves because you know that's the latest uh that it would take right so that's kind of the problem uh you can watch me solve it live right about now hmm um okay hmm let's go hmm oh oh why do they have to be the same that's annoying that actually i was looking for that
|
Can Convert String in K Moves
|
can-convert-string-in-k-moves
|
Given two strings `s` and `t`, your goal is to convert `s` into `t` in `k` moves or less.
During the `ith` (`1 <= i <= k`) move you can:
* Choose any index `j` (1-indexed) from `s`, such that `1 <= j <= s.length` and `j` has not been chosen in any previous move, and shift the character at that index `i` times.
* Do nothing.
Shifting a character means replacing it by the next letter in the alphabet (wrapping around so that `'z'` becomes `'a'`). Shifting a character by `i` means applying the shift operations `i` times.
Remember that any index `j` can be picked at most once.
Return `true` if it's possible to convert `s` into `t` in no more than `k` moves, otherwise return `false`.
**Example 1:**
**Input:** s = "input ", t = "ouput ", k = 9
**Output:** true
**Explanation:** In the 6th move, we shift 'i' 6 times to get 'o'. And in the 7th move we shift 'n' to get 'u'.
**Example 2:**
**Input:** s = "abc ", t = "bcd ", k = 10
**Output:** false
**Explanation:** We need to shift each character in s one time to convert it into t. We can shift 'a' to 'b' during the 1st move. However, there is no way to shift the other characters in the remaining moves to obtain t from s.
**Example 3:**
**Input:** s = "aab ", t = "bbb ", k = 27
**Output:** true
**Explanation:** In the 1st move, we shift the first 'a' 1 time to get 'b'. In the 27th move, we shift the second 'a' 27 times to get 'b'.
**Constraints:**
* `1 <= s.length, t.length <= 10^5`
* `0 <= k <= 10^9`
* `s`, `t` contain only lowercase English letters.
| null | null |
Medium
| null |
997 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem find the town judge we're given a town where there are n people labeled from 1 to n so already this is kind of looking like a graph problem setup and then if you read a little bit below you can see well these in a graph would represent the vertices or the nodes and these down here would represent the edges but let's just read the problem first it's possible that among these people one of them is the town judge we know that a town judge exists if these conditions are satisfied the town judge trusts nobody what does trust mean in the context of this problem well we're given a second parameter trust it's an array of pairs in this case a pair a means that the person a trusts person B so again this is looking like a graph but we are told that the town judge does not trust anybody so the town judge cannot show up on this side of an edge second parameter is everybody except for the town judge trusts the town judge so if we have n people and there exists a town judge and I guess just reading the rest of this if there is a town judge there can only be one person that is the town judge so if that's the case then the town judge will have nus one edges going into them because everybody except for themselves will trust them and we have n people we have to determine if a town judge exists and if they do we will return the label of that judge and we're given these labels and if they do not exist we return-1 so the most Simple Thing Once return-1 so the most Simple Thing Once return-1 so the most Simple Thing Once you kind of determine that this is roughly a graph problem we don't really need to do like a complex traversal like a DFS or a BFS we kind of just need to check if these conditions are satisfied is there a person where the number of incoming edges is equal to nus1 and the number of outgoing edges from that person is equal to zero does a person like this exist well the only way for us to know is to Traverse all of the edges AKA like these trust Pairs and to determine that so that's exactly what we're going to do we'll take a look at this example down here it's relatively simple I will say but basically we're going to have two hashmaps because we want to count the number of incoming edges for every single person and the number of outgoing edges for every single person if we're given n equals 3 that means the people are labeled from 1 2 to 3 and now we will just go through the edges the first Edge is 1 3 what does that tell us 1 three that means the number of incoming edges for three should be incremented it should be now set to one originally let's assume these are all zeros for like the values the number of outgoing edges for one is going to be set to one because we found one Edge so far where one has an outgoing Edge so this will be incremented now to one next let's go to the second Edge it's 2 3 for this the source node the number of outgoing edges for that is going to increase by one and the number of incoming edges for three is going to increase by one as well so that's over here now it's going to be set to two let's assume the rest of these are still zero and we have no more edges left to Traverse so now go going through this we are going to check for every single person from 1 to n we're going to check do they satisfy these conditions let's check for person one is the number of incoming edges equal to n minus one no it's definitely not so one is not the person it's not the town judge what about two is the number of incoming edges equal to n minus one nope and if we were to check the other case like the outgoing edges is not equal to zero either but now when we go to the last person three are they the town judge well and - 1 is 3 - 1 which is judge well and - 1 is 3 - 1 which is judge well and - 1 is 3 - 1 which is definitely equal to two that's good do they have the number of outgoing edges set to zero yep so this is the town judge so as you can see from this solution the time complexity is going to be roughly Big O of n or let's say V plus e where I'm going to say V is the number of vertices or nodes and E is the number of edges because that's how many edges we have to Traverse the size of trust could be different than the size of N and in terms of space complexity it's going to be Big O of V because we're going to have one hashmap here which is going to have the same number of nodes that were given we're going to have a second hash map as well but that doesn't change the space there's one last thing that you might be thinking what if there are multiple people that actually satisfy this condition there's multiple people where that is satisfied because they tell us that for there to be a town judge there has to be exactly one person that satisfies these properties well my claim to you is that if a single person satisfies these conditions then by definition there cannot be a second person who also satisfies those conditions let me quickly explain if we have a person such as this one where we have n minus one incoming edges and zero outgoing edges and they don't explicitly say it here but they say it at the bottom of the description that there cannot be any duplicates in the trust array there cannot be any duplicate edges if that's true how can there possibly be a second Town judge that has nus one people pointing to them how can it be possible a judge can't point to themselves and we know that this person this town judge is not pointing at anybody so at most the second Town judge would only have n minus 2 incoming edges if that's not enough to convince you how can we possibly have two people that have zero outgoing edges and have one person that has n minus one incoming edges assuming no duplicates how could that be possible we need every other person to be pointing at the Town judge how can there possibly be a person that has zero outgoing edges if they're not the town judge it's just not possible so that's why there can only be one town judge this condition here is pretty much redundant to be honest so now let's code it up just like in the drawing explanation I'm going to have two hash Maps I'm going to declare them with default dick that just makes it a little bit easier to handle the outof bounds case so incoming and outgoing they're going to be initialized like this so we're going to go through every pair in trust in Python you can unpack them pretty easily each pair is going to be unpacked into two The Source node and the destination node of course the source node tells us which node now has an outgoing Edge so here we're going to set this equal to itself plus one but with this we'd get a key does not exist error if we were not using a default dict but with a default dict this will actually be set to zero even if the key doesn't exist so that's why we used a default dict and I'm also going to rewrite this like that just for Simplicity now we do the same thing with incoming the destination node now has one more node that is incoming to it so the number of incoming edges to this increased by one now we are going to go through every single node I in range from 1 to n and in Python we have to do n+ 1 it's not inclusive and now we check n+ 1 it's not inclusive and now we check n+ 1 it's not inclusive and now we check is the number of outgoing edges for I equal to zero and is the number of incoming edges for I equal to nus1 if that's the case return I we know only one solution can possibly exist if it doesn't return -1 after we check every doesn't return -1 after we check every doesn't return -1 after we check every single node so this is the solution I'll run it and as you can see on the left yes it does work and also when you determine that there's only one possible solution you realize that we actually can use a single hashmap and instead of counting the number of incoming or outgoing edges we can count the Delta by Delta I mean this the total number of incoming edges minus the total number of outgoing edes edges of course we know for the solution value this would end up being equal to n minus1 which is the number of incoming edges minus 0 which is the number of outgoing edges so basically this would be equal to n minus one now is there any other node where the number of incoming minus outgoing is going to be equal to n minus one no it's not really possible because even if they had n minus one incoming edges which is literally not possible at most they could have n minus 2 and we know for sure every single node is going to have at least one outgoing Edge so the max value for all the others would basically be this n minus 3 so nothing is ever going to be n minus one except for the town judge so therefore we can use a single hashmap we can do this we can say for the incoming we want to increase it by one for outgoing here we want to decrement it by one so that we can get this equation incoming is added and outgoing is subtracted and then down here all we need to check is basically get rid of this and then just check Delta is equal to n minus one this doesn't really improve the time complexity or anything I guess it just saves you half of the space but it doesn't change the big o space complexity but running the code you can see that this also works it did save us some space the run time is pretty random though I think if I ran it again it would be better if you found this helpful check out n code. especially if you're preparing for coding interviews thanks for watching and I'll see you soon
|
Find the Town Judge
|
find-the-town-judge
|
In a town, there are `n` people labeled from `1` to `n`. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
1. The town judge trusts nobody.
2. Everybody (except for the town judge) trusts the town judge.
3. There is exactly one person that satisfies properties **1** and **2**.
You are given an array `trust` where `trust[i] = [ai, bi]` representing that the person labeled `ai` trusts the person labeled `bi`. If a trust relationship does not exist in `trust` array, then such a trust relationship does not exist.
Return _the label of the town judge if the town judge exists and can be identified, or return_ `-1` _otherwise_.
**Example 1:**
**Input:** n = 2, trust = \[\[1,2\]\]
**Output:** 2
**Example 2:**
**Input:** n = 3, trust = \[\[1,3\],\[2,3\]\]
**Output:** 3
**Example 3:**
**Input:** n = 3, trust = \[\[1,3\],\[2,3\],\[3,1\]\]
**Output:** -1
**Constraints:**
* `1 <= n <= 1000`
* `0 <= trust.length <= 104`
* `trust[i].length == 2`
* All the pairs of `trust` are **unique**.
* `ai != bi`
* `1 <= ai, bi <= n`
| null | null |
Easy
| null |
1 |
hello and welcome today we are doing question number one on Leo the most popular question it is called toome we are going to jump right into it given an array of integers nums and an integer Target return indices of the two numbers such that they add up to Target you may assume that each input would have exactly one solution and you may not use the same element twice you can return the answer in any order so we want to find two numbers when summed up equal Target and return the indices of those two numbers so example one we have 2 7 11 and 15 Target is nine so what two numbers give us nine that would be 2 and seven and remember arrays are zero index so instead of starting one 2 3 4 we actually start 0 1 2 3 and which is why we will return 0 1 or 1 0 because order wouldn't matter example two we have 32 4 Target six here we output put one two because at those indices at 1 and two we have two four when added up give us the target six and example three we have 3 three Target is six and we output indices 01 we have some constraints over here we're guaranteed that we'll have at least two numbers in our input nums we have a range for every single number in nums as well as Target and only one valid answer exists so we're guaranteed an answer and only one follow up can you come up with an algorithm that is less than o of n^2 time complexity well first than o of n^2 time complexity well first than o of n^2 time complexity well first what is n^2 time complexity and if what is n^2 time complexity and if what is n^2 time complexity and if you're unfamiliar with time complexity and O of n annotation all it means is we're setting a variable n to represent the length of our input nums so let's say a nums has n elements and n s usually means we're going to have two Loops which means for every single element in nums we're going to be going through nums that many times so that's n into n or n SAR and if you have any questions with this let me know down below I will answer every single question I see so feel free to drop a question but this n squ actually Segways into our first approach because before coming up with an algorithm that is less than it let's actually come up with an algorithm that is n squ and get better from there so for our N squared algorithm we are basically Al going to be going through all of nums and making all possible pairs with our numbers if any pair equals Target then we'll just return the indices of that pair so say I had the following example I have the following input nums and Target four what I'm going to do is I'm just going to be looping through making all my pairs so if I start with my first loop I will have my first number so say I have four well now I want to pair four up with all my other numbers so I'll do four with 7 4 with -1 4 with 3 and four with 7 4 with -1 4 with 3 and four with 7 4 with -1 4 with 3 and four with five and now I want to use seven and make all possible pairs so with seven I will pair this up with negative 1 I don't need to pair it up with four again because four and seven were already covered I don't want to do any duplicates so then I will go ahead pair seven with three and seven with five and basically I'll just be doing that for every single element in my array once I get to -1 I'll pair this up with three get to -1 I'll pair this up with three get to -1 I'll pair this up with three then I will pair negative one up with five and at this point I see that this actually sums up to Target so I'll return the indices of these two numbers so that's what our solution is going to be let's go ahead and code this up so in the beginning I'm going to have one Loop that goes through the entire length of num so four index one in range of length of nums I'm going through my entire input now I'm going to have my second Loop because I want to pair that first number up with something so four index 2 in range and here I'm going to do index 1 + 1 because we don't going to do index 1 + 1 because we don't going to do index 1 + 1 because we don't want any repeats right we can just start pairing from the number after us so index 1 + 1 until the end of the array index 1 + 1 until the end of the array index 1 + 1 until the end of the array so length of nums and I'm going to check if the numbers at the two indices Su up to Target so if nums at index one plus nums of index 2 equals Target at that point all I do is I return the two indices so index one and index two and I want to return this in list form since that's what we're doing in this output so let's go ahead and actually run this code runtime error let's see what happened here so in2 is not defined this should be index 2 there we go rerun this it's accepted and we can go ahead and submit and it is accepted as well before going through our second approach let's just run through a quick example just to see what our code is doing line by line so let say we had this example right here I'm going to delete this going through it really quickly I have index one that's going to Loop through all of nums so index one starts out at index zero and index two is going to be starting at one so equals 1 until the end so zero and one we are basically over here so this is one this is my second number right here now I add these together so four plus 7 because those are the numbers at those indices that equals 11 it's not equivalent to my target which is 4 so I never go into this if statement and I never return which means I am back in this for Loop and now index 2 is going to be two so I bump this down over here I check the numbers again 4 +1 not equal to Target numbers again 4 +1 not equal to Target numbers again 4 +1 not equal to Target so then I go back into this Loop move this to three and do the same thing this is not equivalent to Target I go in here move it down this is now at five so 4 + move it down this is now at five so 4 + move it down this is now at five so 4 + 5 is 9 we don't go into this and we're actually done with this second for Loop right here so we're going to go back into our first and move this to be one so now we're done with four we're going to go into sevens now over here we start off with index 1+ one so this is at one off with index 1+ one so this is at one off with index 1+ one so this is at one which means our second number will start right after this right we don't want to repeat any pairs we're just going to start right after this so this means we are at index 2 7 +- 1 is 6 which is not are at index 2 7 +- 1 is 6 which is not are at index 2 7 +- 1 is 6 which is not four we don't go into this if statement and we don't return we're back into the for Loop we move this down over here 7 + for Loop we move this down over here 7 + for Loop we move this down over here 7 + 3 not four we go back into the for Loop move this down 7 + 5 again not equal to move this down 7 + 5 again not equal to move this down 7 + 5 again not equal to it so we are done with the second for Loop we are back into the first we move this to two this is over here and we start off at index three for our second number 3 +1 is 2 it's not four so we number 3 +1 is 2 it's not four so we number 3 +1 is 2 it's not four so we don't go into this and we go back into the four Loop move this down to four now the number at these indices so we have -1 and five this does equal four when -1 and five this does equal four when -1 and five this does equal four when added together so all we do is we return our indices so we return 2 comma 4 and that is our answer we just saw this whole thing play out and now let's see how we're going to do better than n squar so to do better than n squar we're going to be making use of something called a hashmap or a dictionary and what that is a collection of key value pairs that allows for constant time and insertion and lookup so how do we make use of that what we're going to do is iterate through our input nums and keep track of every number we've seen and the index we've seen it on for example if I have my input right here what I'm going to do is of course I start in the beginning so I start at four I'm going to go ahead and add this to my dictionary and it's at index zero so I will add that as a corresponding value so now when I iterate through I come to seven instead of making Pairs and seeing if they sum up to my target at this point I already know what I want to be looking for my number is seven and Target is four I want to be looking for a -3 so what I'm going to do is I'm a -3 so what I'm going to do is I'm a -3 so what I'm going to do is I'm going to check ifg3 exists in the dictionary it does not so what do I do now what I'm going to do is add my number and index into the dictionary in case I come across a number that can later be used with me to pair up and get Target so what I'm going to do is add 7 and it's corresponding index one to my dictionary and continue moving down so now I come across - now I come across - now I come across - 1 I know what I want to be looking for Target minus my number if it's in my dictionary I will return my own index as well as the index that corresponds with that number and if it's not in the dictionary I will add my number in as well as the index that I am on and that is it so let's go ahead and code this up and then actually run through this whole example step by step so the first thing I'm going to do is Loop through so for index in range length of nums and of course I want a dictionary so let's call this all the numbers I have seen and we're going to initialize it before we get into our Loop so for index in range length of numbs I'm going to set my current number to be nums at index now I want to see if Target minus my number is in scene so if Target minus number in scene I will return my index so index as well as the index of that number in my dictionary so how do we get that we want to find the key of the number in scene so scene of Target minus num holds that index so if that is in scene all we have to do is return this now say it's not in scene if we don't go into this if condition that means we want to add our number into scene and how do we do that we take scene we see what key we want so that's going to be the number and we want its value to correspond with the index so all we do is add our key value pair into scene so scene of number equals index now we can go ahead and run this code it is accepted and we can go ahead and submit this and it is accepted as well so let's just quickly run through this line by line and we can see how much faster this solution is compared to the other one we had so we have a scene and we are looping through our entire input nums so we have index which is going to start off at zero so I have index that starts off right here now I set num to be nums of that index so right now it is four now if Target minus num in scene nothing is actually in scene so we'll never go into this if condition which means we are over here we set scene of num equal to index so scene of num which is four and we set this equal to our index which is zero now we are back in this Loop so index is 1 and our number is seven so index is over here number is seven and we check Target minus number so four minus 7 that's -3 is that in scene it is minus 7 that's -3 is that in scene it is minus 7 that's -3 is that in scene it is not so we go ahead and add our number an index to the dictionary so seven and the index which is one we are back in this for Loop which means index is now moved up over here and we set number to be1 Target minus number so Target minus -1 so 4 -1 is 5 it's not in scene and we -1 so 4 -1 is 5 it's not in scene and we -1 so 4 -1 is 5 it's not in scene and we can add our pair in there so we are going to go ahead and add in -1 and 2 we going to go ahead and add in -1 and 2 we going to go ahead and add in -1 and 2 we go back into this for Loop we move this down we have index three and number is also three Target minus number so four minus 3 is 1 it's not in here we go ahead and add this here and finally we move all the way down so index is four the number is 5 now Target minus number so 4 - 5 is 5 now Target minus number so 4 - 5 is 5 now Target minus number so 4 - 5 is --1 and ne1 is in our dictionary so what --1 and ne1 is in our dictionary so what --1 and ne1 is in our dictionary so what do we do now is we return index which is our current index so we return four comma what is the value of Target minus n scene so Target is four our number is five so 4 Min - 5 is negative 1 what five so 4 Min - 5 is negative 1 what five so 4 Min - 5 is negative 1 what does negative 1 hold in scene that is two so these are our two indices our return for this problem and as you can see we did better in time we only went through the entire array once as opposed to n^2 so we went down from n^2 to O of to n^2 so we went down from n^2 to O of to n^2 so we went down from n^2 to O of n for time but there's always this space-time tradeoff so before we didn't space-time tradeoff so before we didn't space-time tradeoff so before we didn't use any space it was constant o of one now our space has increased to be o of n because our dictionary could theoretically be as big as our input nums so our time is better because it's o n but we also make use of space o of n so we just went ahead and solved tuome if you have any questions at all let me know down below otherwise I will see you next time
|
Two Sum
|
two-sum
|
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_.
You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice.
You can return the answer in any order.
**Example 1:**
**Input:** nums = \[2,7,11,15\], target = 9
**Output:** \[0,1\]
**Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\].
**Example 2:**
**Input:** nums = \[3,2,4\], target = 6
**Output:** \[1,2\]
**Example 3:**
**Input:** nums = \[3,3\], target = 6
**Output:** \[0,1\]
**Constraints:**
* `2 <= nums.length <= 104`
* `-109 <= nums[i] <= 109`
* `-109 <= target <= 109`
* **Only one valid answer exists.**
**Follow-up:** Can you come up with an algorithm that is less than `O(n2)` time complexity?
|
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
|
Array,Hash Table
|
Easy
|
15,18,167,170,560,653,1083,1798,1830,2116,2133,2320
|
1,716 |
hey everyone today we are going to solve the Lal question calculate money in Lal Bank okay so first of all the description said he starts by putting in$ on Monday the first day and every in$ on Monday the first day and every in$ on Monday the first day and every day from Tuesday to Sunday uh he will put in$ more than the day before on put in$ more than the day before on put in$ more than the day before on every subsequent Monday he will put in one more than the previous Monday so let's break down the uh sentence so he starts uh with is $1 on sentence so he starts uh with is $1 on sentence so he starts uh with is $1 on Monday and he will put in $1 more than Monday and he will put in $1 more than Monday and he will put in $1 more than um like a previous Monday so um I think there like a weekly based money so on Monday week one so he put $1 and on Monday uh in week two so he $1 and on Monday uh in week two so he $1 and on Monday uh in week two so he put $2 um on Monday in week three he put in $2 um on Monday in week three he put in $2 um on Monday in week three he put in like $3 and $4 and $5 so this is a like $3 and $4 and $5 so this is a like $3 and $4 and $5 so this is a like a weekly based money and the description said every day from Tuesday to Sunday he will put in $1 more than the day before will put in $1 more than the day before will put in $1 more than the day before so that means so he put in dollar like this so in week one start from $1 on this so in week one start from $1 on this so in week one start from $1 on Monday and the $2 on Tuesday $3 on Monday and the $2 on Tuesday $3 on Monday and the $2 on Tuesday $3 on Wednesday and the $ four $5 $6 $7 and Wednesday and the $ four $5 $6 $7 and Wednesday and the $ four $5 $6 $7 and then in week two so Monday he will put in the $2 do because in the $2 do because in the $2 do because previous Monday he put in $1 so start previous Monday he put in $1 so start previous Monday he put in $1 so start from $2 and $3 $4 $5 $6 $7 $8 and the from $2 and $3 $4 $5 $6 $7 $8 and the from $2 and $3 $4 $5 $6 $7 $8 and the week three and start from $3 because he week three and start from $3 because he week three and start from $3 because he put in $2 in previous Monday and like a put in $2 in previous Monday and like a put in $2 in previous Monday and like a $4 $5 $6 $7 $8 $9 and something like $4 $5 $6 $7 $8 $9 and something like $4 $5 $6 $7 $8 $9 and something like that so in summary so we need to calculate like a weekly base and Day within the week okay so let me explain how to calculate weekly base so we know that we have seven days in a week so weekly base should be day divide 7 plus one so for example Day Zero to day six uh in first week so Day Zero is Monday and six is Saturday no Sunday and uh we will get U um so $1 so because uh we will get U um so $1 so because uh we will get U um so $1 so because let's say um we put zero here divide seven is z right and plus one so past week so he will start $1 on so past week so he will start $1 on so past week so he will start $1 on Monday right so that's why weekly base should be one and uh from day seven to uh 1 so this means from Monday to Sunday in week two so description said uh he put in$ do in uh with week two because put in$ do in uh with week two because put in$ do in uh with week two because the previous Monday he put in $1 right the previous Monday he put in $1 right the previous Monday he put in $1 right so start from um $2 so that's why weekly so start from um $2 so that's why weekly so start from um $2 so that's why weekly base should be two and I think next week um weekly base should be three very easy right okay next let me explain how to calculate the day within the week so this is a very simple so formula should be day percent seven so day divide seven and he will increase $1 every day so and he will increase $1 every day so and he will increase $1 every day so dividing Day by seven and taking remainder will give you right money he put in the bank so let's check this um image so these are index number so day Zero means day one in that case 0 divide 7 is zero right and uh so when index is one so that means day two so oneide 7 is one so he will put a$1 and uh day index two means day three a$1 and uh day index two means day three a$1 and uh day index two means day three so he will put $ two so two divid three so he will put $ two so two divid three so he will put $ two so two divid three s equal two and then next day $3 $ four s equal two and then next day $3 $ four s equal two and then next day $3 $ four $5 $6 and when we reach the like a day $5 $6 and when we reach the like a day $5 $6 and when we reach the like a day eight so index is seven so 7 divide 7 equal Z so he reset the dollars for days and then day nine so index is eight so 8/ 7 is one right so again $1 and the 8/ 7 is one right so again $1 and the 8/ 7 is one right so again $1 and the next $2 okay so let's WR the Cod first next $2 okay so let's WR the Cod first next $2 okay so let's WR the Cod first of all iniz total equal zero and start loing for day in range and n and uh so total plus equal so we need two parts right so weekly base is uh day divide 7 + divide 7 + divide 7 + 1 and uh the day with in the week should be day percent 7 yeah that's it so after that so we should return total yeah so let me submit it yeah looks good and the time complexity of this solution should be order of n because we iterates until n days and the space complexity is o1 so we don't use Excel data structure and then actually I came up with another idea to solve this question so I'll show you how Okay so this idea is a simple mathematics so we know that um so he will put in $1 on Monday and um so he will put in $1 on Monday and um so he will put in $1 on Monday and the next day he will put $2 um on the next day he will put $2 um on the next day he will put $2 um on Tuesday and $3 $4 $5 $6 $7 and a total Tuesday and $3 $4 $5 $6 $7 and a total Tuesday and $3 $4 $5 $6 $7 and a total $28 in the first week and how about week $28 in the first week and how about week $28 in the first week and how about week two so total should be 35 right because uh he will start with $2 on Monday and uh he will start with $2 on Monday and uh he will start with $2 on Monday and the next day $3 $4 $5 and how about week the next day $3 $4 $5 and how about week the next day $3 $4 $5 and how about week three and $42 and I think week four 49 so um $42 and I think week four 49 so um $42 and I think week four 49 so um between weeks there are like a $7 between weeks there are like a $7 between weeks there are like a $7 difference 7 $7 and difference 7 $7 and difference 7 $7 and $7 so and the 28 total is the lowest $7 so and the 28 total is the lowest $7 so and the 28 total is the lowest dollar right how about the highest so in this case 49 so um how can we calculate like 49 so simply we have like a lowest dolls like 28 plus so we need to um add like a seven right three times so um calculation should be week four minus one so which is three right so okay so lowest should be 28 and highest is um like a seven multiply week minus one and 49 and then um now we can calculate total money except the last week so because uh last week is not always like a full seven days um maybe five days and three days so that's why first of all we calculate a total from like a complete like a seven days week so in that case um formula is lowest plus highest and uh multiply weak uh divide two so what I'm trying to say is that so lowest is um like a 20 28 35 and 42 and uh 49 so if we um combine like a 24 28 and the 49 so we will create like 77 and uh how about uh like 35 and 42 so 77 right so um calculation should be like guess 77 multiply 4 IDE 2 so yide two so that's because we have 277 right so um and the week is four so we need like a half of week right because we um pair to numbers like a 28 and the 49 and 35 and the 42 so they are pair so we need like a two pairs so that's why four divide two multiply 77 so we will get uh 54 so this is a total money except the last week and uh in this case so uh we consider like a week four is like a we like full seven days but how about like let's say we have week five and week five is like a three days so in that case we need to add uh like a extra three days so in that case um so um weekly base should be uh week plus one so now week is four so this week four is like full seven days week so that's why um four + one is five right so in week um four + one is five right so in week um four + one is five right so in week five so he will start with $5 and then five so he will start with $5 and then five so he will start with $5 and then $5 $6 and $7 so we need to add um 18 $5 $6 and $7 so we need to add um 18 $5 $6 and $7 so we need to add um 18 to 54 so that means 172 yeah I think uh this is the answer so uh we use this idea uh to solve this question so let's jump into the code okay so let's write the code first of all calculate weeks equal nide 7 so this is like a full seven day weeks and uh days equal n divide seven and I take a remainder so this is a days in the last week and as I told you lowest should be 28 right and the highest should be 28 + 7 28 + 7 28 + 7 multiply uh weeks minus one right and the total should be lowest plus highest multiply weeks divide two because uh we pair two numbers right so now we get the total D except the last week and uh let's calculate the extra day in the last week so Monday should be weeks plus one right and then um calculate the extra days and add um add to total so for I in range and the days and the total plus equal I plus Monday yeah that's it so after that just return total let me submit it yeah looks good and the time complexity of this solution should be order of one so more precisely order of seven days but all7 will be like a 01 so that's why and the space complexity is also o1 we use only simple variables right so that's why yeah so that's all I have for you today if you like it please subscribe Channel hit the like button or leave a comment I'll see you in the next 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 |
1,480 |
welcome to mazelico challenge today's problem is running sum of 1d array given an array nums we define a running sum of an array as running some i equals the sum of num0 up to the nums i so it's like the accumulation the rolling sum i've used so here it's like starting with one then we sum that up to three to six to ten and you can see that rolling some there's no reason to over complicate this problem all we'll do is initialize the length of nums let's do this in a for loop we'll say 4i in range of 1 through n let's just iterate and add the previous sum to the next one so numbers i is going to be plus or equal plus equal to nums i minus 1. and after that we can just return nums and that should be it let's go ahead and test this out looks like that's working and there we go accepted so all of this is oven time um and of and space well actually i don't think with sullivan's base it's actually in place right and yeah very easy one today so thanks for watching my channel remember do not trust me i know nothing
|
Running Sum of 1d Array
|
movie-rating
|
Given an array `nums`. We define a running sum of an array as `runningSum[i] = sum(nums[0]...nums[i])`.
Return the running sum of `nums`.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** \[1,3,6,10\]
**Explanation:** Running sum is obtained as follows: \[1, 1+2, 1+2+3, 1+2+3+4\].
**Example 2:**
**Input:** nums = \[1,1,1,1,1\]
**Output:** \[1,2,3,4,5\]
**Explanation:** Running sum is obtained as follows: \[1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1\].
**Example 3:**
**Input:** nums = \[3,1,2,10,1\]
**Output:** \[3,4,6,16,17\]
**Constraints:**
* `1 <= nums.length <= 1000`
* `-10^6 <= nums[i] <= 10^6`
| null |
Database
|
Medium
| null |
1,958 |
Everyone Welcome to Turn Date Today We Are Going to Solve the List to Depression 19048 Which App We Look Forward to in This Question is Basically a It is Very Simple Question and Will Just Explanation Question and Follow the Approach and You Can You Yourself to the middle end and no problem you will get all my videos and see what is this question ok represented on main to sirf hello viewers resale and veer with color black lips ko hai hmm oh later effigy of victims and point of This good length means particular to me Anupriya changing its color edit absolutely only and only a few comes a point to point and color ko black color ka subscribe color black and white and black color aa hi delicious movie take input ke 120 This Alarm On And See Which Give The Quality Of This Point Which You Have To Change Color Black Color Will Return On That Your Returns Through Specific Tay Recording System Distraction Ki Intestine Inspection Ki Hindustan Inspection Stealth So Let's Ata And in this direction for this will take you that direction history silencer revision in system ashl aur aapke sunao the effigy SDM Vipul Jain Seervi sidhe hai thanks the walking sandesh coordinator jin hai opposite plus this is two plus minus colors - - and plus this is two plus minus colors - - and plus this is two plus minus colors - - and distress - ok By shyam011a Why Not Excel Param Negative And Welcome 0share 0tweet Less Negative And They Will Be Positive That Surya Rashi Point And How Many Points Trailer Record Yes 12345 600 Cement Edison Video Subscribe No 1 And A Coordinator Infosys E Will Maintenance Tours 850 Anti Respective System And Respected Sir Hai Aur Lootere Size School Peeth NCR 85 Okay So It's First Widows To Minus Point In The Column Value - - - Value - - - Value - - - Na Torch Light Shades Of Dr Rehearsal Dusi Re Patthar Se Massa Is Equal To 8 Ki This And Effects Is Dynasty A Man Against Women Have - 101 Na A Possible To Three Opposite Color A Loot In A Boat Will Make A Check Function Will Check For Particular K According To Day C Condition Whole Start Half Inch Will Return True Wealth Will Return Forms and variables in this post the columns ok sir no to initially will have year mouth special you that equal 208 one centimeter check giving worshiping at least three mode on in blindly this trick opposite color na character positive they will use this color black Black Color White And The Opposite Of E Will Have Explained By Which Is Which Can Be Lightened Decide And Giloy And Editor-in-Chief Have Editor-in-Chief Have Editor-in-Chief Have A Smile Accent Opinion Are In The Great Means Will Have Potato Boil That Is Greater Than Or Equal To Zero and acts will extend are the last condition for peon and will have a great color equal to its opposite means or having a great place with black color at the time it means the white color subscribe to that and also will listen while according to the direction will Play important cases and viral decisions will teach ok and novel check date another one which smooth means axis pensiero and speed come great unknown and similar translations for e but e will return ajay to a false sense which has come out of this great end Not from this point no possibility if so how in this condition will return forms and press f4 note and will check to condition basically a that first army chief loot that greater than or equal to one big boss minimum number of this which date number checking This condition that you must have various colors that your a one listen na another one is without in this point is so having at this point as to what are you doing basically van business in second condition that daily pin were glass wale MP hair blast Furnace oil Sudhir and minimum do aaj bhi want minimum preet and how many they need more minute bhun le one minute and multi color of gray color code is simple but what is the relation that the said flat site is office do the five elements in two variables Thoughts Size 8 That Scheduler Will Be Having - - - Var And Will Help You To Endor Having - - - Var And Will Help You To Endor That Was Not Quickly 150 Di ABaby Loot Se A Word 0 Synonym Ki Agar - Dhan Agar - Dhan Agar - Dhan Hua Hai Loot Aur Suno And Suno That Too Tune Along Aa Name of Vivechak in Every Direction is Loot Bluetooth Lappi's Inspection Debris Early Morning Bilbya Will Remain Follow for This Key Side Effect IT Pluck Half Hour PM in Obscene Pass Cigarette Will Pike Particular Value Raghu Dixit of Is and Will Power Are Mode Plus Chief Election Man That A Cemented Special Is Will Move In Turn Will Write A Function Which Will Good Songs Movie Note Particular Okay It's Annual Function And Should n't Do Anything Written On Okay Na Amla Excited Bhool Check Function Which Will Check The Best Effective Particular Coordinator And a moving in a particular direction of values of velvet and values of velvet and values of velvet and according to movies laker and not oak is left side table function now main soya abhi will right teaspoon check function which will take and a great cents row addition and per capita income at this point and then Give Winners And Will Have To Wait Till And Will Give Birth To Two Years I Will Start The Varanasi And It's All Super Active Directory Of Egg In Life In A Handed Over Force No Issues At All And Person Character Opposite And Review System Operator To Story Person Opposite Color Ameer Video not Black Color Loop Condition of Roads and Values in Values in Values in that Active Pattiyan Points of Mole etc. Opposite Kalm Me is Formula Little Tenets Mid Point Color and Frill with Which Effort Length and Width Opposite Color Condition Will Treatment of Every Time E That I Will Fall Sentiment Reaction Variables With Dear Friend E C Vegetables Respectively Will Be Maintained A Hua Hai A Similar Increment Text ITR And Wed Dec 8 Loot That Boat Will Have Lost Condition Test According Access 6p Complicity Roti And Expert Comes Great American To 8 And Why Did Not Follow The Same Condition Is Adherent Will Return For This Page For Fear Of Mountain Means Not From Which Is Not Possible To Have That Or Trade Wait And Condition Android Lite And Will Return For It's Not Possible To Have No Issues Will Return More Condition And Will Submit Loot Sach Bhi Apna Tennis Silai Smooth Divination Likessy All Loot Okay Sonth Bhog Tyag Ke Panno Taylor Hai Or Acid Accepted In The Summit Thank You Can See Date Summit And Thank You Very Much Like This
|
Check if Move is Legal
|
ad-free-sessions
|
You are given a **0-indexed** `8 x 8` grid `board`, where `board[r][c]` represents the cell `(r, c)` on a game board. On the board, free cells are represented by `'.'`, white cells are represented by `'W'`, and black cells are represented by `'B'`.
Each move in this game consists of choosing a free cell and changing it to the color you are playing as (either white or black). However, a move is only **legal** if, after changing it, the cell becomes the **endpoint of a good line** (horizontal, vertical, or diagonal).
A **good line** is a line of **three or more cells (including the endpoints)** where the endpoints of the line are **one color**, and the remaining cells in the middle are the **opposite color** (no cells in the line are free). You can find examples for good lines in the figure below:
Given two integers `rMove` and `cMove` and a character `color` representing the color you are playing as (white or black), return `true` _if changing cell_ `(rMove, cMove)` _to color_ `color` _is a **legal** move, or_ `false` _if it is not legal_.
**Example 1:**
**Input:** board = \[\[ ". ", ". ", ". ", "B ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "W ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "W ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "W ", ". ", ". ", ". ", ". "\],\[ "W ", "B ", "B ", ". ", "W ", "W ", "W ", "B "\],\[ ". ", ". ", ". ", "B ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "B ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "W ", ". ", ". ", ". ", ". "\]\], rMove = 4, cMove = 3, color = "B "
**Output:** true
**Explanation:** '.', 'W', and 'B' are represented by the colors blue, white, and black respectively, and cell (rMove, cMove) is marked with an 'X'.
The two good lines with the chosen cell as an endpoint are annotated above with the red rectangles.
**Example 2:**
**Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", "B ", ". ", ". ", "W ", ". ", ". ", ". "\],\[ ". ", ". ", "W ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "W ", "B ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", "B ", "W ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", "W ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", "B "\]\], rMove = 4, cMove = 4, color = "W "
**Output:** false
**Explanation:** While there are good lines with the chosen cell as a middle cell, there are no good lines with the chosen cell as an endpoint.
**Constraints:**
* `board.length == board[r].length == 8`
* `0 <= rMove, cMove < 8`
* `board[rMove][cMove] == '.'`
* `color` is either `'B'` or `'W'`.
| null |
Database
|
Easy
| null |
468 |
hello guys welcome back to the coordinate it says there 16 from the lead cortisone challenge and today's problem is a valid IP address now for this a problem we will see a different approach to solve this problem before we proceed if you are new to the Channel please do subscribe we solves a lot of competitive problems now let's start with the problem what problem says is write a function to check whether input string is a valid ipv4 address or ipv6 address or run either okay so what we want here is we have a given IP address in a string format and we would like to check whether it's ipv4 or ipv6 if it is not any of this - then we need to return a any of this - then we need to return a any of this - then we need to return a neither in the output so what oh close we have to check for the IP viateur ipv4 address are canonically represented in a dot decimal notation which consists of four decimal numbers each ranging from 0 to 255 separated by dots for example 172 dot 16.2 54.1 this is a valid ipv4 example 16.2 54.1 this is a valid ipv4 example 16.2 54.1 this is a valid ipv4 example besides letting 0 in ipv4 is invalid for example the address 172 dot 16.2 54.0 1 example the address 172 dot 16.2 54.0 1 example the address 172 dot 16.2 54.0 1 is invalid so here if you see the things or the conditions we need to just check for here is we first it needs to be whatever the numbers lies between these dots that needs to be in range between 0 to 255 second rule is the number should not start with 0 so that's the two rule we need to check for the ipv4 and then the for ipv6 address are represented as eight groups of four hexadecimal digits so every groups there are total eight groups and each group can have a four decimal or hexadecimal digits each group represented sixteen bits okay the group are repre are separated by : the group are repre are separated by : the group are repre are separated by : for example the address the given address is a valid ipv6 address also we could omit some leading zeros among 4 eggs at a small digit and some lowercase characters address to uppercase one so given this address though there are some zeros in the leading but it's also valid ipv6 address okay however we do not replace consecutive groups of 0 when live with single MT groups using the two separate columns to pursue simplicity okay for example if there are here if you see is 0 so we cannot remove this 0 and will add as empty space so this is an invalid ipv6 address besides extra leading zeros in ipv6 is also invalid for example so if this is the case then l reading 0 this is not a valid ipv4 ipv6 address ok so from the definition it's a pretty clear that probably we need to do more on like e for if-else conditions to check for if-else conditions to check for if-else conditions to check different rules for ipv6 and ipv4 so there are three different ways we can solve this problem so the first approach we can apply here is with what we can do is we can use the package already inbuilt package available in the or the class called I net or the class called I net or the class called I net address ok this class having a method called get name ok this method will give you if you pass IP address string it will return whether it is a ipv4 object or ipv6 of there so what are the return object just check whether it is ipv6 object or its ipv4 object based on that we will return the result or if any none of them is there then we can return an eye on either in that case so it's a pretty simple solution only single line we need to return or a single line of code we need to write to solve this problem ok the second approach we can take here is reg X approach okay there are already inbuilt reg X or reg X available for ipv4 addresses as well as ipv6 address we can use that and we can try to match with the given IP at if it match then we will written this otherwise this or none of them will match then we will return neither in that case and the third approach is what are the rules that is kind of a brute force alright the kind of rules we have written in the definition itself we will try to implement those rules in our code itself and we can check the IPV what were the string given to in the input we will check for the ipv4 as well as ipv6 and if in any of the case if it fails to satisfy the conditions given to that then we can return neither or not possible from there okay so in this example we will try to implement with the third approach because first to that is already inbuilt functionality given in the Java so we will use a third method to write down a code all right now let us go back to the code editor and review the code for that alright so in the input we have given as IP address as a string so what first we will do is we will split with the different denominators so here it is a splitter is dot and here it is a call and so we will split with that and then we will check for ipv4 the length of the numbers should be four only okay if it is less or higher than that means it is not a valid scenario all right and then let's first understand with ipv4 so in the ipv4 the two rules we had is it needs to be 0 to 255 all these numbers all right and there should not be any 0 starting number should not start with a 0 so this two condition we need to check right so here we will iterate first we have already splitted that number then we check the length then we will iterate for all the numbers ok and then we will check is ipv4 is it satisfying those two condition or not now let's see ipv4 method so here what we are doing here is this condition will check whether is there any 0 starting number having any 0 or not so what we are doing is we are first passing that integer a string to the integer so if there is an zero so it will get removed because if you convert the string to integer in that case it will be converted to the exact number and then again we are converting that to the string and then we will check with the exact string so if there is a string having a zero then both this string will not match because here after you convert from integer to string the zero will not be there so in that case it will be false all right and second condition we will pass that to integer and then we will check whether it is in a range or not all right if here the another condition that we need to check here is let's say if the given number having some alphabets in between 1 7 a so in that case we may have a number format exception so in that case also we are returning a false out like this method or if this also conditions will get passed then we will return true that means that whatever the number we have passed 172 16 to 4 that is passing the ipv4 so we literally - 4 times this ipv4 so we literally - 4 times this ipv4 so we literally - 4 times this method and all the times if it is passing that ipv4 conditions then we will continue all right and then at the end we will return it is ipv4 okay now the same logic we applied for ipv6 so in the ipv6 if you see we will first check whether the SB already splitter so we will first check whether the length is 8 or not all right if it is 8 then only iterate over it ok then we will same logic we will apply we will iterate one by one for given numbers for 2 0 or DB 8 that way we will iterate for all and we will again call our ipv6 yes ok ipv6 also having its own validation rules we have written order so first it says like the length should be between 4 because that is a 1 condition that is given to us so everywhere it should have only 4 characters okay the second condition we will check in that one is it should have whatever the number we are passing that should be base 16 integer it should be it should have zero to nine as well as a b c d e f those many characters that can allowed on that number alright so what we are doing here is if there is any other alphabet other than the hexadecimal so in that case this number format exception we will be we will get when we so what ultimately we are doing here is we are converting this string and trying to see is there any other alphabet other than the hexa okay so if there is any other alphabet let's say aj any of the that alphabet is there character is there in the given number then this will give a number format exception so in that case we will return up false otherwise we are good and it should be greater than 0 and there is one more condition that we need to add is there could be possibility like your number will start with minus 0 okay but minus 0 may not be a valid condition so we need to check the extra condition is that 0 the character should not be the - okay the character should not be the - okay the character should not be the - okay that looks to be good now let's run this code all right looks to be good let's submit it all right it got submitted so that's it in this video hope you like it guys if you have a different solution I would suggest you to write it down in the comment box see you in the next video till the time bye
|
Validate IP Address
|
validate-ip-address
|
Given a string `queryIP`, return `"IPv4 "` if IP is a valid IPv4 address, `"IPv6 "` if IP is a valid IPv6 address or `"Neither "` if IP is not a correct IP of any type.
**A valid IPv4** address is an IP in the form `"x1.x2.x3.x4 "` where `0 <= xi <= 255` and `xi` **cannot contain** leading zeros. For example, `"192.168.1.1 "` and `"192.168.1.0 "` are valid IPv4 addresses while `"192.168.01.1 "`, `"192.168.1.00 "`, and `"[email protected] "` are invalid IPv4 addresses.
**A valid IPv6** address is an IP in the form `"x1:x2:x3:x4:x5:x6:x7:x8 "` where:
* `1 <= xi.length <= 4`
* `xi` is a **hexadecimal string** which may contain digits, lowercase English letter (`'a'` to `'f'`) and upper-case English letters (`'A'` to `'F'`).
* Leading zeros are allowed in `xi`.
For example, "`2001:0db8:85a3:0000:0000:8a2e:0370:7334 "` and "`2001:db8:85a3:0:0:8A2E:0370:7334 "` are valid IPv6 addresses, while "`2001:0db8:85a3::8A2E:037j:7334 "` and "`02001:0db8:85a3:0000:0000:8a2e:0370:7334 "` are invalid IPv6 addresses.
**Example 1:**
**Input:** queryIP = "172.16.254.1 "
**Output:** "IPv4 "
**Explanation:** This is a valid IPv4 address, return "IPv4 ".
**Example 2:**
**Input:** queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334 "
**Output:** "IPv6 "
**Explanation:** This is a valid IPv6 address, return "IPv6 ".
**Example 3:**
**Input:** queryIP = "256.256.256.256 "
**Output:** "Neither "
**Explanation:** This is neither a IPv4 address nor a IPv6 address.
**Constraints:**
* `queryIP` consists only of English letters, digits and the characters `'.'` and `':'`.
| null |
String
|
Medium
|
752
|
521 |
hey guys welcome back to my channel and i'm back again with another really interesting coding intervision video this time guys we are going to solve question number 521 of lead code called longest uncommon sequence part one and before i start with the problem statement guys i just want to request you to do subscribe to my channel hit the bell icon for future notifications write down in the comment section below anything you want to say to me and guys in the end give this video a big thumbs up share it with your friends as well now without making any further delay let's get started so guys the problem statement basically states that we have got two strings string a and string b so for example in this case string a is a b and string b is c d c we have to find out the longest uncommon subsequence so for example let's say a b a and c d c as in both these strings they are completely different and the length of both the strings is same so the longest common of uh subsequence length will be 3 because both of them are completely different and that's why the output is 3 and because both the lengths are also three let's see another input we have got one string a another string bbb again we see that both the strings are different so that's why the output is three because it's the length of the maximum uncommon subsequence and in this case as both are having length three so that's our answer is three in another example we see that both a and b are the same string exact same string so aaa and also b is also same a so in that case if there is no uncommon sequence we get the output minus one okay so uh the constraints are also pretty straightforward guys that both the lengths of the arrays is from 1 to 100 they both contain lowercase english letters now let's jump to the solution so guys by the looks of this problem it might feel a little bit tricky but actually it is very simple let's see one example here so i have already gone through all the other examples but let's see another example a b c d e f g h so let's suppose this is string number a and string number b is sort of like a substrate of this string subset of this string it is only from a b c d to e okay so now if i ask you guys a question that if i want to find out the longest uncommon subsequence between both these strings what will be the answer so some of you might get confused with these words like longest uncommon subsequence and you might take the brute force approach of actually comparing all the characters of this smaller string with all the characters of the longer string to see which characters are not matching and in the same sequence and then adding that length up and finally coming up with the solution so i would definitely say this brute force approach is not the good approach for this question because actually this question is really simple if you just understand it pretty well so what is uncommon subsequence means guys that what are the characters uh i mean if i put up some characters which are which sequence of characters is not equals to the sequence of uh characters in the second string so in this case if i say abcde is definitely equals to the string b but if i add f g and h also with a b c d and e and this becomes a different subsequence is this subsequence common with the subsequence of b no it is actually uncommon and also because the length of this string is greater than the length of b so this also becomes the longest uncommon subsequence as well okay so basically subsequence is a string of characters which are not equal which is not equal to the string of character in the second string and here we see that if the two strings are not equal to each other i mean to say not exactly equal to each other it means that they both are having a uncommon subsequence in that case what we have to find out is which string is the longer string so in this case it's the string a which is a longer string and we just have to return the length of the longest string because that's a longer uncommon sequence okay so i hope the solution approach is clear to you guys so i'll just delete this now and let's jump to the exact code so what we have said if a equals b so if both a and b string are actually equal in that case we have to return -1 in that case we have to return -1 in that case we have to return -1 but if they are both not equal then what we will do we will just find out the maximum length string and that length will become the length of the longest uncommon subsequence okay so that becomes the code let's run this code guys let's see if this works with all the other uh yes it works with this test case and hopefully it will be accepted for all other test cases as well so there you go guys you can see that the solution is accepted so they there it is guys it was just a two line code solution uh but this question sometimes tricks the people who are going into these coding interviews okay so let's see the time complexity uh first of all the time complexity guys is definitely order of n and in this case you can see that we can say that n is actually the length of the shortest string okay uh basically when we are doing this equals function so this equals function is going to compare all the characters of a with all the characters of b so that will take order of n uh basically order of n length and that's why this time complexities order of n so that becomes the random velocity and space complexity is definitely order of one here why because we are not using any extra uh data object okay so that was a video guys that was the solution for this really easy question but i hope that now your coding practice became a little bit better and you understood the solution as well uh if you have guys then do not forget to give this video a big thumbs up share it with your friends as well subscribe to my channel hit the bell icon for future notifications write down in the comment section below anything you want to say to me any feedback is welcome guys and i make your videos almost every single day and uh from monday to friday thank you so much for watching i'll see you guys in my next video until then bye
|
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
|
792 |
792 number of matching sequences this is today's um lead code question let me see if i can solve it given a string yes and an array of string words written the number of words of i that is subsequence of s the subsequence of a string is a new string generated from original string with some characters can be none deleted without changing the relative order of the remaining characters so example a c e is subsequence of a b c d e okay so basically um let's try to understand what is subsequence so this is a string and if we generate any string with all or none no characters from that it is a subsequence but the order should be same so a c e can be a subsequence a b e can be a subsequence a d can be a subsequence but a um d and then b cannot be a subsequence so absolutely fine and here we just have to um written number right okay so um instantly if i have to return a number i think it has to be some kind of a dp solution or something but i'm not good with tp solutions so before that i will just try to understand the question um so let's go with the checklist and then try to come up with the solution so this is my checklist so what's going to be the input there is going to be a single string as string s and number of um array of strings um okay that's fine these are the two inputs and output is going to be integer result something like that and it's um number of return the number of words of i that is a subsequence of s sorry so basically what they want is from the list of words how many of them are sub sequences of string yes okay sequences that's totally understandable cool um let me go through the size um the size of the string let's talk about it um can it be null or empty string it cannot be um as per this okay and uh what is the maximum size so in this case it can be like a huge number so maximum doesn't matter okay and then the words array right uh how much it's gonna be so it's again it cannot be empty and um it goes till 5000 so that's fine and the words the subsequence um basically the word inside the array is going to be at least one and 50 characters long okay and yes and what's up i consist of only lowercase english characters so that comes in this case uh i would ask a question like what are the values going to be like any special characters or numbers or not capital letters anything so only lower case that's good to know and then the checklist starts here so um it goes from test cases that's less edge cases time space so um right now the test case i can think is of there is only one single character um there can the there cannot be even a single subsequence um it can be um the length of the word is equal to the length of string so yeah these are the kind of edge cases and before code i actually do i'll go so design actually all right so let's do the algorithm design let's see how can i solve this question uh let's take this example so we have this abcde and the words are a b a c d a c e and the output is three there are three strings in words that are a subsequence of s so a c d and a c e there is no b so we don't we cannot have that and in this case it's only two so this example looks like a good example to start with um so let's take this and let's see how we can work with it so the brute force approach um that i can think of is iterate over each of the word right and uh like iterate over the list of the words and for each word iterate over the characters and if you can have these characters then this is the subsequence do the same thing for this uh do the same thing for this and this so um i think i can code up the brute force solution but the time complexity of it will be something like for each word so length of the total so word length um let's call it l and we'll iterate over each of that length by number of words and we'll go through s that many times so length of s is equal to m so it's gonna be something like this um and that's it's kind of a linear so far but maybe we can reduce it some somewhat uh let me think if i can do anything else so what if i sort this num sort this um voice array so what happens in that case so i have like a ac d a c e and then b so does it make any difference hmm okay does it make any difference it should make some difference because i don't have to worry about this part again so i can just continue with the checking so if this is this was sorted let's say um i get a and i check it with the a um it's a subsequence so this word is finished so this is subsequence and then the next word comes is a c so i have already checked a right so i just start with c and i try to find c here i find it so now uh i check for d i find d okay and then i have already checked ac but um can i use the stack for this like which character i have already seen hmm okay um there has to be something um so let's see this is a ac c d a c e that is bp i think sorting should make some difference but not able to think how so what i'm going to do is um i'm going to go with the brute force approach for this thing and let me just complete this solution so i'm sorting the words for no reason and then what i wanted to do is i wanted to iterate over each word for word in words right and then starting from uh starting for from each character in word so for this each character so first one is a and okay how can i know that the checking was successful so let's assume this was not there a was not present how it will be um so it will check a then i go c i get c so and then i get d i think this is not right approach i have to have two pointers um so let's say i and j start at zero comma zero and then i go till um ice pointing to the word and j is pointing to the string s so i'll just keep checking until they are equal if it is not equal then i just move the pointer of s ahead that is j and anytime the both of them go out that's um if j goes out then that's uh that's not a subsequence and if i goes out that means it is a subsequence so let's have a result um 0 and then when i is less than length word and j is less than length of word right if uh word of i is equal to word of j then we do um i plus equal to 1 j plus equal to 1 right so what we are doing is i is here and j is here if they match we go to next position in the both the strings now if they don't match c is not matching to b in that case only j plus 1 that will happen so i don't think i even need this case else case just um do the do this right and once this once you do this for the single word um so if i is equal to len of word that means we found the word so in that case result plus equal to 1 and if this is not the case so let's look at this bb right so um so in that case uh the word is bb and we started 0 both of them are so there was a bug here right j should be less than s and uh yeah so now what is happening is a is not equal to b so this is true but this is not true so word of i b is not equal to word of j which is a uh we are here so b is not equal to a so we just move the second pointer so we check now we are here now in that case both of them are equal both of them are b so we go next in both cases so we go to c we go to b that's fine now again it's not equal so we just check we go here then we go here check here we go here and i is 0 1 which is less than the word length and j is out of bounds so we don't increment the result so in that it remains whatever it was yeah so i think this should work um there is a mistake here but again i think it's gonna give me a time limit exceeded when i um when i try to but let's see didn't work white is giving four um let me just change this test case yeah so how it is saying that um why is this happening i equal to lane of word let's see no worries so this is the example this is the time complexity we have w let's say word is equal to this so now i is at zero i and j okay so i is at zero j is at zero and i is less than lane of word which is 2 and j less than len of s which is 5. now word of i uh okay this is a mistake here it should be s yeah i was checking the same thing with yeah how stupid okay now it worked now let's check these two examples again it works brute force solution is working but what is happening is um this loop is going all over the s again so the length of this is really long right so that is bad so i have to minimize it minimize the iterations so how can i do that um if they are in sorted order and i check this and let's say a 80 i'm checking this so this is the correct sorted order right so i find this is equal so that's fine so um so now the next character is a not sure man i'm not sure and that's what i'm saying um i don't know how to improve this but um i'm pretty sure it's gonna give me uh tle so i'll just submit and then i'll check the discuss um to find out how should i have done this solution yeah see time limit excited so now let's go to discuss and efficient and simple go through words in parallel with explanation okay let's see what it what they say runtime is linear in total size of input s and all the words explanation below the code variations of same algorithm described at the end okay using iterator to represent words and their progress okay this is not something i would have come up with um yeah it's not easy to understand python solution with okay why these are using the dictionary so for word in words um of word zero the pin word okay and for care in s words expecting care is okay and vertice of care is equal to empty okay um understand so making this this value as empty or maybe just remove that and for word in expecting cash if len of word equal to one finish subsequent count plus equal to one else vertex of word of one that depend so um i understood this solution basically what they're doing um so basically um what we are doing is for each starting character in the words uh we are putting them into same bucket this is something i was thinking but i was thinking in a sorted way and then what is done is then for we are going through each character in the string and at that character okay uh whatever is starting at that characters all the words that are starting with that character we are going through that each word and if that length of that word is 1 then we are just incrementing the count and then uh if it is not then what we are doing is uh whatever the second character is in that word uh we are appending the remaining part yeah so it's kind of a cool algorithm is there anything simpler than this uh people write simple solutions but it's difficult to understand so uh i got this solution and i'm not gonna waste too much of your time i'm just gonna paste it and so this solution worked but it's not um efficient so let's see if this works and i will try to code it um yeah that's working okay so this is kind of a cool solution i don't know what's the time complexity for this but yeah so yeah bye
|
Number of Matching Subsequences
|
binary-search
|
Given a string `s` and an array of strings `words`, return _the number of_ `words[i]` _that is a subsequence of_ `s`.
A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
* For example, `"ace "` is a subsequence of `"abcde "`.
**Example 1:**
**Input:** s = "abcde ", words = \[ "a ", "bb ", "acd ", "ace "\]
**Output:** 3
**Explanation:** There are three strings in words that are a subsequence of s: "a ", "acd ", "ace ".
**Example 2:**
**Input:** s = "dsahjpjauf ", words = \[ "ahjpjau ", "ja ", "ahbwzgqnuk ", "tnmlanowax "\]
**Output:** 2
**Constraints:**
* `1 <= s.length <= 5 * 104`
* `1 <= words.length <= 5000`
* `1 <= words[i].length <= 50`
* `s` and `words[i]` consist of only lowercase English letters.
| null |
Array,Binary Search
|
Easy
|
786
|
907 |
hey everybody this is Larry this is Thursdays and on November 24th so uh Happy Thanksgiving for everyone who's celebrating hope y'all have a good turkey and whatever it is that you like eating uh in my family actually we usually just get a chicken because yeah we uh family's a little bit smaller so turkey is kind of big and yeah anyway I hope everyone's just enjoying you know the long weekend and so forth I mean I guess if you're American if not then hope you know the end of the week is coming soon for you um yeah today's problem is 907 sum of sub array minimum so let's get started also let me know what you think about the World Cup so fast so many upsets huh poor Argentina but um yeah I'm excited to see Americans and the English tomorrow so we'll see um yeah anyway to get back to today's program it's 907 sum of some away minimums giving it away of Interest oh I'll find a sum of Min P where B ranges for every contiguous sub array of all since answer may be large return the answer module okay so this is basically return the sum of oh um oh okay so I actually I missed wow this is kind of a tricky point for medium isn't it maybe not let me think about it but um and N is 10 uh three times ten to the fourth so obviously you can't do an n-square algorithm just to double check n-square algorithm just to double check n-square algorithm just to double check that because then that will make it kind of silly and also then we can go home and sleep but um okay so these kind of problems where you have to kind of do um every Subway thing um maybe even subsequence depending on how you know the problems constructed they'll just want to separate way in that subsequence the first thing to do is well actually the first thing I need to do is sing the mad song because I uh mud because I always forget my mod uh it's not a real song but I try to put it before because otherwise I forget um okay so the question is uh um just the idea here is kind of go for it um you can come up with a way to construct it backwards and what I mean by that is that um there is an answer right we don't know what it is and in this case we're trying to figure out each um each number for each number how much it contributes to the answer right so that's basically kind of the logic that we're trying to get um try to get through here for a problem like this whether this is apparently separate way mints but there are other problems like subway um the subway sums right for example if you want to get the sum of every sub away not just the minimum then you know you have to you may think about how many times three appears in different Subways right and in this case just three would appear in four of them one would appear in one times two and so forth right um so that's just regular sum now we're trying to figure out the minimum version of it and then the question is foreign I think there is also um we do there is a apparently I haven't solved this before yet but there was like um a Q4 on one of the contests not that long ago but and I struggled with it a bit even I think I got an idea and maybe I'm wrong I don't know but because I was looking at it try because there are a couple ways you can think about it um and the tricky thing is about unique elements um and I think that's the problem that sometimes it's hard because you can think about both ways like we said um and in this case an action both example one and example two there are no duplicate elements but let's say we do have duplicate elements right then what happens um well it is more precisely what happens is that well you can this contribution like let's say we have this is a Subway way well if this is a sub array that means that how do you know you go you're going to say hey this the left one is a Min and so it should be added one to the answer um and then the second thing is that when you process the second one you're like oh that one's also diminished we should process the answer but now we've seen that um we can't do that right so we have to figure out a way to kind of keep it consistent um okay so hmm the first thing that I would do is kind of think about I mean still think about it first um let me think about this I mean there are a couple ways I'm thinking about it but wow this is kind of a hard one for medium right all right I think that gives us a uh something to think about but let's actually go back to the basic first right so in this case then I think all we have to do is try to find kind of the boundaries of the next smaller number uh and then the previous smaller number and then you know those are the boundaries of your uh things that it can be the men right so in this case for example Drew has no movement of freedom on the left or the right um two we can actually go extend I mean this is a very strong let me try the other one because this is a full element away so it's a little bit hard to illustrate um and this one is a it's a mountain so it's kind of bad as well so okay fine uh but let's say we have something like I don't know like this right um the two goes all the way extended to the and this is still a mountain but let's just say we have another five here right and the five here the minimum that goes to the left is four so we have two choices to the left and two choices to the right well technically three because it goes from zero one and two so that means that five would appear within nine Subways right um so we can kind of just sum that up right so for example and what I mean by that is that let's say three how many separate ways does it appear in it appears in one appears in all of them really so on the left it has two degrees of freedom meaning zero and one uh you know the index zero and one uh to the left and here there are three four five six seven so uh what is it did I say 708 a seven to the eight degrees of freedom so two times eight is sixteen right two um just to the right and I think there's six left so there's seven degrees of freedom uh four same thing but six eleven is oh no I lied oh no yeah 11 is fine eleven is you know zero and one so that's two on the right five you can go three on the left three on the right so that's nine I mean I may be off here but I'm just you know using an example right um oh actually this goes two so then now you sum all that up and you know multiply sum it up and then that's pretty much it uh for this one um that's the idea I'm trying to see whether yeah I mean the tricky part of course is the now I think we're fine here except for of course you have to do some math because if we do it naively this will be n Square so we have to kind of um we have to do some kind of um yeah we have to do some problem here wow this is kind of really hard for medium isn't it huh that's kind of am I missing something weird but yeah um but yeah but that's pretty much it and uh for this one assuming that there are no dupes but what if there is a dupe right um then we have to kind of figure out like the um let's say we have multiple you know ones or whatever um that and we'll skip all the numbers so here one the first one what are we doing right so there's two degrees of freedom to the left and then let's just say three or four degrees of freedom to the right okay maybe that works so second one here I'm trying to think so one way to kind of res resolve these kind of uniqueness is introducing a sort of asymmetry with respect to the left and the right and in that you guaranteed that in overlaps um someone else quote-unquote the later um someone else quote-unquote the later um someone else quote-unquote the later numbers would pick up and what I mean by that is that here for example for this one you have five numbers to the left so maybe there's six degrees of freedom but to the right it only goes up to three because you assume that any numbers that includes this one uh the one on the right uh that comes later will get taken care of by that number so in this way it is uh symmetry breaking if you want to call it that even though I know that means something else in physics and it's always cool to say so yeah so that's basically the idea and then now you can do the same thing um and it's something that comes up here and there I don't I think this works here but yeah and it's something that I think I struggled with the Q4 but this is kind of a really hard form um okay so now that we break it down this way so what did we do right um again we're doing naively it's going to be N squared so then here for each let's just write it out but for each number we want to find or um how do I say this all numbers uh oh we want to find the number of numbers that are smaller to the left you know until the break right um and smarter or equal to and also for each number we want to find the number of numbers that are strictly greater than right to the right uh you go 2 to the right I guess maybe that's just very awkward phrasing with the two twos but okay um the reason why I want to write it out is because now we can see if there's a um a linear time algorithm for it and you know I think this is yeah I think that's pretty much it right and um and this is where you know we introduce our good friend uh the mono stack I think yeah monosac because basically the idea here and I this is kind of a hard problem and I don't know if I have the energy to really go over mono stack in a very deliberate way but the idea here is that okay let's just say we all right which I've kept that away but let's just say we have here right the idea behind the having a stack is that um you know we go three we go one uh and then one um yeah so when we process the one we know that every number after that it either is going to be bigger than one and therefore stopped by the one if you will stop the streak or if it's more than one if it's smaller than one it's gonna be smaller than three so then we can pop so that's basically the invariant that we're keeping and because now let's just say we build it up and the stack is now one two and four and then now we're trying to put in a three and the three is smaller than a four so we know that like I said in the future if a number comes in if it's smaller than three it's going to be you know um if it's more than three it's going to be smaller than a four if it's bigger than a 3 then it stops anyway so therefore the four is not necessary and in this way you have this mono stack name monostack because it's monotonically increasing though that's a emerging property of the invariant that we're trying to keep and of course um the key part about keeping this model stack is that um each number will only be pushed and popped once and therefore it'll be linear time and as a result that is basically um yeah that's basically uh that's basically it so yeah okay so let's kind of start implementing that then uh we'll do the first part first and then we'll kind of see and we might just generalize it a little bit but yeah so for X in um okay if length of Stack is greater than zero and here the stack will contain I guess we should have kept the index right um the value is greater than so basically if it's the same we want to pop it off yeah we want to pop it off because we want to keep going okay so yeah so if the stack is greater than or equal to then stack dot pop kind of but uh previous I guess previous six doesn't matter but yeah uh let's just say um Pi is equal to I say right um basically here we're just trying to go back to see how far the index goes um and then once we pop and then at the very end we append back pi x right um but before that we want to okay I just have a Toto um yeah and then here basically we want to add um so X appears how many times so p i minus uh I'm plus one I think is that what I want to say um I may be wrong with that one um yeah and let's kind of see how this looks for now not super confident about I mean it's definitely not right because we didn't do the other side yet but that kind of uh you know run it and because basically we're just doing a little bit of a sanity test as well in the sense that um you know if the numbers bigger than the input numbers like for the test cases for example if I got like 500 I know something else is really wrong um oh whoops I know that something is really wrong because no matter what it should be less than 400 right um okay so I expect that the number is smaller and it looks pretty okay so far actually so yeah um and the other thing that we can of course do is just verify by hand right meaning that if you really want you can also um just write another photo I mean for small cases and even you could put in more cases to check for small numbers where whether this is true and this is just going One Direction so we haven't got the other one yet so we know that this is one but three appears one so that's gonna be three one appears twice so that's two so that's five two appears just one so that's seven and then four appears one that's eleven did I say that well so three plus two is five plus seven plus four says eleven right hmm that seems a little bit off then okay all right let's see oh do I have to care about this the stack at the end I don't know uh one two four sounds right but all right let's see so yeah so this is just sanity checking what we think the code should do and what the code actually does so do we okay so this is huh we popped this oh I got the direction well don't do a bit awkward okay fine because the previous is the smaller number okay so now this is 11 as we kind of um calculated manually and still within range so like I said uh this is why we kind of debug these one at a time sometimes especially when you're not super confident about it so you can kind of spot these things as it happens okay so then now we just have to go backwards and do the other side I think right um we could also maybe when we pop we add some numbers does that work um I don't know well that's let's not try to be too clever for now and then we'll uh go for it so for IX and enumerate um in this case we're going to be worst away because we're going from right to left and then we just do the same thing uh that order come which is weird but in this case now we want numbers that we need the numbers that are smaller you can kind of prove uh at home maybe um I think this is me maybe a little bit off by one um the reason why I say that is because I think we now I think this is a little bit off but I'm gonna just spin it real quick um the reason is I think we're double cutting X in both cases um possibly so yeah um maybe that's good nope hmm okay so looking back oh no the logic is still the same it's just okay that's why because I think I played in my head a little bit too much thinking about the Symmetry um do I need to do this I don't know but because of the geek we just have to not care about the equal signs I think is the idea but it's still wrong though so let's kind of think about again you know now we can debug it knowing that this part is what we expect so then we don't have to worry about playing around with debugging so for that part um but for this point we have to though uh okay let's see what Magica is doing so it goes to four okay I mean it doesn't do anything because we already counted on the left so okay fine and then I think I know what it is I think I just did this in a silly way um because I think I pretty much because I think I was hoping that wasn't the case but I think I did uh made a boo-boo here um and what I mean by that boo-boo here um and what I mean by that boo-boo here um and what I mean by that is because the formula is actually as we kind of go here for example the three is actually the number of degree of freedom to the left uh well to the left and times the number of uh let's do this one it's the number of degrees of freedom to left times the number of degrees of freedom to the right and but what we have here is that I kind of delineerate them or de-quadratic them of delineerate them or de-quadratic them of delineerate them or de-quadratic them a little bit for some reason so I think this is just super well but what we can do is do something like this and then left dot append I minus pi do I do plus one I think plus one actually yeah okay and then now when we go to here um whatever so I was going to write something more clever a bit um but yeah let's just do this and then write that a pen I minus pi plus one because it is a little bit funky because everything's reversed so I didn't want to uh whatever so now we can reverse the right and then for um oh uh for x I don't know left right and sip of oh is it left right and then uh whoops did I have that on top well I guess I did have one more time so then we add um L times y times x and then my divided that's basically the idea uh hopefully this idea is right because otherwise it's just silly I mean I may be off by one and that's fine but um okay so it works for here but not here why is that no that's kind of give it a spin real quick yeah a lot of debugging today maybe I got the indexes more 11 this is query already one the right should be more than one did I do in the wrong order um that is weird actually because white should at least be like four or something so the right part is wrong but the left part is right um is that Okay so it starts with three that's good zero one okay the 81 should be popping so anyone should pop the 94. oh man wow this is just really wrong I'm just being really dumb I mean this I mean it's how did that even pass before that what a silly mistake okay now we there we go I don't I guess this one just I don't know sometimes code has a way of being right for a totally Distillery reason um because it got 11 here right that's really weird okay but yeah uh silliness aside let's give it a quick submit and hopefully not super well yeah first time self 969 day streak um yeah as you can see this is going to be linear time linear space um hope I don't have to go for that part just because um I think this is pretty straightforward with respect to that one and uh you know the spaces or it is linear it would be worse a few times and even symptom but everything is linear um in terms of time that we just like I said each number will be pop and pushed once at most for the left and then also once again for the right so that's going to be um yeah linear time linear space um I think this is a hard enough problem for me to kind of you know uh hang my Thanksgiving on so let me know what you think this is kind of this is definitely not a easy problem I don't uh I mean it's definitely not an easy problem but it's also not I think it's a little bit on a harder problem for medium um though I mean if for people who are very practiced they could get this way quickly but um yeah let me know what you think stay good stay healthy to good mental health Happy Thanksgiving everybody and you know hope you have a lot to be thankful for let me know in the comments what you're thankful for uh this year um that's why I have those they're good stay healthy to get mental health I'll see y'all later and take care bye
|
Sum of Subarray Minimums
|
koko-eating-bananas
|
Given an array of integers arr, find the sum of `min(b)`, where `b` ranges over every (contiguous) subarray of `arr`. Since the answer may be large, return the answer **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[3,1,2,4\]
**Output:** 17
**Explanation:**
Subarrays are \[3\], \[1\], \[2\], \[4\], \[3,1\], \[1,2\], \[2,4\], \[3,1,2\], \[1,2,4\], \[3,1,2,4\].
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.
Sum is 17.
**Example 2:**
**Input:** arr = \[11,81,94,43,3\]
**Output:** 444
**Constraints:**
* `1 <= arr.length <= 3 * 104`
* `1 <= arr[i] <= 3 * 104`
| null |
Array,Binary Search
|
Medium
|
788,1335,2188
|
1,439 |
that a hello hi guys welcome back to I want the question categories 110 Adhavwali 823 600 Avoid pickup exactly one element key and find the sum of elements and to-do list key and find the sum of elements and to-do list key and find the sum of elements and to-do list in element subscribe The Amazing element from this live wallpaper for cars to one plus one I want from the road to Sudhar Gurjar Samaj Party Nak Selective 120 407 Next Flight 143 Leaders Must Not Reflect 0608 Subscribe Absolutely See The Question On I If Not Now Pick One Element From Which You Should Need To And Store The Position Of The Element On Baking Shoaib Akhtar The Amazing To Avoid Food At Similar Creative Actors And Intended to do a position of an element in its relative distance here its position in its truest to this a co nominate also and it to calculate the sum of the element is selected swift avi player and ant available that ant available co switch represents the sum of The Element Which One Cannot Be Next Thing They Need You Know When I Donate With Respect To The Video then subscribe this Video Click Any Other Subscribe To Super Asli Vinod Yadav Minimum Will Always Be Given By Selecting The Giver Elements Of Desires Oh Today sorted in ascending order for the minimum of all the meaning of minimum in 0.2 select loot 0.2 select loot 0.2 select loot protest hu invented this of all Russian a note to contest has no videos taking dowry element and posted in the returns set loot to avoid we find out the starting Element of set absolutely no two combinations with minimum they are present in the beginning website and deposit are so next what will take care see what more information begins from using this acid listen to find out the next combinations half kilometer loot jaane steps ke minus one Time Expressed Molestation Adhuri Twist K - Havan Times Square Minus One Element Swift - Havan Times Square Minus One Element Swift - Havan Times Square Minus One Element Swift End After Allu Arjun Allu Crush On The Element And The Beginning Verses The Sum Of The Mission To Enter In The First Document Select The Element Here And Every Day So Let's Make A Set Hair scientist lay down set a ye rind set and description position the elements in ru0 that rohan a controller to mukesh vanshwali witherspoon you all the everyday morning indexing and 00 one plus two know the types of the meaning of the mid point collect combination remove One element from two elements from the meaning of what is the best element subscribe The list element in the meaning of the smallest element Next element of the element which country in the world A view to include the number present position plus 162 updates in भर्स्त सुहाग Will The Sum Odd plus 162 updates in भर्स्त सुहाग Will The Sum Odd plus 162 updates in भर्स्त सुहाग Will The Sum Odd Merit Soega Dasham Ki Yeh Sapoch 10 A Malik Riders Palawat Sonu Including Foreign Policy Reduce Element To Rock Formation And Elements Are Present Where Are The Element Of Surprise Element And A 104 A Call To Calculate The Some Important Combination Using R Previous Combinations Soe Hain Let's Move At About Us Rock Band Video Loot Hua Tha Hai So Let's Continue Northern Next Element Chicken Select From Every Road With The Next Element Of The Current Position Wearing Her Vehicle Act 10463 So Let's See So Select 0 The Induction Give One 0684 ten laxative increase other elements select this will not only give on Thursday that Bihar 08 straight 100 24 Apr 02 10 2007 98100 time this 509 second the national president sh common man you and post and second combination intersect so let's set swarasan minimum semi spider 07 2008 Loot One Iteration What You Have Me Indiscriminately To Front Then Smallest Modesty 284 Time Sonar Beginning Of The 3710 Element So Let's Point Extension For This Show Currently A View Of Selected 0 And Listen Next Elements 80 Forensic Show Will Translate All Of Them One By One Should Select 0r Answer Welcomes One 0 Select Kar's Neck Select 0021 Sudhir Ventilating Now Let's See What Is The Number Into Your Feet 100008 1021 Shyamalal Developments In The Acid Sure 80 E Will Have To Go Away Look, Bluetooth was expired in this mixer. Hits 28 Sensitive Is That 021 100 Pimple Composed Record Or 2017 Tractors Middle Fast After Dispute 3099 E Want To Traces Improve Next Element Which Of The First Is 57 Minutes Ago This Elements In The Is 9 Days Next Elements Which Can Choose One 104 0 Okay So Let's go straight in the evening 1000 and to do 2010 2011 5 2108 ki and 201 Budha Abhigrah Bankar Sports Pimple Servi 0 Already Present in the Set in the Morning Don't See the Question Other Element Which Similar to Indus and Disease Control Automatically From August Delicacies to Assuring That You and Something you need to take care don't drink and elements in the data structure in the rate states automatically taken care of anti doing so will push the to you and commissioner da show a sensitive hair loot 0 ki and 1628 to bank university phone thank you small Job Literacy Sub 1hour Last Impression Research Will Stop This From Per Set N More Increase This Let's See What Are The Next Commission 50 210 Is Of Top Three Do Subscribe Is Range The 1020 Plus 6060 So Let's Eat In Middle Its And Mobile May Samet A Loot why not sleep that 11:00 weak 1611 [ __ ] share end 02 that 11:00 weak 1611 [ __ ] share end 02 that 11:00 weak 1611 [ __ ] share end 02 actors dr is so enemy hot sex deposit 2017 hai witch 102 don't wash statement also point co end and whole station server morning don't oo doing meditation circle - south understand man doing meditation circle - south understand man doing meditation circle - south understand man twist president end The Beginning set the answer for the key term which was looking for the answer is a knot which team is the answer discussed in the beginning subscribe The Amazing doing this point of elements in elementary and definition of elements which can login in is the loot Number of Rose Enzyme Number of Rose Present in the Matrix Shuddha Swar Time Complexity of Work Properly Find No All Gautam Ise Any Problems in the World in the Land of the Giver and You Can Any Time Comment in the Comment Section and Subscribe and Share the Video Subscribe my channel thank you
|
Find the Kth Smallest Sum of a Matrix With Sorted Rows
|
running-total-for-different-genders
|
You are given an `m x n` matrix `mat` that has its rows sorted in non-decreasing order and an integer `k`.
You are allowed to choose **exactly one element** from each row to form an array.
Return _the_ `kth` _smallest array sum among all possible arrays_.
**Example 1:**
**Input:** mat = \[\[1,3,11\],\[2,4,6\]\], k = 5
**Output:** 7
**Explanation:** Choosing one element from each row, the first k smallest sum are:
\[1,2\], \[1,4\], \[3,2\], \[3,4\], \[1,6\]. Where the 5th sum is 7.
**Example 2:**
**Input:** mat = \[\[1,3,11\],\[2,4,6\]\], k = 9
**Output:** 17
**Example 3:**
**Input:** mat = \[\[1,10,10\],\[1,4,5\],\[2,3,6\]\], k = 7
**Output:** 9
**Explanation:** Choosing one element from each row, the first k smallest sum are:
\[1,1,2\], \[1,1,3\], \[1,4,2\], \[1,4,3\], \[1,1,6\], \[1,5,2\], \[1,5,3\]. Where the 7th sum is 9.
**Constraints:**
* `m == mat.length`
* `n == mat.length[i]`
* `1 <= m, n <= 40`
* `1 <= mat[i][j] <= 5000`
* `1 <= k <= min(200, nm)`
* `mat[i]` is a non-decreasing array.
| null |
Database
|
Medium
|
1327
|
1,235 |
Hello friends, in today's video let us put the list to be discussed, this problem is called Maximum Profit in Job Dealer Problem, hence here you are set up and every job is the next time when your ante and with In this, when profit is associated with whatever you want in life, then you have to use it in the virtual tour, so that your profit becomes maximum, in such a moment, you have to choose such number chop which will make you live, it is play time for you. If you can do a job, then you have such an optimal number, job score, profit maximization, if you have a problem, if there is no job on hatred, there is no new job interview, and for subscription, you have to chant here through the example, when will you get the answer, job number one and which Reference edit using number four 122nd Here also we can give you 12345 but you will get a profit tax when you use the first features app first one more yourself then how is zither 360 then if you use this then you will get 12345 Vashishtha then friends We discuss you that this demonic like this which is number one that this and this which is number two which is number three third number you have got knife problem how is the money so if you have to select then first of all I would like you to more There will be an effort to take more jobs. Your means is told that in the afternoon there will be 1 job school, second number and job, if you take the job, then please subscribe the number as soon as possible for more profit, then subscribe you and the number 90, subscribe a probe. Till this, it ended on time, so what all did it do and then it cut the card of me that you have to destroy Saddam Hussein at least before the end time because what will be the benefit of this and the jobs that come after him too. Like share and number will increase and Sun will end on the zodiac sign. After this, the team which is number three, by the way, before the mask, if you had taken number two first, then you have seen us, you will turn on your setting, Asadhya 384, ever Pratap did it. Take, if you are not able to come then what do you have to do on job vidmate side, if you subscribe to this page, now we will do a message text zero ok then you definitely become then shift the camera to yourself and try so that you can subscribe Subscribe to the channel, subscribe, you get it okay and you subscribe that if you subscribe someone, subscribe job school, then it gives you your trophy Muzaffar, okay now you tweeted this with it and things are done in a good way. Let me tell you, if you can take any job etc. in the current job, then what should be the condition, which will be the end time of the previous job, if you take it from Kumar Karan Johar's talk time on the left side, subscribe our channel and subscribe next subscribe If not time, then our number two is our antacid, our time has increased again, then what are we, when it is yours, then its start and time is second, do not forget to subscribe our current professional course which is Aadhaar number with Star Club Liverpool. So, this is our ghagra, so one and a half inches from here, subscribe and subscribe, now queen, whatever we do with tempered glass, we will start our mixer profit by doing this, in the middle here, a little bit of grease on the problems, even a little bit, should be away, now we are on stage. I saw it in the show Pinup Hamla Khan Jab Ameer and Tiraha We have no need from here Girls presented more than half Now the deposit has gone Benefit which is subscribe profit first time profit If you come here, we mean like if you are here Was that subscribe here subscribe quid file manager ok and we have also kept the current way, what is our time, this is the market's time and what have we mentioned, according to the related also end time from our time, le singh and So, we can make the cut from here or if we complete it quickly and in a good way, please subscribe to Azhar Himanshu, subscribe, and along with this, we also have to do this for you, what is the quantity, try this, on this current position, you can see his Tweet on the left bar so this is the problem laxative fans which nature last few tips so we are five inches six and a half inches from here so you click real that friends how we will do it through this channel like if you subscribe You can subscribe by doing this, see subscribe, this 1000 profit from zero was given to your friends, now we will like our one and a half inch from here and will start from IS but one to intermediate. But the half lace that was kept here means that I have come here and your 800 more will be crossed and the enjoyment of your album is zero or bread is zero, okay then what will I balance on that day. Will put 19 Now I have subscribed to each other Subscribe to our channel Subscribe to us and after that whoever you are Jhala's life will become Jhala Asun and if - but Jhala's life will become Jhala Asun and if - but Jhala's life will become Jhala Asun and if - but is not there then what should I do whatever you are here The opportunity will come and he can do it with you in such a way that if you job number induction is ok that you have this neck EU minute then what will you do on it, will you take the difficulty on it which you will take on regular reaction, that you subscribe Indian Idol EP 104 Ad Will do and while bathing together subscribe and this disgusting so it is logging from both sides so you can write in your comment section in half an hour from today I will make this with love still if there is no problem So, respectively, it is a boy, along with this, if there is any effort for me, please do tell this to everyone. Friends, if you like my work, then please like this video, subscribe to the channel and see you soon in the next video and thank you friends. Thank you. have a nice dp
|
Maximum Profit in Job Scheduling
|
maximum-profit-in-job-scheduling
|
We have `n` jobs, where every job is scheduled to be done from `startTime[i]` to `endTime[i]`, obtaining a profit of `profit[i]`.
You're given the `startTime`, `endTime` and `profit` arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.
If you choose a job that ends at time `X` you will be able to start another job that starts at time `X`.
**Example 1:**
**Input:** startTime = \[1,2,3,3\], endTime = \[3,4,5,6\], profit = \[50,10,40,70\]
**Output:** 120
**Explanation:** The subset chosen is the first and fourth job.
Time range \[1-3\]+\[3-6\] , we get profit of 120 = 50 + 70.
**Example 2:**
**Input:** startTime = \[1,2,3,4,6\], endTime = \[3,5,10,6,9\], profit = \[20,20,100,70,60\]
**Output:** 150
**Explanation:** The subset chosen is the first, fourth and fifth job.
Profit obtained 150 = 20 + 70 + 60.
**Example 3:**
**Input:** startTime = \[1,1,1\], endTime = \[2,3,4\], profit = \[5,6,4\]
**Output:** 6
**Constraints:**
* `1 <= startTime.length == endTime.length == profit.length <= 5 * 104`
* `1 <= startTime[i] < endTime[i] <= 109`
* `1 <= profit[i] <= 104`
| null | null |
Hard
| null |
790 |
Hello everyone in this video we will discuss about the problem domino and domino tearing so basically what we have given one domino so basically this domino its height is two and with e one and we have given one domino like that we need to Fill two crosses and would be using this domino and domino OK and we need to tell the number of ways in which we can tell using this domino and domino OK so let's start from the beginning so for an eve we would be having just one way Placing Dominoes Vertically for A and B Two Ways Here by Placing Dominoes Vertically and Placing Dominoes Vertically for A and B Of ways to fill the board OK so how we can do that So basically to find the total answer what we can do we can partition the total length into two parts OK so how we will partition it something like that let's say there is one Partition at one length and the remaining length will be n-1 There is another partition and two lengths OK remaining length will be n-1 There is another partition and two lengths OK remaining length will be n-1 There is another partition and two lengths OK so the remaining length will be n-2 One partition could be at n = n-2 One partition could be at n = n-2 One partition could be at n = 3 OK then the remaining length will be n - 3 one 3 OK then the remaining length will be n - 3 one 3 OK then the remaining length will be n - 3 one partition could b at n f at length four and the remaining partition wood b f of n - 4 like that and so let's say four and the remaining partition wood b f of n - 4 like that and so let's say four and the remaining partition wood b f of n - 4 like that and so let's say the total number of wedges to tile n-1 cross board wood b f of wedges to tile n-1 cross board wood b f of wedges to tile n-1 cross board wood b f of n -1 and this wood b f of n - 2 If We -1 and this wood b f of n - 2 If We -1 and this wood b f of n - 2 If We Just Say We Don't Know the Answer But We're Just Guessing How We Got the Answer for n-2 n-1 and Guessing How We Got the Answer for n-2 n-1 and Guessing How We Got the Answer for n-2 n-1 and n-3 Something Like That's A It Will Be My n-3 Something Like That's A It Will Be My n-3 Something Like That's A It Will Be My f of n-3 Like That f n - f of n-3 Like That f n - f of n-3 Like That f n - 4 Let's say the total number of ways to tile n cross two is f of n then it would be the answer The total answer would be f of n-1 in number of ways to tile the remaining f of n-1 in number of ways to tile the remaining one area to cross one area and the number of wedges will be one because there is only one way to tile to cross one vote using one domino plus that wood will be f of n - 2 * number domino plus that wood will be f of n - 2 * number domino plus that wood will be f of n - 2 * number of wedges to tile to cross two areas so what are the number of wedges to tile to cross Two areas so basically there are only two wedges right one way is that and another way is using horizontal domino right but if we see close we have already calculated the vertical wedge in n-1 how can we say that for wedge in n-1 how can we say that for wedge in n-1 how can we say that for example it is guaranteed that the Last tile of this partition of n My end one partition will always be a vertical domino because there is only one way to tile the last one so that is this one and let's suppose there can be one of the pattern while tiles n -1 where The last tile is also tiles n -1 where The last tile is also tiles n -1 where The last tile is also a vertical domino since the total area would be remaining n minus total ranth would be remaining n- minus total ranth would be remaining n- minus total ranth would be remaining n- 2 so as we can say that this is n -2 and this is to is 2 so as we can say that this is n -2 and this is to is 2 so as we can say that this is n -2 and this is to is nothing but this thing is right because n my f Of n-2 we have already n my f Of n-2 we have already n my f Of n-2 we have already calculated and we are adding this to vertical domino so that vertical domino will result in duplication so we need to take only two patterns two wedges which will give us a unique answer because of the previous one wedge of tying n -1 We Have Never Seen Two previous one wedge of tying n -1 We Have Never Seen Two previous one wedge of tying n -1 We Have Never Seen Two Horizontal Place Side Because The Right Side Was Fixed With One Vertical Domino Right So We Can Only Take This One And We Can Not Take The Vertical One Because Vertical One Will Give Us Duplicate Answer So What Are The Total Number of wedges to tile 2 cross to here is only one because we wo n't take duplicate one okay plus f of n-3 into the number of wedges to tile this area n-3 into the number of wedges to tile this area n-3 into the number of wedges to tile this area and ha what will be that area so again we need to include only The Unique Pattern We Need to Avoid the Duplicate Pattern Then How Then What Are the Unique Pattern Also use a domino to tile like this okay so for that all this states is already covered both in f of n-1 and in f of n-2 so we will only take this two of n-1 and in f of n-2 so we will only take this two of n-1 and in f of n-2 so we will only take this two in our answer so that is why I am multiplying it by two because there are only two wedges okay plus f of n - plus f of n - plus f of n - 4 f of n - 4 f of n - 4 f of n - 4 into number of unique wedges to a two tile this wad ch is 2 cross 4 number of unique wedges we need not the duplicate one so the number of Unique Ways It Would Be Like That Okay So Basically Here Is One Toman Here Is Another Toman And Here We're Having A Domino Hair Okay So That Would Be One Way Okay Another Way Would Be If We Reverse That Thing Like That One Domino One domino second trono and third is this one is domino okay so there are only two unique ways you can say that we can have the states like that one where we will use something like that and this one domino and domino combination but to clarify that As we've seen this is already covered elsewhere in f of n-3 and in already covered elsewhere in f of n-3 and in already covered elsewhere in f of n-3 and in previous states OK so we won't take all these things so we will only take the unique one so the unique base to tile the last four length area. What would be I multiplying it by two similarly if we go for ff a minus f then what is the unique way to tile to cross the board so basically this to this if and what are the unique ways okay so the unique way would be How it will be this One and this one okay so there are only two ways the other one would be the duplicate one which is already being covered in the previous state so we won't do both okay so it will be something like that okay so we have seen a pattern here and While by seeing the pattern we can say something while with the pattern can we get our answer using that pattern let me write the same equation again after replacing a with n-1 then what will happen this l replacing a with n-1 then what will happen this l replacing a with n-1 then what will happen this l b n-2 i Am not writing one because that would be the same thing n-2 i Am not writing one because that would be the same thing This is the right way to subtract this two equations what will happen this n-2 n-2 will cancel out within itself n-2 n-2 will cancel out within itself n-2 n-2 will cancel out within itself n4 will cancel out n5 will n5 cancel out and f6 n-6 will also cancel out and f6 n-6 will also cancel out and f6 n-6 will also cancel out with this n - 6 then what will with this n - 6 then what will with this n - 6 then what will Remain so we will get f of a this side minus f of n - 1 this side ect f n - 1 f of n - 1 this side ect f n - 1 f of n - 1 this side ect f n - 1 plus we are having 2f of n-3 here and 1 f of n-3 having 2f of n-3 here and 1 f of n-3 having 2f of n-3 here and 1 f of n-3 here so if we subcut two we will get f n -3 here so if we subcut two we will get f n -3 here so if we subcut two we will get f n -3 One Time And If We Write It More Nicely It Would Be f of n = 2 * f of n = 2 * f of n = 2 * f of n-1 P f of n-1 P f of n-1 P f of n-3 That is nothing but our recurrence relation Okay so once we get the recurrence relation then writing the code It's very easy we just need to use a dp because of the recurrence relation lets say the total number of ways is denoted by a dp less state so we can have something like find base ok and in that we will be passing one argument and so here We will be making one dp table indp of size n pw and we know few things d p of 0 would be one p of 1 would be 1 dp2 would be 2 so dp0 would be one because no way is also a way what is zero significance Signified the way to tile 2 cross 0 area so there is no area so no way is one way so that is where dp0 is one and dp1 tail to cross an area using a vertical domino so put it through the tile ts thing so for rest of the things we can use solution ok wt w n to d n to right for loop we just want to simply say kd p of a w bd p of aa -1 * 2 ps d p of aa -1 * 2 ps d p of aa -1 * 2 ps d p of aa -3 and at The End We Need To Write A Question That Will Give Answer I Hope You Understand The Problem Thank You
|
Domino and Tromino Tiling
|
global-and-local-inversions
|
You have two types of tiles: a `2 x 1` domino shape and a tromino shape. You may rotate these shapes.
Given an integer n, return _the number of ways to tile an_ `2 x n` _board_. Since the answer may be very large, return it **modulo** `109 + 7`.
In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.
**Example 1:**
**Input:** n = 3
**Output:** 5
**Explanation:** The five different ways are show above.
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 1000`
|
Where can the 0 be placed in an ideal permutation? What about the 1?
|
Array,Math
|
Medium
| null |
984 |
oh hello and welcome here we are let's take a few seconds make sure the audio is working see one two three yeah it's working very good all right I'll pop the chat out so um here we are another day wow I uh um you know I don't know what to say I had a kind of a rough day today um I think I can get right into this here just see I don't have anything I don't want to show um yeah I think we're good I think it's good okay whoa all right uh life is Life's a challenge you know really is there are a lot of things to say about it a lot of things I could say about what happened recently for me but I don't want to go into too much detail I just say I had kind of a rough day today phrase it that way um yeah I do want to keep practicing um despite the uh challenges of my personal life um so I'll do a little bit of that to now so here we go given two integers A and B return any string s such that s has length a plus b and contains exactly a letter A letters and B letters the substring a does not occur in s and the substring B does not occur in s a is 1 B is 2 ABB bab and BBA are all correct answers A and B are between Z and 100 inclusive it's guaranteed that such an S exists with a given a and b okay um so probably the easiest thing to do is just um figure out which of these are larger um and basically interweave A's and B's right so this idea won't work though if a at least one a can't be woven between every B phrase it that way so basically A and B have to be in a certain proportion otherwise this is not possible um necessarily so it could be done that way um the problem with that though is you probably just want to keep a and b of equal size as you go and the reason why just alternate A and B as much as you can the reason why you'd want to do that is um if you let's say you use let's say you do B every moment and then you every you know two B's and then an a you do it things do things in that way um if you do it that way and a is actually like let's say a is like it's not half of B right so a was half of B you could do it that way but if it's not then um let's say a is a little bit more than half of B well at some point you're basically going to run out of B's if you just always do two B's and 1 a so you could do one b and 1 a once they're equal to each other um whichever one is larger you just do that one first until they're equal it's probably the easiest way to do it um and we could say could do something like the following um trying to think uh do you have to be careful you could also do uh dynamic programming here if you really wanted to it's another idea but I don't know if they really need to do that um yeah I think whichever one you have more of if they're equal you just go back and forth you know a b if you have uh if there's more of a and less of B then you want to do more a and vice versa do more B's the tricky thing here is that uh yeah you do two and then one so that way you can just always do ababab afterwards yeah that's easy way of doing it um while something like the following A and B um if a is greater than b something like this should work uh not exactly correct but yeah okay you could just make this else I could just make this else that's kind of basic idea I think this works it's fine um generate the string okay so one small issue you could probably see here is um some point you basically run out uh and one of these are going to run out when that happens um just have a loot yeah something like this try a whole bunch of different cases here oh okay uh right I think it's got to be and not or I think I did that wrong once one of them runs out then it stops yeah I kind of get that wrong all right let's try some other test cases let's do like 100 and 100 let's do like um 33 and 66 the other way around and let's do some random things like two and zero or zero and two 0 and one or like five and three some strange unusual things okay um I don't have a proof that this is always going to work but I think this works I think so could even go so far as to modify these slightly I don't know if you can still do this actually don't know if this will still work oh it works that's interesting cool uh what about the other yeah they both work I think I'm going to go for it I don't know if this is correct there might be there might there could be something you know something specific that I missed here um that would suck I'm just going to go for it some Edge case or something I missed oh got it sweet all right submit it five times we'll do the next one I'm going to do um I'm going to um yeah I'm going to stop the stream oh I'm not getting 100% though stream oh I'm not getting 100% though stream oh I'm not getting 100% though that's kind of disappointing I'll stop The Stream and then start it again so yeah if you like this like the video don't forget to like it 100% got there uh like the stream it 100% got there uh like the stream it 100% got there uh like the stream don't forget like the video don't forget to like it and you like this um kind of like my channel and give me a subscription I guess follow me on my you my YouTube channel all right yeah we'll keep going
|
String Without AAA or BBB
|
most-stones-removed-with-same-row-or-column
|
Given two integers `a` and `b`, return **any** string `s` such that:
* `s` has length `a + b` and contains exactly `a` `'a'` letters, and exactly `b` `'b'` letters,
* The substring `'aaa'` does not occur in `s`, and
* The substring `'bbb'` does not occur in `s`.
**Example 1:**
**Input:** a = 1, b = 2
**Output:** "abb "
**Explanation:** "abb ", "bab " and "bba " are all correct answers.
**Example 2:**
**Input:** a = 4, b = 1
**Output:** "aabaa "
**Constraints:**
* `0 <= a, b <= 100`
* It is guaranteed such an `s` exists for the given `a` and `b`.
| null |
Depth-First Search,Union Find,Graph
|
Medium
| null |
791 |
hey everyone my name is puru rhoda and i welcome you all to this channel today we are looking at the problem custom sort string this is a medium level problem only code and it is on the easier side of the medium spectrum now let's look at the problem order and str are strings composed of lowercase letters in order no letter occur occurs more than once okay order was sorted in some custom order previously we want to permute the characters of str so that they match the order that order was sorted more specifically if x occurs before y in order then x should occur before y in the return string now what this question states that our order string is sorted in some custom order it's not like abcd it's some custom order and before that custom same custom order we want to apply that same custom order to our str string so basically we want to sort our str in the same manner as our order is sorted so now let's look at the example state that c b a so that means c will come before b and b will come before a now the string is abcd now as c will come before a we will put c at starting as we know b will come before a so and after c so we will put b after c and before a and now we know a will come at last so we will put a at last now after that we are left with this character d now d can come at any place because it is not specified so he can come at first he can come at last he can come in middle so we can come at any place so cb ad is an answer okay so we can even have that answer dcba cdba cbda so these are all valid answers because our the cba order is being followed so now it's if you look closely it's a very easy problem uh the very first approach that we can use is to create two loops we can convert this string into an card array and we will create two loops first one iterating over the array and the second one iterating over the sdr for a particular character in order we will look when that character occurs in the string and when that character occurs then we will add that character to a string that would create a new return string that is to be returned so we'll add that character to the string and replace the specific index and care array with zero so when we do this are these elements those occurring in the order will be sorted in that particular order and the elements that don't occur in the order string that example d in this case will be left so that we will need to sort our array that care array we took earlier and after sorting that we will need to put all the remaining elements and concatenate them at the end at the starting or anywhere in the string so this is a fairly simple approach i will show you the code that you can write for this approach so you can pause this video and have a look at it but today uh now we are going to take a look at a more optimized approach so i'll first write the code and then explain you alongside so now we will create an array that will count the frequency of how many times a particular character is being repeated in that string so as the it will be counting for all the alphabets so size of this area will be 26 okay now we have initiated this array now we will create a loop and read through the every character of the sdr string so that we can know the frequency of the heavy character so now what i have done here is i am i taking over the every character of str and at their position of that character so what i'm doing is i am looking at the character and that is at the ith position suppose it's b so the sky code for b is 98 and 97 is for a that is why i am subtracting 97 so if it's a the sky code will be 97 and if i subtract 97 from it so it will return zero that means our index will be zero so with starting with zero with index we will increase it that correct for every time that character occurs now this is very simple thing to do now the next thing we will do is we will iterate over the order uh string and for that uh particular character we will check the frequency and add that particular character according to that many that much frequency so uh this here alpha order dot care at i minus 97 so order dot carrot will give me the index for the particular character and this here will provide me the frequency that is how many times that particular character is to be repeated now i need to add that specific character this many numbers of time so what i will do is i'll order dot error i not repeat so i'll use this repeat function so repeat function works on string and we are getting the character over here so i need to convert it into string so now what this step will do is i take that this character and then convert it into a string and then repeat it for the number of times that character occurs in this string str so after this step will be done we will have that first character that is the first character in the order and it will be added the number of times it is repeated in sdr now as it is added we need to change its frequency to zero so what we will do is we will take this position and set its value as zero that's it now after the step is done all the characters that occur in the order will be uh that occur that are present in order and are also present in str will be sorted now the characters that don't occur in the string order but are present in the string str will be left for that we will need to create another loop i'll just copy the same line over here why i'm taking this i is less than 26 is because this time we are not iterating uh over the uh any specific area we will be iterating over this alpha array because we will be adding the alpha those alphabets whose frequency is still present that is not set to zero so we will take it care so we will get the character as we were to create that specific pair into integer we were mine uh subtracting 97 from that character to convert that index into character we will add 97 so i plus 97 will give me an sky code for that particular index and this care will convert it into a character and this will this whole thing will convert it into a string now with string i'm using this repeat function will provide me with the frequency now here i don't need anything sort of like this i just need the frequency of that particular ith position so now let's return okay let's try to run this code so you can see this is working let's submit it so this code is accepted so this approach of ours will take the complexity of n and this is a fairly good approach that you can use if you want to improve your complexity if you want to reduce your time by a little bit more then you can use string builder but that is not very worthful because it will reduce your time by just milliseconds it won't reduce your complexity from over to anything else so this was the video hope you like it and i'll see you guys in the next one
|
Custom Sort String
|
split-bst
|
You are given two strings order and s. All the characters of `order` are **unique** and were sorted in some custom order previously.
Permute the characters of `s` so that they match the order that `order` was sorted. More specifically, if a character `x` occurs before a character `y` in `order`, then `x` should occur before `y` in the permuted string.
Return _any permutation of_ `s` _that satisfies this property_.
**Example 1:**
**Input:** order = "cba ", s = "abcd "
**Output:** "cbad "
**Explanation:**
"a ", "b ", "c " appear in order, so the order of "a ", "b ", "c " should be "c ", "b ", and "a ".
Since "d " does not appear in order, it can be at any position in the returned string. "dcba ", "cdba ", "cbda " are also valid outputs.
**Example 2:**
**Input:** order = "cbafg ", s = "abcd "
**Output:** "cbad "
**Constraints:**
* `1 <= order.length <= 26`
* `1 <= s.length <= 200`
* `order` and `s` consist of lowercase English letters.
* All the characters of `order` are **unique**.
|
Use recursion. If root.val <= V, you split root.right into two halves, then join it's left half back on root.right.
|
Tree,Binary Search Tree,Recursion,Binary Tree
|
Medium
|
450
|
1,750 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem minimum length of string after deleting similar ends we're given a string s consisting of only three different characters and this actually isn't really super important for this problem we're also given a algorithm here described in these five steps that we can perform on the input string s the idea is that we can pick some prefix of the string where all characters of that prefix have to be the same so for example if we had a string like a BB a prefix would be starting from the beginning of the string and in our case the prefix has to be the same character so we can pick this or we can pick this but we cannot pick this because there's two different characters there and so there's a second rule for the suffix is just from starting at the end of the string and the same rule applies where the suffix has to have the exact same character in it now with a prefix and a suffix the other rules are that first of all they can't intersect so they cannot be overlapping also the characters from both the prefix and the suffix must be the same I think this is worded kind of Ambiguously but basically they mean that if we have two a's here or just that we chose the character a here we have to have the character a on this side as well the quantity does not have to be the same we could have had for example two A's here and then maybe three A's over here so this is this prefix that we chose this is a suffix and this is perfectly valid but if we were to include a B in the suffix or the prefix we cannot do that after these are chosen we just want to delete them so the idea here is that we want to minimize the string s after performing an operation like this and in order to do that I think the first way I kind of approach this is think about what kind of decisions or choices we can actually make given these rules and the interesting thing is that it's not as much as you would expect like we actually don't have many choices ches here because think about any example input string for example consider this string here so well of course we want to start at both of the ends of the string because we're choosing prefixes as well as suffixes and of course the characters have to be the same right like if there was an X over here and there's an a over here we literally just can't do anything because we need to pick a prefix here and a prefix can be of a single character but they have to be matching like we have to have the same character on both sides now in this case they are the exact same character we have an A here and an a here so the simple thing that we can do is just consider this the prefix this is the suffix and then we're done then we shift our pointer inward now we get to something interesting we get to the part where we actually have a choice or you might think we have a choice we have a b here and a b over here you tell me would we ever want to just pick a single B from both of the sides given that there are two B's over here we should try to be greedy we should try to take as much as we possibly can because right now there's two be's here and a single B here well there could be 10 bees over here and maybe one bee over here or two or three or four however many there are we can take as many from here and as many from here so of course that's what we're going to do we're going to take all of them from each side there's no point in Saving any of them because we if we take all of them then we end up at the next character and that character has to match if the character does not match in both positions then we can't really do anything anymore anyway so that's why this is a greedy problem and this is how we're going to approach it anytime we shift the pointer the left pointer here and the right pointer here we have to have matching characters and then we basically shift the pointer until we reach a new character same thing over here we would shift it up until this point this is basically a two-pointer point this is basically a two-pointer point this is basically a two-pointer solution and the only thing is when do we stop the algorithm well in this case we're going to get both of these B's and this B now we get to a on both sides that's fine now we've gotten the a as well now our pointer is going to be at one character now even though the character is the same so this is very similar to like the palindrome algorithm kind of but here is the difference even though this character is the same we actually cannot remove it given these rules because remember the prefix and the suffix should not intersect so basically usually with palindromes and many two pointer Solutions we check that the left pointer is less than or equal to the right pointer that's what we usually do but in this case we are going to check that the left pointer is strictly less than the right pointer so forget that equal sign this is one possible way that the edge case could end up now it's also possible that maybe this C didn't even exist so we got rid of the B's here and here even though there are two characters remaining they are different characters like the left pointer is technically less than the right pointer so this does work out okay let's code it up the time complexity by the way is linear there is no extra data structures needed so this is a constant space solution so I'm going to initialize our pointers left and right at the ends of the string so left is at zero right is at the length of the string minus one and just like I mentioned we are going to continue while our left pointer is less than the right pointer there actually is a second condition we want to make sure that the characters at each of the pointers are the same because otherwise we can't really continue the algorithm and if they are then what we want to do is take the left pointer and shift it as much as we can so while well before we do that let's actually save the character in a temporary variable so we're going to save the character that both of these uh point to in Temp and while the character at the left pointer is equal to Temp we are going to increment our left pointer we also want to make sure that the left pointer has not crossed the right pointer so here I think we are allowed to just put less than or equal while it's at that character let's keep shifting and we're going to do the exact same thing with the other pointers so I'm actually just going to copy and paste that so while the right pointer is equal to Temp we're going to take the right pointer and decrement it by one and that's pretty much the whole code so at the end we just return what the size of the remaining portion of the string is so basically the remaining portion of our window here so we can take right minus left and add one so this is the whole code let's run it to make sure that it works and as you can see on the left yes it does and it's pretty efficient even though this time it was a little bit less than the first time I ran it if you're preparing for coding interviews check out NE code. thanks for watching and I'll see you soon
|
Minimum Length of String After Deleting Similar Ends
|
check-if-two-expression-trees-are-equivalent
|
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times:
1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal.
2. Pick a **non-empty** suffix from the string `s` where all the characters in this suffix are equal.
3. The prefix and the suffix should not intersect at any index.
4. The characters from the prefix and suffix must be the same.
5. Delete both the prefix and the suffix.
Return _the **minimum length** of_ `s` _after performing the above operation any number of times (possibly zero times)_.
**Example 1:**
**Input:** s = "ca "
**Output:** 2
**Explanation:** You can't remove any characters, so the string stays as is.
**Example 2:**
**Input:** s = "cabaabac "
**Output:** 0
**Explanation:** An optimal sequence of operations is:
- Take prefix = "c " and suffix = "c " and remove them, s = "abaaba ".
- Take prefix = "a " and suffix = "a " and remove them, s = "baab ".
- Take prefix = "b " and suffix = "b " and remove them, s = "aa ".
- Take prefix = "a " and suffix = "a " and remove them, s = " ".
**Example 3:**
**Input:** s = "aabccabba "
**Output:** 3
**Explanation:** An optimal sequence of operations is:
- Take prefix = "aa " and suffix = "a " and remove them, s = "bccabb ".
- Take prefix = "b " and suffix = "bb " and remove them, s = "cca ".
**Constraints:**
* `1 <= s.length <= 105`
* `s` only consists of characters `'a'`, `'b'`, and `'c'`.
|
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
|
Tree,Depth-First Search,Binary Tree
|
Medium
|
1736
|
1,721 |
um hello so today we are going to do this problem called swapping nodes in a linked list so what the problem says here is that we get a the head of a Lincoln list and then in teacher k um and we want to return the head of the linked list after swapping the values of the kth node and K note from the beginning and the values of the kth node from the end right so the kth node so here for example k equal to 2 so the second row of the big from the beginning and the second row from the end we want to replace the two swap the value so 4 here and then 2 here for the second example five we want to swap the fifth from the beginning so one two three four five this one here and then here one two three four five this one so we swap these two right um yeah so that's the idea let's see how we can solve it um definitely the easiest solution of all is just to use extra space and just transform the linked list into an array here and then swap the values in an array it's easier to find the positions K from the start and K from the end and then once you swap reconstruct the linked list right so different so that's very easier but it's not a very clever solution that uses pointers but let's just quickly go over it and then we can go over the more clever solution right so here it is what we do is just we create an array right we go through the linked list so every time we do not know that next and then we add the values to the array and once we do that we take the since the um the numbering here is one indexed uh we want to subtract it by one because array is zero index it and this is in Python just means the length of the array minus K right same thing here this just means the length of array minus K so basically just decade from the end and so we swap the two values case from the start and K from the end and then we recreate the linked list um basically going through the array and each time the node.x would be the node each time the node.x would be the node each time the node.x would be the node with that value and we don't know that next the only tricky trick we are doing here is that um to have to not need to do any special condition here for the head we just create a dummy node and that Domino will point to the head and we can return just the Domino next and that will give us the head so this is a pretty sureful solution but we can actually do better than this we can just do it with pointers on the Lincoln place so let's see how to do that um okay so the idea for this solution is that we can move a pointer all the way to the k case places so we move one point I'll just call it to N1 so we move N1 to basically we first we have a pointer right to K position and let's call that the first node that we want so the kth1 so this would be N1 and then once we reach this we'll Place Another pointer on the head right so once k equal to Z K is rigid right we place a node and two at the head and then we keep traversing until we reach the end using pointer P here but this will tell us basically let's say k equal to 3 right so we place our pointer we keep advancing our pointer until it reaches k equal to 3 which is here and so we mark this as the first node that we want to swap and then we place another node here in two and now we keep advancing the pointer until p is at the end when p is at the end and 2 would be just at the end minus K right why because the gap between p and here is K right and so as we move both at the same time right as we move both in one and P on each iteration at the same time when P reaches the end the Gap will be maintained because we will still move each of them uh one by one node each time so the Gap will be maintained so once the p is at the end the Gap is K and that's exactly what it means to be K from the end right so that's the idea let's see how we can apply to this example um solos here um so K would be equal to 3 right so what we can do is keep decrementing K until we reach zeros we stop right so first we start out just with p so first we have P here we advance K become equal to 3 2. and then we advance again k equal to one um so k equal to 3 and then here we subtract is equal to two we subtract here is equal to one we subtract here it's equal to zero and so we stop here and so this is N1 we Mark n one here and now we put N2 here in the head and now we advance both right so what this tells us first is let's mark this down so if once K is equal to zero we want to mark n1sp and we want to Mark in two as the head and this is for a while loop while P hasn't reached the end and of course on each iteration we want to advance p right but once we have N2 right once we set it here we're going to keep advancing it along with um with P so if and 2 here we want to advance it if we had set it before we reach the position K we don't want to care about the N2 because we want to maintain the gap of K so here um that next if it was set already which means we have friction K right okay so now we advance both at the same time right so the first one we move we put N2 here we put P here so now K is equal to -1 so now K is equal to -1 so now K is equal to -1 uh yeah of course I forgot to do this here we need to decrement k each time um and then we advance N2 again so N2 is here p is here k equal to minus 2 we advance N2 again p is here k equal to minus three k doesn't matter really right now because one situation is zero we don't care so just imagine we sub we um we decremented each time okay so now we advance again and two we have P here um and then we reach the end and now our K node case from the end is six and this one is three so we swap the values here so this would be six this would be three and we can say here that we just swap the values right so this would be in the vowel with N2 Davao and we swap in Python you can do it in one iteration for other in one line for other languages you can use a term variable um yeah and that's pretty much it right um and so yeah this is a nice trick to obtain um case from the end um while just traversing the Lincoln list um in terms of time complexity we are just doing one traversal to the linked list so it's oven time um for space we are not doing any extra space here so one um yeah so that's pretty much it for this problem uh let's code this and make sure it passes these cases okay so here's the code for the solution we just saw so we mark p first at the head of the linked list and then we have two nodes and one and two and then we keep traversing until we reach the end and each time we decrement K and once K reaches zero we set N1 to the pointer and N2 to the Head and then we can also do this by the way here it doesn't have to be at the end at the front and so we advance P each time and once we set N2 we want to keep advancing it along with p and then at the end once we reach here we know that N1 is at the kth position with position and N2 is at the kth position from the end and so with swap the values and then we'll return the head of the linked list um so pressure forward there let's run this um okay actually it looks like so this would be in two and one uh we just want this to be done here okay yeah sorry um it has to be done before we change it um okay so let's submit okay so that passes this cases um yeah so that's pretty much it for this problem uh please like And subscribe and see you on the next one bye
|
Swapping Nodes in a Linked List
|
maximum-profit-of-operating-a-centennial-wheel
|
You are given the `head` of a linked list, and an integer `k`.
Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._
**Example 1:**
**Input:** head = \[1,2,3,4,5\], k = 2
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5
**Output:** \[7,9,6,6,8,7,3,0,9,5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= k <= n <= 105`
* `0 <= Node.val <= 100`
|
Think simulation Note that the number of turns will never be more than 50 / 4 * n
|
Array,Simulation
|
Medium
| null |
1,758 |
all right so let's talk about the minimum change to make automatic final training so this question is pretty simple so you can only contain zero and one and then you can go for two uh zero one or you can go for one zero one here so basically you can do like this i'm gonna say i'm gonna create a two uh to counter so enter i would say kinda warning on the two okay this is actually like this is actually easy if you want to validate 0 1 this is going to be if i'm up 2 and the first index if i mod 2 it's actually good to uh all right and i need to create a chart so you could do a structure so if i'm r2 is not it's not uh it's not equal to c minus zero then you increment your counter one and then else if uh sorry not uh not else it's still e so if uh one zero one if you want to validate this right so this should be like one zero right and then the first index uh based on the current chart so the value should be equal to zero right i won't i want this to be zero so i multi equal to c minus here if that is equal so you value it right and c2 and then when you return right basically you just have to know like which one is a minimum violation right so i'm going to say method mean c1 atomic c2 and this will be the solution so let me run it right so i pause the test so this is definitely going to be more efficient so you can use else right and then and c2 crossbars and this can be more efficient than uh then just get rid of else right so i can just say extra length minus c1 and this is the most optimal way to do it so uh anyway so the timing space are the same no matter what method you use the time is going to be all of n the space is constant and you just have to know if you want to satisfy this string right but you want to validate it you want to validate this right so it's going to be not equal so just making sure you know the idea you are you want to validate this so you want to increment your counter based on the violation and this should be the solution so if you uh feel happy with the solution please leave a like subscribe if you want it and i'll see you next time bye
|
Minimum Changes To Make Alternating Binary String
|
distribute-repeating-integers
|
You are given a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa.
The string is called alternating if no two adjacent characters are equal. For example, the string `"010 "` is alternating, while the string `"0100 "` is not.
Return _the **minimum** number of operations needed to make_ `s` _alternating_.
**Example 1:**
**Input:** s = "0100 "
**Output:** 1
**Explanation:** If you change the last character to '1', s will be "0101 ", which is alternating.
**Example 2:**
**Input:** s = "10 "
**Output:** 0
**Explanation:** s is already alternating.
**Example 3:**
**Input:** s = "1111 "
**Output:** 2
**Explanation:** You need two operations to reach "0101 " or "1010 ".
**Constraints:**
* `1 <= s.length <= 104`
* `s[i]` is either `'0'` or `'1'`.
|
Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to be assigned to this number.
|
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
|
Hard
| null |
914 |
I I I I want a safe channel, I have to take a saree, it is cut according to my device, 131 two pieces take time, but it is not easy, it is not true that its fans are not enough. And there are guards, there are some technical tricks, make some story line policy, what about those whose health numbers remain, you want to divide them into groups, how angry you want to be, not cooked enough, you yourself choose, divide them into as many groups as you want, do it. You will have 10 minutes tomorrow in the office due to some conditions of your patients from Bigg Boss that you can make as many groups as you want but keep as many people in a group as you can, by choosing wrong dreams, you will become two in Agni Pawan, if two people are in group-1. If you are coming, then two people are in group-1. If you are coming, then two people are in group-1. If you are coming, then keep all the things that you have created, both of them should have it. If these were group accounts, how many groups will be there, it will not be your choice, it does not even have this condition, there is a condition on the elements in the group, what should this cross all be done with? As many groups as there are in all forms, we need accounts from all of them. Another condition is that all are similar and one and a half team accounts and similar, one account is greater than one, we need all the salt in it, as many group chops as we can make, how many people can we adopt in one group. Yes, you keep it, choose Robert, if you keep three in a group, then there should be three loops in all, at least 2 should be closed and everyone did not do this, also I was divided into one, there is no light, the express should be for two hours and all the groups. So now you have to tell me, is it possible to do this with one number, can this be said to them, join the group, get a free SIM number of spinner and give the number, become a game, then I will give you a cup of semolina. Let me tell you, what has not been done right, we have also made a different account, due to the influence of Sove Sangh, how many times have we become everyone, only then will I say goodbye, don't look at what currency is coming, the net balance has been kept randomly at ₹1. Note of 4 is 2036 Front part is 3 ₹1. Note of 4 is 2036 Front part is 3 ₹1. Note of 4 is 2036 Front part is 3 to 4 clearance and shear it 12 How is this kept Don't sing when thinking of dividing your divide How many people are in the group If in a group I have subscribed them 4416 That Agni of 144 Why did you do the grouping in the Chaat Chakli topic, in the historical notification also, do the grouping of one scooter and four wheels. Now, if A would have adjusted the answer, then tell me what would be the correct answer adjustment in this condition when all the closed ones in the remaining are all force a visible on tight like This note ca n't be collected from the top answer is yes, if you have kept four guns in your group, now there is no cancer in the teen, then keep it in 43 other form that you have to keep Hussain, then one more charge, keep in mind, one day he will be left as your friend. You can keep it somewhere, you can keep it in a group, there should be numbers of save type in the bank account, there should be numbers of all the groups, so if you are angry and decide this then the answer for this would have been there, if there was a total number of princess line here. Then but here it is one because again it is divisible so it is correct so we will make these last two groups so that 12 cancers of training 341 379 411 I want to tell you is this possible right in this case I am asking you this approach It is right, 15 crores, think that you can get this flower, it is not right, if your group size is a small S, you have made a mortgage which comes in a fit third, it uses a SIM, first of all, what is the smallest mortgage here, but group sai sir, you have made the smallest. If you want to do something then Gulab, where will you get stuck, don't write till the remaining two clearances 4316 So this guy who is sleeping here, how will you get stuck where the money will get stuck, you will take the size of the group as the smallest hostage and now you will give him three or six cancers 44 You cannot divide it but if you have made two groups then division is possible, then you can put a divider from here, like if you serve it with the test, you will be able to do it easily, you will know the size of this group, it is here. So many people, their victory is series, the size of the group will be the number which divides all these members. If you divide all these numbers, then you will be able to do such a grouping that if you want to get rid of all the brothers from Shimla Purnia, then if there is a number which divides all these numbers then If it divides all the old people, on the day the life goes out, if the butt is under the person due to which the hair goes otherwise then the matter will not be resolved, if this ribbon comes then why will the matter not be resolved because what is the meaning of making the junior second group, right Shubham. If you don't have the ribbon ultimately, if you become like a serial, then anger is what it means, I have become a science, I will make a cut blouse which is required by cyclists, so that you will always be happy, take care like you, if it makes grated near GCD, friends, I am one of the few. Selected and do if the cheerleader dies then your answer tube is anger choose you from that website all the numbers are divisible then you will be able to distribute and divide all the numbers yourself in the price of cement of science and you will be able to divide the ribbon which If it comes then there is no such number one cigarette, why would I make it from here, if some company requests it, then if there is any other number then the answer is not possible, make a plate of soap in plus light for you and its record Pandey was told. That you fold it quickly and they need it is this function that Faiz Ahmed Faiz ki system gise karna se loot word 2 500 first of all don't keep making request then hai Ashraf Wasim Ak of in teachers of india hai Ashraf Wasim Ak of in teachers of india hai Ashraf Wasim Ak of in teachers of india jariya tarf entries vs interior continuing Is equal to a new face map that Abu wanted at the time of loot which is IPL 2018 model take dot loot plus map mein kuch to kya fit kar do match mein map dot net dot print take off a corresponding fool become and corresponding fool become and corresponding fool become and that dipole Is night fall due from Chennai to defy and yes is everything fine, is the traffic and this water if there is any value in President, you can take it out from play store, if not President then take out zero, then why are you becoming his plus, now these slanders are the flower of infidelity, garlic is your certificate. So this part cut nickel take source code like and spongy will ask please sister in it and from five tax appointed on it so this was the only solution we had host but 350 swear now sexual now congress won me days I came out, there is a need to take it out, if I don't say so then public dare to react, that's why I am explaining to you two things that Bigg Boss 200 Haridwar birds are medium low flame, I am going to Facebook only from butt equal to zero, so your middle There is a divider, you will be able to return it by installing Shatrujit Chawal again, so as if you take it as soon as you go, these are easy people, if that guy comes to zero because of some mother, then it will be zero only then. Start doing rice on this Start doing rice on the map That on the set So 10 notice from the balance Nothing but A t-shirt A t-shirt A t-shirt So then I take the shape of To start the rice I have done this Now pimple is two, which is Paltu, which research ABC D hand map is donated, if we answer it in time, then the answer is equal to this A, the answer is equal to G, only the answer is and which is quarter inch jewelery from here, then from here You will come out, if the value of the answer is a better request, then return the answer as cute and bluntly, brother, yes Allu, this is the way of cumin, keep its size, it will become a matter of advice, if it is one person at this time, it is okay, how to give some lighting. So sufficient is a different thing, then the prince climbs, Ajay had to do it quickly on the Google Play Store Cotton Shyam, so by making Yuvraj Singh 's hands smart and then by cutting, 's hands smart and then by cutting, 's hands smart and then by cutting, you can adopt the significance. It is very simple in this, I will tell you. Gift pack is an interesting function in which you are fitting, look at the pie that is made, then point near her. If I do Udaipur in the map, then I want my body president to be one and a half inches from you and my sister to lick her, if she is not pregnant then zero. If the guy here clicks on it, then here you will get the frequency so far, in which you have bought the campaign by becoming your plus, then look at it and then it is quarter inch, find the answer from zero downwards, as you will get it, then in which match. Travel cover of Chennai Super Kings took out a T-shirt on time and started towering over it took out a T-shirt on time and started towering over it took out a T-shirt on time and started towering over it and the blue ink jets of it till now that the day guarantee you want handmade if you want a lot of how to remove both kidneys first of all zero that Nepali Now for six, from which you can extract only and only visit to and add link, you have 242 marks, your final is like the answer of the person of previous Tak, then it is like a square with the next value, which can be extracted through many banks. Neither fanatic did this, refused, when did you check that the current situation is sitting, are there recorders? Why did you check after checking? If it is regular then why else Paul? But this is a simple request, even if Gomez does the recording and makes a copy. Religion will convert in less MB. If you remember the time of inter team off then it is clear that the reporter of yours inside, I have taken a print out that Pira's one point is 100, fixed for this video, see you in the next video, what happened to Jhaal. One is Jhaal Loot Jhaal Ajay Ko Loot Kapildhar
|
X of a Kind in a Deck of Cards
|
random-point-in-non-overlapping-rectangles
|
You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card.
Partition the cards into **one or more groups** such that:
* Each group has **exactly** `x` cards where `x > 1`, and
* All the cards in one group have the same integer written on them.
Return `true` _if such partition is possible, or_ `false` _otherwise_.
**Example 1:**
**Input:** deck = \[1,2,3,4,4,3,2,1\]
**Output:** true
**Explanation**: Possible partition \[1,1\],\[2,2\],\[3,3\],\[4,4\].
**Example 2:**
**Input:** deck = \[1,1,1,2,2,2,3,3\]
**Output:** false
**Explanation**: No possible partition.
**Constraints:**
* `1 <= deck.length <= 104`
* `0 <= deck[i] < 104`
| null |
Math,Binary Search,Reservoir Sampling,Prefix Sum,Ordered Set,Randomized
|
Medium
|
912,915
|
1,192 |
hey everybody this is larry this is day 24th of the april leco daddy challenge uh hit the like button hit the subscribe button join me on discord let me know what you think about today's prom critical connections in the red work now i'll let you know what i think about this form uh if this is the problem that i think i am or it is uh but yeah i usually stop this live so it's a little bit slow fast forward but for this one it is a connection that removes will make yeah so i was wondering whether because it looks like you know there's a critical path and you have to try to figure out what critical paths there are um which is of course um uh in graph theory it's just called bridge finding and yeah and this end is gonna be ten uh 10 to the fifth um so the naive way of doing it where you know you try removing every edge and seeing whether the graph is still connected well that's not going to work so basically this is bridge finding and to be honest i don't feel like it is gonna be on or like it's one of those things that are just such a trivia type problem that if you don't know it's probably okay to not learn it because uh at least if your goal is for uh interviews um for competitive programming it still comes up from time to time but it's actually not that common either um in either case but yeah um so you need to google something i would google something like uh find a bridge in a graph um i do know how to solve this in linear time but i'm not going to go over the map the uh this algorithm too deeply um because there's a lot of literature out there this is a relatively stan i mean it's not standard it's just that this is uh standard is the wrong word because um but it is one of those uh graph theory problems that allow you know that people teach in textbooks and stuff like that and as such a lot of people know it but it's also like people know it because they were taught um you could put maybe figure it out if you're really strong in using that first search and having a couple of observations um which but these observations i just remember so i could kind of go uh from this from scratch but uh but yeah oh yeah and this is not even a hint this is just using tarjan's algorithm and i was just curious what hindi can give you that's just you know finding a bridge and of course similar to what i was saying if an algorithm has someone's name on it you know it's probable that it's okay that you didn't come up with it i think so this is kind of a almost like a useless interview problem as a result um or like you know like you can learn it but i it doesn't i don't really think it comes up that often on interviews but i could be wrong uh so you know i would study things that are more um that would come up more commonly unless you really ran out of things to study for um but yeah but the idea behind uh excuse me i have some i have allergy so like my foe is a little bit itchy but yeah but the idea behind this is just um it's just this idea of back edges um and i'm handwavey a little bit as i say said try to find uh like because this is such a topic that people have discussed that you can probably google it and it'll give you a good enough uh literature on it so i don't feel like i'm to go that deeply into it but the general idea and this is going to be hand wavy is just that um if you draw a graph um and you do it that first search uh you kind of want a definite search tree um a path is critical if you think about it from in a perspective of a deaf research tree um a path is critical if there's no way to go to a point before that path exists so basically if you do a recursion and you go you know lower under on the recursion stack um there's no way for you know there's no edges from a lower note to an earlier note so that's kind of the general idea um and then you kind of you know from that idea there's a lot of bookkeeping so let's get started um you know you can also google this algorithm because like i said you're probably not gonna um figure it out for me i have this idea so i might not implement it correctly because it doesn't um doesn't come up that much so i might just mess up but you can watch me you know try to implement something that i know the algorithm of live and then see what happens right so yeah so i just edges is the code to i like to put things in an adjacency list so yeah so connection is just a and b right okay and now we have to set up a few things i don't um yeah i think yeah okay it's time i never know when these uh keywords as well so parents for you to know yep i don't know if this is necessary it's been a while i like to make this an uppercase n just for consistent with my other code in general um uh first visited something like that maybe i could roll that into uh yeah i'll try i'll go for readability i generally uh okay let's actually use this and then oh yeah the lowest point that it can visit it's also just i think and yeah and then so i think those are greatly the idea of setting up and then we just do for um x in range of n this is from just seeing if this is one index or zero index or several index i guess that we need to answer right okay and then now it's a little bit messier so okay so let's just say music true um so yeah so then first visited of current is equal to t uh maybe t one and then the lowest that we can visit is also t now is it t or node nope okay and then now for uh x and edges of current if not visited of x complied the first search x um but before that we want to set the parent of x is equal to current okay um and then now we have to look back and i messed this up enough time to know that i always have to say this part out loud so the lowest so i think i've been just kind of thinking about this too much but uh but yeah but so far what i've done is that okay for each node i was focusing on thinking about this part that's why i haven't talked about this now usually i'm more talkative about it but yeah for here let's just say for every you know we go from every node and if we haven't visited this node yet we do it that for search um in this case i think this is a con connected graph so i think it would you only need to do this once but in theory if you have a forest or something like that then maybe you can yeah that's just my general pattern and here um we mark it as visited so that we don't visit it again and this is the time that it is first visited and this is the lowest that it can be visited um meaning that this is the earliest uh past that can get to and this is just setting up the parents um do i need the parents please forget if i need the parents uh yeah i think we do actually okay and then now the lowest of current is equal to the lowest that the debt first search can go so it's just and then lowest of x um but basically this is saying we update the lowest uh on the if you think about the recursion tree um the earliest time that um an edge that is connected to this edge can go um yeah so else so if this place is already visited and the parent of x is not equal to current meaning that if we already visit this price or the other way around so hmm no yeah uh if x is not you go to so we already visited and this is not literally like the back edge like literally the parent then we um do something similar where then we said that you go to the first visited of current uh or can i mix it up no i mixed it up yeah okay um yeah basically this is saying that if the edge that we're looking at we already visited um and it is not literally the one that is like we just visited then that means that it went above the edge that we visited and then we want to see what is um what is the time we visit that area and that we set the lowest current here um and then here now we just do if the lowest of x is greater than um the first visited of current then we want to add this edge as the answer right uh x and current i guess um because basically this is saying that okay we look for all the um you know we have this recursion tree um we went for all the things that can possibly visit and all the things i could possibly visit um we cannot get to a node that we visited earlier and in that case that means that this edge going from the current node to the x node meaning that this edge um if we remove it then everything will be contained and therefore or you know it would separate the two uh the two graph right that's basically the idea um i think that's roughly yet i think i have to set some non logo on t actually but i think this is mostly it um yeah let's give it a try usually i test a little bit more while i'm coding it but uh obviously this is now wrong i'm just trying to look at other examples but okay um can i mix these up oh this is the lowest of hmm that's it like i said i usually mess up one of these so i'm trying to figure out uh did i mess it up here so okay and did i actually visit uh that yeah that seems okay yeah this seems okay so what did i do wrong let's print out current real quick i set up the edges correctly yeah it should be okay so we do visit everything so if we haven't seen x yet we set the pattern of x's in current yep we do a definite search of x well that sounds reasonable and then now we check whether the lowest of the current node um and this is and then we set it to the lowest of the x because that should be updated with whatever recursively and if oh is this right oh yeah okay i think this is right um that's all okay let's take a look so one three so where do we go first we want zero one two one and then two and then one should go to the three right uh okay so this is not even getting here does this go for at all did i mess something up hmm oh i am dumb oops huh i'm so used to these i don't know how that still mostly worked but okay fine okay so that's good just a little silly mistake i was wondering i looked at that code and i keep on saying like it just looked okay but in a weird confusing way but yeah so this looks good um yeah there probably may be some edge cases let's try at least one of them oh that's just a two uh okay looks okay let's just give it some more secrets for time's sake uh may test a little bit more intensely if i wasn't um okay cool i was worried for a second that might get time limited but this is linear time as i'll go through in a second so yeah um so what is the time complexity of this right well this is going to be called um n times where n is the number of vertexes and for each edge we will go you know each edge that each connection each edge that we're given we it will correspond to one well i guess technically two but you know um over one number of edges in edges and for each of those edges we only visit it once right so this is going to be linear time in um in the size of the input which is all of read type we plus e where v is the vertexes and uh yeah and u is the number of edges so and in terms of space as we mentioned well this is going to be of e um so yeah so that's going to dominate and all these are all v where v is and which is the number of vertexes so we get linear time linear space and that is i believe that's tarjan's algorithm i actually don't remember um that i just remember for me to remember is just to remember the invariant of this problem and observations that um that what i said about the tree as i mentioned before i'm not gonna go into that deeply just because uh this is a well-known algorithm so uh this is a well-known algorithm so uh this is a well-known algorithm so there are probably a lot of literature about it and i am a little bit lazy to kind of or like i'm what i'm gonna if i were to explain off my head it's probably not gonna be complete because um you know that's just the way it is uh because i didn't do any research about this it's just me solving this live right um but yeah uh the other one that you might kind of see that is similar uh just to kind of give you another thing is it's called um articulation point in a graph and that's the one that is instead of finding an edge you find a node that um yeah and you have a similar algorithm here to this one where you know instead of an edge you look at the node and that node will allow you know it's just a different if statement essentially um i believe that it's because i have to think about it again um but the concept is still that you know you have these uh that for search trees and then yeah you want to you know uh a point uh vertex is an articulation point if you cannot reach you know to a time to know that you have visited before that which is connected to graph into two different ways um but yeah um yeah i think that's all i have i think yeah um maybe i could explain this part a little bit more but i think that's what i have let me know what you think um hit the like button the subscriber and join me on discord like i said i don't really buy you this one that much for an interview um but you know here it goes so yeah uh take care of yourself good luck on the weekends for the contest and stuff but you know enjoy your weekend hope you have a great weekend and i will see y'all later bye
|
Critical Connections in a Network
|
divide-chocolate
|
There are `n` servers numbered from `0` to `n - 1` connected by undirected server-to-server `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between servers `ai` and `bi`. Any server can reach other servers directly or indirectly through the network.
A _critical connection_ is a connection that, if removed, will make some servers unable to reach some other server.
Return all critical connections in the network in any order.
**Example 1:**
**Input:** n = 4, connections = \[\[0,1\],\[1,2\],\[2,0\],\[1,3\]\]
**Output:** \[\[1,3\]\]
**Explanation:** \[\[3,1\]\] is also accepted.
**Example 2:**
**Input:** n = 2, connections = \[\[0,1\]\]
**Output:** \[\[0,1\]\]
**Constraints:**
* `2 <= n <= 105`
* `n - 1 <= connections.length <= 105`
* `0 <= ai, bi <= n - 1`
* `ai != bi`
* There are no repeated connections.
|
After dividing the array into K+1 sub-arrays, you will pick the sub-array with the minimum sum. Divide the sub-array into K+1 sub-arrays such that the minimum sub-array sum is as maximum as possible. Use binary search with greedy check.
|
Array,Binary Search
|
Hard
|
410,1056
|
1,260 |
Robber Guys Welcome Back To My Channel English Video We Are Going To Solve It's Too Good To Show What Is Governor Statement Here Given A To Read Off Side Is Minute Ventral's Unit To Shift Brigade's Times In One Search Operation Element Attitude Is A Boost To great i g plus one element airtel.in - Wants to plus one element airtel.in - Wants to plus one element airtel.in - Wants to grade five plus one zero element and great and minus one mode 2808 sirv problem hai kya agri de rakha hai do digit ok end into end size ka aur 1 inch idhar kya Seeing that what we have to do by giving is that we have to shift it till the times. What is given to the grade only in the operation. You have been told that if the element of the grid is back what do we have to free it on which I G? Plus on the dominant skin column on the phone, it is okay that end has boiled in it that if this is the last element of any disease, 10 minutes next column, then it will not happen, what will have to be done next, the first Olympics of the disease, okay then you will see here. That's - 52 - minute say last most - 52 - minute say last most - 52 - minute say last most last element last Olympian in here see on Islam I Amit Saxena share this play 10 here okay so in this problem canvas gram pal mein ke vande has been placed Diet minute, we have to do all these biscuit operations till one time, okay, if you have given then once you set the other one, then shift it again. Okay, so look here, where to save the world, next. Olympic is on the next column, you are on the next column, free is on the last column, it is on the next row, it is on the first column, and here it is on the first column, then full is on the column, and the column is on five, six is on the first column. On column is on five, six is on the first column. On column is on five, six is on the first column. On its next row, on the first column, here on Happy Seven, on the maximum, on the next column, on the eight column, on the maximum, a pin or colors, emphasis on it is the phone here, so what we will do till one time, if we set it, then we will solve this problem. How will we do that? Let's see what we will do here. Na took one, we will follow the gas. Hmm, okay, according to this, what will we do with this rectangle and death index, we will do this with the fabric value ing gift jewelery here, so we have this here and column here. But if you form then here you have done the size of the disease is correct Roca size is book size and is of English here this is great size so what is possible in both are three both say this also three Yes, and this is also okay, first of all, what will you do, will you create a broken vector, here was the scene, what will you do after this, everyone will only expel you from Jio, okay, now what will we do here, this is a pro. Okay, where will we give it a loud gallery, this will be the form, so here what you have is zero instead of zero, so here in the give one example, you will do Z plus i.e. do Z plus i.e. do Z plus i.e. you will divide 051 with hand gesture and then divide it. If you do it, will it be done by 200, then if you do a model of zero for free, then here also it will be that zero will go to one or it will be how many of z plus of plus, which is only if we do 1051 by three cases, then it will be one i.e. Where do we have to give the value of G-20, if we want to i.e. Where do we have to give the value of G-20, if we want to i.e. Where do we have to give the value of G-20, if we want to stay on the zero line, then what is before this video channel is one, this is the value of the grade which we have made here, we will give it here, then I would have used another color here and here. But it will be considered as one, then what will we do? For 0, we will see whether the SIM is a young man or not. Here I have come here, A plus one, two, three, you will be forced to divide by 09, then the theory will be ok, then how will we do one 0? You will divide by plus one two three, where will 2017 go here, then you have to do it, but here we have done it, then we will see that this is 0202, where to give its value, so here it is 10 two, so G plus two plus 131. If we do 0, then plus two plus 13430, this is what it is right here that after doing the next here, the earth has come on the floor here, you will do the same job, so what will be all this, get this next value here and only here. Trained value only here, then here neither, now try this and fashion, we will see that it is intact, it is doing, for 102, we will see that it was 1020, this is zero plus, i.e., if 1020, this is zero plus, i.e., if 1020, this is zero plus, i.e., if you do this from the second entry of Vansh Court, then 0 plus. If we use Mukti one again, the same thing will happen, then this is plus K i.e. hero will happen, then this is plus K i.e. hero will happen, then this is plus K i.e. hero plus one, we will make it 3710, so this is what we have to do in this, right here, we will increase its value here, we will keep it here, then what do we do? If you look at one side, you will see it or not, if you look at it for want, then there is one, that is, 101 plus one, if you share two, Rafi, if you divide, then you will divide 2051, from three to four. If you commit murder, then we are pizza plus one or not, bun plus one. We will do it from two or three, this is what we need to eat, its value is told to us, if we have to give it here, then it will become white again, we will do the prescription for benefit, from here or from, if you do it, then see, the intake will come here, where will it come here and where. Will come here but we will see this fort breaking down, where will the value of two go, if we see that then we will rally to-do, two go, if we see that then we will rally to-do, two go, if we see that then we will rally to-do, two plus will divide by 1343, one plus two and if you do this model then 040. If we follow from Plus i.e. two plus 1343, then what follow from Plus i.e. two plus 1343, then what follow from Plus i.e. two plus 1343, then what will we do? Zero, this is what we have to do, we have to put it before it, nine has to be put here, how to do this code, let's see, first of all, what we have to do is to-do, to rate the tractor, what we have to do is to-do, to rate the tractor, what we have to do is to-do, to rate the tractor, right tractor. Will take intention tennis person's size date size eligible then one stop will see na in your great is zero take here against excise act then you will sign here the reason for this done in all it happened that what will we do we would have saved two rupees Have inch i0 Then what will we do Ninth Day No Grade Three Grade Spelling Mistake Its Eyes Loot i Plus This is done Then what will we do We will live Na Television President Stand Bridge Ajeeb Plus done What were scientists doing Universe1 I Plus was replacing the Z Plus thing, it was dividing it, Dot Print Rocky S is evidenced by Road Size Free Mode, what is that called, it was cut from the grade side, CI would be there, what did this model of Z Plus do? It was great from our side that Idea dot Raees, this is done, by pressing it, someone used to say great, I send it like, I will indicate, my work will be done, then what will we do on return, we will add it so that the return is complete. It's time to submit, it's time to thank you.
|
Shift 2D Grid
|
day-of-the-year
|
Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times.
In one shift operation:
* Element at `grid[i][j]` moves to `grid[i][j + 1]`.
* Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`.
* Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`.
Return the _2D grid_ after applying shift operation `k` times.
**Example 1:**
**Input:** `grid` = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\], k = 1
**Output:** \[\[9,1,2\],\[3,4,5\],\[6,7,8\]\]
**Example 2:**
**Input:** `grid` = \[\[3,8,1,9\],\[19,7,2,5\],\[4,6,11,10\],\[12,0,21,13\]\], k = 4
**Output:** \[\[12,0,21,13\],\[3,8,1,9\],\[19,7,2,5\],\[4,6,11,10\]\]
**Example 3:**
**Input:** `grid` = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\], k = 9
**Output:** \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m <= 50`
* `1 <= n <= 50`
* `-1000 <= grid[i][j] <= 1000`
* `0 <= k <= 100`
|
Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one).
|
Math,String
|
Easy
| null |
3 |
Hello hello friends welcome to my channel again and special we are going to talk about letter code pack problem longest serving and petting character 200 feet Agrasain if you are there then please subscribe NDA if you like it then please like it ok so let's start For which I had started the playlist of Topper Interview Questions and Applied Questions, so this is the problem which is this playlist problem and I have already uploaded the first and second problem video, so if you have not seen it, then the subject definitely came up once. Please note that the link to the solution for the second question will now be on the button, so if you have seen it, then check it out and once again I will definitely tell you that this is a statement, read it once for this play list, what is the flag written here? If you are targeting this to gas companies then you should like this, okay what will this be but for technical interview, it is job based, it has background, it will clear you, will make you strong, but I would say that you can only face ok on companies like Google. There is no need to target, but if you are thinking of placement in any company then you should start this playlist once you have questions, if possible, do it and subscribe. Okay, so now it is school, so he has started the line. It is very simple and straight forward to tell how father Mahadeva has acting, what to do in it is difficult to find the length of the longest serving and you have to print the length of the gas tanker for which there will be no matching character. Okay, so this is very simple to understand. The cutting will be ours, I can take it on the board on the internet, as if we will have characters soon, till 0291, it will be locked here, it is not getting better, okay, so this is done, now we wear it in school also, Alawalpur fast is over, there will be a reaction, there should be a pause in the past, maximum. When our length will be made, how much land will it have, then it is okay to remove assistant in this fort, so now let's go a little, let's look carefully at our custom, what is there in the pen stand, your length will be only up to 51234, its length is That will be okay so if you try this after the author is removed when in school that you will be watching then here it is okay we are Indian source position on were hunters April - closed circulation so were hunters April - closed circulation so were hunters April - closed circulation so what will you do with these two A pan for male gender What will you do now Every PS Will you repeat the character How far is the military Such a possible position that I got here till here There is somewhere for the first position Now let's assume that I will get here For the third position tell me so If we are getting it at the position, then the loss is on the display. Come, I will check the image from the position. I will take out the image till A position where the return of the end fitting is being received and its length will be seen in mine - I seen in mine - I seen in mine - I plus one will be added. I will do it for all and SP will be maximum, I will front it, so if you look at the substance till now stand 1504 India, to do the thing, if you reply like now, then you will have complexities, it will go sexual, now means, what will happen to you, this 10.9 sexual, now means, what will happen to you, this 10.9 sexual, now means, what will happen to you, this 10.9 app launch Done, there is 9584 on the pattern, otherwise four will be set here and hour of five will be missed by 500 yards. This plus, if you feel like it, there will be new uploads, so basically what will happen to you, it will give you TA DA if you used this app. So yes, this is right, it is not wrong by any means, but this deposit is not fit according to the complexity, so now we will cover it by using it and what we will do with it, we will do it in a proper way and according to the complexity of ours. You should set the question, that is your solution, let us look at it, now what are we doing, we are preparing for the gas, let us first understand and where we can save our time. If you want to find out, then we had gone for the first audition like this, here I am going in this position, if we look at these two carefully, there is some common part here which is happening every time in the calculator, this thing happens again and again - Bar bus calculator for every again - Bar bus calculator for every again - Bar bus calculator for every environment is tech comment for till time so every time calculator is happening if we do not want to calculator this thing a text then what will happen to us that their time was sleeping earlier they can tell Now let us understand this in a different way, first of all, let us understand the concept that we are taking in this compact, this is the packet, okay NDA is ours, this is how it is, I give it in character to some extent, right now in teacher character, till now Okay, now look, let's subscribe, we would like our password to be simple, so only yes, okay, so if it is black, then if we are looking at the next character, this is the next character, then this next correct can have two positives. Till now the block of the problem is fine, I have checked everything till now, so let us look at any rectangle character along with this block, there may be two positives here, either way, it will not do anything, Means which is in our block. It will be added directly, nothing will be there will be no problem here and it will be white in the block that Aishwarya is fine, what should I do? This block is there and after taking the actor on it, they will change their name as Defeating Character. If there is no problem in this, then this lock will increase. What will happen in the disc by closing the length? One of its clocks has fallen, the plane tech increases and if nothing like this happens then the problem coming here is that the problem is in the sense of your repeating. If you have used this character in your blog, then first of all we understand the corporation for the first one, like this example is given, after the lock is locked, then you have addressed taking one, then you have broken for a reason. Only then you do n't have any problem in your budget. Now look after yourself, no problem because Baker is already not in balance, then by putting this you can only have problem with your wife, even then if you are against first then second one will be like. If there will be a problem, then no, if it is the reverse, then there is no problem, only then there is no one, do it before this, then put it in it, now there is 1 glass, now you will see ours, if till then you have not subscribed to Apna Bagh, then subscribe, instead of hanging by spreading the toes, one To explain the mango tree and Laxman, I am going to share this photo, as long as I have a cutter, I want to add this one, if I try to add one, then I have a problem. Why Acceptance and Punished at One Time is already in our block, so what to do in this block, if we are trying to do it, then it will have to be done as a criminal, till then I will have to remind all the letters, so all I have to do is subscribe. Removed it and set it here as the 9th box length. Time is done. Okay, now I will put it in one place which I was liking at the time of second. Now see, I will try to add it. C is the reason to remove him because immediately after submitting it here, after submitting the question, if you don't subscribe, then we have reached this limit of removal and appointment only when it will be removed, after that we will remove one and a half, everything that is without solid will be deleted. Come here, it's okay that this seat got late and my manifest like DSSSB, after that now C will come, so look, we have kept with you since August to see the MPs of both, if you do n't keep the button directly for Raghbir, then you had ABCD key tied with you. Okay, now what we have to do is let us do this thing, now what are we seeing in this thing, this is our subscribed part, this is the part, we do not need to fold it equally, now see how it is happening, now where is it? Two-three things which are being used are where is it? Two-three things which are being used are where is it? Two-three things which are being used are Chakrayudha and MS Word where needed but only what kind of character you mean I am also going to be mostly used here, now I am using it fanatically for this, right. If you stop here then you can use map and waste up till here but I have used it for this I will store the tractor frequency for the character and you see in this team given that it is not just the English character, now you will also get the English symbol in digits. There will be end space also, okay, so I will use it for today's rally, so I will keep the vacancy in my tractor and our block is in two interviews for the block starting point of Indian Point, so here we have our torch, it is going to be used. Is 2.1 A So 2.1 A So 2.1 A So now what is India and now if you understand then if you have understood then now I am saying this because it is the least then you will understand what I am doing that I am basically a first point But till here for the encounter, I see if the shortcut points are joining it, if you want to input the lettuce character in your blog, then you have to see the connection of both of them and see if there is no problem, then it is simply sprinter, no paper. Set it ok and here if you have to calculate the length, I have this eye and this is the chapter then it will be very simple - - First use this and if there is problem then subscribe that if the frequency of this character becomes zero then calculate in it. If it does n't become 0, then remove me until it becomes zero after consuming it. Like from now on, from half the pile in your block, there was this problem, there was beans, there was the problem, auspicious problem, death, you got the problem but if someone's talk If I remove it in this way then I will face a problem, pregnancy will not be 40, it will not be zero even after removing it, when we remove it will remain swollen, then this loop will be checked, will we take it by quarter inch or not? We have to go by increasing the first one. That young man go up and subscribe if you want to subscribe then select here if you are not subscribed then meet it with a cross your code which is there I salute you were kept in maths for 10 in the court nice one because it The maps which I opened because I set the set point to 180 would have always been dry. As far as what is available by train is greater than useless, after closure, it means you will have the question of dust inches, so first of all you have to check the baby for testing. If there is a balance, then we will not have that unremitting character. There will be no character in it. All the tunes of Swift are written 60. After that, what we are doing is check in sec. Kilo. Let me put the character in the second point which is 'A' check in sec. Kilo. Let me put the character in the second point which is 'A' check in sec. Kilo. Let me put the character in the second point which is 'A' basically. If you are not going to put it then how come what was seen here is fine so let's see here if frequency is 30, what we mean is that somewhere in the block which is already there is one upcoming character and that can be present. Printing means that we have to go by removing it from behind, so basically before consuming it, we removed it to a minimum and this character is a reminder and we put it in front, so to move it forward means that we have removed that block which is ours, this is this block. Now we will remove that character from here, okay so this thing has happened, this has to be done until the pregnancy becomes zero, then if it becomes zero, then what should I do, now I will use this character in my blog. If added, it is derived from the accident and the seconds are fine till 2001 and in that case, do the calculator with each of your friends. If you see, here I update it with the calculated amount, then after doing Kaliyug till the time it is reached. Till then I will subscribe, after that I will return it. So this much money will be debited in this question. You must have understood the question explanation code, everything. If the meeting was held as a point of order, then you can ask me in the comment. Edit Telegram channel. You will take it for joining planning, there also you can ask the doctor about this question, the link of these question calling code is given in the description box below, you go and check it out once and a question is very good for toe pointer constipation. If the question is a two point question in which it does not do then you can explain it well with this explanation and why we use point here, how are we using it, then basically the printer becomes right, it becomes zero when it is okay. Hmm, I will understand that till the loss of my second, I will make the knowledge of line first - so if we make the knowledge of line first - so if we make the knowledge of line first - so if we see, it will be two in. VPN approach for students is ours which is much better than the brute force price. So if you did not understand that So how did it happen here at the point, so you repeat it once again, okay by going back and if you understand, okay, so this was so much in this video, 39, now the next is dominant.
|
Longest Substring Without Repeating Characters
|
longest-substring-without-repeating-characters
|
Given a string `s`, find the length of the **longest** **substring** without repeating characters.
**Example 1:**
**Input:** s = "abcabcbb "
**Output:** 3
**Explanation:** The answer is "abc ", with the length of 3.
**Example 2:**
**Input:** s = "bbbbb "
**Output:** 1
**Explanation:** The answer is "b ", with the length of 1.
**Example 3:**
**Input:** s = "pwwkew "
**Output:** 3
**Explanation:** The answer is "wke ", with the length of 3.
Notice that the answer must be a substring, "pwke " is a subsequence and not a substring.
**Constraints:**
* `0 <= s.length <= 5 * 104`
* `s` consists of English letters, digits, symbols and spaces.
| null |
Hash Table,String,Sliding Window
|
Medium
|
159,340,1034,1813,2209
|
450 |
Half of our today's problem delivery in binary search tree means tasty, now we have descendants, if anyone is committed to delete the value of the goods, just delete this number, okay, then we will have to do it to everyone, then skin elementary. Mid the best e After clicking on that what to do is to do your main operation delete e New Delhi limit in BSD Okay so now we have to search the limit first of all so to make it true we gave our point like idea now inside BSP There is a property that inside the binary search tree, the number of women present in all the equipped solutions will be greater than the value of that particular note, okay, and the value of the one which is on the black side will be less than that note, okay, so here But if you reach on time, it is more than water, now all the big reasons are in its favor and if it happens in a week, then you will feel left from your point, it will definitely be somewhere on the side, now we have reached here, let us have tea when we have got it, this is its sequel. So, this one will be budding, our first task will be completed. Delete the search ribbon comments element. Now we have to add and delete this mask. By doing four with this, we can sleep first, anyone on the left, anyone here most of the days. And in diet too, someone is sub-nano second, in life in diet too, someone is sub-nano second, in life in diet too, someone is sub-nano second, in life someone is best and white, someone in name is the third last to ask in life, someone is fort left, someone is right in life too, first of all he sees the condition, I fell in Banaras, tenth eleventh. If Pi is in twelfth, what will we do in this case, we will directly go to this period and delete this note located here, we will undelete it, BSP will still be there, so the attacker will be inside the heart during this period, instead of directly tap return, OK, show more. Why are the fans angry in that and second case, I love you that I was five, that's good too, okay, free to four, okay, we are lemons in this, but we don't have to visit, now whatever has to be done, what do we do here if the applicant deletes it Okay, so let's connect this and this, nothing, now we will subscribe for that, okay, this subscribe means return, there is a left subject, that particular is non-stick, now there is something on the non-stick, now there is something on the non-stick, now there is something on the left in the development of our third soap and society. No, if there is something in life, then what to do inside it, connected to pipe 632, sir. Okay, so we will edit it here and make it the highest, that is, we will connect to it, all this is only our day will also come, torch here. It is a light subject, if I share the benefits then it is okay, a little bit, he will understand in it, okay, I give two separate taxes to this passenger here, 110 and 511, other hands free seats were the seventh, yes, now this one which If we delete it then what will we do to delete it, for the same reason, even after replacing it, when our BST is a binary search tree, then what will we do in it, we can do two things in it or So general of your channel, whatever is the maximum note, replace its maintenance, okay and delete that turn because the extra will go, okay, what else can you do, if it dies, then replace its minimum balance. And if it keeps on deleting the nutrition and co, then what can we do that if our glue is stuck to the subject person, that is, in the replacement, the growth could be increased to a maximum of nano, then we replace it with the pan. Look at the time, here we have replaced this note, now we have replaced this Navodaya, we have a strong one, what will we do in this, we will delete the others, I will delete Dilip Deaths objectively, to delete this note, using recension problem, delete. If you do then why do this function further, we will see for ourselves what type of note it is, we will start it from that time onwards, it is okay with love standard, all four conditions, what is to be done inside it, the most important one was that your heart is enough for this day, now Ajay. Do it to Ajay that this matter question delete no day Tasty examples kept three This is directly placed inside this file 3624 7 Inside this we have to delete cheese and with Okay so first of all we will search it white but somewhere with fat If it has increased in the right house and writing in our life, we have got this note, okay, now we have checked the last one, subscribed in the most, if we want two of these, then what do we have to do, we can do these two things or you can do the left software. If all is well with that flat, then there is a maximum value, either we will delete that round by replacing it with it or we will delete it by replacing it with the minimum value of the side that is possible. Okay, so what they have to say in this question is that when It is till the minimum balance which I had deleted by replacing it, we will have to do the same, the question is, okay, so now how will we look at the even number, now let us come to the calculation using if our balance is far away, right? Something has to be done within it, break the record on the world record, otherwise we have to burn Saturn. Okay, now I search that element. If the value of the increase is the value of this route, it is more of ours, as in this case. What should we do, we will use black paper, that is, the left of milk and that is the ace, this laptop teaspoon, which will be used to delete the element, okay, you call ahead, in the Tilak of Digit North Road, delete the committee in it, just like this. Sorry like this if the value is definitely that teaspoon of milk was right equal you New Delhi this note lie's flash light like that I have deleted it I felt tip if instead of the conjunctive root of the third right if you give me a bag of milk equal today If that happens, what do we have to do, that we have to delete the phone number, that we have to delete this North, Uttar Pradesh, what do we say if one route's f12 is equal to the end of both taps, if both the taps are right today milk Don't take a 1222, then we will delete it on tap festival and tweet it directly, if the one who left the milk, the one who left it, how should he get upset and leave, that Rudal should no longer be a journal, notification meaning and the writer of the milk, he knows, what will we do? If there is no milk light, then we will delete that note and make a separate vegetable out of it. Done milk left is fine, Shimla is optional in it, brother, what will happen here if the last one of the route is that it is our city and tax is but. Doodh kar life were in, that doesn't mean sulking, if there is something in Lakshmi Baikunth bright, then we will return a ride of the route, okay and this is our last with if, that means this is what is left, last cash loot winner na and right me nanna. And if someone's chest is back, then what to do in this case, then the smallest element point, Colonel fly31, here in this case, they have done right, everything is fine, small salman, then what we have to do is to make a small statement point, interior smaller responsibility is the most. It is dirty, so we create a separate function for that country, when I will helplessly animate in this one, that in these tears, this molest, I will pass it further, that 19 is fine, then it is not stopped, the root that If this milk unites another record then it becomes red then we will return tap A Okay okay if in 9th where will we get the slimmest smooth element will be found inside this person till the time our right vegetables when as many as our subscribe most element that juice - The element subscribe most element that juice - The element subscribe most element that juice - The element hua is inside it, so what should we do if the one of milk is left present, okay, if we get upset, yes, sorry, a wise, the hu of the root is the present, we are welcome, okay, so here we define a smooth. Let's do this, the interior makes the minimum equal to zero, there is still more and we make the minimum equal, till now it is in our channel, it is of milk, what will be the value, nothing has happened, brother, let me give cotton a moment which is cheating. Afact is good, okay and let's do the tax here that the roti was taken, the value of Hindi will get tired, in the knowledge side, okay, the knowledge ticket will be available to Amitabh Bachchan, now that we have replaced the stories, this model is definitely going to be replaced, I am waiting. Replace equal to a slum pass the ghost's right toe ok root's responsibility is to play we have to replace this with this then this is the value of its a one moment tu main gym playlist ok but what should we do So, now we have to delete the volume of milk to be replaced, then whatever is right for milk, we will pass the torch light of equal you delete no root and now which one do we have to replace, create replace a, okay, we are here. And now our Choudhary, I don't have anything to do but turn on the doctor, let's turn off the torch and see, oh wow, it's 2013.
|
Delete Node in a BST
|
delete-node-in-a-bst
|
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return _the **root node reference** (possibly updated) of the BST_.
Basically, the deletion can be divided into two stages:
1. Search for a node to remove.
2. If the node is found, delete the node.
**Example 1:**
**Input:** root = \[5,3,6,2,4,null,7\], key = 3
**Output:** \[5,4,6,2,null,null,7\]
**Explanation:** Given key to delete is 3. So we find the node with value 3 and delete it.
One valid answer is \[5,4,6,2,null,null,7\], shown in the above BST.
Please notice that another valid answer is \[5,2,6,null,4,null,7\] and it's also accepted.
**Example 2:**
**Input:** root = \[5,3,6,2,4,null,7\], key = 0
**Output:** \[5,3,6,2,4,null,7\]
**Explanation:** The tree does not contain a node with value = 0.
**Example 3:**
**Input:** root = \[\], key = 0
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `-105 <= Node.val <= 105`
* Each node has a **unique** value.
* `root` is a valid binary search tree.
* `-105 <= key <= 105`
**Follow up:** Could you solve it with time complexity `O(height of tree)`?
| null |
Tree,Binary Search Tree,Binary Tree
|
Medium
|
791
|
849 |
hey everybody this is larry this is day 16 of the general elite code daily challenge hit the like button in the subscribe button join me on discord let me know what you think about today's prom um yeah i don't know what else to say about that it's saturday uh there's a contest in about an hour saturday for me maybe sunday for you there's a contest in about an hour so hopefully this is a good warm up we'll see today's problem is 8 49 uh maximize distance to close this person um definitely especially these days now you would have a mask on i suppose uh but yeah uh let's say you have uh you one at least one empty seat and at least one person seating uh maximize that distance to the closest person okay so you have this then the coasters is two okay um of course this person is three seats away okay um okay so i think this is pretty straightforward to be honest um there are a couple of ways you can do it i think you can actually just look at all the gaps and then do a mathematical formula because there's three spaces you know and then the edge is kind of the beginning in the end i think that should be okay uh there's this so you can just do like one pass and do count or something like that um yeah i mean i guess we could do it that way another way of doing it is just you know like that same idea with prefix summer you want to call it dynamic programming that's fine and then do one for prefix for one for suffix and then you could see how far from the left how far from the right and then just take the min right um in the middle of those two and then the max of the min of those two right so that's definitely a thing as well um yeah uh yeah i mean i think that's all uh i think i'm gonna do it the way where we just count the gaps and then that should be good so yeah okay so i'm just trying to think about how to handle the first case and the last case um i think we can i mean these things are always a little bit tricky to kind of handle um and so yeah uh just at least once empty cinema okay so uh yeah okay so you can have something like and in theory i was thinking about like different ways of handling this like maybe add like 20 zeros to the left and technically that would be okay um because also not maybe not 20 but like n like a function of n um but and it'll be okay but that's like a little bit too raised for the three extra thing maybe that's okay yeah let's do it that way maybe that's a little bit funky but uh no now let's just do it with if statements i think we could do it so yeah so okay so let's say cur uh so i also think there's a way you can use group by but maybe i'll do that okay so i'm gonna use goodbye with the same idea with seats and then now we have seats something like this right and then if you do a print um just to kind of see you should have for example you have one uh three zeros one okay this isn't really okay but um yeah but conceptually right so then now you have um i guess type and then items in seats and then you print items right um so i might i always i just came from outside and i think my voice is a little bit um not gonna lie just a little bit awkward that's weird um i think it's because i convert this to less than as being a little bit awkward just do it here then because there are elevators so and once you go for an iterator um things aren't good anymore which is why this is happening so there you go um but okay and all we care about is the length of these list of course but yeah um let's say we have t length of list of items um and then we group this into a new uh thing and then now we can do this again in case you're wondering how one liners have written though i didn't really start out doing this wanting to do one liner but yeah uh actually there should be a tuple so need an extra thingy my voice is very i don't know i just came from outside so i think my voice is a little bit awkward because it's very cold it's actually 18 degrees fahrenheit which for you in celsius is probably negative five or something negative six maybe more negative seven i don't know something like that right so it's very cold outside and i think i needed to uh lubricate my foam a little bit first but oh well maybe next time okay so now we can go from left to right um right and um i don't want to do it okay now i think we can add a frame without wasting too much space right which is that we can add basically add hmm yeah i don't know uh okay uh sorry friends i'm like being really indecisive so let's convert this to a deck same idea but now we can check the first and last item very quickly and then removed them um and then here what i wanted to do which is why i'm doing this so i keep on like thinking about it in my mind about how to implementing though the idea is not really that hard um is that okay now if the first um if there's a empty seats to begin with then we want to take out the set first seat right so that means that if um seats of zero and we have to make sure that the length is great i guess the length is always greater than zero but if length of seats is greater than zero and seats of zero um the first element is equal to zero that means that we start with empty seats then and the most then the space that you have and i guess what um yeah the space that you have is just um this number right which is the number of space meaning that for example the opposite of this let's say we have this oops then that means that you want to take the first seat and that's three seat away from the next one right that's basically the idea and also just for symmetry's sake we'll do it this way because we're going to re-end with empty seats and this is the same idea but of course um the last um in the end instead um we want to return best at the end and then now then it just then now we can assume everything is in between and the two cases there's an odd case in the even case so if it's odd it should be pretty straightforward maybe um let's say our number is just three then actually we add some ones if this is three that means that you're plus one over two away right pretty straight forward so yeah um for uh let's see type and count in seats uh best seats plus one over two right um that's for odd what happened to this even so even if it's this and of course you can take one of the middle ones which will be two away so that's actually same formula technically you don't need the plus one or just c over two but that should be the same because four over two and five over two is the same right um at least if you round down or truncated so we can kind of give it a spin this looks okay for this one looks okay here of course you can do it in another way but i don't know today i just feel like doing it this way um my apologies for not explaining as much maybe my voice will recover a little bit but uh but right now not so much um so i think what i want to do is just double check a few cases uh at least one seat is occupied okay fine no i guess that's one of the things but oh yeah and of course um i think i don't have a even case um though this part of course you already know what you're doing so it's just a bad way that's the right answer because inferior way terry there's the wrong answer so it's a little bit uh cheating or whatever but yeah oh no huh did i mess that up why does this give me two huh well it's a good thing to get the sloppiness out of the way but oh i am dumb i had this here but i had this in my mind but i just forgot to put it in and unfortunately i did not test a case where we have a string of ones which is why um but yeah because i was okay so you see i was thinking about it but then i just didn't think about it because i was like rushing it i was thinking about the zero cases enough i think that is one risk about doing these videos and doing it live is that sometimes i'm thinking about how to explain it and how to reason it um and sometimes because of that i get distracted i forget like in my mind i wanted to do this but then i got i it happens and my bad uh but let's give it again and hopefully this time i'm actually right uh but yeah and hopefully this um this knocks some silliness out of the way and that like you know is a good sign for the future um because uh maybe today it'll make me more careful because i'm like larry you're doing silly things like this so uh so yeah okay streaker 656 uh let's go over the complexity really quick um the way that we do complexity is actually linear space because of this um but linear time is optimal um you have to read the input you can do this actually without all this funky stuff uh to be honest you could just do a rowing counter and then which has exactly the same logic but just a counter when you go from left to right um but you know i think this way is slightly slightly uh less confusing but um i don't know or like that not confusing i was gonna say slightly less um slightly less error foam but as you can see you can still make errors but i don't know i mean if you forget to check that it's an empty seat i feel like you can write it in any way and you could just forget it so that's a little bit silly what did i do last time uh okay yeah so the last time i oh no the last time i did the what i said the dynam programming slash prefix something of taking it from the back and then um yeah uh cool uh that's all i have for this one uh let me know what you think um good luck on the contest later stay good stay healthy good mental health i'll see you later bye
|
Maximize Distance to Closest Person
|
maximize-distance-to-closest-person
|
You are given an array representing a row of `seats` where `seats[i] = 1` represents a person sitting in the `ith` seat, and `seats[i] = 0` represents that the `ith` seat is empty **(0-indexed)**.
There is at least one empty seat, and at least one person sitting.
Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.
Return _that maximum distance to the closest person_.
**Example 1:**
**Input:** seats = \[1,0,0,0,1,0,1\]
**Output:** 2
**Explanation:**
If Alex sits in the second open seat (i.e. seats\[2\]), then the closest person has distance 2.
If Alex sits in any other open seat, the closest person has distance 1.
Thus, the maximum distance to the closest person is 2.
**Example 2:**
**Input:** seats = \[1,0,0,0\]
**Output:** 3
**Explanation:**
If Alex sits in the last seat (i.e. seats\[3\]), the closest person is 3 seats away.
This is the maximum distance possible, so the answer is 3.
**Example 3:**
**Input:** seats = \[0,1\]
**Output:** 1
**Constraints:**
* `2 <= seats.length <= 2 * 104`
* `seats[i]` is `0` or `1`.
* At least one seat is **empty**.
* At least one seat is **occupied**.
| null | null |
Medium
| null |
60 |
Coming soon on this show Today they are going to see the problem Open the permission sequence from the list Find the challenge Net see the problem first 20 * Set off these numbers from which you can 20 * Set off these numbers from which you can 20 * Set off these numbers from which you can generate and factorial unique permissions right that is not given and that you need to find With permission sequence equip this example for any chancellor's equal to three light bill that 213 let's see how it game a for any one to three you can generate six pressure 989 culture three unit to find third permissions 1234 answer that now the solution on the root can be How To Generate All Permissions For Catering And Returning History But Forget You Will Have Time Complexity Of Anti Bacterial Can We Think Something Better I Let Sperm Donation For Any School 30000 Pattern Hair During This Way Through Which They Can Skip Communication A For Any 124 All The per medication can another start from one to three four nine to get all the permission starting from one can be written as one plus permission of two three four which will generate permission of two three four and develop and 128 others where entered put permissions witch Will start from one Similarly we can find all the information which will start from two MP3 MP4 Some time will be six permissions for each loot no when is description me stations from one and two that Chinese to file path permission information will be available in this block No work has been reduced to 3 because benefit welcome edition now you will go inside this formation of 12415 the third permission no problem will reduce 253 definition of 124 that and I have already selected three from the prevent step ok now permission and 124 can start From another one to three four so they can write as one plus permission of 214 dashmi can find all the information starting from way pending one to all the best nov24 that similarly how to preparation of one four plus per mad no one else does not need to Find Third Administration Will Be Available In This People Redmi Spirit Will Start From 80K Has Been Reduced To One Because You Have Kept To Permissions If The Problem Has Been Reduced To K Equal To One Of Formation Of One And Charles K Equal To One Means You Need to Find First Information 148 Will Give One Forest Answer Civil Right One Four 200 Gr Will Be 3210 Let's See How They Can Did So I Will Be Valid for Android Phones and K Kulu 0 Mins for the Liberation of Science for Me to Front Part Permission So If You Want One Answer Where Will Store Answer Numbers Are Established To All The Results From Which Will Make Answer Finishing Influential Calculated Pack To Retail And Also Edit Speech Will Used For Making The Answer A 90 Number Hai List Will Contain 1234 And It Will be calculated for 49 adanky - - they need to calculated for 49 adanky - - they need to calculated for 49 adanky - - they need to find what permission finding and minus one factorial fennel david 19408 loop 69 I will calculate do subscribe spent thursday to the ninth decrement that he induction into effect until means husband - sexual step and into effect until means husband - sexual step and into effect until means husband - sexual step and give them to Mp3 has happened that the salt of the Nau case is 2 and the I have Reduced in the Nine Mike Hold to and Reduced I 9 May Quantity 2 and Reduced from Witch Prewells in Remote So I Will Again Calcutlet the Patrolium and Vikram 6123 Latest 2915 Vich Indicate For the index equal to a defect Tubelight to the first Indian to Baahubali 2 and removed from the list Android user's brother Chhotu - ki naukri hai Vikram 0 reduced playlist one for victory 382 has been reduced and destroyed to a known fact into - Hee Saunf Bam 225 192 a known fact into - Hee Saunf Bam 225 192 a known fact into - Hee Saunf Bam 225 192 subscribe to the Page if you liked The Video then subscribe to the Page है झाल झाल झाल झाल झाल की ए
|
Permutation Sequence
|
permutation-sequence
|
The set `[1, 2, 3, ..., n]` contains a total of `n!` unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for `n = 3`:
1. `"123 "`
2. `"132 "`
3. `"213 "`
4. `"231 "`
5. `"312 "`
6. `"321 "`
Given `n` and `k`, return the `kth` permutation sequence.
**Example 1:**
**Input:** n = 3, k = 3
**Output:** "213"
**Example 2:**
**Input:** n = 4, k = 9
**Output:** "2314"
**Example 3:**
**Input:** n = 3, k = 1
**Output:** "123"
**Constraints:**
* `1 <= n <= 9`
* `1 <= k <= n!`
| null |
Math,Recursion
|
Hard
|
31,46
|
401 |
The festival I wore this Adarsh Mishra and The festival I wore this Adarsh Mishra and The festival I wore this Adarsh Mishra and you urination dress, today we are going to talk about the problem of binary lust on the list, it says to the problem that this will save you battery, it is a hand watch which has four LEDs in your top section and Those four ladies are representing your hour from zero to 11th Kunwar is representing the clock in the clock along with the falling and its appointed and appointed or you it means war and two that station means that LED It represents zero or that they ever had Delhi Sidon the right side, it means that if I have four sons, then there will be four children in the clock. Well, there will be four children, so now the corresponding words of four means the light will be early, we will see the poor and more salt at four o'clock. You can tell by looking at the car, okay, so here it is telling us that if we look at the clock below, it is like this clock, then here itself we understood that this is that 842 and what is this is what we need. How many hours has it been and this section is 4 to 6 minutes 1642 One good thing is that 04:50 I hate minutes 1642 One good thing is that 04:50 I hate minutes 1642 One good thing is that 04:50 I hate that you subscribe to the channel and became a Buddha 04:50 With this your vehicle which became a Buddha 04:50 With this your vehicle which became a Buddha 04:50 With this your vehicle which is representing the time here to tell you the time. Ajay helps here. If you look at your example, now tell what time attacks in it, what we have here is for and what else is 3216 to and it means how much in it till 4 1 minute. Not subscribed, here also the weather is fine and the number of leaders who are present at this time will have a rally, there will be no rally and it means that there will be no tomorrow in that particular LED, simple. What you have to return is all the possible time zones that can be in the watch. If that number is on then tell them how many possible number of times ours can be. Now do n't forget to subscribe the skin and subscribe 04:50 Okay so here your 100 meters is simpler than us here, there must be some bleeding heroine, we cannot do it like this, we do not have to keep zero in the first place, there is a rule of minutes in the purse, here ours can be two digits from the minute. And we can add 1000 like if I say that it is 10:02 then like if I say that it is 10:02 then like if I say that it is 10:02 then this is also your argument and you say that 10:02 is this is also your argument and you say that 10:02 is this is also your argument and you say that 10:02 is like this and Twitter means you can put zero here, there is no problem, okay, now its On example like you first of all I make my house so here this 124 is a sum is my one part and sum 3216 840 this is my watch okay now the value of friend it means that in this whole watch there is only one disgusting good 10 Minutes, we have been going for 2 minutes. If I tell you here, apart from the quality, this one could have been more, then how much space would be there. 04:11 It would be completely four o'clock. then how much space would be there. 04:11 It would be completely four o'clock. then how much space would be there. 04:11 It would be completely four o'clock. Well, it is possible that this one is on or this one and Mutual is possible. So we will take this way, what is the possible time, that is, it is 24 hours for a child, so you are asking that you must have understood. Okay, now I have figured out all the possibilities of the voice, now let's get it done in a minute. It is possible that this is going on, that means 0132 minutes of camp, I have got 2012 minutes or 16000 and 2 minutes and minutes till this possible hour subscribe time, you have to put it in a list and give it in the answer, we are asking you a question, okay So the first test is possible only when we scroll down to the bottom and it is comfortably said below that turn on is only art, meaning it is a tweet which is on. Okay, first of all, what do we tell you that please assume that our Here 3 minutes this is one two three is excellent a table total earnings today uk artisan credit time how much is happening why accident charge together children 1684 21 this is happening for 30 minutes 07:31 so this is my first time happening for 30 minutes 07:31 so this is my first time happening for 30 minutes 07:31 so this is my first time Also good, now it is possible that we may not consider it in the minute section. Now here, if we remove it can reach 3240. There can be many possible ways on this platform. Here, this is still my art. It is B town, I am also calculating how much time is it. 07:47 minutes. Okay, if is it. 07:47 minutes. Okay, if is it. 07:47 minutes. Okay, if we tell you that if we do a little oil change like we did, you will also do it here, remove it and here the system. Let's run it, okay, in such a situation, you will feel something else, meaning, what will happen, will things keep going on, what time will you come? 07:55 Maybe, okay, and this is the option of Amavasya, remove the device, that means, there are many such options which you can If you come? 07:55 Maybe, okay, and this is the option of Amavasya, remove the device, that means, there are many such options which you can If you come? 07:55 Maybe, okay, and this is the option of Amavasya, remove the device, that means, there are many such options which you can If you can check side by side then what time will it be in that city, it is the last minutes of the match that now those who supported me in all their minutes have been martyred, they have been chaired one by one, now what will we do, will you try to change it? So how are you? How are you? Gyawali, Patanjali lamp is lit, still my eyes are not watering, so how much time is passing now, then you will see it like this: 11:30, 1147, 1155, etc., will see it like this: 11:30, 1147, 1155, etc., will see it like this: 11:30, 1147, 1155, etc., something like this, you will find time passing in all such vitamins posts. Okay, so now we were watching here, the perspective of watching it was such that we were wondering why it could be because this one and so on, then these days we and this one and so on, then these days we For this can also happen in all the possible ways, so not like this, subscribe to the feed in the computer. Now, first of all, we will discuss with you here, as it means to me, 12:00, here, from which to means to me, 12:00, here, from which to means to me, 12:00, here, from which to subscribe. If you forget, then here it is a matter of 90 that you will have to make more calls and it is like conduct, in this it is from here that you understand that if any number is mine and if we have to copy it in it then find out its binary and finally Where ever it is, get it done and it must be done for the minimum hour, one hour and from 12 o'clock till here, Meghnad does it, so I will go from here to here, see how much time can be taken, okay if we talk, then it is minute to minute. You can sit for 3 minutes, it must be like this, all these possible minutes have been used, this is my minute and all these possible have been used, this is the list of my alarms, you must have understood, it would be good if we tell you that it is the time of zero. What does sending zero mean? Job minor is how much 0? Okay, now let us represent it in the middle because here we need to rep the idea in the middle. There is none of these four here. Now we will understand that here is zero mine. Time is happening, sometimes there is a shadow in what is happening. Well, if I tell you that if minutes are my work, then how will I do it in minutes Meghvar 00 and you see, now you will not have only one here, if someone Disturbance is good so children, if it is happening in 10 minutes then back to minute can be possible then subscribe 100 minutes for 2 minutes, if one minute is happening in one minute then we can see then in whatever time is possible. Subscribe Minutes are happening, what does it mean that one will be lit and with 4 minutes there will be only one lit two lights, here will be soon, how will we know this, so soon, so how can we remove this, we asked you What is this, I explain to them the modern budget of this thing that suppose what we said here is that we have decided a range of accommodation and time, whatever question we have, now we will put it on this and check all the voices and all the minutes. If at that time our Whatsapp number and lights are on or not, to remove it, at a point time it is 01:40, remove it, at a point time it is 01:40, remove it, at a point time it is 01:40, it means it will be on at an alarming time and the phone will be on within minutes. Well, we can do this. How will we know if there are so many birds on then how much will be the caravan's winery 0 Okay and show us the camphor powder then how much will be the honorarium 100 Okay now why I have written 0 here is because there are 4 minutes here and its Now for the minute, I have filled four here, it means there is a match on 4, but if I want to show that it is but, what should I write on moon or should I write that on 0, this is fine because you have paan under for, so here we have seen this presentation. Okay, now tell us how many recruitments will be done in this, when 01:40 would be happening, recruitments will be done in this, when 01:40 would be happening, recruitments will be done in this, when 01:40 would be happening, you would look with your eyes and say that the ideal will be sexual and it will be so, it will be more, well, if I tell you how to tell it, then you guys will know as much as it is happening. So it has aloe vera so here you get another subscribe that I click on search here 11:00 I said yes 11:00 I said yes 11:00 I said yes 11 kids 32 minutes are going on okay so now tell me how many lights in this clock at 11:30 There will be tell me how many lights in this clock at 11:30 There will be tell me how many lights in this clock at 11:30 There will be no water, how many LEDs will be on, you can see here and for this we need how it happens, 40 32, it happens, 1234, 50, how many people, how many per hate, how many in hate, it happens only once a week, okay. Now my object here is, why what happened that we are given this turn on and we know how many lights will be lit and now we do not know what time it will be happening, so we will consider all possible times, okay all possible. If you do a year's time, then the answer can come between where and where, I may have, it is difficult for me, where will 0512 go, so I have decided that they can tell our viewers in the range of these 12th, now every hour. Accused for 3000 1000 it is possible find out in all these there will be increase in if it melts or melts is equal to what we have given here how many lights are on in my clock at this time quickly you look up here turn on that If it comes equal, that number is from the office, it means that the time is valid for me and they are going to take the time and keep it in the result, then we will put the result and make a MP list here, I have the results here, I have made a list of what to do and After that I appointed that subscribe for 1 minute, 1 hour, possible minute, 2 minutes, subscribe the channel, for that you got as many minutes as you have done, if all the numbers are coming in the number one account, if that Now you become equal to the turn on which is given to you. If we become equal to him, it means that for the time you have taken out his bandhi here, by pounding half of it, our same take off but for that particular hour and minute, if it is so, then it means that Meaning this hour and this minute to put it in Ghee that if the number one in plus minus minute is equal to the number one under is equal to that means that time so we can have in so this 09 so please this thing I here We have to pay attention that how should we do the patient, if there is a single bed, here we have to use this format 'Zero', then use this format 'Zero', then use this format 'Zero', then we cannot put 'W', then we cannot put 'W', then we cannot put 'W', then what should we do here, use the formatting ' what should we do here, use the formatting ' what should we do here, use the formatting ' War', see in the video. If you can understand it, War', see in the video. If you can understand it, War', see in the video. If you can understand it, then how do we have to repeat it? First of all, if our stray goes, then we have told before this that send A on a voice means integer value, so I have interviewed here that we have not started it at all. After this, see here, two values can be given here, see here, two values can be given here, see here, two values can be given here, now it can be for minutes because what can be one, can be two, can be a fan, can be something, but if this can happen, then two butts will come, so I have here. Come that to keep you empty twice, for the percentage, I have refined meaning for the interview minute, that is, for the war and how many possible days can be there in that, I have given two boxes, your possible can be here, so for me. Paisa Tutti Ok, if ever it is four o'clock here, then I will not put these stars here, this is why I have to put the roster here because it is a minute, but I said the opposite, I was telling the matter for the hour, so as not to take offense, for the minute, you see. Look, what I said for minutes, send here, it will mean vintage car rally, after this I said, keep two well, Orient got empty here twice and after that, I can put it in zero here like this is my four yogi belt. From April 1st of 4th, it will be zero by using this line, so I have seen this here, you understand this at this time, okay, this is done, now the cases are not confirmed or not, so it means that both the boxes. Is it that if it doesn't fit then zero ca n't go anywhere behind then there is no problem, zero option is a single bed, so which one gets made first, so to represent this thing, I have done the formatting, after making you see such a big issue, watch the formatting video. If you read then you must have understood the thing here that we have to please you in this way, you will come for this for 5 minutes and this immortal time will come, we will paint this, in the list named Result, your total which is all possible in pimples. It's time, he will come to us, after this we will finally return, I will follow the result. Did we know that we were sold turn on here, while how much of our lighting is running at that particular time, we were given that giver here. This is life, so now we can take them out, so if we can, subscribe, it's been 10 minutes, it's been 10 to 15 minutes, subscribe for Is it equal to turn-on, is it as Is it equal to turn-on, is it as Is it equal to turn-on, is it as much as our clock is burning at this time, whether its lights are running fast in Mahaman Free or not, for those possible times, if it is fast, they are possible time ballots and were holding them up, desert. If you copy it above and copy it to me, you will get a better understanding here that there is no doubt that you can tell your time or commission, then I will make another video on this. If I get interest, tell me. I think you should understand this much by now, Jhala.
|
Binary Watch
|
binary-watch
|
A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.
* For example, the below binary watch reads `"4:51 "`.
Given an integer `turnedOn` which represents the number of LEDs that are currently on (ignoring the PM), return _all possible times the watch could represent_. You may return the answer in **any order**.
The hour must not contain a leading zero.
* For example, `"01:00 "` is not valid. It should be `"1:00 "`.
The minute must be consist of two digits and may contain a leading zero.
* For example, `"10:2 "` is not valid. It should be `"10:02 "`.
**Example 1:**
**Input:** turnedOn = 1
**Output:** \["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"\]
**Example 2:**
**Input:** turnedOn = 9
**Output:** \[\]
**Constraints:**
* `0 <= turnedOn <= 10`
|
Simplify by seeking for solutions that involve comparing bit counts. Consider calculating all possible times for comparison purposes.
|
Backtracking,Bit Manipulation
|
Easy
|
17,191
|
480 |
hi Ricky here this is little code question number four eighty sliding window medium this is the hard question let's get into all right our median is with value in an order to integer list if size of the list is even there is no value like this there are no needle so the median is mean opportunity value example this is the all the odd lengths so video means the middle number three this is evil so we needed to add left aside of neither the past right side of the middle divide to solve two point two five given an array knows there is a sliding window of size K which is moving from the para draft of the array to the very right you can only see there no K numbers in the window each time the sliding window moves right by one partition your job is to after mediatory for each window in the original array for example couponing is Tata and pays to be check with example I'll start the window side is three so wind Omega C R 1 2 3 and you start very lot to better light and step-by-step so in to better light and step-by-step so in to better light and step-by-step so in this time unfortunately this one is little not ordered so we needed to sort first so in this time minus 1 3 so media needs to be the number one next it Mulder once there and next day is three minus one minus three so median is minus one next - OH - three so median is minus one next - OH - three so median is minus one next - OH - t minus 5 meter is minus 1 next - 3 5 2 median is 3 next three next - 3 5 2 median is 3 next three next - 3 5 2 median is 3 next three five six median is five next three six seven we didn't see so we needed to return all over medium value like this alright I think it is I think maybe we can implement we the proper solution so I think and require you to start with proper solution I can let you see first we need to iteration the one time step by step that is the first and there's a creditor getting the items from nonce getting the case I a dense for loans like this and then next is getting next is this three is soaring to get media number after nine maybe we can find media number wrong and then put alpha waste and their little death okay let cultivation H calculate the time complexity is the first iteration is M and then each iteration time we need to sort operation so this M log and okay the Terran all over asia another is constant time so I think time complexity is M multiplied and pines and node M and this is quite big so if we improve the with this maybe it could return the time overflow so we needed to optimize more okay is there any good idea all right okay this is my idea my dear okay start I will get the window first and then get window first and then second a story but this is only the case length escape so this is the sorting take the K log okay not a no go ahead it must be smaller and worst case is you know okay next re-cap medium and therefore I will turn it up the first item one the five is I will put this one to sorted array with final research you know a binary search take the pony lobia and then first we need to tell okay and then first ten complexity is K log K plus 1 iteration and then multiply lovely and it much it's from what if a stood there and modify log L and M but if I and know where so we will implementation we do this approach alright let's go to code okay the first I will import the Python module for binary search from binary selection aha finally selection equal to by seller left because it must it item is not a unique tentative means there are multiple same value in there so in this time I will choose only the left side of value and then next line needle insert for a certain advantage all right and then first okay first let's make our media there get median function it is sad because that is the same never so Ananse this is list Vicki J and K same as medians writing in do i written is differe needed to flood and we will check me that are lengths of the notes eight anonymous check either the case because case is the same as window and they're this not always leasing the window value so i think lends --lens okay is much faster light so I will use cake and then I will speak operation with mask one if this one is true and lengthy is odd so in this time I just returned noms case divided - oh this one is correct case divided - oh this one is correct case divided - oh this one is correct no actually they start from minus 1 so minus or plus 1 is in this did you make it make sense and then yes lungs okay divide two PLUS loans taped by the 2-1 divide it - is it okay no it's not good divide it - is it okay no it's not good divide it - is it okay no it's not good because we needed to get product number all right and then I will make one list names output to return and then I needed to window and it must be get from non-case window and it must be get from non-case window and it must be get from non-case and then he must eat a lot and then I will put a lot of people and mossad using can medium we created maybe we need to serve that comedian and then food bingo and K now we get the first media video okay now let it ready for our is ranging from one because we already get the first value and length of lumps and then it must be start to before the case right before thanks - Kay and then if needed before thanks - Kay and then if needed before thanks - Kay and then if needed trust what because it is that from water and I will first next I will remove the first item of notes okay window with Mossad up and then I will delete noms then I needed to find the very first island from windows so I will use binary search by research and little depth because I will delete the first item - which left and window lungs like no I - which left and window lungs like no I - which left and window lungs like no I minus one because we start with okay next to be needed to do in dope part and then next we put in put it do item then must be that is the next step this is window and then this is nonce and they be for us to be already Khaled of the first item now item is it case three now is two and then we need to put this one is quarantined X plus three minus one because now is length is K minus one which makes sense alright in salt okay and then let's put a window and and finally I already turnout for okay let's all I all right ALPA seems good okay let's sound awesome okay let's check the complexity okay down okay this is linear this take the cable kid okay and firstly we needed to Caleb okay and then it take em and each iteration in need binary search blow their like final search local key right because I'd be just by necessity case like so finally time complexity is M multiplied log k plus K okay so yeah I think this is time complexity okay let's calculate the space complexity speaker is there any data structure there are one list Lexie's am linear time and no order so I think it take linear space but if we will tone counter output this is steady this is attack only K case must be smaller than so we can say Ms take the big ol k space complexity thank you
|
Sliding Window Median
|
sliding-window-median
|
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values.
* For examples, if `arr = [2,3,4]`, the median is `3`.
* For examples, if `arr = [1,2,3,4]`, the median is `(2 + 3) / 2 = 2.5`.
You are given an integer array `nums` and an integer `k`. There is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position.
Return _the median array for each window in the original array_. Answers within `10-5` of the actual value will be accepted.
**Example 1:**
**Input:** nums = \[1,3,-1,-3,5,3,6,7\], k = 3
**Output:** \[1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000\]
**Explanation:**
Window position Median
--------------- -----
\[**1 3 -1**\] -3 5 3 6 7 1
1 \[**3 -1 -3**\] 5 3 6 7 -1
1 3 \[**\-1 -3 5**\] 3 6 7 -1
1 3 -1 \[**\-3 5 3**\] 6 7 3
1 3 -1 -3 \[**5 3 6**\] 7 5
1 3 -1 -3 5 \[**3 6 7**\] 6
**Example 2:**
**Input:** nums = \[1,2,3,4,2,3,1,4,2\], k = 3
**Output:** \[2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000\]
**Constraints:**
* `1 <= k <= nums.length <= 105`
* `-231 <= nums[i] <= 231 - 1`
|
The simplest of solutions comes from the basic idea of finding the median given a set of numbers. We know that by definition, a median is the center element (or an average of the two center elements). Given an unsorted list of numbers, how do we find the median element? If you know the answer to this question, can we extend this idea to every sliding window that we come across in the array? Is there a better way to do what we are doing in the above hint? Don't you think there is duplication of calculation being done there? Is there some sort of optimization that we can do to achieve the same result? This approach is merely a modification of the basic approach except that it simply reduces duplication of calculations once done. The third line of thought is also based on this same idea but achieving the result in a different way. We obviously need the window to be sorted for us to be able to find the median. Is there a data-structure out there that we can use (in one or more quantities) to obtain the median element extremely fast, say O(1) time while having the ability to perform the other operations fairly efficiently as well?
|
Array,Hash Table,Sliding Window,Heap (Priority Queue)
|
Hard
|
295
|
724 |
hello everyone in today's video I'm going to be showing you this cool the code problem called find pivot index now a pivot index is defined as any index such that the sum of the array to the left of the index is equal to the sum of the ray to the right of the index so using our example here this is just a first example um the pivot index here is three so that is here right here now just to elaborate the reason why this is the pivot index is because the sum of five and six is eleven and the sum of these is 11. so those two match which satisfies our condition now when I was first doing this problem it wasn't totally clear to me the what the optimal solution was now it what I ended up driving was to use you know two arrays you know one was a running sum from the left and one was a running sum from the right now using this approach and you can derive the left sum and the right sum for any given index so for instance uh if our pivot index which is right here so this is index three so we can see that the left sum is 11 and the right sum is 11. now this solution is fine and it works well but you as you can see there's quite a bit of extra memory here I don't want to spend too much time on this solution as the optimal solution uses no extra memory but the code to this solution it looks like this moving on to the optimal solution which in my opinion is easier to code and understand I just think it might be hard to get to the solution on the spot but the whole intuition for the solution is that if we know two-piece vibration we that if we know two-piece vibration we that if we know two-piece vibration we can derive the missing info from the info we already have so using our example again in I'm going to pick an index that's not the pivot to show this but if we choose say that I is here so when we're iterating through nums we'll imagine that I is at index one so we know that our first piece of information is that we're going to know that our sum is equal to 28 so if we summed up every number in the array it comes up to 28. so our second piece of information is that we're going to know what the left sum is for any given index so as we iterate through the array we'll be able to calculate the sum going from left to right so that's going to take up this square right here now what we're looking for in this case is this write sum now I'm going to draw the total sum kind of on the bottom so it's easier to visualize but what we're looking for is this so red is equal to green minus blue and then technically we also have to subtract um the current um uh the current value at I so we'd also subtract I and the code for this solution looks like this algorithm has a worst case time complexity of 2 to the N which simplifies to just o of n in the space complexity this is where the solution is different from our first one the space collector here is constant um but yeah that's pretty much it hope this helps bye
|
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,557 |
hi this is Josh from Over the shoulder coding and I'm going to go over Lee code problem today for number 155 minimum number of vertices to reach all notes so this is today's daily problem and we're going to try and tackle it in about 15 minutes or so let's get started so given a directed acyclic graph with n vertices numbered from 0 to n minus one and an array of edges or the edges are also an array from eye to eye represents a direct Edge from the node from I to node to I okay find the smallest set of vertices from which all nodes in the graph are reachable it's guaranteed that a unique solution exists and notice that you can return the vertices in any order so we have an example here input is n equals six edges is a 2d array zero one zero two five three four two and they've helped us visualize this there's an edge zero to one and zero to two to five three to four to two and the output is zero three so it's not possible to reach all the nodes from single vertex from zero we can reach one two five and zero and from three you can reach three four two five so we all put zero three so if we need to reach all the edges we need to start from zero and three and the second example input n equals five edges are zero one two one three one four two four so we have zero one two one three one four and two four and there's nothing feeding into zero two or three there's things being into one and four so the output is zero two three notice that vertices zero three and two are not reachable from any other node so we must include them also any of these vertices can reach nodes one and four got it so we have to start from at least zero two and three um and we're gonna have less than a hundred thousand nodes the edges will have fewer than a hundred thousand edges or all possible nodes connected uh Edge will be length to Zero from the edges will all fall within the nodes and all edges are unique Okay cool so um here they're already saying set so my mind in Python we're going to use a set class to return the set of vertices so we can track and remove vertices from the set so uh just to make sure we can handle the nodes and edges and then I think we'll create a set of all nodes and then iterate over the edges and remove nodes when we can access system so when there is a path from zero to one we can remove one from all of it and then return list of starter notes so just to handle the input so let's make sure we can handle this and I'll try to list and let's run this and see what happens just to make sure we're handling the inputs correctly so here we're messing up a little bit let's try it again all right so we are detecting six nodes and five edges so we can create a set of all nodes and let's just use this as starting nodes because we'll return it at the end of the nodes we have to start from and iterate over all the edges and remove nodes when we can access them so here for Edge and Edge is if so we have from which is the first index of an edge and two is the second index of an edge from is a reserved board so I'll use source and destination if the destination is in the set of starting notes we'll remove it otherwise we'll keep iterating over all the edges and here I'm just going to print the list of nodes I can print it after each time we remove just to check what's going on and here why don't I just print the edge that we're going for so if I run this and I iterate over all the edges oh so I'm not getting anything here because the set is empty I need to populate the set from all nodes so for high in range and set Dot dot add I so then our set will be populated just make sure let's run it see what happens am I using the wrong syntax all right so I need to use starting those that add so we start with all the nodes we iterate over the edge from zero to one so we remove one because we can access it so remaining notes looks like this and as we iterate over the next Edge we remove it as well we remove five we can access four so we remove that and now we're at zero three and we have this Edge four to two but we've already removed two so this looks right to me and so I can just return a list of all the starting nodes and see if this works all right so it works let me submit and see how we did I'm printing too many things so why don't I delete or I could even comment out my print statements but I'll just delete it right now all right looks like we were able to solve everything we did a pretty okay run time and memory so you know not amazing not terrible but we're able to solve this in linear time because we're iterating over endnotes and the length of all edges so worst case scenario we uh you know are still always going to iterate over all the edges at once which is pretty okay the memory we take up is just the set of all notes which also isn't huge and I think this is a pretty reasonable solution we did it in maybe sub 10 minutes so uh there's probably if you see this as part of uh coding problem you'll probably have multiple cutting problems or multiple parts of this where this is just one part but I think this is a pretty straightforward solution so if you have any questions the source to this is in the description there's a link to that or just comment let me know if you have any questions thanks
|
Minimum Number of Vertices to Reach All Nodes
|
check-if-a-string-contains-all-binary-codes-of-size-k
|
Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`.
Find _the smallest set of vertices from which all nodes in the graph are reachable_. It's guaranteed that a unique solution exists.
Notice that you can return the vertices in any order.
**Example 1:**
**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,5\],\[3,4\],\[4,2\]\]
**Output:** \[0,3\]
**Explanation:** It's not possible to reach all the nodes from a single vertex. From 0 we can reach \[0,1,2,5\]. From 3 we can reach \[3,4,2,5\]. So we output \[0,3\].
**Example 2:**
**Input:** n = 5, edges = \[\[0,1\],\[2,1\],\[3,1\],\[1,4\],\[2,4\]\]
**Output:** \[0,2,3\]
**Explanation:** Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.
**Constraints:**
* `2 <= n <= 10^5`
* `1 <= edges.length <= min(10^5, n * (n - 1) / 2)`
* `edges[i].length == 2`
* `0 <= fromi, toi < n`
* All pairs `(fromi, toi)` are distinct.
|
We need only to check all sub-strings of length k. The number of distinct sub-strings should be exactly 2^k.
|
Hash Table,String,Bit Manipulation,Rolling Hash,Hash Function
|
Medium
| null |
155 |
he was of gasma quite here I detect encoding stuff on twitch and YouTube check description for all my information join the discord a lot of perks a lot of being in the discord there's a lot of like talented engineers and they're studying for specific things so also I'm doing this live on Twitch right now I do stream for hours every night so if you want to watch these live you can just follow me on Twitch and check them out so here I'm doing min stack this problem it has a lot of likes only reason I'm doing it is because I saw this post on the main page saying questions to do for a beginner I don't know what qualifies this person to make this list that's fine it doesn't really matter you don't need qualifications I guess but we got this min stack right here is one of the only ones I didn't do so I was like all right let's just do it basically design a stack we all know what a stack is where you just put elements if you don't then you might not be able to do this problem but you're just putting elements onto a stack and the most recent element you put on goes on the top so if I put negative 3 on that's the top then I put negative 4 that's the top then I put 0 that's the top then whatever I put most recently is at the top and then when I pop 0 comes off pop negative 4 comes off pop negative 3 comes off so pop gets you know popped off the top whatever is on the top so and then yeah push puts it on pop pops it off top just looks and gets the access to the top of the stack it doesn't retrieve it pop actually pulls it off so we want to just make a regular stack except we want to implement retrieve the minimum element in constant time ok so if we look at this example we're just going to have this stack we have this stack class that we want to implement all these methods right we want to implement a push pop top and get min so they push negative 2 that goes on then they push 0 that goes on then they push negative 3 now you freeze the top what's the minimum of all of those negative 3 so we get the min it's negative 3 then we pop so negative 3 comes off then we get the top 0 would be the top because negative 3 came off and then we get the minimum of 0 negative 2 and negative 2 is the minimum so that's the whole thing right here so yeah let's just implement it there's two ways to implement this one uses two stacks one uses one stack we're gonna go with the two stack one first because it's a little bit easier to understand so basically you're just gonna have a regular stack for your numbers because this whole problem is literally a regular stack all of these three methods are part of a regular stack they're built in methods to write your stack only thing we have to worry about is getting the minimum and constant time okay so we'll just have this regular stack it can be called stack or whatever you want to call it and then what we're gonna want to do is have a second stack and this is only gonna keep track of new minimum values so you can call us whatever you want I'll just call it min Val's so there we go we don't even need the constructor to do this and what we'll do I guess is let's implement these two first because they are the easiest we're gonna put the minimums on the min stack the regular element every element is going on the stack but only the minimum new minimums are seeing are going on the mins okay so we're just when we return the top of the stack the regular element stack it's gonna have all the elements so we're just going to return sorry stack peak it's just a built-in method already so it's just a built-in method already so it's just a built-in method already so that's fine the minimum is only gonna have the minimums so the most recent minimum will be at the top of this one so we'll just return min Val's key all right that's pretty much it now these are the only things we have to add some logic to so basically what we're gonna do is when we push things on to the stack we're just gonna do a regular push element onto the stack and when we pop things off of the stack we're gonna do a regular pop things on the stack the only difference is we need to add some logic for the minimum so if the if let's say if min Val's is empty so if there's no minimums that exists yet then obviously this has to be in the first minimum element so we'll say if min Val's is empty or there's one other case if the peak is less than or equal or no if X is less than or equal to the current minimum which is the peak of this stack so is less than or equal to min Val's peak then we want to push this also on to min Val's so min valles gets its minimum pushed on so if there's no minimum yet we push it on to the mint we added as a minimum and/or if it's we added as a minimum and/or if it's we added as a minimum and/or if it's less than the current minimum value otherwise and every element gets pushed on to the regular stack anyway now pop we do need to do also a check for okay if stack key dot equals min Val's dot peak sorry then that means the element that we're popping is the minimum value so in that case we need to pop from the minimum value as well so we need to do min Val's dot pop and stack will get popped as well so I think this should be good honestly sorry what is this great brace expected okay might be so there you go that's the solution using two stacks you just have one stack that's regular because it's basically all the built-in methods of a stack and all the built-in methods of a stack and all the built-in methods of a stack and the only thing you have to keep track of is these minimums so the minimums get put on whenever we see a new minimum we push it on right if X the element getting pushed is less than the new minute the most recent minimum push the minimum on and always push on to the regular stack always pop off the regular stack but make sure you if the one you're popping off the regular stack is the minimum you got to pop off the minimum stack as well so min boughs keeps track to the minimums stack just keeps track of there were all of the regular elements there is one other way to do this problem and we can go over that right now this is going to be using one stack only so what happens is actually I'll just show you it because I don't want this video to go on forever here's it here it is basically it's this guy has the solution right here you just keep a variable to keep track of the minimum you have a regular stack and then when the value is less than the current minimum variable you're gonna push onto the stack and you're also gonna reset the min so that's pretty much it the only difference is you're going to push the you're gonna push the minimum when you find a new minimum you're gonna push the old minimum onto the stack because when you pop off in it to the minimum you have to make sure you have the second minimum right before so when you're pushing on to the stack a new minimum you make sure you have the last minimum put on right before it so if you ever have to pop off the minimum you have the second minimum right there right at the top so you're actually adding extra elements to this that you wouldn't want in there if you wanted to just keep track of all of the elements so if you wanted to loop through the stack in the solution and like print out all of the elements it wouldn't be what you wanted if you just wanted to keep track of the actual elements so it's actually not I actually disagree with using one stack in this case just because you're gonna have extra you're having you're putting these minimums that you don't even need want on the really like you it's better to use the two stacks if you want clarity and to actually keep track of elements so that's pretty much it this was my first live problem so let me know what you guys think I think this was my first log problem so let me know what you guys think thank you guys for watching I'm gonna do some more problems right now and appreciate you guys like and subscribe and I'll see you in the next video alright see ya
|
Min Stack
|
min-stack
|
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the `MinStack` class:
* `MinStack()` initializes the stack object.
* `void push(int val)` pushes the element `val` onto the stack.
* `void pop()` removes the element on the top of the stack.
* `int top()` gets the top element of the stack.
* `int getMin()` retrieves the minimum element in the stack.
You must implement a solution with `O(1)` time complexity for each function.
**Example 1:**
**Input**
\[ "MinStack ", "push ", "push ", "push ", "getMin ", "pop ", "top ", "getMin "\]
\[\[\],\[-2\],\[0\],\[-3\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,null,null,null,-3,null,0,-2\]
**Explanation**
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2
**Constraints:**
* `-231 <= val <= 231 - 1`
* Methods `pop`, `top` and `getMin` operations will always be called on **non-empty** stacks.
* At most `3 * 104` calls will be made to `push`, `pop`, `top`, and `getMin`.
|
Consider each node in the stack having a minimum value. (Credits to @aakarshmadhavan)
|
Stack,Design
|
Easy
|
239,716
|
152 |
everyone welcome back and let's write some more neat code today let's look at maximum product subarray and this is actually a dynamic programming problem and i'm going to show you how to solve this problem easily so we're given an integer array of numbers and we want to find the contiguous subarray that contains at least num one number and has the largest product so in this case we have a 2 a 3 a negative 2 and a 4 and the largest continuous product we can make is 2 and 3 because 2 times 3 is 6. that is the largest product we can't really make it bigger because there's a negative 2 if we multiply this by negative 2 it's going to be negative 12 that's not bigger than 6. so what's like your first idea how to solve this problem maybe brute force right is there a brute force solution to this well we want to find a subarray right so why don't we just try every single subarray so let's say all sub arrays starting at two we got one sub array two sub arrays three four right and for each of these let's just calculate the product right like the first one is two the next one is two times three times negative two the last one is two times three times negative two times four and we end up saying that so far the biggest is this but we're technically not done yet all of these sub-arrays contain yet all of these sub-arrays contain yet all of these sub-arrays contain two so now let's look at all sub-arrays two so now let's look at all sub-arrays two so now let's look at all sub-arrays containing three so we got one right just three then we got three times negative two times 4 and basically we repeat this process now you can tell that this is not super efficient the time complexity is big o n squared for each of these numbers we're going to end up having n sub arrays and we see that the total number of elements we have is also n right it's n elements in the array so we're going to get n times n is n squared so my question is can we do better and how can we do better maybe there's some patterns to this problem that we can use to our advantage to find a better solution than n squared so let's look at one example do you notice anything about this subarray well all elements are positive so what does that end up doing like this is all positive so we got a one okay and next we want to check this sub array okay multiply it by two we want to go even farther check the three okay multiply it by three and what if we kept having positive elements four five multiply by four multiply by five do you notice something up until this point our product is going to be a one up until this point it's going to be a two up until this point it's going to be a six up until this point it's going to be a 24 up until this point is going to be 120. if we have positive numbers no matter what happens they're going to keep increasing right so this is the simple case if we get all positive numbers then our product is always going to be increasing so now let's actually look at the opposite scenario what if we had all negative numbers because all positives is easy you just multiply all of them and you get the max product but with negative numbers it's a lot more tricky so let's look at the first number so up until here the max product is just negative one and then we add a second element a negative two and then what do we get negative one times negative two and we know that the product of that is two right positive two now the last sub array we check from all the way from negative one to negative three so we introduce one more value a negative three and now if we multiply all three of these numbers together we see that our product actually got smaller now it's negative six and what's going to happen if we had a another element over here what if we had a negative four then we multiply by negative 4 and now we see that our product is going to be 24. so you see that when you have negatives consecutively the sign is alternating so when you want the maximum it makes it kind of tricky to have negatives but we also see that even though we got a negative six over here there's actually a subarray that has a better solution if you just take these two numbers negative two times negative three we get a positive six so why did we get a negative six over here how can we find the real maximum which is positive six so even though we're looking for the max product sub array we're actually also going to need to keep track of the minimum as well and i'm going to show you why so first do you at least agree with me that if we want to find the max product array sub array of this of the entire thing it might be helpful for us to at least solve the sub problem which is the max product subarray of just the first two elements first and then use that to get the entire one okay that makes sense we know that the max product subarray of this is two now if we had a positive three over here then we would say okay if i can get the max sub array of the first two elements and multiply it by three i'm gonna get two times three it works when these are positive numbers but we actually have a negative 3 over here so i'm gonna say get the max product sub array which is positive 2 but let's also get the minimum product sub array of these two as well and what do we know about the minimum what's the minimum product sub array of these two it's going to be negative two so i'm going to keep track of both positive and negative so we have a positive 2 and a negative 2. we keep the max and we keep the minimum so now when we want to compute the max product subarray when we include this 3 then we can compute that using both of these values so we know that when we take the maximum 2 we get negative 3 times 2 which is negative 6 and we know when we take the minimum we get negative 3 times negative 2 and that gives us a result of positive six so we know the maximum is positive six and the minimum is negative six so we take positive six and put it over here and we can take negative six and put it over here and hypothetically maybe we get another element and this time whether it's positive or negative right so in this case let's say it's negative 4 we will be able to find the solution because the minimum or rather we're looking for the max product sub array and we know if we take negative four multiply it by the current minimum which is a negative number negative six we will end up getting 24 which is what we're looking for but if you reverse it what if we had a positive 4 here instead well in that case we can say okay positive 4 multiplied by our maximum right our maximum which is positive 6. so 4 times positive 6 we get 24. we still get it right so this if we maintain the maximum and the minimum we have all the information we need as we continue to add more elements to our array so now let's just look at one edge case so we're talking about positive numbers and negative numbers but we know that one last edge case exists the dreaded zero value right so what if we had a zero value and then maybe some other numbers three five our zero is gonna kind of kill us right it's gonna kill our streak like look what's going to happen to our min and max if we take 6 multiplied by 0 we get 0 if we take negative 6 multiplied by 0 we get 0 again right x times 0 equals zero and then if we try taking this zero and making it a product of maybe three and five it's going to continue being zero right because any number times zero is going to be zero so i'm gonna decide to handle this in a different way so anytime we get a zero value i'm going to reset our max to zero or rather to one and i'm also going to reset our minimum to 1 and the reason i'm gonna do this is because i don't want to kill our product right i'm just going to say that zeros are ignored we don't really care about zeros and the reason i'm setting this to one is because then when we start introducing new values like 3 it's just going to be 1 times 3 right which is going to end up being 3 so 1 is like a neutral value for us so those are the main things we want to maintain the max and minimum of our product and we want to handle the zero case by resetting everything to a neutral value like one okay so now let's code it out i'm going to say our result is initially just going to be set to the max value contained in nums because we at least have to set it to some value we can't just initialize it to 0 because what if we had an array with just one number and it happened to be negative one right in that case this is our max product which is even less than zero so zero is not a good default case and i'm going to maintain the current min and the current max and i'm gonna initialize these to one e because we know one is like a neutral value and then we're just gonna start iterating through every single number in our input array we know that if we ever get to a zero we do not want to handle that we don't want to add that as a part of our product so we don't want to mess up our current min and max by multiplying it by zero because then it's going to stay zero forever so instead what we're going to do is we're going to reset our min and our max to one each and we're just going to continue to the next iteration of the loop if this doesn't execute that's when we're going to actually do our code and recompute the current min and current max so our current max how are we actually going to compute it well in python it's really convenient for us because we can say okay the current max could potentially be the new number that we just found multiplied by the current max if the current max happens to be positive and n is positive it could also end up being the input value n multiplied by the current minimum right what if n is negative and current minimum is negative then this could end up being a positive number which could be our current maximum the third option is n itself because what if we had an input such as negative one and eight well in that case the current min and max is going to end up being negative 1 and either of those numbers multiplied by 8 which could be our hypothetical n value it's going to end up being negative 8 so 8 it's by itself which is n is the maximum and the fun thing about python is that look we just put three values into our max function some languages don't allow for this but there's obviously ways to get around it and so now that we have our current max we can do the exact same thing for our current min so we can actually take all three of these values copy and paste them and then put them in the min because we want whatever the min containing n is and it could be anything it could be n times current max n times current min or n itself so an example would be negative one and negative eight if we multiply these together we get a positive eight but we don't want that we want the minimum which could be just negative eight by itself which would be this third case but this is where i always end up with a bug so do you see how we actually recomputed the current max but we want to use the old current max so i'm actually going to have a temporary variable up here temp and before we end up reassigning current max i'm just going to compute current max times n and then save it in temp so then we can use it down here so we're going to replace this with temp so this way we're always keeping track of what the current max is and what the current minimum is and so we can update our result after each iteration of the loop and we want the max product so we can take the maximum of result itself because result could still be the max current max and current minimum so that's actually it like we've done it and we can now just return what our result and so this is actually not that much code and it's not even like when you look at it's hard to recognize that it's even a dynamic programming problem because it's not like we're storing an entire array like dp and then having an array we're just maintaining two values current min and current max and what they tell us is for let's say for example we were at this value n then we're going to have the current maximum of this subarray and the current minimum product of this subarray and then when our n gets shifted to the next value we're going to have the current maximum of these three and the current minimum product of these three and then by the time our n value is out of bounds we will have the current max and the current minimum of the entire array computed so it runs efficiently and that's because we're only iterating through the input so instead of being n squared the time complexity is just big o of n the memory complexity is big o of one because we are not using an array we're just using uh single variables i hope this was helpful if you enjoyed please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon
|
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
|
443 |
Hi Gas Welcome And Welcome Back To My Channel Today Are Going To Discuss And Other Problem But Before Going Forward If Not Like The Video Please Like It Subscribe To My Channel And The Bell Icon So That You Get Notified Whenever Posted New Video So Without Others For date let's get started problem is string compressor very easy problem see are given same characters write what they have to do is see you modify this area only and see have you return d length of modified ok so what do you have to do this See Have You Return D Length of Modified OK Modified Are See Have You Return And What See Have You Be See Have You Basically Compress This Date See Will Be Checking Like Ho In Similar Characters Are There So A Is Un Ring Too Times Consecutive Right Consecutive Si Consecutive Repeating Characters So Si Will Si Ho Me Consecutive Repeating Characters Are Dear Let's Say A Is Un Tu Times So Si Will Be Compressing These Are In D Form Of Like A Give De Count Tu Times Ho Me Times Tu Times Ho Maani Times are cream so this will be modified so this year which is of length 7 bill b reduce you and are of length six so d output they have you return so output bill b six okay I hope you understand d one so every if you C are has only one character right so if d count c here they have life d condition date if d group length is one only apind d correct so this phone the brother is n current give it one of date letter only in d output a bill less No Way Bill Note N Come Count Bill Note Get Appended Only D Letter B Get Bill B N Pending OK No See This One This Test How So Every Count of A Is It What One Again So Only A Bill B Appendil Count of A Bill Note B Offended Because It's Count Is One After Date Be Is Ho Money Times 20 Are Cream 12 Times So Be And Give 12 Bill Be Serrated In Individual Characters Individual Strings Like Van Tu Similarly 133 So It Will Be Van Three Problem I Hope You Understand D Problem Let's C Ho C Can I Project Very Easy Recommend First of All You Try Yourself So I Will Take D First Taste Right A B C Will B C You Have To Modify In This Year Only So This Reason Given This Is Basically A Character Hey given zero one you three five and six only see do not have taken in respect so what see will do right see you will have pointers okay they will have two pointers I will let you know same see will be taking 2 pointers see ho you will Get to no tha you have to him tu points see van point will be him you travel right obviously see have you go tu h position and check weather they are from like de previous character was from or not like see will maintain a count what is un Count of current character right date is one thing which have you do which is pretty much clear okay see have you count be in time be last be in times in this way you modify this arel like this so see will have second point Will be string C Will be managing Are output area Write it Will be managing D Final output Try and so approach I hope you understand Ho You have you think Will be used Let's be C Ho They can do What I would do Pointers I would be Loop below Bill forward right Have taken today zero obviously because i bill consider this no science i am starting from one and one same because of this character weather d previous character is equal to the current character forward ok increment tu je bill no come her in date how what they Bill Do Way Bill Increment J And Way Bill Also Count Increase Account S Character And Its Count In D And D Previous Character And Its Count So In If Then Not Equal Way Bill First Of Which In Character Of I Bill Be Used On D Final Output Editor wall date it a so every only but style this get replaced and a bill come every d new character bill b and if the council d character count this more give one write only they bill append the count if so c every more give one They bill not en count they bill only are pen d letter so they bill have n condition every date if d count is greater than equal tu right if it's more give and equal tu in date how only in character's i her They bill increment i plus also you bill do once they have store har so i bill no come har council vikam zero na forward and count also will increment by one ke bill come har come tu ke bill increment and to forward no again character ke is Not be so again it's time tu also they have tu increment her previous character witch give it greater equal tu swan count increment her previous character witch give it greater equal tu swan count increment her previous character witch give it greater equal tu swan count bill also get so i bill come every and every ing last count tu zero no because its d Start of New Character Sorry Increment D Count You and They Forward J Her Also D Previous Character Ise Se So Count Bill Increase and You Bill OK So This Is What The New Ares And Its Length Is What Ho Much Sex Become More Clear See What Way Are doing start from van initial count will be van further count initially van start from van and j will go tel d character size same it will go vikas exercise because si want tu show d last whatever will come last van also end k plus count plus Every time ok and if d previous character is not equal tu d current character right this condition so what they bill do first of jo bill store it in d previous character in tu d current of i this basically i plus min date first of jo it bill get store in d i and let i bill increment ok so you can write it like this also after this i plus similarly every also you can write it a i plus ok and after date way bill c if d count is greater than equal God give you 12 right way bills convert this count into a string like this and give way bills character by character because they have you store 12 together bills have you store d h character zero last return i witch is d last index so i hope you Understood the problem de time right so we are just doing a single travels from de video helpful please like it subscribe to my channel by
|
String Compression
|
string-compression
|
Given an array of characters `chars`, compress it using the following algorithm:
Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:
* If the group's length is `1`, append the character to `s`.
* Otherwise, append the character followed by the group's length.
The compressed string `s` **should not be returned separately**, but instead, be stored **in the input character array `chars`**. Note that group lengths that are `10` or longer will be split into multiple characters in `chars`.
After you are done **modifying the input array,** return _the new length of the array_.
You must write an algorithm that uses only constant extra space.
**Example 1:**
**Input:** chars = \[ "a ", "a ", "b ", "b ", "c ", "c ", "c "\]
**Output:** Return 6, and the first 6 characters of the input array should be: \[ "a ", "2 ", "b ", "2 ", "c ", "3 "\]
**Explanation:** The groups are "aa ", "bb ", and "ccc ". This compresses to "a2b2c3 ".
**Example 2:**
**Input:** chars = \[ "a "\]
**Output:** Return 1, and the first character of the input array should be: \[ "a "\]
**Explanation:** The only group is "a ", which remains uncompressed since it's a single character.
**Example 3:**
**Input:** chars = \[ "a ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b "\]
**Output:** Return 4, and the first 4 characters of the input array should be: \[ "a ", "b ", "1 ", "2 "\].
**Explanation:** The groups are "a " and "bbbbbbbbbbbb ". This compresses to "ab12 ".
**Constraints:**
* `1 <= chars.length <= 2000`
* `chars[i]` is a lowercase English letter, uppercase English letter, digit, or symbol.
|
How do you know if you are at the end of a consecutive group of characters?
|
Two Pointers,String
|
Medium
|
38,271,604,1241
|
93 |
hey everybody this is Larry this is day 21 of delete code daily challenge hit the like button in the Subscribe button join me on Discord let me know what you think about today's Forum restored IP address let's see what this is about um okay seems like this is uh yeah so I've added IP address okay oh yeah hit the like button I always said I don't know I feel like I need more sleep but yeah and also I'm going to do a bonus question after this so definitely hit that Bell and we want to do a little bit more let's do it together uh we still IP address so okay so given okay uh I mean you wouldn't construct anyway but okay and then there's no leading zeros or something yeah no dealing zeros okay so I mean again I think I said this yesterday and you didn't watch it yesterday then I'll say it again I suppose but it seems like uh the return or the valid IP address so that means that this is probably going to be oh like it's hard to enumerate everything without enumerating everything anyway oh like that's the lower bound of the cost um in terms of uh it's gonna be at least output sensitive right the size of your output is going to be um yeah and also uh kind of similar to yesterday um you know so what you know I mean we looked at boundaries to go to 20 but can we even be a little bit more precise maybe good you know if you're a little bit less strict you could say oh it's 2 to the 20 right um and the reason why you could say is 2 to 20 is that you can imagine uh a 2 to 21 maybe to the 19 side because let's say there's um a number of 90 or 20 digits right what does that mean that means that there are 19 spaces in between all the digits for 10 days 29 20 digits and between each of the space this could be either a period or not right so that you know for example so in that um in that uh what should we call it uh and then that says it's gonna be two to twenty right naive one well what's uh what's another way of thinking about it right well we actually only need three dots to create four numbers right so that means that okay now we still have 19 spaces we only need three dots and that is of course 19 choose three something like that right in 19 choose three I'm gonna plug it into my calculator real quick my calculator in Google is only about 969 so that is definitely so if you want to uh check that but another thing too I mean okay so let's say you didn't have Google or you didn't I don't know want to type into your calculator of course 19 choose three is roughly speaking going to be 19 times 18 times 17 uh time uh over let me have to do over this way over three times two times one um I mean and this is of course just six but this is roughly speaking and cube is what I'm trying to get at um and you kind of uh structure it out that way so and of course and tube for 20 is going to be uh what's my cut it's gonna be 8 000 but even 8 000 is fast enough right and then maybe if you're just over six that's gonna be you know 20 Cube over six is going to be like you know 1500 and that's I mean of course that's a more conservative bound because you know we choose 20 instead of these things I could do in my head but yeah so that convinces me that it is going to be fast enough um and then beyond that we just have to do it and usually it's something like this times n but n is 20 so it's fine so yeah so let's do it um and again this is going to try to do a Brute Force kind of way um how do we want to do it maybe we do it the same way we did it yesterday we have the index maybe we have like left for the number of dots left right um yeah so yeah okay so yeah if index is equal to n then maybe we yeah a pen can um or something like this yeah maybe something like that depending on how we want to do it we can always change it later right and then otherwise uh otherwise then for each left we just look at up to three digits right so for I in range of one two three um three digits because you know it goes only up to 255 so it has three digits so okay so then if um and this is and maybe you could kind of uh play around with it a little bit but um yeah if S Sub hmm test of index uh this is going to be the length so maybe we could just do it and like this zero one two right so then now we're going to do right something like that um so what I mean and there are a couple of ways you can check the leading Zero part I'm just going to be lazy about it um so yeah if SF index is equal to zero um what does that mean by S Sub index is equal to zero that means there's really only one way to go about it which means that we have to recurse um index plus one left minus one current right uh and also maybe if enough is equal less than zero will return so we don't have to check uh this is basically because uh and this is actually this um because that means that if it's zero then we have to use it for a zerleness there's no way about it um and here um plus I is less than n then yeah and then maybe we check that int of this thing is between zero and I mean it should be between zero I mean there's no way to get negative so but might as well as a value completion then uh I think we don't return anything so we just do it this way uh but yeah um here then we check to see if it's if it is the case then we index plus I plus one uh left minus one uh current and I did tell which up here currents should be an array so now we will append uh zero and then currently pop um current we have pen this thing and this should be a period thing but yeah and that's pretty much it I think I mean we have to call it once I think I don't know if I remember to do it last time but uh four parts and then currently in a way let's see if this works um am I maybe I'm off by one on this one I always forget how to do the powers on this one okay so I mean this looks good uh but I forgot to add this to the thing that's why uh yeah and then here the dupes is why um right is that true no there's just three what why did I do that huh there you go so that was actually just bad okay so because it shouldn't be do because um I was wondering why it was tubed well it was wrong because for other reasons and assumed we do because the way that we did it doesn't want anything more than once otherwise the band would be inaccurate uh okay so 10 26 day streak yep what's the complexity here again we already kind of did it's going to be n choose three which is all of n Cube um but I mean I guess technically because at a certain point you just can't have enough I don't even have asked something I mean I guess it could be 20 just return nothing but if it's two five it has like uh 12 digits right so can't even be that big but in theory I guess technically I don't know how you want to say it man choose to wait for some small values event ah cool that's all I have for this one let me know what you think uh yeah I'm gonna do a lot of problems but so stay good stay healthy take your mental health I'll see y'all later then take care bye
|
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
|
42 |
Hello Friends In This Section We Are Going To Discuss About Another List Co Problem Trapping Rain Water Divya Famous Interview According Question Given Interior Field With Negative Winters Different Elevation Map Edition Here With Love You All Will Calculate How Many Units In Water Park With Problem Egis Of elevation rainwater for this problem list subscribe to tuesday meaning of local minutes ago that find the water death at age indicates what is that is the president of united with water in the united states in tune in total units of water know how To How To Calculate Oral Water Level Plug Level Of Water Level In The Mid Term Water Level Subscribe Element Value From The Current Person Loot One Unit Of Death In Which Height Ironing Current 1203 Units Update No How To Calculate Water Level Site Which Indicators HOW TO FIND THE VALUE ATTACHED INDEX AND YOU LOOK AT LEAST TO BRING WATER IS GETTING PREGNANT BOON C BUILDINGS CLICK SUBSCRIBE BUTTON THIS PARTICULAR BUILDING WATER LEVEL DECIDE WHAT IS THE MEANING OF THIS IS IT A KI NAW THIS IS THE TALLEST BUILDING WITH WATER Level Will Be Still Here Comes The Water Level They Do Minimum Submerge Building Will Decide Water Level Identify The Left And Right Side Maximum And Minimum One The Water Level Indicator In Order To Identify Different Subscribe Value Current Element Value From SIM Good Night Before Writing The Formula of Climate of Dafa Malaise Minimum of Left Side Maximum Height of Murder Right Side Maximum Height - Current Element at Index Which Maximum Height - Current Element at Index Which Maximum Height - Current Element at Index Which Give Water Department Given in These Applied for Pune Index Andhi Railway Station Map Beerwa Identify Maximum Similarly To Travel To Identify Maximum Set Same Process Veerwal Left Side Right Side Subscribe This Process Will Impact Of This Prominent Will Do Complete Work Will Dhoop Maximum Item On Both Sides For All Indians At One Time Hotspot Of The First And Clean This Will Start From Fear To Identify Left Side Maximum Fiber Glue Match This Indicate Left Side Maximum 0383 Lage In Some Cases It But In This Case It's On Left Side Will Start From Subscribe Right Side Maximum 8d Index To Zinc When Maximum Right Side Height Is For Independent Maximum Right Side Height Is Find In this index phase void 59 liquid water which will start from Indian middle age minimum 0580 - - Indian middle age minimum 0580 - - Indian middle age minimum 0580 - - negative it is sure to be a minimum of one Kama 518 minimum one - 3 - minimum of one Kama 518 minimum one - 3 - minimum of one Kama 518 minimum one - 3 - to if ignoring on negative number 10 minimum of 353 is the smallest then MP3 - 1135 Mistry - 01 - 1383 - - 205 guest has come the fighter matri minimum mein stree - wwc2 fighter matri minimum mein stree - wwc2 fighter matri minimum mein stree - wwc2 minutes after death 538 minimum current element is 2321 units after death come to minimum - ₹499 number 90 se zameen death come to minimum - ₹499 number 90 se zameen death come to minimum - ₹499 number 90 se zameen entertainment 2013 subscribe total units of water content writing To subscribe The Channel Ajit Singh Ji A Higher Oil Depot Mitra Signature From List To Relax Declarative Variables In This Way The Rituals To Rain Water Printing Capacity Final Result Will Include Android Pimples Jhal Ki Also Will Declare Indices Travels Are O Which Vegetable Will Be Used Toe travel from left side hai hua tha very good fight will be used toe travel from rate side effect novel used oil in us tractor agreement value from right side absolute value jhal jai hind it's back neck left mix karna hai 123 only blend left max than update left maxwell hai ha hai hua tha zhal calculate current element by one increment take index pawan step that is are element value from right side absolute value david o 12345 days write max then update right maxwell hai hua tha zhal otherwise calculate death at current element that decrement only by index by One Step At That 108 Rumor Look Return Result Is Be Done With Coding Let's Kunwar Code Is Already Written With Amendment For Some Time The Restless Function Patrolling Trap Function With Multiple Input Tray Electronic Homes Ronit Roy Is That Result And Expected To Trap In Rain Water If there is solution, please like. Thanks for watching. Please like this video and subscribe our channel. Thank you.
|
Trapping Rain Water
|
trapping-rain-water
|
Given `n` non-negative integers representing an elevation map where the width of each bar is `1`, compute how much water it can trap after raining.
**Example 1:**
**Input:** height = \[0,1,0,2,1,0,1,3,2,1,2,1\]
**Output:** 6
**Explanation:** The above elevation map (black section) is represented by array \[0,1,0,2,1,0,1,3,2,1,2,1\]. In this case, 6 units of rain water (blue section) are being trapped.
**Example 2:**
**Input:** height = \[4,2,0,3,2,5\]
**Output:** 9
**Constraints:**
* `n == height.length`
* `1 <= n <= 2 * 104`
* `0 <= height[i] <= 105`
| null |
Array,Two Pointers,Dynamic Programming,Stack,Monotonic Stack
|
Hard
|
11,238,407,756
|
1,419 |
Ajay Ko Hello viewers welcome back to my channel I hope you enjoying all problems meaning of uploading him subscribe my channel please do subscribe can also share with your friends to this problem from difficulties minimum number of frogs cropping in different characters which represents a combination of distinct Perform Different From Subscribe And Mix Return Minimum Number Of Different Craft In The Giver Subscribe Internet Subscribe Printing COL The Crossing Middle East Related CAB With Letter Game OK C R O L Id The France To Print All Latest Feature Crush 100 Withdrawal Multiple Characters in Subscribe subscribe and subscribe this Video Subscribe Example Subscribe and CR O L&T and Verizon Subscribe 31 CR O L&T and Verizon Subscribe 31 CR O L&T and Verizon Subscribe 31 From Here Tuck Two Crafts With Two Return The Number of Vinod Number Forms Required to Completely Destroy Share Rock Former Senior subscribe this Video give Recovery Subscribe subscribe like Share And subscribe The Amazing And A Soft Servi And This Question On Your Second Day Box Rock Recent Profit Sikray Back To Construct Super Distic Per Generator You Needed To Drops Explanation Add Ka Settings Show Light Red Light CR And To Wake Up Sid Si to ro erect sahi ne to front complete edison electronic distraction pinpoint living guru needed from middle name and subscribe complete the problems effigy of all securely locup subscribe like and subscribe button and oy give oo that and might find what is the minimum number of Frogs Dash Liquid Festival Dandruff Bombs And 861 Have Only Disha Latest C R O N K And What They Are Doing A Director Subscribe How Many Time Subscribe Us Akbar In The Giver Subscribe Skin Sirf The Amazing And Share And Subscribe To Ka Note Wale So All Dear Not Valid Comment Veer Vikram Singh CPRO and Share Thank you liked The Video then subscribe to subscribe our Channel subscribe and subscribe Problem Subscribe 15 Breast Cancer This return on so many 20 contestants 102 Anything to Validate That Melt Fraud Toilet Channel Subscribe subscribe Video plz subscribe Statistics Current Events of the Day MS Word 20th Health C Free Porn For Grade S The World Level Subscribe The Channel Must Subscribe And Serve The Twitter The Amazing According To Thursday Subscribe And Subscribe The Amazing Share And Subscribe To A Nominee 20 Carat Period Springs And Voice Award Seervi Way Witch Point Index Dash liked The Video then subscribe to the Page if you liked The Video then subscribe to How to See Na Lein Skin List Festivals in English 151 UMTS Dates for the New Frock Guru Subscribe Electronic Cigarette is Hybrid SIM Slot They Were Not Placed Ours Not Want To See The Other Wise The Reader Dr. That 100 Similarly For Any Other Unit Stretch Your Voice Of Lazy ROC Are You Alone With A Smooth Shell Of Withdrawal From CR To Amazon Liter - Dr. R.C.L. Cs CR To Amazon Liter - Dr. R.C.L. Cs CR To Amazon Liter - Dr. R.C.L. Cs subscribe and official maps of map of Russian will subscribe and official maps of map of Russian will subscribe and official maps of map of Russian will turn it upside down jackal oy festival in the field of this chakra subscribe skin subscribe channel subscribe list playlist a's sister near man etc number four cancer not saying The Can Live With His Parents Host Turn On 200 Welcome Back To Bank Account Related Ancestry People Search Send A The Basis Of String Of Crops From Great Judgment Plus 2 And Fasting Sir Liquid Liner Mist Hi Dhund And Robbers Ne Ki Siyar OCR Oye Friends How Many Now Dam Are Really Form Humne Lift Au Hua Tha Mani Now How Many Now Seervi And Were Not Giving Track Number Of The List Subscribe 10000 Complete The Subscribe 502 Why I Want The A Particular Difficult Characters Account Introduction Till Subscribe And The Problem Subscribe Thank You From Subscribe And In The Space A Significant Diabetes Patient Ko 1000 In That Case For Doing This Year Gone Into English And Map To Receive New Updates Reviews And News Today List Subscribe To The Page if you liked The Video then subscribe to the way Similarly for Oye Gandu Ghus Neeraj Ko Hang Out for At Least 100 Grams Saunf Farar 992 Encounter Aadat Current Caritas R Right Subah Chalenge Isi Time 100 Ko Clean Sweep in the India Subscribe Now to Receive New Updates - Subscribe to is Updates - Subscribe to is Updates - Subscribe to is these days shooting scene be induced in from map to right and left and right to and subscribe now CR solid removed from that in the country to map to see and to measure servi and 230 rates with a similar thing and different accuracy Oye Yusuf problem turn on this and similar that mid- is available on loot any of the missing as per good turn on this and similar that mid- is available on loot any of the missing as per good night 28 Oye withdrawal love you do the thing from subscribe like and subscribe Skin that if side before returning officer is equal to point this point see all the do this and record of SIM not seeing is elected president M from which tiffin list have anything left or right play list account this gang and note 000 should be kept Front Friend Anything At Least Count Is Zoom Not For Single Drop Of Water Due To Return To Avoid Food At Least Count Number Of Frog Data Request You To Give You Problems Create And Subscribe Must Subscribe 2014 Morning Free At Sector Beta-2 Morning Free At Sector Beta-2 Morning Free At Sector Beta-2 Order of Length Addison AB Tarf and Sincere Calling Mental Stress and White Morning Mode of Channel Gautam Do Something Like Adding Elements and Removing Elements from Previous The Meaning of Elements from the Calling The Scored and the Time and Space subscribe this Video subscribe and subscribe dooba its advantages to vote for boys subscribe 158 254 subscribe thank you are the different subscribe and share and [ you are the different subscribe and share and [ you are the different subscribe and share and subscribe button and subscribe 1238 subscribe we gift from the sims vihar running and f5 providence and scotland five maximum number 502 and five and Distributor In This Point 491 Hair Oil Fully Agreed For Using This Year's Space And White 54551 Bird That In Practical The Space From Practice Match Loot 100 Spot Where To Avoid Using String Builder And Five List Sunni Hai Ko Again And You All Guys How Much Land Toe lift se secure subscribe our Channel subscribe this Video plz subscribe Will be removed from the pigmentation subscribe comment section thank you for watching my video issue hormone subscribe add toe favorites to my channel and also share thank you friends please don't forget to click The Bell Icon Effect Bell Icon You Will Get Notifications for All My Future Videos Science and Thanks for Watching Eventual Problem Front Very Soon Children End By A And Listen
|
Minimum Number of Frogs Croaking
|
minimum-number-of-frogs-croaking
|
You are given the string `croakOfFrogs`, which represents a combination of the string `"croak "` from different frogs, that is, multiple frogs can croak at the same time, so multiple `"croak "` are mixed.
_Return the minimum number of_ different _frogs to finish all the croaks in the given string._
A valid `"croak "` means a frog is printing five letters `'c'`, `'r'`, `'o'`, `'a'`, and `'k'` **sequentially**. The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid `"croak "` return `-1`.
**Example 1:**
**Input:** croakOfFrogs = "croakcroak "
**Output:** 1
**Explanation:** One frog yelling "croak **"** twice.
**Example 2:**
**Input:** croakOfFrogs = "crcoakroak "
**Output:** 2
**Explanation:** The minimum number of frogs is two.
The first frog could yell "**cr**c**oak**roak ".
The second frog could yell later "cr**c**oak**roak** ".
**Example 3:**
**Input:** croakOfFrogs = "croakcrook "
**Output:** -1
**Explanation:** The given string is an invalid combination of "croak **"** from different frogs.
**Constraints:**
* `1 <= croakOfFrogs.length <= 105`
* `croakOfFrogs` is either `'c'`, `'r'`, `'o'`, `'a'`, or `'k'`.
| null | null |
Medium
| null |
1,943 |
Hello so today we will discuss the list role number one four three do subscribe painting come so I will explain you in short question what is shikar basically what is given in it some segments are given which has starting and pending index of each statement and Some color of each segment which is this 5 to 7 minutes color this segment color 0 editing this segment So now what we have to do is to give a final result vector here add the equivalent of whatever overlapping segments are there like you If you see till 104 then there are two overlapping segments here 549 stop new shirt man 145 episode 104 carrying the luggage of both did not wake up photo five plus 98 similar second and thanks a comment made from here your 427 here will go to 16th of sever noida Here's the starting segment again and from here where toe poked. Similarly what we see here is same here also like from intake till education you will have a segment which is not like this or from day 6 till house point plus. Will remain nearby Reduce 2004 like way father ok so basically this is our problem set mode off and when schedule comes then in this the segment is till five on kalyan stand then 16 is Sara color distributor ok so what do we do discuss a list I have a very good meaning of discussing the solution or ₹ 100 This is good meaning of discussing the solution or ₹ 100 This is good meaning of discussing the solution or ₹ 100 This is posted by this wall in aa hai, so what he has done very well, what is the spelling of the diagram, see this, he has said that now, whenever someone is starting, someone Starting of Judgment, when you go to the ending, the event happens after, okay, so what is happening here, there are 3 more events denoted here, okay, what is happening in the first event, two more things, 2 to 3 minutes. And if it is adopted then fortin add point then where the statement will be shot I will add its colors so here my segment will end so there I will loot the color - then add I will loot the color - then add I will loot the color - then add point 4 my segment this one is coming to an end So I did Forteen - 5th Vikash, initially is coming to an end So I did Forteen - 5th Vikash, initially is coming to an end So I did Forteen - 5th Vikash, initially what was my initial statement and so here is the comment due to the effect of five plus one, so friends, we went to 349, after that I saw that next time, turn off the front and turn off the ride point of airplane mode. Then here I saw that 40 current time is judgment and other from protein, I have to edit it fortis - five, death father will fortis - five, death father will fortis - five, death father will not contribute and added seven that it is doing 718, so our current color here is doing 1622. Then 16th will be our continuation. A National TV does not do any new event or events means that a segment starts and does not end, then the next one will come on our terms and then seventh we will see that two segments are happening, so our current color. Mix remained 6 - 7 - our current color. Mix remained 6 - 7 - our current color. Mix remained 6 - 7 - 9000 so here we saw that all the events of three coordinates are happening 141 condition so our result became till 104 and not want to take much 80 current color mix donate this point For each segment one floor and 512 hair current affair minister, our overlap will be one segment, like my photo was in till 104. Till now it is fine, so this is my 115 here, then in the second event, what happened in the seventh was 72. From here, that previous event was on four, so a new segment will be created for seventh, there in my color, Pooja's sixteen is fine. And no one will consider 0 at the end, as long as all the segments are over, okay, similarly, first half the exam, like here we have two more segments, zero plus 90, which means he has taken some current color, let's say zero, which is an imaginary segment. Have zone starting right to zero plus decided rebellion or starting then deactivate our six pack and doing so here he saw a new segment and f5 so added current colorful 9 to it then current pen And 2001 went, then next even, our seventh year 971 was ending after hitting under-20 4 - 115, so like this, was ending after hitting under-20 4 - 115, so like this, was ending after hitting under-20 4 - 115, so like this, take out China Talking in this Earth, whatever our current color is coming there and we take it to the previous index here. What was the previous one? So whatever color of Intex from previous till now, this is basically my news segment of the current color, so this was the basic approach. Now let's move on to the code, how is it okay to complain about this? So my already here is the accepted codec. I am the same. Okay, so this is what I am taking segment input, then I took the map, why did I take the map because I will wait from left to right, meaning whoever gets contacted first, here any event will happen by aspects, I want. That I should process it first, okay, that's why I took the map, in the internal map, all my 21 articles will remain in short term, meaning there will be minimum job index or minimum index, any event will remain here, it will remain in mine first that I am okay. And so I am player A, it will basically perform whatever auditor pressure you want at the login time but update delete any thing okay. So what I am doing is add it at the beginning of every segment and here - I am doing okay. add it at the beginning of every segment and here - I am doing okay. add it at the beginning of every segment and here - I am doing okay. In the ending - let me do this and you know that In the ending - let me do this and you know that In the ending - let me do this and you know that all this is my event caring index so all the events will be done, I am leaving it in the egg map and there I will basically update whatever current system is starting or will be adding it. If the color is negative then it will support, so here I store that update in my map, what updates are possible on which index, okay, after that I am not doing anything, after that I am deleting a current color from the color. Gas ko - wale some previous there Gas ko - wale some previous there Gas ko - wale some previous there was no time and I will do all the events next proper grate so I am seeing that if my previous is not and color is also not conflict current color is not zero and previous is also not minus one Rather, already some previous has come, so I will populate the results, so what will be the result here, previous, whatever is the even talk ring index, this current you know door index of current color, this will become a new one of mine as those events will end. Okay like that means till there I have created a new secret after that I will update the color that is on the index okay because here we have seen that your pending index is exclusive so that's why I have already skipped that result. I have to update later, it's okay, here like yes, which you give problem statement, given this house, follow a segment, left, button, right, is not included, okay, so first I will change the current color and later I will update the color, so I have changed the color. By updating that event, whatever event will be updated in the index, and made the previous one, the current one, the previous one, that is, I had made all the index events prevented so that they can be added to the next session and become our previous one. Okay friends, I have checked the results and if this result is nothing, I have taken a vector where it will leave it from the new and looping segment, then this was my code, you comment it and see, little pass is okay, so there it passed. It's 33.3 percent time there it passed. It's 33.3 percent time there it passed. It's 33.3 percent time complexity edition. So this was a very good problem in all the elections. The article is basically kind of online in all the aspects where you can do events Gautameshwar and update accordingly. Handed over guide channel. If you liked this video then please like it. And subscribe so that I can make more such videos 100 Ko Kahande Khand Stay Safe and Have a Nice To Thank You Too
|
Describe the Painting
|
count-pairs-of-equal-substrings-with-minimum-difference
|
There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a **unique** color. You are given a 2D integer array `segments`, where `segments[i] = [starti, endi, colori]` represents the **half-closed segment** `[starti, endi)` with `colori` as the color.
The colors in the overlapping segments of the painting were **mixed** when it was painted. When two or more colors mix, they form a new color that can be represented as a **set** of mixed colors.
* For example, if colors `2`, `4`, and `6` are mixed, then the resulting mixed color is `{2,4,6}`.
For the sake of simplicity, you should only output the **sum** of the elements in the set rather than the full set.
You want to **describe** the painting with the **minimum** number of non-overlapping **half-closed segments** of these mixed colors. These segments can be represented by the 2D array `painting` where `painting[j] = [leftj, rightj, mixj]` describes a **half-closed segment** `[leftj, rightj)` with the mixed color **sum** of `mixj`.
* For example, the painting created with `segments = [[1,4,5],[1,7,7]]` can be described by `painting = [[1,4,12],[4,7,7]]` because:
* `[1,4)` is colored `{5,7}` (with a sum of `12`) from both the first and second segments.
* `[4,7)` is colored `{7}` from only the second segment.
Return _the 2D array_ `painting` _describing the finished painting (excluding any parts that are **not** painted). You may return the segments in **any order**_.
A **half-closed segment** `[a, b)` is the section of the number line between points `a` and `b` **including** point `a` and **not including** point `b`.
**Example 1:**
**Input:** segments = \[\[1,4,5\],\[4,7,7\],\[1,7,9\]\]
**Output:** \[\[1,4,14\],\[4,7,16\]\]
**Explanation:** The painting can be described as follows:
- \[1,4) is colored {5,9} (with a sum of 14) from the first and third segments.
- \[4,7) is colored {7,9} (with a sum of 16) from the second and third segments.
**Example 2:**
**Input:** segments = \[\[1,7,9\],\[6,8,15\],\[8,10,7\]\]
**Output:** \[\[1,6,9\],\[6,7,24\],\[7,8,15\],\[8,10,7\]\]
**Explanation:** The painting can be described as follows:
- \[1,6) is colored 9 from the first segment.
- \[6,7) is colored {9,15} (with a sum of 24) from the first and second segments.
- \[7,8) is colored 15 from the second segment.
- \[8,10) is colored 7 from the third segment.
**Example 3:**
**Input:** segments = \[\[1,4,5\],\[1,4,7\],\[4,7,1\],\[4,7,11\]\]
**Output:** \[\[1,4,12\],\[4,7,12\]\]
**Explanation:** The painting can be described as follows:
- \[1,4) is colored {5,7} (with a sum of 12) from the first and second segments.
- \[4,7) is colored {1,11} (with a sum of 12) from the third and fourth segments.
Note that returning a single segment \[1,7) is incorrect because the mixed color sets are different.
**Constraints:**
* `1 <= segments.length <= 2 * 104`
* `segments[i].length == 3`
* `1 <= starti < endi <= 105`
* `1 <= colori <= 109`
* Each `colori` is distinct.
|
If the chosen substrings are of size larger than 1, then you can remove all but the first character from both substrings, and you'll get equal substrings of size 1, with the same a but less j. Hence, it's always optimal to choose substrings of size 1. If you choose a specific letter, then it's optimal to choose its first occurrence in firstString, and its last occurrence in secondString, to minimize j-a.
|
Hash Table,String,Greedy
|
Medium
| null |
1,625 |
hey everybody this is larry this is q2 uh of the weekly leco contest 211. uh hit the like button hit the subscribe button join me on discord uh and we're gonna go over lecture graphically smallest string after applying operations so this one it's a lot of reading it's a really tricky problem uh if you look at the scores from the leaders uh they all solved it like the last there are a couple of mistakes here and there but you know like seven minutes for you know like 10 minutes for a super limit okay it's you know finished third and also super smart um that means that there's some like weirdness about this problem right in general there's a lot of reading uh maybe people just didn't want to read it as well but basically the core part to notice for this problem is that the number of states is actually not that big the thing that you might think about is that the two operations you can do one is rotate s to um by b right so okay let me copy and paste this here so that we can kind of go play around with it so they're two operations right um you have the second operation which is rotate by b uh you know for the for our purposes b could be any number but um but let's just play with the idea that this is one because we're trying to think about the worst case that could happen right so we can rotate s to the right by one right um because in that case then in total you can keep on doing it and just end different ways of doing it right so worst case is equal to rotate by one uh n times right so that's the number of states uh at least in one dimension uh and then now the operation the first operation it's kind of that's the thing that i think for me took the longest to kind of convince myself a little bit is that you only need to care about the odd index you don't have to choose any index you don't have to uh there's only one index and what does that mean when it's only odd index right uh that means that all the odd indexes and all the even indexes will move in the same time right meaning that there's no um and what i mean is that they're all correlated uh you may think of the term like independence this is the opposite of that right every odd index is dependent on each other so you can kind of think about it as like you know when you move one like the odd index one you also move to add index three right so they have to move together and when you move together the states are the same right there's no differentness that comes with it i'm a little bit hand-wavy here little bit hand-wavy here little bit hand-wavy here uh there are mathematical explanations as well but that's kind of my way of explaining it and similar to rotate by one we're going to just choose a is equal to the worst case for step one is oops the worst case for step one is to go to add by one because if you keep on adding by one then you know you have to do it ten times right so this is at most ten times um and now how do you combine them together as we said uh the odd indexes are correlated and the even indexes are correlated in the same way because if you the only way that you could adjust even index is if you rotate it by a given number and then you know go on right so that means that in this case you can do the first up the unique number of ways so you could kind of divide the first operation to two different operations in the worst case may not come up all the cases right which is that you could break it down to two operations this is actually add a to all odd indexes and then we already talked about the worst case and also add a two or even indexes um which is basically what this uh so this is you know at most 10 times uh this is at most 10 times as well if we have this operation but we rotate it by let's just say we rotate by one and then do it right so if you do it that way you could count yourself that at most um because these things these two are independent and when they're independent you multiply each other right so that means that in this operation at most is about 100 times right so you have 100 different unique combinations of odd indexes and even indexes and how it changes by the rotation and then now this is 100 times and then and each of the 100 times you do this rotation of the odd and the even like you have two hands and they're only adding even um you can also shift uh left or right uh you know at most end times as we kind of talked about here i say rotate or maybe i just raise shift maybe that's real because i think i'm a little bit confusing so what that means is that it is at most a hundred times n where n is almost 100 anyway so that means that this is going to be 100 square number of states um so that means that no matter what you do no matter how you do it you're only going to see a hundred square numbers right uh and based off that i use the breadth first search uh you could also do a deferred search or something but basically uh you do this operation one at a time and then you just take the uh the lexicographically smallest string after that and basically that's what i did um i put in the initial string i've said that as the best as the example i put in scene though i think actually i messed up a little bit and that i actually didn't set like s should be in here um but that's still okay because you just add one operation i guess e but basically here i convert it to an array just for easier for uh programming uh this is just shifting it by adding a to all the odd integers uh the odd indexes and then this is converted back to string put see if we have already seen it we haven't processed it then we add it to the queue uh and this is the shifting by uh b right so you know you can do some maps i did some math to kind of make it go right instead of left so that's easier for me to understand you might not need to know that or understand that but that's basically how i did it um yeah uh let me know what you think about this problem it's tricky but a lot of it like the coding it's not easy per se but it's also not the hardest part of the problem even though for q2 uh this is a pretty hard q2 um and yeah once you know once you nailed it down that um the number of states is fine it's that few then this becomes straightforward you know you have to maybe work out some implementation detail uh but yeah and you can watch me stop this from live during the contest next slow today okay i ate all right index multi s to the right by b foreign okay hmm let's do this is there an easy solution to this because this seems a little tricky so you see this one we get to agree prefer search because all the numbers are dependent on each other or the odd one so you could definitely search uh a breakfast search okay etc because it's going to be 10 times 20 okay this is pretty hard to prove on the b maybe i don't know um oh now we can a to order on index um okay um also oh this isn't right let's see if it works so okay one this to the right um you 250 24. it just times out a little bit sad uh thanks for watching uh this you know video uh let me know what you think hit the like button to subscribe 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
|
Lexicographically Smallest String After Applying Operations
|
group-sold-products-by-the-date
|
You are given a string `s` of **even length** consisting of digits from `0` to `9`, and two integers `a` and `b`.
You can apply either of the following two operations any number of times and in any order on `s`:
* Add `a` to all odd indices of `s` **(0-indexed)**. Digits post `9` are cycled back to `0`. For example, if `s = "3456 "` and `a = 5`, `s` becomes `"3951 "`.
* Rotate `s` to the right by `b` positions. For example, if `s = "3456 "` and `b = 1`, `s` becomes `"6345 "`.
Return _the **lexicographically smallest** string you can obtain by applying the above operations any number of times on_ `s`.
A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"0158 "` is lexicographically smaller than `"0190 "` because the first position they differ is at the third letter, and `'5'` comes before `'9'`.
**Example 1:**
**Input:** s = "5525 ", a = 9, b = 2
**Output:** "2050 "
**Explanation:** We can apply the following operations:
Start: "5525 "
Rotate: "2555 "
Add: "2454 "
Add: "2353 "
Rotate: "5323 "
Add: "5222 "
Add: "5121 "
Rotate: "2151 "
Add: "2050 "
There is no way to obtain a string that is lexicographically smaller then "2050 ".
**Example 2:**
**Input:** s = "74 ", a = 5, b = 1
**Output:** "24 "
**Explanation:** We can apply the following operations:
Start: "74 "
Rotate: "47 "
Add: "42 "
Rotate: "24 "
There is no way to obtain a string that is lexicographically smaller then "24 ".
**Example 3:**
**Input:** s = "0011 ", a = 4, b = 2
**Output:** "0011 "
**Explanation:** There are no sequence of operations that will give us a lexicographically smaller string than "0011 ".
**Constraints:**
* `2 <= s.length <= 100`
* `s.length` is even.
* `s` consists of digits from `0` to `9` only.
* `1 <= a <= 9`
* `1 <= b <= s.length - 1`
| null |
Database
|
Easy
|
2335
|
1 |
hello everybody my name is Ryan powers I'm going to be coding through the leak top 100 and I hope that a lot of you will be joining me this is my first video so hopefully it goes smoothly but yeah so the first problem on the leak code top 100 is too soon so we'll be starting with twosome so I'm given array of integers return indices of the two numbers such that they add up to a specific target and this is important here so we're looking for the indices not the two numbers right like so it says target is nine then we would be looking for two and seven so we're not returning to seven returning zero and one because the index of two is zero and the index of seven is one right so you may assume that each input would have exactly one solution so we don't need to handle any edge cases here each input has exactly one solution so we will find a solution so we don't need to handle you know the edge case where the solution does not exist and we can only use the same element twice so we can only just may not used to saying only twice right so if the target was four then we cannot use two twice we cannot say 2+2 is 4 because that is the cannot say 2+2 is 4 because that is the cannot say 2+2 is 4 because that is the same index so how would we go about solving this problem so there are two solutions to this problem there's the there's a order n-squared the there's a order n-squared the there's a order n-squared solution in this problem which is the quote unquote naive solution to this problem which is one of my favorite terms naive solution to a problem because usually the first solution that I always come up with my doing algorithm that is uh is the naive solution so and then there's a ends order n solution to this problem so first of all we'll take a look at what the N squared solution of this problem be so welcome to my whiteboard Apollo omit apologies for the handwriting it's actually really hard to write on these computer whiteboards with the mouse but I'm gonna do the best I can I might try to come up with a better solution if I actually end up doing hundred videos which I hope to do but for now this is the best I can do so bear with me so okay so the N squared solution to this problem so how do we go about solving that all right so we would first look at the value two and we would just go through the array and we would look at every single value for that particular number so for two we compare it with seven we add with 11 and 15 and we would say okay no that does not equal the target and then we would move on to seven when we look at every number after seven we wouldn't have to go back and look at two because we've already we already compared to a seven when we iterated through with the value of two so we just need to look at the numbers after seven so we look at seven and we would compare with eleven okay 18 is not equal to target then we'd go through and we look at 15 we say oh great we found it seven plus 15 is 22 and we're done alright so that is the order of N squared algorithm and why is it N squared well it's N squared because for each item in the array we have to iterate through the entire and now we don't exactly have to iterate through the entire array again if we had iterated all the way through then we would have had another call here and if you look at this an N squared algorithm would look like this right so we would have four calls for each item in the array right so that would be six sixteen total calls are operations in this array and in this we only have okay one two three four five six seven eight okay one two three four five six seven and eight right we only have eight so what is that's actually N squared over two okay so we would have had eight items in this array and n squared algorithm be 64 but in this algorithm if we would only have 32 operations or top times iterating through but when we do time complexities we only pay attention to what is actually dictating the increase in time right so the main a indicator of how long it's going to take to run this algorithm is this N squared right it's how many times through this array where n is the number of elements in the array that we have to look at so since 2 is a constant as n grows it's really going to have a really small effect on the run time of the algorithm so we just ignore constants so that's why you would say this is actually an N squared algorithm so this is a naive approach to this problem which is the first time I saw it is the answer I came up with but that there's a better solution in this problem there's an N and order n time complexity answer to this problem and how could we come about solving that problem in the way that you come up with this problem and in the way that you usually come up with these more efficient solutions to these algorithm problems is thinking about okay what is all the information that I have like because in this other problem here this other problem I would say we're not using all the information we have right we're just using the number that we're looking at and we're just saying this is equal of 22 you know but there's more information here and that's usually the key to come on coming up with these other solutions and I would just encourage you and I'll try to do that point it out every time I solve a problem with you guys but like what is all the information we have and how can we potentially use it so here what is all the information we have I prepared the second white board in advance because erasing and then every writing takes a long time as you can see I'm my writing is terrible but what is all the information we have right okay so we have a current value right so at each spot that we're looking at we have a current value and right now our current value is 2 okay so right now the current value is 2 we start if we start from this index all right and I'll just write our indexes up here because we're going to be using them all right okay so we have current value which is two but we also can have the target value which is 22 so we can if we want to and I'm just going to represent so we can if we want to with the pair is we can read and count calculators pair right so we take the target and we subtract their current value then we know what the number is that we need to get to reach the target right so at every index in this array we know the current value and we also know what it's pair should be so we can check and see if we've already seen that value right if we've already seen the pair value and we know then we know already what the answer to the problem is now the tricky part is that we don't need the actual number right we need to index okay so we're gonna go through so the pattern that we're gonna use here is we're gonna look at two right and we're gonna create an object okay that's not very good but alright so here's a little object here and we're gonna store the pair values right but the first thing we're gonna do is we're gonna look for - all right is we're gonna look for - all right is we're gonna look for - all right we're gonna look for two in our object we're going to say okay is tuned our object and if two is in our object then we will have stored the index of its pair value so we'll have the index of our current value and then we'll also have the index of the pair because we've all we've already seen it if it's in our object right so the first thing we're going to do is we're going to check for two and say okay is to in our object no two is not in our object so we're going to calculate its pair value so it's pair value is T - the value so it's pair value is T - the value so it's pair value is T - the current value which is two so it's pair value is going to be 20 okay and then at 20 we're gonna store the index of two so the index of two is zero all right and then we move on to seven and we're gonna say okay is seven in our object no seven is not in our object so we're going to calculate its pair is 22 minus seven which is 15 and we're going to store the index of seven so the index of seven is at index 1 and then we're going to move on to 11 and we're gonna say okay is 11 in our object 11 is not in our object so we will calculate its pair 22 minus 11 is 11 so 11 is pair is 11 and remember we can't use the same number twice so we would have to have a second number 11 yeah just to solve this problem with 11 is the answer so the index of 11 is going to be its pair which is the current value 11 which is that index 2 which is kind of confusing but we're not going to run into another 11 so the next thing we're gonna do is we're gonna go to 15 and we're going to say is 15 in our object we're gonna say yes absolutely 15 is in our object right so we know that we have a solution so the current value here is it is 15 and that is at the index of 3 right so we can return the current index which is 3 and it's pair which is one right because how did we get the one right we so we took seven we subtracted it from 22 and we found the number 15 and we stored the index of seven there so when we ran into 15 again we looked at it in our object and we saw okay yes we have seen a number already that when you add it to 15 equals our target value and that value is at index 1 right so we just grabbed the current index and then we match it up with the index that we stored in our object so how would we code so all right so that's order n right that's an order n solution why is it order n it's order n because we only have to iterate through all of the items in the array one time okay so how would we code that up so let's go over to lis code all right so two numbers sum so the first thing that we're going to do is we're gonna create an object so hey boss object so this is the object that we're going to store all of our pair values in and then we to loop through the array so I equal 0 okay so we're looping through all the values in our object and we need to grab our two values right so just to be really clear about what I'm doing I'm just gonna say concept our current value is at knowns I and then the pair right so we also want the pair so our cost pair we'll sit there so the pair is at Target - the current value right so what - the current value right so what - the current value right so what's the first thing we do the first thing we need to do is we need to check to see if our current value if we have stored that value already in our object because if we started already in our object then we're done right so let's check will say if object knowns we're sorry current if object current value and I'm gonna say does not equal undefined and the reason why I'm gonna say does not you go undefined is because if for some reason we stored the number zero and in our object and we checked and just said like if object current and that equates to zero that would be false e so we would not we wouldn't get the desired outcome that we were looking for so anytime that we're storing numbered indexes and we're checking for truth eval use I always if I know that zero is a possible answer I always use does not equal undefined just to avoid that book right so if object current does not equal undefined then we know that there's an index there that we can use right so we can say object current so object current and I so we can return object current and I so that would be the index of its pair and then the current value that wrong else if it's not in there then we distort its pair value all right we need to store the pair value of that current number in our object and we need to store the index of our current value under that label in our object so we would say object pair right hair that we're looking for equals okay and then so that should get us the right answer so let's run it I'm gonna move myself all right cool so that was accepted that's great I always like to look at the output the more details this is why I really like we code because I know this is kind of a simple problem but once we start looking at harder problems and when you're doing these problems on your own I encourage you to look at these okay so this is like 61 percent right so this is the output of all the people who have submitted code to this problem and it gives you like the runtime of your problem you can see where does your prop where does your solution lie in all of these and you need to run it a couple of times because I don't know exactly why but if you run it a few times you'll get an idea of how efficient your solution is and whether or not you should keep trying but this is definitely the most optimal solution in this problem so I'm just going to run it again and hopefully I get like a hundred or something so that we cannot feel good about what we did all right eighty eight point four nine percent that's great you can also look at other people's code too if you want to and see you know maybe how they tackle these problems by like I use this thing here you can kind of zoom up on you know the best runtimes for this problem and you can see you know how other people have attempted it and this is basically what we did here we said okay if it doesn't go undefined then return I don't know these crazy variable names that they use anyway my name is Ryan and I hope you will be joining me for the next time when I saw the second problem and Lee could top 100
|
Two Sum
|
two-sum
|
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_.
You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice.
You can return the answer in any order.
**Example 1:**
**Input:** nums = \[2,7,11,15\], target = 9
**Output:** \[0,1\]
**Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\].
**Example 2:**
**Input:** nums = \[3,2,4\], target = 6
**Output:** \[1,2\]
**Example 3:**
**Input:** nums = \[3,3\], target = 6
**Output:** \[0,1\]
**Constraints:**
* `2 <= nums.length <= 104`
* `-109 <= nums[i] <= 109`
* `-109 <= target <= 109`
* **Only one valid answer exists.**
**Follow-up:** Can you come up with an algorithm that is less than `O(n2)` time complexity?
|
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
|
Array,Hash Table
|
Easy
|
15,18,167,170,560,653,1083,1798,1830,2116,2133,2320
|
981 |
this video we're going to look at a legal problem called time based key value store so in this question we're going to show you two approach to solve this problem one is you can use a tree map to solve this problem and the other one is you can use a binary search a lot of programming languages like python which doesn't have tree map in the standard library so that's why i gave two solutions in this approach so basically the question is that we've given a uh we basically want to create a time based key value store right a key value store class um right this is our key value store class right uh which is called time map that supports two operations one is people to uh set right so similar to the hash table that we have so in this case we pass in the key the value and this it also takes a time stem variable right so we want to store the key value along with the given timestamp right you'll need to have a another operation called gets right it takes the key and the timestamp and be able to retrieve the key right we retrieve the value based on the key and the time step right so uh first of course we have to match the same key and the other thing that we have to watch out for is for in this git operation is that let's say if we have a timestamp uh if we cannot be able to find that timestamp right in this given key then we have to return the largest timestamp that is close to the timestamp that we passed in right and this is these are the object right so these are times them correspond to these keys we have to return the largest timestamp that is closest to the timestamp that we passed in so in this case it's three okay so let's take a look at an example here so let's say we create an instance of timestamp right and then we set foo right as the key and then the bar is the value and then timestamp is one so our state will look like this right and then if i want to get so the key is foo and then the key the timestamp is zero right if i want to get a value right that is that has the same key and the timestamp is less than or equal to the current time step that in this case we have a we have nothing right in this case if there's no values we just return an empty string right because in our state you can see we have a timestamp is one that's bigger than right the current timestamp so we cannot find it right so in this case if we cannot find it we just return empty string so now you can see let's say we have this one right here where a key is foo and then the value is one uh in this case we'll just return var because in this case we want to find a value right that has a same key and timestamp in this case is less than or equal to the current time step which is this one right here right now same thing here because 1 is less than or equal to 3 so we just return bar so let's say we have this thing right so now our state will look like this so we have the key is one the values bar and we have another key is this and the value is also is bar two right so in this case if i want to pass in four right so now i'm expecting this one right because i cannot expect this one because i want to return the largest uh timestamp right that is close to the current timestamp so therefore we just returned the uh the bar two right and same thing for five right in this case i want to return right a value that has the same key that uh that is largest timestamp that is close to the current timestamp in this case it's going to be four okay how we can be able to solve this problem using uh tree map so tree map in java uh basically use the map interface right so you can see here this map interface uh extends right this sorted map extends from the map interface and then this tree map class right basically implements this sorted map interface and you can see here this tree map is basically a map that is sorted according to the natural ordering of its key so it's very similar to a binary search tree right where we have a tree that it that all the elements on the left side is less than the current dose value and all the nodes on the right side is bigger than the current notes value right key points is that for operation like add remove contains key time complexity is big o of log n where n is number of elements in the tree map right uh whereas hash map in this case does not have an order but tree map keeps the element in sorted increasing order right so we can be able to find an element very easily in a login time complexity map has this function called um called floor key four key right so in this case this floor key function returns the greatest key right the greatest key less than or equal to the given key or null if there's no such a key so let me show you an example right so here first we create a instance of tree map right and then the key is integer and then the value values the string so in this case we put some values in the tree map right so we have the key the value and then if i want to pass in the if i want to get the greatest key less than or equal to six right um in this case we can just say temp dot floor key right we pass in the key right in this case six it will return us uh three right in this case it will return is three right so the greatest key less than six right is three right this also works if we have a timestamp that is the key is six right let's say this is six right it will also return six right so if so basically it finds the greatest key that are less than or equal to six um right less than or equal to six so what we can do instead is that we can be able to create a tree map like this right so once we create our map and then the string is basically our key and we have a tree map inside the map right and in the inside the tree map we basically set the timestamp as the key and then the value is the string uh the value is going to be the value of the tree map right so what's going to happen is that we're going to have this function right here set so it takes the set sorry the key the value and the timestamp and then we check to see if we already created this key right in this case we if we don't create this key in our map we create it uh we'll create an instance of a tree map for that and then what's to happen is that we're going to get the tree map right once we get the tree map um we're basically just going to insert the timestamp as the key and the value is going to be the value right so once we so this part is pretty easy and then if i want to retrieve a element right if i want to retrieve the value right the greatest key less than or equal to the given key what we can do is that first we check to see if the table has the key right if it doesn't have the key we just return empty string then what we're going to do is we're going to get the tree map from our table and then what's going to happen then was is we're going to call this floor key function we're passing the timestamp so in this case just like the just like this just like what it says so if there is so if or no right if there is no such a key right so in this case if we cannot find a key that is greater than uh greatest key less than or equal to the given key then we just have to return now so what's going to happen then is that if it's null we just return empty string otherwise once we find the small timestamp right the greatest key less than or equal to the given key then we're just going to return that value right so that's basically how what's going to happen if we use um uh in this case a uh tree map right to solve this problem and as you can see time complexity in this case uh for set in this case it's gonna be big o of one right worst case scenario is it could be big o of n right for uh for insertion map but for getting the element in this case it's going to be log in because uh when we perform the search in tree map right in this case uh entry performing a search entry is basically login time complexity right so in this case we have to find the key right that is less than or equal to the given key so we have to use login time complexity to solve this right so it will give us a login uh time complexity for searching the item right so now let's take a look at how we can be able to solve this problem using um binary search right so like i said earlier like a language like python doesn't have tree map in the standard library so what you have to do is that maybe you have to use binary search right so for binary search um in this case what we do is that we can do something similar right we still using a map the key still is a string but in this case we can have a list of time value right we can instead of creating like another table what we can do is that we can be able to have a list right and notice that in the question it says that um the timestamps for all time.set um the timestamps for all time.set um the timestamps for all time.set operation are strictly increasing that means that um if i want to insert an element like it's basically in order right in ascending order it's in increasing order right so i can instead uh insert zero insert one insert so insert y insert four right but in this case like the question said it will always be increasing right like i cannot have a negative four here right i cannot have a value that's decreasing order right it will not happen it will always be increasing for example 14 right so in this case what we can do is that um when we insert the value onto the list right in this case we have a list we guarantee that the list is sorted so if the list is sorted we can be able to perform binary search so you can see here we created in uh we basically create a class called time value which has a time which has a value right and then what's gonna happen is that when we insert a value we take the key a value a time step we try to see if the map contains this key if it doesn't we just create the list right and then once we get the list we will add that the current timestamp and the value onto it right so it's very simple right but for finding the value what's going to happen is that it takes the key and the timestamp we check to see if the map has uh if it doesn't have the key of course we would just return the um in this case a empty string right so once uh once that we pass this condition right we're going to get a list and then we will perform a binary search and what's gonna happen is that we're gonna have our left we're gonna have our right our left is basically like we have a list right we're going to have our left pointer and our right pointer and then while the left plus one is less than the right first we're going to what we're going to do is we're going to get our mid right we're going to basically uh you performing binary search right we check our nip index right if the mid index is equal to timestamp then we can just return the mid times uh the mid time value that's the value right the mid time value right in this case the mid-time value this case the mid-time value this case the mid-time value is let's not get mid else if the mid value mid time value that time right the timestamp is less than the timestamp then we have to search on the right so we get left is equal to mid right otherwise if the mid time value that time is bigger than the time stamp then we just have to search on the left side right so once we uh basically complete our search right we will have a situation where left pointer is less than the right pointer so first we check the right so we see if list.getright.time is less so we see if list.getright.time is less so we see if list.getright.time is less than or equal to the timestamp if it is we can just return that value right if not we check to see if let's start get the let's not get uh let's not get left that time is less than or equal to timestamp if that's the case we just return that value otherwise we can just return mp string right um because in this case we just like i said just like i mentioned we know that the left pointer is less than the right pointer so we first check the right we want to find the largest value that's greater right the greatest key uh that is smaller than the given time step right so in this case we first check the right and then we check the left so basically you can see this is also another way we can solve the problem and time complexity uh for this operation in this case is gonna be login right um because in this case we're using an array and we're performing binary search and the time complexity for this one in this case is going to be constant time complexity but worst case scenario is going to be linear right because in this case where uh we're basically have to uh allocate the space right because in this case for appending a element onto a list or an array list in this case on average it's going to be constant right but worst case scenario could be linear time complexity for insertion on a list right so basically there you have it and thank you for watching
|
Time Based Key-Value Store
|
delete-columns-to-make-sorted
|
Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp.
Implement the `TimeMap` class:
* `TimeMap()` Initializes the object of the data structure.
* `void set(String key, String value, int timestamp)` Stores the key `key` with the value `value` at the given time `timestamp`.
* `String get(String key, int timestamp)` Returns a value such that `set` was called previously, with `timestamp_prev <= timestamp`. If there are multiple such values, it returns the value associated with the largest `timestamp_prev`. If there are no values, it returns `" "`.
**Example 1:**
**Input**
\[ "TimeMap ", "set ", "get ", "get ", "set ", "get ", "get "\]
\[\[\], \[ "foo ", "bar ", 1\], \[ "foo ", 1\], \[ "foo ", 3\], \[ "foo ", "bar2 ", 4\], \[ "foo ", 4\], \[ "foo ", 5\]\]
**Output**
\[null, null, "bar ", "bar ", null, "bar2 ", "bar2 "\]
**Explanation**
TimeMap timeMap = new TimeMap();
timeMap.set( "foo ", "bar ", 1); // store the key "foo " and value "bar " along with timestamp = 1.
timeMap.get( "foo ", 1); // return "bar "
timeMap.get( "foo ", 3); // return "bar ", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar ".
timeMap.set( "foo ", "bar2 ", 4); // store the key "foo " and value "bar2 " along with timestamp = 4.
timeMap.get( "foo ", 4); // return "bar2 "
timeMap.get( "foo ", 5); // return "bar2 "
**Constraints:**
* `1 <= key.length, value.length <= 100`
* `key` and `value` consist of lowercase English letters and digits.
* `1 <= timestamp <= 107`
* All the timestamps `timestamp` of `set` are strictly increasing.
* At most `2 * 105` calls will be made to `set` and `get`.
| null |
Array,String
|
Easy
| null |
2 |
hey guys welcome back to another video and today we're going to be solving the lead code question add two numbers all right so in this question we're going to be given two non-empty linked lists representing two non-empty linked lists representing two non-empty linked lists representing two non-negative non-negative non-negative integers the digits are stored in reverse order and each of their nodes contains a single digit add the two numbers and return the sum as a linked list so in simple words we're going to be given two different linked lists and each of the linked lists of ends up representing a single number we want to add them and then we want to output a linked list of the added sum so you may assume that the two numbers do not contain any leading zeros except for the number zero itself okay so you might not you wouldn't have something like zero one if anything you just have a number zero perfect so one thing you do want to realize is the fact that it says reverse order so what exactly does it mean when it says reverse order so in this case we have two pointing to four pointing to three now in this case if you just look at it you might think the number is 243 but remember that it is stored in reversed order and since it is stored in reverse order over here the values that we're going to end up getting is going to be 342. so this over here is at the hundreds space this is over here is the tenth and this over here is at the unit place so 342. now this actually makes it a lot easier for us to add the numbers now before we actually go through how we can solve it in the beginning you might think uh all you need to do is just add its corresponding value in the other number for example two and five so you just add it up get seven now over here the problem is once you get six and four you actually end up with the value of ten so you can't store the value of ten over here you can only store a single digit so what actually ends up happening in such a case so in this case like as it is with normal addition you're going to have a carry forward and the carry forward is going to be the number one so in other words the 1 is going to get carried forward over here so in this case we have 3 plus 4 which equals to seven plus one because the one is to carry on so it's pretty simple and let's just see how we can do this real quickly so this is the exact same example and all i'm gonna do is write the numbers so 243 is the number 342 and the reason for that like i said earlier is because it's in reverse order and this 564 is the number 465. now one thing you do want to realize is that these two could be of different lengths they do not necessarily have to be of the same length all right perfect so when we add these two numbers what do we get so we get five plus two which is seven pretty simple now over here we get six plus four ten so in this case as it is with simple addition what is the value that ends up going over here so we get six plus four equals ten but what is the value that goes over here now the value that goes over here is whatever is at the units place so it's pretty simple so whatever is at the units place which in this case is the number zero and everything else gets carried on so in this case the number one gets carried on now what you want to do is we're not just adding the values of the number one and number two we're also going to take care of our carrying on so this case will be four plus three plus seven four plus three plus one giving us a value of eight hundred and seven and all we need to do is we wanna convert this into a linked list so this would be seven zero eight because we wanted reversed order okay perfect now so in this case uh you can kind of understand that the formula of addition is going to be the value at number one the value at number two plus whatever the carry-on the carry-on the carry-on is so what we're going to assume is that when we do not have a carry-on when we do not have a carry-on when we do not have a carry-on the carry-on is going to have a default the carry-on is going to have a default the carry-on is going to have a default value of the value zero so in this case uh in the beginning our carry-on our carry-on our carry-on is going to be zero so it would be five plus two plus zero so in this case uh we get the value of seven and seven is less than ten so we don't have any carry-on don't have any carry-on don't have any carry-on so the carry-on for this as well is so the carry-on for this as well is so the carry-on for this as well is going to be zero so 6 plus 4 which is 10 and then 0 and in this case we do have a carry-on we do have a carry-on we do have a carry-on of the value 1 so we need to account for it so that's why we added at the very ending so the idea of this should be pretty simple and let's just real quickly see how it actually works in terms of a linked list okay so in this case uh the first value we're gonna get is two and five so we're gonna add them so just you can just kind of assume as two pointers over here so the first pointer is at two and then at five so we're going to add it and we get the value seven we're going to create a new linked list node with the value seven so this figure is a new object of the linked list class perfect so now uh we move both of our pointers to the right by one so this moves right by one and this moves the right by one as well perfect so now we have four and six and this gives us the value of ten now in this case remember we're going to have a carry on a value and this is just going to be a variable which starts off at the value zero so in this case we have the value 10 so to our linked list we're only going to be appending whatever is at the units place so seven is going to only point to zero and the carry-on in this case carry-on in this case carry-on in this case is now going to get updated and the carry-on and uh carry-on and uh carry-on and uh so the actual value is 10 so the carry-on is going to be whatever value carry-on is going to be whatever value carry-on is going to be whatever value we get divided by 10 right so it's everything except for what we have in the units place and we're going to be doing integer division in this case okay perfect so in this case uh 10 divided by 10 gives us a value of 1. so the carry-on is now going to have a so the carry-on is now going to have a so the carry-on is now going to have a value of one over here now in this case we move our pointers again to the right so now we have six oh sorry four and three so now we're going to end up with the value of seven but we need to account for the carry-on but we need to account for the carry-on but we need to account for the carry-on which is one so this would now end up becoming eight giving us the value of uh seven pointing to zero pointing to eight but in this case um so technically so then we go to next value and how it will look like is in a linked list the three since it's the ending it's now going to point to none and this is also going to point to none okay and now when you move the pointers they're both going to have be at none and in that case since both of them do not have a value we're going to stop our iterations now one thing you do want to notice is they could be of different lengths so in that case what we're going to do let's say there's an extra value over here then we're only going to move the pointer for whichever has a value existing and for the other value we're just going to assume a value of zero okay so this over here works out pretty well but we also want to look at one more condition where we might have a small problem or we just need to account for it right so let's say we're doing four so this is the linked list right so four is actually a node and we also have the second list is the node six that's it four plus six pretty simple right so when you add it you get a value of ten but how exactly do you account for this in our question or the way we're solving it uh so it's pretty simple but let me just show you where we actually end up lacking so we have the two pointers the same place and the carry-on just starts off place and the carry-on just starts off place and the carry-on just starts off with the value of zero right in the very beginning now in this case you have four and six and now when you add them up you get a value of ten so in that case you just take the units of whatever value you have at the units place which is zero oh sorry okay so which is zero and that is going to be part of our linked list now in this case uh one is now going to be the carry on so let's write it on so the carry-on is so let's write it on so the carry-on is so let's write it on so the carry-on is now one okay so now in this case what's going to end up happening is we're going to move our pointer so remember four points to none and simultaneously six is also going to point to none now in this case like i showed you earlier once both of them reach a value which does not exist so in other words when both of our pointers reach the very ending we're going to stop our iterations we don't really need to do anything else and that's what happens over here we're stopping and this ends up becoming our answer which is wrong the answer should actually be 10 but this over here is just the value zero so what exactly do we have to consider so the consideration that we need to make at this point is once we reach none for both the numbers so this number and this number when we reach the ending for both of them and even at the ending if there is some value at our carry-on right like we have in at our carry-on right like we have in at our carry-on right like we have in this case then that means that has to be added so in simple words we have six and four and all we're doing is we're only accounting for how many places there are so in this case we're only going to be accounting for one place because six has one place and four has one place so we only account for the zero but we're not accounting for the one and ten right so we're not accounting for the full value which is ten so the 10 over here is an extra space that we need to account for and to do that what we're going to do is if there's a carry-on over here if there's a carry-on over here if there's a carry-on over here we're directly going to add that as a new node so to see how that looks like we had the value of zero and to this its next value is now going to be whatever is at our carry on which is one and this right here gives us a value of 10 since it's in reverse order and that's the correct answer all right so for looking at the code one thing that we're going to have over here is going to be a dummy head so the dummy head you can think of it as just as a space holder right and i'll show you how this is going to work like it's pretty simple so in this case uh we have so we're creating a new node with the value of zero but at the very beginning we don't know what that value is going to be right so or in this case right we're creating a new node with the value of seven but at the very beginning we don't know what that value is going to be so to kind of account for that we're going to have a dummy node okay i'll just call it d and this dummy node is nothing else but a placeholder we're going to define it at the very beginning and all it does is just there so that we can attach other values to it so in this case for example what we would do is to our dummy value we're going to start off at there for the sum and the zero which we get here is going to be pointing so the dummy node is going to point to the zero and the same thing goes over here so the dummy node is going to be pointing to the seven for this uh when we are doing these two over there right so the whole purpose of this is just as a placeholder and at the very ending what we're going to end up returning is whatever is to the next of the dummy node a dummy node so in this case that would be the number zero and in this case it would be the number seven and whatever is after that okay so it's a pretty simple concept to understand but yeah that's what we're using and you could give it a value of zero you could give it a value of none or whatever okay and now we're gonna have our carry and the carry like i said is gonna start off with the value of zero now we're gonna have a pointer now the pointer over here is going to be for the sum list node okay so let's just call it current and where is it going to start off from so current it's going to start off from our dummy head over here so that's exactly where it's going to be so current is going to be equal to our dummy head and now you might be asking what about the pointers for the first number the second number so for that we're just going to directly use these values over here so l1 is going to be pointer the pointer for the first linked list and l2 is going to be the pointer for the second liquid now we're going to go inside of a while loop and in our while loop we're going to keep going as long as l1 or l2 has a value right so as long as either of them has a value we're going to keep going and while okay you want to notice that we're doing or right so at one point one of them could not have a value so we do need to account for that so because we're accounting for the fact that something could not have a value at one point we need to check if l1 has some sort of value at that point so if l1 has a value then in that case we're going to have a new variable called l1 underscore val and this is going to be equal to the value in l1 and uh if you're confused about where i'm getting dot valve from over here we have a class which is predefined for us sorry um okay so this class is predefined for us and it has the attributes value which equals this value and next which equals to whatever it's pointing to okay so that's exactly where i'm getting these um dark vowel and dot next from okay so now l1 underscore vowel is going to hold that value and if this is not the case that means that l1 does not have a value and in that case l1 underscore val which is right over here is going to be given a value of zero and the reason for that is so if this is not the case we would assume that there is some sort of value in l2 so in this case when you end up doing l2 plus l1 all you're doing is l2 plus 0 so it just has the value of l2 so that's all we're doing over here now again all we're going to do right now is we're going to copy this and do the exact same thing for l2 over here okay so we're going to check if l2 exists then we're going to check uh then we're going to have a variable called l2 value and that has to be equal to l2 dot vowel else l2 underscore value is going to be equal to zero okay so that's going to be it should be pretty simple okay so now over here we're going to have our sum variable so let's just call it sum underscore and that is going to be equal to our l1 value so l1 underscore value plus the l2 value plus the carry-on right and again in the plus the carry-on right and again in the plus the carry-on right and again in the very beginning the carry has a value of 0 and that makes sense because in the units place you cannot have a carry which is not equal to zero so that should be it for this over here and now once we're over here uh we need to form our linked list so to do that we're gonna do current dot next and current.next over here next and current.next over here next and current.next over here is going to be equal to whatever is at the units place of this value and to do that actually one more thing we want to do is we want to make it a object of our list node class so to do that we're going to do list node and what exactly do we need to give it the value in this case the value is going to be equal to some underscore mod 10 okay so whatever is just at the units place so that's going to be it for that and now we need to do two things so one of them is to update our current pointer and all we're doing is current is now going to be equal to current.next be equal to current.next be equal to current.next since we're going to move it to the right by one space and now the other thing we need to do is update our carry now the carry in this case is going to be equal to our sum divided by 10. now one thing you want to notice is this over here is going to give us a floating point value so just to kind of um so to fix that problem we're going to be doing integer division so pretty simple so the same way how we updated our current pointer we're also going to be updating the pointers inside of the list node 1 and list node 2. so to do that with what we're going to do is we're first going to check whether we are already at the ending so if we're at the ending we're not going to do anything else so to do that we're gonna do if l1 so that means that if l1 has some sort of value and it means that we're not at the ending yet and in that case we're going to move it to the right so l1 is equal to l1 dot next now simultaneously we're going to do if l2 and we're do we're going to be doing the same thing so l2 is equal to l2 dot next and that should be it for our while loop and at the very ending there was one other condition that i showed you about and we need to account for that right now and that simple condition is if we still have a value in our carry so in this case if our carry has some sort of value what we're going to do is we're first going to convert it into list node object so list node and it's going to have a value of the carry itself and this over here is going to be current.next so current.next current.next so current.next current.next so current.next is going to be pointing to this value over here and that should be it so at the very ending we just need to return a value and what we're going to end up returning going to be dummy head dot next okay and that's going to end up returning the actual head that we have and if you submit this should get accepted okay so as you can see our submission did get accepted so finally thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe thank you
|
Add Two Numbers
|
add-two-numbers
|
You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
**Example 1:**
**Input:** l1 = \[2,4,3\], l2 = \[5,6,4\]
**Output:** \[7,0,8\]
**Explanation:** 342 + 465 = 807.
**Example 2:**
**Input:** l1 = \[0\], l2 = \[0\]
**Output:** \[0\]
**Example 3:**
**Input:** l1 = \[9,9,9,9,9,9,9\], l2 = \[9,9,9,9\]
**Output:** \[8,9,9,9,0,0,0,1\]
**Constraints:**
* The number of nodes in each linked list is in the range `[1, 100]`.
* `0 <= Node.val <= 9`
* It is guaranteed that the list represents a number that does not have leading zeros.
| null |
Linked List,Math,Recursion
|
Medium
|
43,67,371,415,445,1031,1774
|
1,047 |
hey everybody this is larry this is june 28th of the june the code daddy challenge only a couple more days to go so give yourself a pat in the back hit the like button and hit the subscribe button join me on discord let me know what you think about this problem and if you somehow just stumbled in um i'm gonna also do the july challenge as usual uh i think i have a 400 something days going i haven't missed one yet since april of last year you do the math i think it's for something but um so yeah so i'm gonna keep that going anyway uh today's problem is gonna be remove all adjacent duplicates in string uh i usually solve these live so if it's a little bit slow and i ramble on a little bit eh you know fast forward or whatever you need to do okay so this problem is you're given s lowercase english letters we're moving to adjacent we repeatedly move we until we no longer can so we just compress oh okay so you don't you remove both of them not just one of them and you kind of keep doing it so this one screams stack to me and i think if you have because you can think about it and i don't know if this is the clean way to think about it but the way i think about it is that um you know sometimes you have to think about how to process them you know you try to figure it out in linear time then if you try to figure out a linear time you can only go left to right or right to left and then you just try to figure out what can you do when you go left to right or right to left but you know you can just reverse it and not if the problem calls for it in this case as you add one character at a time you can remove a duplicate by comparing the last character with the or the current character of the last character and because of that um you can kind of keep on redoing that and then removing it so that of course you can actually emulate that with a string but of course that also has a natural translation to a stack and that's basically what we're going to do here um yeah basically every time we add a character we remove the previous one and in this one because yeah i mean i didn't even take a look at n yet like i guess if n was small enough you could do something n squared but in this case given that n is equal to 10 to the fifth it is you know and our algorithm is of n so i don't have to worry about running time for the most part um because it's going to be fast enough you may ask yourself also while they're getting this question like is there an n log n solution and when i see a problem like this i don't really feel like there's a login answer because you're not looking previous or you're looking only on immediate neighbors right so there's no like real lookups in either direction as you kind of go further away so all sorting for that matter so for me that did not need to be um so i didn't so i don't think there'll be an again i'm just going over my thought process and that's why when i first saw it i'm like oh this is just a stack um yeah and the finance is unique i mean you i guess that's true so yeah so let's get started so let's have a stack and then now just for character and s we there are a couple of ways to do it i mean you can just compare it to the top directly you can add it and then compare the last two which is what i'm going to do i suppose and stack my one as you go to stack -2 then stack that -2 then stack that -2 then stack that pop stack dot pop you just removes the duplicate and then at the very end stack will you know i mean i do a little bit i wouldn't say cheating but just that stack will contain in order uh the string that we need so we go from left to right on the stack which is a little bit obviously not a not an inherent thing in a stack but i guess the more kind of knowledgeable thing to do would be to pop everything off the stack and then reverse it but this should be good let's uh let's put in more test cases first before you know maybe test some edge cases i think this one is good at compressing them out okay there was not a right test case wasn't sure also things may get weird so all right cool all right let's give it a submit yeah it looks good uh like i said because it's linear time and linear space i don't really worry about complexity um i think that's pretty much it um yeah i think um i think if you so there are a couple of things one is that if you really so if you have to use extra space and you're not changing the in the input then this is the best you can get i think you can actually do this in place with a two-pointer type thing in place with a two-pointer type thing in place with a two-pointer type thing um you know with a pointer as an implicit stack on digital input string of course this actually doesn't work in python but in certain languages you can do that and then you chop it off or something like that like certainly in c maybe c plus type thing maybe not c plus string but maybe you know because then you could just denote the last thing is zero but i guess in theory there could be all one in place algorithms if your language supports um characters strings or character arrays or strings in a funky way if you don't know what that means then it doesn't really matter to be honest um but those of you who are using a language that support that then you can get it you know one extra space if you will uh using basically the same idea but using point uh like the two finger two point diagram not like pointless pointers i mean a little bit of that as well um and the thing that is left is that uh oh yeah and i would normally also say that in place algorithms are terrible because you change the input and usually people don't want you to change the input why are you changing my input leave my input alone but in this case with the function name called remove duplicates i could kind of see that see an argument for doing in place because you're trying to act on an object not just get an answer as a result of an object right so i could see that so i'm a fan of that but yeah that's what i have for this one i think uh easy monday maybe uh hope y'all have a great week happy monday and you know let's finish up june and i will see you later stay good stay cool and to good mental health bye
|
Remove All Adjacent Duplicates In String
|
maximize-sum-of-array-after-k-negations
|
You are given a string `s` consisting of lowercase English letters. A **duplicate removal** consists of choosing two **adjacent** and **equal** letters and removing them.
We repeatedly make **duplicate removals** on `s` until we no longer can.
Return _the final string after all such duplicate removals have been made_. It can be proven that the answer is **unique**.
**Example 1:**
**Input:** s = "abbaca "
**Output:** "ca "
**Explanation:**
For example, in "abbaca " we could remove "bb " since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca ", of which only "aa " is possible, so the final string is "ca ".
**Example 2:**
**Input:** s = "azxxzy "
**Output:** "ay "
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of lowercase English letters.
| null |
Array,Greedy,Sorting
|
Easy
|
2204
|
916 |
hey everybody this is larry this is day 25 of the lead code daily challenge in march uh hit the like button the subscribe button join me on discord there's a lot of cooking and loading and stuff like that um yeah i couldn't find my glasses if you were watching yesterday i don't know where my glasses are so uh yeah so i'm just gonna continue doing that but yeah so i'm watching this live oh watching you're watching this live maybe now i'm recording this live so it's a little bit slow fast forward and all that stuff today's problem is word subset given a and b are words okay oh maybe i'll read it b is a subset of the word a if every letter in b is in a okay so yeah okay um okay and doesn't have to be in the right order though in this case does that be in the right order no it doesn't have to be in the same order if for every alien would as you know so for universal even word a from a is universal for every b and b is a subset of a return a list of all universal words in a okay let me read this again in english my reading is really bad today sorry okay so for every b is a subset of every a okay um let's see let's look at the constraints i mean to be honest this is a fake constraint um i mean it's not fake but you can do it you can there's a easy compression to 26 characters and then after that you could do whatever you like probably linear um yeah so i'm just trying to think right now whether there's a clever way to do this and i think there is right um because so okay so tonight so there are a couple ways to do it um i'm gonna go over really quickly so listen carefully because i'm not gonna actually type it um but you can slow it down or rewind if you need to but yeah but the so the naive solution is just you know a times b which is too slow um you know that's not going to cut it uh given that they're ten thousand and each word only has ten characters or something like that um yeah and then the question is okay can we compress b right well for you know for each b we can go over uh an a and yeah and then the first thing you do is just using um uh using a dictionary right um or a counter a frequency map which maps you know that's the first thing you process everyone and then that compress 10 to 26 i guess it's not that much slower faster but the key thing to note is that you can intersect or to be in a way um and the way that you intersect it is um uh how do i say this like taking so ticking um and you can kind of reason this out a little bit uh you can take your time to reason it out but the idea i would say um and these are i would also just be clear these are observations that i'm making live so and i probably would have made it already or i already had the ideas as i'm reading this problem and it is not prepared i didn't read this ahead of time so at this point i've you know people sometimes ask me how many problems i've solved and i probably am close to five or six thousand problems in my life uh maybe more maybe less i don't know i don't i mean at a certain point how much can you count right um so a lot of things are similar a lot of things are familiar so then you know these things right but yeah but the thing to ask yourself is okay can we combine these words together in b so that we can do you know uh each word in a and a lookup time because if we could get this done in a constant e time then you know that's gonna be fast enough because then it's just linear in a right um so yeah so then the question is okay well we know that an obvious thing to do for each word in b is to compress it to a frequency map and then the question is well can we combine each word in a good way right and actually i think this one is a good uh one trick to illustrate it um because then okay what happens when the words or when they're characters that are overlapping right well you take the max of them because here you only need one o for two of the b two of the words um we're here you need two o's because there's no one here but let's say this word is yio um you still only need two rows so then the i the thing to do here is um for each um yeah for each word in b we take the maximum of the frequency count and then from that we look at each word in a and whether those frequency count matches um and because you can do that in linear time so linear means a couple of things so i mean everything is going to be linear but it also helps to be more precise because uh there's the number of characters there's number of words and then the number of characters total number of characters which is word times characters roughly but they're not they don't have to have the same length so it's not precisely what times character but it's just a sum of the characters right um but yeah but i believe i have enough to go on so let's play around with it i'm going to use f for frequency let's put let's use counter though um now count is just a shorthand i get some questions recently about whether you should use counter in an interview i would actually say no i mean like if you're on an interview just use something that you can explain something that people know something i encounter and on an interval you will use the hash table and it's you know uh it's pretty straightforward it's just you know forget you do like dot get um you know key and then default value or something like that and then that's good enough for most people um but you know the reason i use counter is just uh it has a default value of zero because there's a counter uh for any key and i'm just a little bit lazy to be frank um yeah so actually maybe let's do it let's call this uh b intersect right this is in the section of all the b's and i like the other and then yeah for word and b we can calculate the map of um i think this works i always forget whether that automatically gets i guess it from each one character or not so i always have to check because i don't know if it um i don't well okay this is a bad example actually because they only have one letter uh there's two rows in this example no okay um i guess this is also a bad example because i always forget well i guess actually no that works because i just worry that it takes a word at a time so it's a little bit inconsistent maybe it's consistent because it's one word versus a list of words anyway i'm bad at it that's why i do it this way but uh yeah and actually i don't mean set of course i mean as that counter and this is the frequency table right i actually wonder if um i wonder if there's an operation that does this like what is beta oops what does this do but i would also recommend not doing something like that but i'm just also curious about learning myself so ignore me for a second and fast forward for a little bit uh okay so i guess the intersect no we didn't wonder in this section anyway i was thinking of something else like not the union either like so i guess you just have to write some custom logic because basically the idea is that okay for hmm what is the cleanest way to do this um yeah i guess it doesn't matter uh maybe we could do something like four character in f dot keys um b intersection of c is equal to max of b intersection c or f sub c right we don't have to update f so and things that are already in b that are not already in c then they don't get updated so that's basically the idea and there you go you have the intersection of order uh frequency map of the order tables and we could kind of just print it out real quick to show you this one i know about but i just want to print it out just to be like okay for example now there's five rows one a one e and you know there's two rows on here right um i might have to change it back just so that i know what the right answer is um but anyway and then now we can do word by word right um and then we have answer is equal to an arraylist and then we can do something like f is equal to collections.counter is equal to collections.counter is equal to collections.counter of um word and then now we can do the now we want the intersection i think um and then the question is which so this is the intersection syntax but you can also write it out uh more um more directly right or like you know you could have just four loops to kind of calculate this i would recommend it to especially on an interview uh because right now i'm just showing off a little bit python syntax and i would probably not recommend that uh but yeah if this is equal to uh b intersection yeah um because what does this mean right that means that for everything in b in this section f is a superset if there's something that's in b so you know the intersection of f and b in the section um if something's that's in b and not in f um well then you're missing and then this will be force right so that's basically the logic here um i for bitwise operators i always forget the language and the order of operation even though this is technically you know a little bit different so i just want to uh so i always do parents um anyway uh because i don't remember it then answer is append word and then we can return answer let's give it some running code okay that is the expected answer because i added way too many things uh this is the you know montage version of the video i hope that one day they oops they bring the one button click thing to uh to um to the daily contest or dirty daily whatever um also why i'm typing while i'm doing this i think i started last year in april because that's when the lead code daily thing started so i'm almost coming up on one year of lead code you know thing i'll probably make a special thank you for it or not a special thank you just like a post about it uh definitely well thanks for all your support throughout the year um it's uh you know started as a pandemic hobby and now look at us now hopefully trying to get our pandemic soon um yeah okay let's see is that good that looks good so let's give it a submit cool um and if you really want you can actually this could be a one-liner this actually this could be a one-liner this actually this could be a one-liner this could maybe a one-liner could maybe a one-liner could maybe a one-liner um so yeah you can definitely be really clever be one of those like cool looking kits with uh the really short code do i have no interest as long as we it's really preferred code is a little bit readable um but yeah um so what is the cost here well for each you know for you this counter thing um yeah so this con this is linear in the size of the word um so that means that every character and every word will get looked at once by this collective thing you can think about this as a for loop uh through a hash table and just incrementing it right so that's basically the idea here just to explain a little bit uh you have this then you know for c and word um f of c and grand one of course you have to do an extra if statement of zero and something like that but that's basically what this is the shorthand for um and it comes in handy for some competitive stuff um but you do pay a little bit of a performance uh and then here um you know this is only gonna be at most 26 characters though also um i mean it's 26 in that it can only have lowercase letters or 26 letters but of course the length of b is only up to 10 so this is even 10 right so this means that this is linear as well in size of the total number of characters in b um and this is all of one roughly i mean this can actually and also to be honest um this could be an array of 26 characters i use counter because i'm lazy um and this as well it could be in the way of 26 characters um so this is you know you can say you can make some judgment about hash tables and or one lookups but you can actually replace this with a 26 character away so this is all one right um so that means that for each character in b we do over one so this is going to be length uh over length of b right um and then in a similar way this is linear the size of all the characters in word um this is the only one that may be a little bit confusing to read but as i said you can unroll it to a set intersection or you know frequency table in the section but notice that f of course contains at most uh 10 characters and b in this section also contains at most 10 characters so this is going to only do like if you want to unroll it to a manual for loop it's going to only have 10 operations so that's linear um one for each character that's in word at most and yeah and then there's also a set comparison which is also linear um in the size of the word so this is also in total of length of a so that means that because you have these two in series um this entire thing is going to be o of uh land of a plus of land of b and this is not just um i mean this may be a little confusing because i it is a little bit confusing for me to write this way this is not just ten thousand this is the number of characters um that means that each character is processed um over one times um in both a and b so this is linear in the size of the input um and in terms of space well and we actually kind of use constant space or of alpha space depending on how you want to define the size of the alphabet because as we said this can be a 26 character thing but that's also the max right you cannot have more than 26 items and be in the section or this is 10 even um but you know which is less than 26 as you know so that means that we actually use constant space or like i said alpha space where alpha is the size of the alphabet because if you're using a non uh non english or whatever alphabet that's more than or less than 26 characters then in theory um it could be more but that's still all of alpha um you know uh in this case it's bounded by the number of characters that's why the alpha doesn't necessarily come in but you can also maybe make an argument that is or alpha or min of alpha or characters but in this case it's always going to be the characters because it's at most 10. um so yeah so linear time constant space uh let me know what you think um i think that's all i have uh hit the like button it's a subscriber and join me on discord and you know you have a good day you have a great night have a good rest of the week have a good weekend yeah stay good stay healthy stay well you know to good mental health and i will see you next time bye
|
Word Subsets
|
decoded-string-at-index
|
You are given two string arrays `words1` and `words2`.
A string `b` is a **subset** of string `a` if every letter in `b` occurs in `a` including multiplicity.
* For example, `"wrr "` is a subset of `"warrior "` but is not a subset of `"world "`.
A string `a` from `words1` is **universal** if for every string `b` in `words2`, `b` is a subset of `a`.
Return an array of all the **universal** strings in `words1`. You may return the answer in **any order**.
**Example 1:**
**Input:** words1 = \[ "amazon ", "apple ", "facebook ", "google ", "leetcode "\], words2 = \[ "e ", "o "\]
**Output:** \[ "facebook ", "google ", "leetcode "\]
**Example 2:**
**Input:** words1 = \[ "amazon ", "apple ", "facebook ", "google ", "leetcode "\], words2 = \[ "l ", "e "\]
**Output:** \[ "apple ", "google ", "leetcode "\]
**Constraints:**
* `1 <= words1.length, words2.length <= 104`
* `1 <= words1[i].length, words2[i].length <= 10`
* `words1[i]` and `words2[i]` consist only of lowercase English letters.
* All the strings of `words1` are **unique**.
| null |
String,Stack
|
Medium
| null |
1,690 |
hello everyone welcome to chorus camp we are at 11th day of june leeco challenge and the problem we are going to cover in this video is stone game 7. the problem statement says alice and bob take turns playing the stone game and i'll start first as usual as per any other stone game problems so here they said there are young stones arranged in a row and that is given as an integer array and on each player's turn they can remove either the leftmost stone or the rightmost stone and we calculate the score of each player by equal to the sum of the remaining stones in the row and as usual bob is going to lose the game so he decided to minimize the score's difference but alice goal is to maximize the score difference so finally if they both play optimally we have to return the score difference between alice and bob so let's understand this with an example so here is a given example in the problem statement and as for the problem statement alice is going to start the game and he can take either the leftmost or the rightmost stone from the row so now he is going to take the rightmost stone which is of value too because if he takes the minimum value then his score is gonna get maximum so now alice score is some of the rest of the stones so that is gonna become 13 and now it's bob's turn and bob is planning to take the left most stone which is a value 5 so the sum is 3 plus 1 plus 4 which is 8 and now again the alice turn and now he's gonna remove the stone three so that the sum becomes five and out of one and four bob is planning to remove one so that the score is four so overall the score of alice is going to be 18 and score bob is going to be 12 and the difference is actually going to be 6 that is what we are going to return so how are we going to approach this so here in the problem statement they have given two hints the first hint says it is gonna be small enough for an n square solution also they suggested us to try a dynamic programming so we are going to go for a dp solution so let us get into the concept so we all know dynamic programming is nothing but solving each sub problem and then getting a bigger solution from those results so we are going to start from a very base case for example consider there is only one stone a and alice is going to pick the stone a in that case after he picks the stone there is nothing left in the row so his score is anywhere going to be zero so next consider there are two stones a and b if alice is planning to pick the stone which one would he pick so if a is having the higher value and b is having the lesser value then he would pick the lesser value one because he want to maximize his score so if he pick the lesser value one then he will get the higher value stone as his score so obviously he's going to pick the lesser value 1 then his score or the overall score of this game is going to be max of a comma b because he would be picking the lesser one and the score will become the maximum one so if either b is maximum he'll pick a and b is the score if a is maximum he'll pick b and a is the score so hope you're understanding this so next moving on to three stones if there are three stones and alice is planning to pick one so in that case he has two options to pick either he can pick a or c if suppose we fix that he is picking a in that case his score will actually become b plus c and now we have only b and c left so in b and c bob has to pick one so out of b and c he wants to maximize his score so in that case he would be picking the minimum one out of b and c and his score will be the maximum value so out of b and c whichever is the max would be the score of bob so b plus c is the score of alice and it will be subtracted from bob's score so bob's score would be max of b and c so this is coming from the previous sub problems solution that is a and b can be solved as max of a and b same way after picking a only b and c left so b and c can be solved as max of b and c so overall it is nothing but alice score that is sum of whatever he picked minus max of the left over stones but this is not end with here this has another option that is what if alice picks c in that case the score is going to become a plus b which is nothing but the leftover stone after picking c so this is the score of alice and now bob has options to pick either a or b and get his score so in that case bob would opt to pick the lesser stone value so that his score get maximized so again it is coming like max of a comma b would be the score of bob so overall it is going to give us alice score minus bob score so these two can be the possible solution for a b and c and we have to either pick one so which one would we pick we want to return the maximum score difference so out of these two options we would be picking whichever is the max so overall to solve abc we would be pick max of b plus c minus max of b comma c or a plus b minus max of a comma b so hope you are understanding this and this problem is going to go like this so again the last one is for abcd it is nothing but the sum of rest of the elements if he pick a minus max of b c d comma a plus b plus c it means if he picked d it is a plus b plus c that is sum of rest of the stones minus max of abc and it goes on like this is going to be the solution for each sub problem and we are going to derive our dp pattern based on this so simply we are going to check every time this pattern for every i that is nothing but we are going to have a dp array which is going to store the solution for each sub problem that is dpf 0 is gonna have for only one stone or the first stone in the given array and so on and the n will have the dp of pleating all possible stones given the input so finally we are going to written what is there in this cell that nothing but dp of n minus 1 so now to do this we are going to get the help of a prefix sum array as we all know prefix sum is nothing but calculating the sum so far to that point in an array so we are going to first calculate the prefix sum of all the elements in given in the stone array and we are going to calculate these sums by using that prefix sum which is nothing but if there are four stones then to calculate the sum we are going to cut off the leftmost element and add the rest which is nothing but the sum of d minus sum of a same way to calculate abc we are going to take the sum till c if there is a some calculator till d we are going to ignore the last cell whatever till c we are going to take that from our prefix sum to calculate the max of bcd and max of abc and stuff this is the value actually we are going to store in our dp array so for dp of 0 it is going to be 0 because that is the base case for big dp of a comma b max of a comma b will be stored and this we are going to use in the next sub problem same way once this is this sub problem is solved its solution is going to be used for the next the problem and so on so hope you're understanding the solution this is obviously going to work in big o of n square time as given the hint so let's go to the code now so yes let me declare n as the size of our stones array as we are going to use this variable often and my dp so i'm gonna have two for loops i and j and i is gonna point at the end of the given array and j is going to point at the beginning of the given array so that we will negotiate or cut down the end and the starting by using these variables and we are going to check if our i is not equal to j which means we are not pointing at the same stone then in that case we are going to calculate our prefix sum that is sum so far and as i said we are going to calculate our tp equal to max of a minus temp and b minus tp of j so here a is nothing but we are going to pre-calculate the value pre-calculate the value pre-calculate the value which is sum minus stones of j which is nothing but the first set of values the first prefix sum and also b is nothing but sum minus stones of i that is cutting the first and last value so a is some cutting the end value and b is some cutting the star starting value so here it is a and b minus i said dp of j is going to have the previous solution of our sub problem so once we update its value it is going to change for the second sub problem so we are going to have a temporary variable to store the previous value so that we can use it here for the calculation so i am going to declare every time a temp variable and because it has to consider the i as well so every time we are going to calculate a new dp we are going to update our temp value so that we will use this in our next iteration so yes once iteration is done our dp of n minus 1 is gonna have the result so yes this is it let's run and try okay so yes let's submit yes the solution is accepted and runs in 28 millisecond which is 92 percent faster than other solutions 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
|
Stone Game VII
|
maximum-length-of-subarray-with-positive-product
|
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, they can **remove** either the leftmost stone or the rightmost stone from the row and receive points equal to the **sum** of the remaining stones' values in the row. The winner is the one with the higher score when there are no stones left to remove.
Bob found that he will always lose this game (poor Bob, he always loses), so he decided to **minimize the score's difference**. Alice's goal is to **maximize the difference** in the score.
Given an array of integers `stones` where `stones[i]` represents the value of the `ith` stone **from the left**, return _the **difference** in Alice and Bob's score if they both play **optimally**._
**Example 1:**
**Input:** stones = \[5,3,1,4,2\]
**Output:** 6
**Explanation:**
- Alice removes 2 and gets 5 + 3 + 1 + 4 = 13 points. Alice = 13, Bob = 0, stones = \[5,3,1,4\].
- Bob removes 5 and gets 3 + 1 + 4 = 8 points. Alice = 13, Bob = 8, stones = \[3,1,4\].
- Alice removes 3 and gets 1 + 4 = 5 points. Alice = 18, Bob = 8, stones = \[1,4\].
- Bob removes 1 and gets 4 points. Alice = 18, Bob = 12, stones = \[4\].
- Alice removes 4 and gets 0 points. Alice = 18, Bob = 12, stones = \[\].
The score difference is 18 - 12 = 6.
**Example 2:**
**Input:** stones = \[7,90,5,1,100,10,10,2\]
**Output:** 122
**Constraints:**
* `n == stones.length`
* `2 <= n <= 1000`
* `1 <= stones[i] <= 1000`
|
Split the whole array into subarrays by zeroes since a subarray with positive product cannot contain any zero. If the subarray has even number of negative numbers, the whole subarray has positive product. Otherwise, we have two choices, either - remove the prefix till the first negative element in this subarray, or remove the suffix starting from the last negative element in this subarray.
|
Array,Dynamic Programming,Greedy
|
Medium
| null |
1,648 |
hi everyone it's albert today let's solve the leak code contact question cell diminishing value color both the question statement so we have an inventory of different color balls and there's a customer that wants to make orders of balls of any color and when selling balls to the customer the value of the ball is determined as the number of balls of that color that we currently have in the inventory so let's say we initially have six yellow balls in the inventory and the customer will pay six for the first yellow bowl and after this transaction it will be five yellables left so the next time when we sell the yellow ball it will be a value at five and we are given an integer array inventory where each element in inventory represents the number of balls of the eighth color that we initially own and there's also another input orders which is the total number of balls that the customer wants and we are allowed to sell the balls in any order and we have to return the maximum total value we can earn after selling orders of color balls and the answer might go large so we have to return the result modulo 10 to the power of 9. so for this example we have two different colors of both the first color have two bowls and the second colors have five and the customer wants to buy four balls in total and the best way to sell the balls is to sell the first color one time and the second color three times so the total value will be two plus five plus four plus three which is 14. the intuition to solve this question the key algorithm is like a greedy approach we want to sell the balls with the most amount first in order to gain the highest value and the key equation to calculate the total value is the arithmetic series sum which is the sum of n plus minus 1 plus all the way up to n minus d is n plus minus d times d plus 1 divided by 2. and later we will see how this equation come into play with the algorithm now let's look at the code okay and first is to reverse sort the inventory array because we want to start with the boss with the biggest amount and we will add a zero at the end of the inventory array as the terminating condition a result variable is what we will return at the end and k is the number of color of balls which has the biggest amount and we will see how k works in the next section and going through the array if the current color has more balls than the next color then first we will check if we have enough orders to make this many transactions if we do then define div as inventory i minus 1 and the total value we can make from this transaction is the arithmetic series sum and we will subtract orders by k times diff and if we don't have enough orders then we will first calculate the quotient and remainder of orders divided by k and then we will add the arithmetic sum to result and then the remainder to the result as well and finally is to return result module 10 to the power of nine and at the end of the for loop we have to increment k as well and it will be more clear to see the code in action okay and here we'll be looking at example three so first is to reverse sort the inventory array so the largest element would be at the front since we want to sell the balls with the largest amount first and result is initialized to zero and k is set to 1. and the meaning of k is in the inventory how many color of balls has the largest amount so initially we only have one color in the inventory has the largest number of balls which is 10. and first calculate the difference between the first and second element which is two and this condition holds so it means that we are able to make two transactions with the current orders and the total values of this transaction will be the arithmetic sum which is a 10 plus 9 so we will add 19 into result and k will be updated from 1 to 2 because after these transactions the first element will become eight so we will have two group of eight in the inventory and we will subtract the two transactions from orders so it will become 18. so after this transaction the inventory array will become this and the current result is 19. okay and following the same process now is to calculate the difference between the second and third element the difference is two as well but notice that now we have two colors of ball which they both had eight balls and this condition still holds it means that we are able to sell these two colors of both at the same time so the total value we can get from this transaction is k times the arithmetic sum and the result will be updated from 19 to 49 and k will become 3 and orders will become 14. so this is the inventory after the last transaction and following the same logic the difference between the third and fourth element is still two so we will add k times the arithmetic sum to result and after this transaction result will become 82 and k is now 4 and orders is 8. okay and for the last element this if condition still holds so we will sell k times the arithmetic sum and then result will be updated from 82 to 110 and now orders will become zero and if at any point in time we don't have enough orders to make the transactions then we will run this part of a code first is to calculate the quotient and remainder from orders divided by k and then update result accordingly and this will conclude the algorithm finally let's review so the core algorithm to solve this question is a greedy approach that we want to sell the balls with the most amount first and then a key equation to calculate the value we can get is the arithmetic series sum which is this equation the time complexity of this approach is log linear since we have to perform sorting at the beginning and the space complexity is constant and that will be all for today thanks for watching if you like this video please give it a like and subscribe to my channel and i will see you in the next one you
|
Sell Diminishing-Valued Colored Balls
|
minimum-insertions-to-balance-a-parentheses-string
|
You have an `inventory` of different colored balls, and there is a customer that wants `orders` balls of **any** color.
The customer weirdly values the colored balls. Each colored ball's value is the number of balls **of that color** you currently have in your `inventory`. For example, if you own `6` yellow balls, the customer would pay `6` for the first yellow ball. After the transaction, there are only `5` yellow balls left, so the next yellow ball is then valued at `5` (i.e., the value of the balls decreases as you sell more to the customer).
You are given an integer array, `inventory`, where `inventory[i]` represents the number of balls of the `ith` color that you initially own. You are also given an integer `orders`, which represents the total number of balls that the customer wants. You can sell the balls **in any order**.
Return _the **maximum** total value that you can attain after selling_ `orders` _colored balls_. As the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** inventory = \[2,5\], orders = 4
**Output:** 14
**Explanation:** Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3).
The maximum total value is 2 + 5 + 4 + 3 = 14.
**Example 2:**
**Input:** inventory = \[3,5\], orders = 6
**Output:** 19
**Explanation:** Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2).
The maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19.
**Constraints:**
* `1 <= inventory.length <= 105`
* `1 <= inventory[i] <= 109`
* `1 <= orders <= min(sum(inventory[i]), 109)`
|
Use a stack to keep opening brackets. If you face single closing ')' add 1 to the answer and consider it as '))'. If you have '))' with empty stack, add 1 to the answer, If after finishing you have x opening remaining in the stack, add 2x to the answer.
|
String,Stack,Greedy
|
Medium
|
2095
|
377 |
hey guys it's off by one here and today we're going to be solving combination sum 4. in this problem we're given an array of distinct integers meaning that we don't have any duplicates and the array is called nums and they give us a Target integer called Target and they wanted to return the number of possible combinations that add up to Target so as we can see here we're given an example where the nums are one two and three and our Target is four and they tell us that there's seven different combinations that can lead to this we can also see that we can reuse the same combination as long as it's in a different sequence so how can we break up this problem into smaller sub problems than we can solve so let's see if our Target is four let's say we use our num of one so we subtract one and now we have three so now the real problem is going to be how many distinct ways can we make three well we can have one and two and one right two and one and then a three and that's four different combinations okay well what if we subtract one from three this time how many combinations make up two well we know that one and one make up two and just the number two makes up two so that's two distinct combinations so now we go to 2 minus one we get one and there's only one way to make one and that's just with that and if we add up all of these we get seven different combinations to make up four so let me show you what I mean using a better drawing so I've ever written a problem here and we have the same numbers and the same Target so what we're going to do is start with our Target and then make some branches and on this Branch we're going to subtract one this one we're going to subtract two and this one we're going to subtract 3. so that way we can see what leads us to is a value of zero because if you get a value of zero then that means that's a valid combination and let me just show you what I mean so here we have four minus one that is three here we have four minus two that is two and four minus three is one and now we do the same thing we Branch off from each one of these and we do the same thing subtract one two and three well we can see here that three minus three is zero so that's a valid answer and three minus two would be one three minus one would be two and now we do it again so one two and three so this is invalid because two minus three would be negative so that's not a valid way to get to four two minus two is zero so that is a valid way and then two minus one would be one and then finally we can finish off this tree here by doing it again one two and three one minus three is negative so that's not a valid way to get to four and same thing with two and then one minus one would be zero so we can see that every Branch off here we have three different ways to get to four actually I forgot to do this one here too so let's see we subtract one two and three so these two are invalid and this one is equal to zero so we have four ways to get to four and as you can see here for two we already calculated two over here and we know there's two different ways to get to that so we're just doing repeated work here but let me just go through it so it makes more sense so if we subtract one two and three this is invalid this would give us zero and this would give us a one and now we Branch off again one two and three this is invalid and this would give us zero and now we have this one again so let's just finish that off we have one two and three for our num values and these two are invalid because they give us a negative and then this would be zero so as you can see we're doing the same work over and over again and that's how we know that this is going to be a dynamic programming problem so what do I mean by that well like I said earlier we already used this too before here so we don't have to redo the work over here and to do that we can just store the result of two in an array let's call it results and whenever we have a two again we can just access result at 2 and see how many different combinations there is to get to four from there so let's just look at this two here so we can see how many different combinations we can use to get to four so as you can see if we go two one and one we end up getting to zero here so that's a valid combination and then if we go from 2 to 2 we get to zero here so there are two valid combinations to get to if we have a two so here I've Rewritten my array that we're going to use to keep track of how many different ways we can get to that number so next up we're going to solve for one so here we have a one how many distinct ways can we get to the zero well we can see there's only one way and that's by using one so we have a zero here so we can just initialize this to one okay well what about for three here well if we start at three then we know there's four distinct ways to get to the zero because we hit it four different times so we can just initialize this to four so in total we have seven zeros and we know that just from looking here so we can just initialize our result at four equal to seven and we would return this in the problem but now we need to come up with some kind of algorithm to be able to calculate this before getting to that there is one last thing we have to do and that's to initialize our base case so we would have result at zero so what do we want to set that equal to well if we think about it we should set it to one because whenever we access index 0 that means we hit the zero so we want to return a one if that ever happens so for example here if we're trying to calculate our result at 3 we can do result at 3 minus three which would be equal to result of zero and that should return one because we want to add that to the result of three so we can say result of 3 is equal to result at 3 minus three plus results at three minus two plus result at three minus one and as we can see here result at three minus three is zero results at three minus two is one and result at three minus one would be two so if we add two plus one we do get four and I know this is really messy so let me clean this up so here I've Rewritten the array and I pointed out the indexes just to make things a little clearer and I'm going to name the array results to make it easier to access in our pseudocode and also I want to point out that these indexes are the target so for example if our Target was 1 we can say there's one distinct way to get to one if our Target was two there's two distinct ways if it's three there's four distinct ways and so on so now let's get into our pseudo code so what do we want to do well we know we want to iterate through every single index in result because that's the only way to calculate the final Target so we want to find the number of distinct ways we can get to one two and three and then we can find four from that so let's just write that so for all indexes in our array but what do we want to do so let's say we start at this point here well we want to check all of these numbers as well to see if they're valid and see how many distinct ways we can make up one so we can also say for all nums okay well now what do we want to do so let's say we're checking for index one so let's just do our decision tree again so if we do one two and three we can see that two and three don't produce valid results we put X's here and this gave us a zero and the reason these weren't invalid is because 1 minus two would be negative one and one minus three would be negative two and those wouldn't be a valid index in our result array so what we can say is that if I minus our number is greater than or equal to zero then that means we have a valid number and index so now that we have that what do we want to do well we know we want to update our results at our current iteration but what do we want to update it to well again let's take a look at another example so let's say we're at 3 if we do 3 2 and 1 here we'll get 0 and here we'll get a 1 and here we'll get a 2. so we want to add the result at zero result at one end result at two so I guess we could say here we want to add our current result plus the result at I minus our number so in case it's not clear the reason we do result at I minus number is because we want to calculate results at three minus three so when we use our number three here we want to see how many distinct ways we can make zero and like we said earlier that would be one and then we want to do our result at 3 minus two so now how many distinct ways can we calculate one well if we look here we see that there are only one way to calculate one and then for result at three minus one we're trying to calculate how many distinct ways there is to get the two and we can see that is two and if we add all of these together we get four so that's going to be it for our algorithm and then at the end we can just return this last index over here since that's a Target we're actually looking for so for our time complexity we're iterating through every index in the array which is of size Target and we're also iterating through every number every time we go to one of these indexes so our time is going to be o of n for the target times m for our numbers and then for the space we're only using the result array and that's of size Target so we can just say the space is O of n now that we have that let's get into the code so I know there was a lot of explaining but the code is actually pretty simple so first we want to initialize our array and we want to initialize it with all zeros for a length of Target plus one because we want to have room for our base case and we want to initialize our base case to be equal to one and then from here we just want to iterate for I in range of one all the way to Target so we're gonna have to do plus one for that and the reason we start at one is because we already have our base case here and there's no need to go through it so for every index what we want to do is check every number and see if it's valid so for Num and nums we want to check if I minus that num is greater than or equal to zero and if it is then that means it is a valid number and that will produce a valid index and now we just want to update our result array at the current iteration to be equal to the result at I plus result at I minus our number and this can actually just be simplified to this just to make it a little neater and that's it after that we can just return the last index in our array which would be index Target and that should work so as you can see this code is pretty efficient and now I'll go through the code manually so I've written our example here we're going to be using nums and our nums are going to be one and two and our Target is going to be three so pretty similar to the example we've been doing but just a little shorter to save time so initially we want to set our result array to all zeros for a size of Target plus one and as you can see here the size of this array is four and our Target is three so that makes sense so that's checked off and then our result of zero is equal to one so I've already initialized that there so we're good there and now we just want to iterate through all indexes so we're going to start at I equals one and from there we want to check for every number in our array nums we want to check if this would be a valid index so I minus num well our current num would be one so I which is 1 currently minus 1 is equal to zero so that is valid so what do we want to do here well we want to update our result at I to be equal to the current result plus result at I minus num meaning that we want to add results at 1 minus 1 which is index 0. So currently at zero and zero plus one is one and now we check for number two well we know that one minus two is negative so we can just skip that and go to the next iteration so now we're going to be at I equals 2 and we're going to check every number in our array to see if it's valid so let's start with 1. so 2 minus 1 would be equal to 1. so that is greater than zero so we want to do is update our results at 2 to be equal to the current result plus the result that I minus num and I minus num would be 2 minus 1 because we're currently looking at our first number and that would be results of one which is equal to 1 here so we want to update this to one and now we go to the next number two so let's see two minus 2 is equal to zero so that's a valid number so now we want to update our result array to be equal to our current result plus result at I minus num which would be result of zero and as you can see result of zero is one so we want to add one plus one so that would give us two and now we can go to I equals three so now our I is equal to 3 and now we want to iterate through the nums array so for nums in Num we want to check if it's valid so let's start with the one here and let's see result of three minus one well this is positive so we're good here and now we want to update result at 3 to be equal to the current result of 3 plus result of I minus num and if we're doing one that would be a result of two so we want to add two to zero and now this is going to be 2. and now we go to our next number two so let's see three minus two is equal or greater than equal to zero so we're good here again and now we want to update our results at three to be equal to the current result that three plus resulted I minus num and result at I minus num would be result at three minus two which is result at one and we can see that is one there so we would add two plus one and that would be our new value of three and then after that we just return the result at Target so result that index three is three and that is correct there are three distinct ways to make three by using two one two and one if this video helped in any way please leave a like And subscribe thanks for watching and I'll see you in the next video
|
Combination Sum IV
|
combination-sum-iv
|
Given an array of **distinct** integers `nums` and a target integer `target`, return _the number of possible combinations that add up to_ `target`.
The test cases are generated so that the answer can fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[1,2,3\], target = 4
**Output:** 7
**Explanation:**
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
**Example 2:**
**Input:** nums = \[9\], target = 3
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 200`
* `1 <= nums[i] <= 1000`
* All the elements of `nums` are **unique**.
* `1 <= target <= 1000`
**Follow up:** What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
| null |
Array,Dynamic Programming
|
Medium
|
39
|
77 |
hello everyone welcome back here's what I'm saying and today we are going to tackle a very interesting lead code problem combination so this problem is uh all about generating combination of number so it's a great opportunity to explore some fundamental Concept in combination so the problem asks us to generate all possible combination of key numbers from a range of 1 to n so now let's break down the approach before we dive into the coding so uh for example if we have N4 and Q2 we need to choose uh sets of two numbers uh from four so total combination is 6 and we need to return all of them as in this example so and we are going to be implementing a custom generator function so generate combination to generate all possible combinations so this function will take two parameter element which represent the number to choose from and now which is the number of elements in each combination so we'll start by converting our elements to a tuple for efficient indexing and initialize an array current indices to the first num indices and we then enter a loop where in each iteration we generate a combination by picking elements from our Tuple using the indices in current indices and this combination are then yelled so let's start our coding and yeah so I will implement it and then explain everything so def generate combination LMS num element Tuple will be double element total will be Len element Tuple and if num greater than total we return and current indices will be list range of nums and while true yield yields Tuple element tapu or I in Range current indices so now that we got the generate combination function down let's move on to the next step so we need to increment the indices in current indices to generate new combinations so we start from the end of current indices and move toward the looking for an index that hasn't reached its maximum value which is a position from the end of element table so if we find such index we increment it and set or subsequent indices to be one greater than the previous index so F4 index in Reverse range num if current index not index plus total minus num we break and else so and we repeat this process until we have generated all possible combination and if we don't find any index to increment we break out of the loop and return from the function and return and current indices index plus one or J in range plus one num and current indices J minus 1 Plus 1. so yeah as mentioned before we repeat this process until we generate all possible combination and if we don't find any index to increment we just break out of the loop and return from the function and finally in the main combination method we call our core logic so generate combination with range 1 2 N plus one and key as argument and the return combination are tuples so we use a list comprehension to convert each combination into a list before returning so return list of combination 4. combination in generate combination range 1 to n plus one four key so this is our implementation so uh let's run it and see if it's working so yeah oh working perfectly and now let's take a deeper look at the logic behind this code so the key part is a condition if a current index and not index plus total num so this part and it checks if the current index has reached its maximum value index plus total minus snap so is the maximum value that the index at index can take so if the current value is equal to the maximum it means we need to move to the previous uh index and by using the condition we ensure that we always generate combination in increasing order so for example for n equals four and key equals to our function will generate 1 2 then 1 3 then 1 4 and so on so this is a standard method in combination for generating uh a combination in a combined Network mathematics so without a replication and it's quite efficient so uh this is all for this video so last part is to submit and see how our code works so I'm submitting it and let's see so our code is really random efficient so it bid 99.9 with respect to memory uh beating 99.9 with respect to memory uh beating 99.9 with respect to memory uh beating yeah this big and this peak as well and with respect to memory it looks like it'll be seven percent but if we look so most of the solutions are 80.3 memory and our solution is just 80.3 memory and our solution is just 80.3 memory and our solution is just 80.7 so it's not a big difference 80.7 so it's not a big difference 80.7 so it's not a big difference uh and yeah this is due to using uh different uh data structure and yeah all right so I hope you found this uh video helpful in understanding how to generate combination in Python and if you did please give it a thumbs up And subscribe to the channel for more coding tutorials and challenges and if you have any question or comments feel free to leave them down uh below and if you uh posting uh the solution uh will be posted in the description in other programming languages like C plus Java JavaScript and c-sharp in the JavaScript and c-sharp in the JavaScript and c-sharp in the description so as always thanks for watching keep practicing happy coding and see you next time
|
Combinations
|
combinations
|
Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers chosen from the range_ `[1, n]`.
You may return the answer in **any order**.
**Example 1:**
**Input:** n = 4, k = 2
**Output:** \[\[1,2\],\[1,3\],\[1,4\],\[2,3\],\[2,4\],\[3,4\]\]
**Explanation:** There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e., \[1,2\] and \[2,1\] are considered to be the same combination.
**Example 2:**
**Input:** n = 1, k = 1
**Output:** \[\[1\]\]
**Explanation:** There is 1 choose 1 = 1 total combination.
**Constraints:**
* `1 <= n <= 20`
* `1 <= k <= n`
| null |
Backtracking
|
Medium
|
39,46
|
1,838 |
hello hi guys good morning welcome back to the new video this video going see the problem frequency of the most frequent element and this question has been asked by Amazon Uber and D bank it's a most frequest asked question in Amazon in last six months so please make sure that if you're preparing for plac intership do this question very carefully cool let's see uh that what it say we'll go on to the very intuition very deep how to explain interview please so focus on the intution rather than just PR statement itself so it just says that again we will mark off every important word the frequency of an element is the number of times it occurs in an array so the word frequency defines is that how frequent it occurs in the array itself in an array cool now we are having an integer array called as nums and integer K we have integer array as a nums and integer K and in one operation you can choose the index of nums and increment that element by at that index by one so just randomly choose any of the existing value of nums and then increase that value return the maximum possible frequency of an element after performing the at most K operations K operation were increase an element by one so I can just add one just K times so basically in total I can increment K all the numbers in total I can increment by K so that is what it what this lines infers cool and again it just says that the maximum possible frequency of an element so basically just says that if I have an array of size of let's say element 1 2 3 4 5 so five has a frequency of one so can I make other elements as a five itself so that the five's frequency can increase right so that what we want ultimately in this question uh if we have this so we know that okay we can in total increment the numbers by five right so I can just say what if I plan to make four as everyone so that I can just plan to increase the frequency of four so right now the frequency of four is one but I plan to increase the frequency of four so I plan to make this two also of four so I'll just increment by two so I have used two of this remaining is three I plan to increment this one by four like two four so again I have to add a three so again I use the entire three I will remain zero and again I'll make a four so you know like you can see I increased the frequency of four and that became the frequency of 4 as 3 so that is ultimately what we want so now coming on back that what we wanted we want the maximum possible frequency for sure if we want the maxim possible frequency we will try to take any of the existing element say in this question I took a four what if I plan to take the existing element as two and I plan to make the others as two also so that is one thing okay I'll just plan to take any of the element from the array itself and then just plan to make everyone a same now Aran why not you plan to make everyone as three okay if I just say why not to plan make everyone as three for sure if you plan to make everyone as three you cannot make a 4 S3 you can only make a two S3 but I'll ask you're only task was to make everyone same if you plan to make everyone as 3 for sure you will make 1 S three and 2 S three right rather I would say make 1 S2 and 2 S2 so that you won't actually need to increase the existing element also here you would not have to increase two itself but if you plan to make two as three also so for sure you will have to make two as three also which will actually incur a cost for you which you don't want because you want to make as many elements as same as possible so one thing that okay we would not be making three as the element or basically we only plan to make the element in the existing array are in y not 5 which means the more element again the same concept for the two three was the more element for four three was a Les like less element so for sure we will not make more or less elements as the same frequency one we will just pick these elements from the AR itself and try to make them as same now okay this is fun thing that okay we'll just pick off the element from the and then try to make the other elements same as that of that me element now me element can be this we'll see that how we plan to make it but one thing we have to know we have got to know that we'll just choose this element itself now one thing if we are allowed to only increase not decrease so for sure if we if I plan to make everyone as five now I cannot make everyone as five I can only make the Lesser elements than five as five right so if I plan to make everyone as five so I can only plan and pick one and three I cannot touch a seven so for sure if I plan to make any element as most frequent element so I just plan to make other smaller elements than him as him so other smaller elements than five which are one and three I plan to make them as five so for sure kind of an infer of Sting we can think of that maybe we have to sort but it is not important to solve because I just I'm concerned about only the lower elements I'm not saying I need the next smaller element itself or something like that so I'm just concern okay maybe just the lower element I need maybe I can just edit on the itself I might not need sorting that is one intuition which we have got so far but if we see that we have a k limit given it is not infinite K I can just achieve or I can have I have a limit of K for sure if I have a five so if I want to make everyone as five so I just try okay let's make one other element as five next okay let's try to make other element also five so for sure if I have five I have firstly try to make a three as five rather than one as a five because to make a three as a five I need a cost of two to make a one as a five I need a cost of four it's much better to actually make one of them which means three as a five first and then whatever remaining I have I try to make a list for the value as a five itself so because I greed want maximum number of elements to become the same frequency so with this fact we know that for sure I will have to go in the order of smaller elements so for this five I just have to go for three first to make it actually equal to five and then go to one to actually make it equal to five do we get to know that we will have to do a sorting so for sure first operation which we have to do is sorting for sure now other thing is let's say okay we have to make this number as five now for sure I was going backwards and checking can I make it so what will happen if I go backwards and step like let's say I'm currently at this poter now pointer you can just have any p r l i anything you can have like I just named it as R I'm just okay I'm just currently at this index it's just a pointer and I'm trying to go backwards it is what my task says to me now let's say uh I want to go length backwards because I want the maximum number of elements of basically maximum length as to become as five so I'm just planning to go length backwards so for sure if I go length backwards then what could be my L just simply if L would have been existing there so r - L + 1 would have existing there so r - L + 1 would have existing there so r - L + 1 would have been equal to length so for sure L would actually become Rus length + 1 so I'm actually become Rus length + 1 so I'm actually become Rus length + 1 so I'm just I just got to know that okay if I am at R and I plan to go length backwards so my L will look something like this I have got my L now uh what my task is how much length I can go backwards or basically just saying okay how much I can make elements in this length as same frequency see so what I need to achieve to make everyone as five if I want to make everyone as five so five something like this will happen now I got to know that my L is here because I planned to make my length as same so I know my l is here so for sure this length is actually nothing but r - L + 1 is the length itself which I r - L + 1 is the length itself which I r - L + 1 is the length itself which I which we have already known right and we also plan to make everyone as five so for short the sum I need right now I my target my what I want is actually nums of far which is this value five into three which is the length right which is the length so I want this but it is not what you want it is what you have is this some already sum so my sum is right now 1+ 3 + 5 so this is the sum is right now 1+ 3 + 5 so this is the sum is right now 1+ 3 + 5 so this is the sum from L to R which I have so which is what I wanted okay which is what I have now again is it what I have only sufficient but there's one thing also I have I also have a k which means I can also increase that range some with some values so for sure I can just go anywhere and increase and I know greedily firstly I will just try to increase this then whatsoever remaining is this I'll increase this and then go on so forth so for sure I also know that I can add a k so this is what I want this is what I have for sure if what I want is actually lesser than equal to what I have for sure I can achieve this and make everyone as five what if I have this as more for sure I cannot achieve it so I can achieve it only when I have this condition that what I want is less than what I have for sure but you saw one thing that you want to find the sum in this range now if I ask you to find while doing a query while doing and finding the sum in this range what you will do you will use a sliding window so for sure first we get the intuition of how to use sorting now we get the intuition how to use a sliding window so for we get to know okay that we will have to apply a sliding window logic to find the sum the main Logic for sliding window is to find the sum now okay to find the sum that is done but what I wanted was this length as the maximum length so while finding or while doing a sliding window while finding the sum keep on checking this condition right here and I'll dry run like no worries I'll dry the entire thing but the logic is first important before dry right so we know how to know that it's a slight question now when we have known this fact we will actually want to maximize our length what we'll just do simply go and do a sliding window whenever we'll get the maximum length for sure we just update our maximum frequency maximum L as an answer now what we'll do is move R now sliding window again sliding window has two variations simply again remember this fact sliding window two operations make it as a template because for sure many people just get confused in sliding window always keep on moving R and always again always keep on moving r as soon as okay you have moved R you have an L now check until this condition now condition is what you have now until this condition is not satisfied how this condition will be not satisfied when this is more this condition will not be satisfied until this condition gets satisfied keep on moving l so until unless like while this is happening keep on moving your L keep on moving your l so that you will finally whensoever this condition gets satisfied or like this is wrong I'm saying while this is true while this condition is not satisfied which is when the target is more than what you have for sure this condition will not be satisfied so the this thing more will be true so while this fact is true keep on moving your L as soon as this fact which is while this condition becomes false for sure you will drop out which means now you have the correct range so you will have this correct range of lnr and then you can update your answer so again if the condition gets unsatisfied move L so for us this condition was like out condition so ultimately I'm saying while this is while this condition is true keep on moving your L that is what we want and for sure as soon as the condition gets unsatisfied your Loop will break and for sure you will have the correct lnr range to update your maximum length or the maximum frequency ultimately let's try uh it's pretty simple but yeah keep remember this fact what I told you move L and then again the St has two variations move you moved like you move R for sure r other factors in this there are two variations which means L strings right and get to a value when the condition becomes satisfied other variation is l will only come one step because we know that okay if this length for sure is four I know for sure the max like the at least length four I have and I only am concerned about the length itself I'm I know okay the value is four the length value is four and I'm concerned about the length so if I don't want to decrease the length Beyond first I'll just increase my L like increase my L just once I'll not like shrink my entire L to the very minimum I'll just only decrease my length one and I'll like next time increase my R decrease l r with this fact but what if I want to have a sum in the range then I have to shrink my entire L because I'm not concerned about the length I'm concerned about the sum so this one no worries I'll just show you in the code itself but meanwhile let's see how the siding window will actually work for sure initially you will have again I said you will move your r one step you will see R is here next time R is here R will always move one step for sure so next uh but r l will always start from zero itself so L is all starting from zero itself now for sure is what the as soon as you have as soon as you land into a loop you will increase your current R because you are at this R your initially your sum was Zero you will you landed on this R add a value of one in this R cool now you have this dust total it is what you have okay is what you have what you want this one but for the length of one so this is what you want this you want a one and also you have a 1 + 5 six want a one and also you have a 1 + 5 six want a one and also you have a 1 + 5 six so what you have is six and what you want is one for sure it is more so it is possible increase the maximum frequency by one cool now go on your R has moved for sure it will for sure move ahead L was still remaining at the zero itself it was still here L is still here now I'll just again check now just no worries as soon as you moved your R please make sure to add the corresponding I here the total was one add the corresponding four get the new Total cool now again what you have 5 + 5 Total cool now again what you have 5 + 5 Total cool now again what you have 5 + 5 you have a 10 and what you want a four into the length is r - L + a four into the length is r - L + a four into the length is r - L + 1 four into the length is two which is r l + 1 you got a eight you which is r l + 1 you got a eight you which is r l + 1 you got a eight you wanted like you have a 10 you want a eight for sure or it is true it is less than equal it is true cool so this is satisfied again increase the maximum frequency earlier it was one now it has become a two again move ahead with your R now earlier the L was here itself now what I have right now is again as you moved your R please add eight in your existing answer which is five so total was five add eight get a 13 now you have got a 13 for sure uh you have this length so what you have right now you have a 13 plus 5 you have a 18 what you want 8 into this length which is three because 8 + 8 + 8 length which is three because 8 + 8 + 8 length which is three because 8 + 8 + 8 you want a 8 into 3 it actually 24 bro I have 18 I want a 23 it is more which is it is not less than equal to for sure this condition is false which means you have to increase r as I showed you while this condition is there which means your wanting is more than what you have for sure increase your l so for sure I'll increase my L again I'll go and check what I again as you increase your L please make sure bro to decrease your total also so before increasing you had your L here firstly decrease your total I'll get to a 12 so now my new Total is 12 itself right not 13 again I have now increased my L again go and check okay bro what I have right now is 12 + 5 I have a 17 but what I want is 12 + 5 I have a 17 but what I want is 12 + 5 I have a 17 but what I want is bro I what I want this eight into this length which is two I want a 16 I have the 17 it's good cool bro just move on so I'll just update my maximum frequency length again it is it will become a two again you will move your r will always move ahead in the next step again your L was pointing here itself if you remember your L was pointing at four right so you will just move ahead your R you will add a 13 to your previous total which is 12 you'll get 25 is a new total value or a new sum again what you have is 30 I have what I want is 13 into this length which is three I want a 13 39 bro it is more so increase your L and again keep on increasing your L until this condition is satisfied so that is a v Loop now I'll just increase my L okay uh bro I'll just increase my L again as you increase your L please bro make sure to decrease total it will become 21 total has become a 21 again my new value which I have is 21 + 5 I have 26 what I want is 13 into 21 + 5 I have 26 what I want is 13 into 21 + 5 I have 26 what I want is 13 into this length which is actually again 26 it's true for sure uh increase your maximum frequency by two so this is how you will go about let's quickly code it up and before that uh for sorting it's O of n log and for just simple sing it's actually o of n again to sort we have not used any extra space but while sorting uh Java and C++ but while sorting uh Java and C++ but while sorting uh Java and C++ takes login space while python takes o of n space so for sure uh just make sure that you actually infer this indirect space which is being used cool let's quickly see the code again it will be pretty simple as what we saw um I'll show you both the variations completely Shing and not string at all so firstly as we saw earlier also that what we want right now is firstly have a sort because I want the order of these element and I want it to not impact other elements now I want the total LR and stuff and you will see the total can actually become more than the length limit so although you can have only total and just cast other variables but you will see that I actually needed LR but then multiplying my nums which is integer into LR which is also integer it will become an integer but that can actually go overbound so I have to cast that up so rather take everyone as long no worries in this part um so what I will do is what I want is maximum frequency or the maximum length uh right now you see maximum frequency maximum length for sure can be one because of this question itself length is one but let's take it zero or one anything whatsoever you want to take you will actually get this increase now you want an L you want a r uh you want the total also currently the total is also zero I don't think we want other variables oh we also want an N which is the length because I will actually go for this length so I'll just do a uh do size now uh our standard side window approach will be just keep on moving your R you have initialized your R so no worries just initial just get although if you don't even initialize it still it will get initialized but yeah I just usually have a habit of writing uh like this now you have moved your R forwards as soon as you have moved your R just make sure that you add that corresponding value in your total so I just simply add that value but now we have a task to move you our L now again uh we have seen that we only will move our L when it is actually for sure L we move only when it is less than which means L plus one is less than equal to R only then because L and R are L is behind R is forward and again the main condition was that our Target like what we want is more than what we have what we want was nums of R into the length was R minus n + 1 now I'll only move when minus n + 1 now I'll only move when minus n + 1 now I'll only move when I want which is more than what I have is total plus the value of K only then I will actually plan to move my L now before moving your L please make sure that you reduce that value from a total so I'll just reduce that value and also justy incre simply increase your L now when I have got the lnr correct lnr just update your maximum frequency and you can also name it as maximum length as maximum frequency and also the value of Rus L +1 which is the also the value of Rus L +1 which is the also the value of Rus L +1 which is the length of this corresponding now ultimately return the maximum frequency now it should run um considering we did not do any error maximum frequency okay R was missing now uh I hope that you guys got it now this was that you completely shrunk and you see while which means you completely shrunk your L now in this question I'm just want the maximum possible range if I have got the range of four I can just continue this range parallely I don't need to shrunk this range to two and then increase the r again right so in this case only when I'm concerned about the length and I'm concerned about the maximum length which means I'm concerned about the length and I want to increase the itself so what I can do if I have got a length let's say of four so this if condition will make sure that I'm only decreasing it once and okay I decrease it once and next time my R will increase so for sure my length will only keep on expanding and never will shrink right again uh this should also work and this is another fact which you have to make sure to actually optimize it although runtime will you will see that it is not much optimized it will see 173 and 170 not much increase but in an interview it is very much important to actually showcase that you don't want to actually shrink it entirely and then move on ahead I hope that you bye
|
Frequency of the Most Frequent Element
|
number-of-distinct-substrings-in-a-string
|
The **frequency** of an element is the number of times it occurs in an array.
You are given an integer array `nums` and an integer `k`. In one operation, you can choose an index of `nums` and increment the element at that index by `1`.
Return _the **maximum possible frequency** of an element after performing **at most**_ `k` _operations_.
**Example 1:**
**Input:** nums = \[1,2,4\], k = 5
**Output:** 3
**Explanation:** Increment the first element three times and the second element two times to make nums = \[4,4,4\].
4 has a frequency of 3.
**Example 2:**
**Input:** nums = \[1,4,8,13\], k = 5
**Output:** 2
**Explanation:** There are multiple optimal solutions:
- Increment the first element three times to make nums = \[4,4,8,13\]. 4 has a frequency of 2.
- Increment the second element four times to make nums = \[1,8,8,13\]. 8 has a frequency of 2.
- Increment the third element five times to make nums = \[1,4,13,13\]. 13 has a frequency of 2.
**Example 3:**
**Input:** nums = \[3,9,6\], k = 2
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 105`
* `1 <= k <= 105`
|
Calculate the prefix hashing array for s. Use the prefix hashing array to calculate the hashing value of each substring. Compare the hashing values to determine the unique substrings. There could be collisions if you use hashing, what about double hashing.
|
String,Trie,Rolling Hash,Suffix Array,Hash Function
|
Medium
| null |
1,011 |
hey everyone welcome to Tech wired in this video we are going to solve problem number one zero one capacity to ship packages within D days you will see the logic on the code for this problem now let's dive into the solution so here I've taken the second example from the lead code website so here we are given two inputs one is weights input array and then the number of days so basically we need to find the minimum weight capacity of the ship that will enable me to transfer all of these weights within the days that is given so basically you need to find the minimum capacity that is required to transfer all of these weights within the given days right so we are going to solve this problem using binary search right so initially I will have the left and right pointers where the left pointer will be the maximum element in my input array that is 4. then my right pointer will be the sum of all elements in my input array which is nothing but 16 in this case now I will find the middle value in this given left and right pointers so to get my middle value I will add left and right pointers and divide by 2 so I'm going to get 10 in this case so 10 is my middle value then I'm going to initialize two variables one is day another one is total weight so this will help me to keep track of the days that we are iterating through and total weight will enable me to keep track of the weights that we are adding on each and every day right so now we will start so I will be having two Loops one Loop will do the binary search and another one will enable me to add the weights and we are going to check that we are not extending the maximum weight right so now I've done the first binary search and I kept left pointer S4 and mid value as 10 and right pointer as 16. now I start adding the beats so initially I picked the first way that is 3 and I will add that to my total weight so it is 3 then I need to check the total weight whether it's greater than my middle value it is not greater so I just keep adding the next weight right so it will become Phi now I need to again check whether Phi is greater than 10 no I'll just keep adding the weights now it is 7 now I need to check whether it's greater than middle value no it's not so I will just adding the weights now after adding 4 now it's greater than my middle value so when my total weight is greater than the current middle value then I will move to the next day then I will initialize the current weight that is nothing but the 4. I am still at the first iteration of my binary search right so I'm just keep on adding the weights and moving to the next day in the second Loop right so my second Loop restarts again I will move to the next weight and I'll pick that weight and then I will add that to my total weight then I will check whether it's greater than my current middle value it's not so I'll just keep on adding now it becomes 9 after adding 4 now I again I need to check it's not greater now after finishing that Loop now I will compare the original days with the day counter that we are tracking if the original day is greater than my day counter that is two if three is greater than 2. now I will move my R pointer and point it to the middle value now this is my R pointer right so basically we are reducing the maximum capacity so we need to find the least capacity right so we are just shrinking the range the maximum minimum range and then finally we are going to return the left pointer where my minimum weight capacity of the ship will be occurring so now I am resetting my day and my total weight which is nothing but 1 and 0 then I'm going to again calculate the modal value so now new left and right pointers are 4 and 10. now again I am going to find the middle value by adding left and right pointers and divide by 2. in this case I am going to get 5 so by adding 4 and 6 and then dividing by 2 I'm going to get 5. so this is my new middle value now again I need to start adding the fix I will add 3 to my total weight now I need to check whether it is greater than my current middle value no it's not greater so I'll just add the next one this Phi now again I need to check whether it's greater than my middle value no it's not greater it's equal so if it is equal I'll just keep adding the next weight so I'm going to add the next weight I'm going to get 7. now the weights are greater my total weight is greater than my middle value so when this happens I move to the next day I'm increasing Day by one then I am pointing it to the current weight my total weight is now the current weight I'm just initializing 2 here this is my current weight now I will add weights so I will add 4 to my total weight now it will be 6 whether it's greater than my middle value yes it is greater I will move to the next day and I will initialize total weight as my current weight that is 4. right now I will add one to it I will just pick the next to it I'll keep adding the weights now it becomes Phi now again I need to check whether it's greater than my middle value no it's not greater so I just add the next weight to my total weight then I'm going to get mine by adding 5 to 4 right now I need to check whether my total weight is greater than my middle value yes it is greater right so I will increase my day then I will initialize my total weight as my current weight which is nothing but 4. now I am done with my weights input array now I will compare the day counter that is 4 and the original days that is three if my day counter is greater than my original days then I will move my left to pointer by adding 1 to my middle value that is 6 in this case so my left pointer becomes 6. then if I keep on doing the same method I will be having my left to pointer pointing to 6 then left pointer is the minimum weight capacity the ship can transfer all of my weights within the base that is given so finally I will return left pointer now we will see the code before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys so initially I'm going to have my left and right pointers so left will be Max of my weights right then right pointer will be the sum of all of my values in the weights input array then I will write then while loop until my left pointer is less than my right pointer right then I'm going to calculate the modal value that is left Plus right and divide by 2. then I'm going to have the day counter where I'm going to initialize with one then I'm going to have the total weight where total weight will be 0 at the start then I'm going to write another loop so I am going to get each and every weights from my weight's input then I'm going to keep on adding to my total weights then I'm going to write a if condition if my total weight is greater than my middle value then I'm going to increase my day counter I'm moving to the next day then I am assigning total weight as the current weight then I'm going to write another if condition where my day counter is greater than my given days in the input original input right if it is greater I will move my left to pointer to the next value of my mid value right then if it is not it might day counter is less than my number of days given then I will assign mid value to my right point right then finally I will return the left pointer I think it's fine let's run the code as you guys see it's pretty much efficient time complexity is log of N and the space is constant space happy learning keeps supporting cheers guys
|
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 |
54 |
so spinal matrix all they want to do is go through the matrix in a spiral while adding those elements into an array or a list and then return the list so uh i've seen some people the way they do this problem is where they set let's say they have these boundaries and you could just think of this as like row zero and whatever uh this last row is i guess would be row two and this would be column you know whatever columns this is i guess column six or five something like that but anyway the numbers aren't important they think of these red boxes as boundaries and all they would do is they'd print out the first row or the entire row so all the way to the end and then they would move their boundary down they would cut it off here and then they'd print out the next row or not print out they would add to the list going downwards anyway and then they would update the boundary after they do that so you would end up cutting all this off so now your new boundary is like this rectangle right and they would do the bottom side and then they cut this off by you know updating their boundary after they do that and then they'd finally do this they'd do the left side cut that off by updating their boundary again and then finally they'd finish by doing the last they just repeat it let me draw a better arrow than that and so yeah they would just keep updating they would just keep looping while updating their boundary after every time that they go across down across again and then up again so anyway um that's one way to do this problem but i'm going to do it a different way and this is actually the way that i came up with without seeing like a solution or anything so another way of thinking about this problem is that let's say the most outer thing is a layer and then the next most outer thing is also a layer so here we would have two layers these red lines are just using the red lines to show that these are layers and you know if we had a bigger and bigger matrix the way i'm thinking about is that the most outer thing is a layer and then so let's call that layer zero and as we work our way inward that'd be layer one then layer two layer three et cetera um and so let's just take this most outer layer all i'm going to do is print everything across in the first layer then i know because i know i'm going to do the same thing on the bottom i'm only gonna go i'm only gonna i'm gonna stop here when i'm going uh when i'm printing downward and then i'll do the same thing across and then you know the same thing on this side and then we'll increment our layer so this would be our next layer and we'll just repeat it and then we're done uh so this is how i came up with doing this problem and i'm going to code it out oh there are some corners so i guess got to go over so a couple things so first off like we have to be able to calculate how many layers do we actually have in a matrix so um based on this so uh if we look at this had two layers right two layers all you'd have to do is look at the minimum of the number of rows and the number of columns so here there's six and there are three rows right well you know this is one two three rows okay so you would look at the if we have three rows all we have to do is divide it by two and that gives us well this integer division this will give us 1. so what we're going to say is if it's if we have an odd number of rows we just add 1 and this will give us the two that we want this is saying that this is two layers and just to make that super clear like let's just say this we can so we agree that this is two layers right because of this so this is layer one this would be layer two and if i added let's say i just added a fourth row here well then we would have four to four over two which is just two and let's just show that there's two layers still so this would be one layer and this would be two layers i can't draw two layers cool so if it's a so all we have to do is check if we have an odd number we take the minimum of the rows and columns divided by two and if it's an odd number of rows or whatever or odd number of columns depending on which one we took as a minimum then just add one to it and that's the number of layers um and then from there we just got to do the whole logic of printing out a cross down and all that okay so let's actually code it out so first let's just start by declaring the thing that we're going to return so this is just a list and this is the thing we're going to add to new arraylist do return the list we need the number of layers so int layers equals okay so to calculate the number of layers we need to know uh whether we have smaller columns or smaller rows or the min of the two so let's just call that min dimension equals math.min equals math.min equals math.min of the number of rows and the number of columns and i don't need to worry about an off by one index out of bounds thing here because we're guaranteed at least one row and column okay so we have the min dimension let's call it dimension and to calculate the number of layers we need to check first if the min dimension is odd or even so if it's even then it's just min dimension divided by two for example if we have two rows then two divided by two would just be one layer and if it's odd then if for example if we had three rows well that's actually two layers and so what we want to do is min dimension divided by 2 so 3 divided by 2 would give us 1 but we have two layers so we just need to add one okay so now we just loop through our layers so end l equals zero l for layer uh l is less than layers plus l and we're going to add horizontally cross or add horizontally right and we're gonna pass in our matrix us in the layer pass in the list okay and we're going to add vertically down and i'm going to write these methods in a second this is just to make the code look nice so add horizontally to the left uh pass in matrix l and list and then add vertically up oh my god i can't type matrix l list okay we need to start writing those so private void add let's just copy paste i don't want to type that all out okay then and pass in the matrix pass in the layer pass in the list oh my it's been a long day okay uh add horizontally right matrix layer list and now we need to figure out what's our row what's our column that we're gonna so this is where our starting point and then you know we're gonna loop through it and we're going to do something like list.add matrix list.add matrix list.add matrix row column and that would be it this would be the entire method this is pretty much what all the methods are going to look like we just need to figure out what the starting point is so this would just be layer because we're starting on the top left corner and layer is going to be zero in the beginning then it's going to be one etc uh the column will also be layer that's top left corner and again layer will be zero so column will be zero and this is what we want zero and then it'll be one then two okay then we wanna say we're going across we wanna look through our columns so we wanna say c is less than matrix dot length so this is the number of columns minus our layer so that to make sure that we stop short you know on the next iteration of this um and we just want to do plus c so that's done and since we're already doing horizontal let's just do the horizontally to the left okay so let's calculate our starting point first of all so we start in the top horizontally to the left we're in the we have to start from the bottom right corner so this will be matrix dot length so this is the last row minus one so make sure it's not like minus one because it puts me in the last row and then i just want to subtract the layer to make sure i keep going like inwards and this is the exact same thing except instead of the row we're gonna do the column okay and let's just delete all this okay so if we want to go horizontally across we need to decrement through our columns so we need to do c greater or equal to layer yeah code so layer will be zero the first time so we want to go all the way to the end and then next time it'll be layer will equal one so we stop one short of the end okay and we just want to do minus c and oh and then so i think i mentioned earlier but there is one little corner case where if let's say we have an odd number of rows so if we have something like let's just say we had like this is the matrix they gave us one two three this was the matrix well so we had just have like a one by three here uh or one by three matrix so our ad horizontally right we'll add this to our array so let's or our list let's say this is my list to add horizontally right we'll add those three elements but then if we just leave this the way it is add horizontally left we'll also add these three elements you know from starting from the right to the left so we don't so this only happens when there's an odd number of rows so what we want to do is just check we just don't want these to compete oh and by the way the reason this happens for an odd number rows is because uh we calculated the number of layers and the layers is basically the min dimension divided by two but on the that if there's an odd number of rows or odd number of columns then our add horizontally right and add horizontally left they're gonna they're both gonna compete for or not compete but they're both gonna add that center uh row so anyway all we got to do is check if matrix do we have an odd number of rows matrix.length mod 2 equals matrix.length mod 2 equals matrix.length mod 2 equals 1. so we have an odd number of rows and so if we have an odd number of rows and oh this needs to be down here and the row equals the middle row just return yeah so if we have an odd number of rows and we're at the middle row just don't do anything because this guy is going to handle that and we don't want this guy to do it okay so now let's just do add vertically down let's just copy paste this just rename this add vertically down okay and just get rid of this get rid of all that okay and you know what i might as well copy and paste it for the add vertically bottom or not down and bottom up add vertically up okay let's do add vertically down so for adding vertically down we're in the top right row but remember we or where's the white board so really quick remember when we're doing downwards we don't want to include this guy or this guy we only want to do the basically everything in between uh the whatever our top are horizontally across and horizontal yeah our horizontal method said we don't want to include that um sorry i'm having a weird having a hard time like phrasing it correctly but i think you guys know what i mean um so anyway r equals not the first row but the first row plus one and the column so we're in the top right so then this would be the last column minus one which that would put us in the last column actually i think that's what we want and then minus a layer yeah so this puts us in the last column and we just subtract the layer and yeah i think we're good so now let's just do so for looping downward we're that means we're iterating through the rows so then r is less than the matrix dot length minus 1 minus the layer and then plus r so this would so may this is the last row but again this r less than so we're doing r less than the last row this is actually going to put us at the second on the first iteration when layer is zero this will stop short at the second to last row okay and we are almost done we just got to do add vertically up so adding vertically up around the bottom left corner so that means we're in the last row so matrix dot length minus 2 because -1 would put us at the last row because -1 would put us at the last row because -1 would put us at the last row we want to be the second to last row so that we don't include that whatever our horizontal method included minus the layer okay and for the column we are in the bottom left so then that would just be layer because on the first iteration this will be zero and then yeah the next iteration will be one okay so and then we want to iterate through our rows in order to go up so let's do it would be r is greater or equal to layer plus one because again if this is layer zero we don't want to include that first row so we just add one to the layer and then we're just gonna do minus r so the word because we're decrementing up in the up direction and the last thing is again if we have an odd number of columns we don't want this guy to add whatever this guy added because they're gonna both compete for that like that center column so we just need to check is major actually let me fix the spacing do we have an odd number of columns and if we have an odd number of columns and our column equals the middle column then just return i think weird let me fix that space is bugging me so i think we're good is there any anything else nope let's just run this cool and that's how i thought about this problem so uh i know it's a little different from like how other people did it but i just thought it was a cool i just like i like thinking about the matrix and layers i just because you can apply that to other problems um so that's why i wanted to do a video on it but anyway uh if you found this video helpful and give it a thumbs up if not sorry but anyway thanks and peace
|
Spiral Matrix
|
spiral-matrix
|
Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,2,3,6,9,8,7,4,5\]
**Example 2:**
**Input:** matrix = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\]\]
**Output:** \[1,2,3,4,8,12,11,10,9,5,6,7\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 10`
* `-100 <= matrix[i][j] <= 100`
|
Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row.
Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not.
|
Array,Matrix,Simulation
|
Medium
|
59,921
|
1,431 |
hello how's everyone this is lead coding today and when you start with a very new playlist in this playlist I will add solutions to the question starting from the very easy one gradually moving on to the intermediate questions and then finally to the difficult ones so even the complete beginners can start with this playlist and can gradually increase their skills as we move on to the difficult problems so please share this video like this video and subscribe to the channel now let us move to the very first problem of this playlist that is kids with the greatest number of candies the problem description says that given the array candies n an integer extra candies with a candy I'll this is the number of the candies so the eyath kid has for each kid if there is a way to distribute extra candies from the kids such that he or she can have the greatest number of candies among them so we have to distribute the exo candies among the kids and we have to tell the particular kid is having the greatest number of candies or not so why don't we give all the extra candies to that particular kid for which we have to decide whether he has maximum number of candies among all the kids or not so we are going to give all the extra candies through that particular kid now notice that multiple kids can have the maximum number so we have to check whether a particular kid after giving all the extra candies to that kid is having the magazine number of candies or not let us look at the very first example we have three extra candies we give these three candies to the very first kid the total will be 5 and 5 is in fact the maximum so it is true in this case then we have three plus three is six after giving extra candies so 6 is also makes u then we have five plus three eight which is again maximum then we have 1 plus 3 which is equals to 4 now this will not be maximum as a third kid here 5 candies which is more than 4 finally 3 + 3 + 3 6 again this is finally 3 + 3 + 3 6 again this is finally 3 + 3 + 3 6 again this is maximum in the entire array one way to approach this problem would be as follows let's say this is the configuration which we have now in this configuration we go to the first kid give 1 X can you do this the total will be five and we will check in the remaining array whether the five is the maximum element in the area or not so we will traverse the entire area and you will find that five is in fact maximum and the answer will be true for this kid next we will move on to a second kid and we will give one extra counter to this the total will be three we will traverse the entire array and you will see where the three is the maximum element or not we see that the first kid has four candies so which is of course greater than three so this will not be able to have maximum candies answer will be false for this one similarly for this one also the answer will be false for this one also answer is false for this also the answer is false so that's what we see in this task for the first one is to rest it is false now when we talk about the time complexity of this solution it will be of n square how let us break this down first we are standing at the first kid and we are traversing the entire array except the first one it will be n minus 1 iterations next you move on to the second kid and for this one also we traverse the entire area except the second one to check whether this is maximum or not so for this also we are traversing n minus 1 times similarly for the third fourth and fifth one so n minus 1 up to n times it will be n into n minus 1 which is equals to n square minus n so the time complexity is Big O of n square in this case what else we can do is instead of traversing the entire array for each kid we can find the greatest element in the array so here it is 4 now we have one extra candy so to the first one we give one extra candy it will be 5 is greater than 4 so answer will be 2 in this case for the second one if we give one extra candy do this the summation will be 3 so 3 is still more than four which is the maximum in the airing so it will be false again one plus one is two which is smaller than the greatest element which is four so it will be false in this case similarly we can approach this problem so this will take Big O of n time what we did you find the greatest element in the array and compared the number of the candies that a particular kid have plus the extra candies with this maximum element of the array now let us try to implement this so we have a maximum see which is equals to zero initially this will be the maximum number of the candies in the entire array so author a belongs to candies what this auto function do is it will take each element from the candies we will then try to maximize maxy is equals to maximum off max c comma a now if max c will have the maximum number of the candies throughout theory then we have to compare or a belongs to candies if a plus extra candies it's greater than or equals to max see then answer dot pushback answer is something which I haven't yet created so I have to create dancers well answer will be our vector of type bool also dot push back to in this case in all the other case answer dot push back false finally written the answer let us try to run this vector Chris working fine next instead of doing this another way to find the maximum could be using this function from here directly max element candies dot begin candy stopped and I think they should give us the maximum element or a totally star here ggu scheme is the correct answer so this is basically a steal function which we give us the maximum element from the area so this is it for the solution so if you want me to upload the solution video to any particular problem you can comment down below please share this video with your friends comment any queries which you have and please do subscribe to the channel ll keep uploading to this playlist and gradually increase the difficulty level as you proceed thank you
|
Kids With the Greatest Number of Candies
|
all-ancestors-of-a-node-in-a-directed-acyclic-graph
|
There are `n` kids with candies. You are given an integer array `candies`, where each `candies[i]` represents the number of candies the `ith` kid has, and an integer `extraCandies`, denoting the number of extra candies that you have.
Return _a boolean array_ `result` _of length_ `n`_, where_ `result[i]` _is_ `true` _if, after giving the_ `ith` _kid all the_ `extraCandies`_, they will have the **greatest** number of candies among all the kids__, or_ `false` _otherwise_.
Note that **multiple** kids can have the **greatest** number of candies.
**Example 1:**
**Input:** candies = \[2,3,5,1,3\], extraCandies = 3
**Output:** \[true,true,true,false,true\]
**Explanation:** If you give all extraCandies to:
- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.
- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.
- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.
- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
**Example 2:**
**Input:** candies = \[4,2,1,1,2\], extraCandies = 1
**Output:** \[true,false,false,false,false\]
**Explanation:** There is only 1 extra candy.
Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.
**Example 3:**
**Input:** candies = \[12,1,12\], extraCandies = 10
**Output:** \[true,false,true\]
**Constraints:**
* `n == candies.length`
* `2 <= n <= 100`
* `1 <= candies[i] <= 100`
* `1 <= extraCandies <= 50`
|
Consider how reversing each edge of the graph can help us. How can performing BFS/DFS on the reversed graph help us find the ancestors of every node?
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
1912
|
389 |
hey how's it going um just running a little script here uh pre-computing spacing on some sentences pre-computing spacing on some sentences pre-computing spacing on some sentences and they'll be stored in a cache database but let's take a look at the daily lead code because it's after 6 PM my time find the difference you're given two strings s and t string T is generated by random shuffling string s and then add one more letter at a random position return the letter that was added to T um okay uh c s c t equals counter s counter t and then um 4K in CT if s of if that's a what if s of K is lesser than um no if CS of K is less than c t of K then return k so 8 oh 400 Days that's fun uh let's see I do the same thing last time and oh this is probably a lot slower if the strings are short enough doesn't matter all right I guess that's it
|
Find the Difference
|
find-the-difference
|
You are given two strings `s` and `t`.
String `t` is generated by random shuffling string `s` and then add one more letter at a random position.
Return the letter that was added to `t`.
**Example 1:**
**Input:** s = "abcd ", t = "abcde "
**Output:** "e "
**Explanation:** 'e' is the letter that was added.
**Example 2:**
**Input:** s = " ", t = "y "
**Output:** "y "
**Constraints:**
* `0 <= s.length <= 1000`
* `t.length == s.length + 1`
* `s` and `t` consist of lowercase English letters.
| null |
Hash Table,String,Bit Manipulation,Sorting
|
Easy
|
136
|
3 |
[Laughter] hey everybody this is larry this is day 10 of the june lego day challenge hit the like button to subscribe when drama and discord let me know what you think about today's prom uh so hopefully you know you enjoyed the intro yeah i don't know earlier today i had a power outage apparently happens like once or twice a year in aruba so i was planning to do some coding and stuff like this but no power no coding so yeah but now i am i do have power and hopefully this is not good that's not what i do all right that's good enough hopefully knock on wood uh we'll have good power and internet um for this problem today's problem is longer substring without repeating characters okay this is a very early problem it seems like because it's literally number three um yeah and i feel like was that yesterday's problem that we just did that was two pointers uh yeah so basically this is an uh an idea another idea of greedy slash two fingers but this one is a little bit of a variation um in that it is sliding window so sliding window is greedy in that the solution is one of the different ways that you can do as long as you hold an invariant um it's not always easy to prove but this one you can kind of think about it as like you get a state that is true and then you wiggle it a little bit and then see how long you can extend it and it's still true if it's no longer true then that means that there's one of two things right that means that let's say you know let's say you have here you know you have abc and now you see an a well obviously this cannot be uh there is a repeating character there so this cannot be the longest substring right well there are only two ways to do it one is removing this a which we already checked that's the idea and then the others we're moving this a and then this can be a possible longer substring of course you can keep on extending it in this case not actually but that a is now part of the longest substring and see how long that can go so in that way it is sliding window it is greedy and it is two fingers two pointers whatever you would like to call it um yeah let's go i don't really have anything else to say so uh yeah and as you go let's just implement so then after left pointer is good to see yeah i mean i think so one key thing with while we're programming in general but especially with these two pointer things is trying to think about whether you want things inclusive or exclusive because basically the way that i think about is that i have two variables right or two pointers like i said and now i have to think about whether they're inclusive or exclusive so i was going to write something like this but the way that i'm actually going to write it is for right is in range of n and then you know s we do something as of right so that means that right will be inclusive by the time that we get increments right and then left will also s sub left will also be inclusive oh no s of left will be exclusive inside the set right um and okay i think that's good basically now we have uh a set of characters let's just say we call it scene and then just the longest for zero something like that maybe even twofold to one but maybe there was an input yep there was an input so you can do that um but yeah and then the idea here is that right is inclusive left is exclusive inside the range and it's just about letting us uh write these things a little bit easier um so sometimes you want to think about whichever one is easier to code which one is easier to explain and all these things right and here yeah so now we process this so that after at the end of this uh i guess technically right it's not inclusive but by the time you there's no operation between right and you execute it so that now basically uh if subray is in scene well or while this is unseen i guess technically yeah all right yes left we've seen that um we move is it remove um you can also yeah and then and here we know that this is exclusive or we say that this is exclusive because s of left is uh inside the range right that means that the left variable is not inclusive so yeah and then left we increment um and that's pretty much it i think uh what's it called uh s scene that s array longest uh equals max of longest and size of the scene you can also keep it very well but it's fine i think and then i think that should be good unless i did something stupid which happens a lot actually lately okay looks okay i think the only tricky case is empty but i think that's okay too unless i have some like outbound type thing which i don't think i do um could be wrong though of course that's why we test because we don't know to give a submit cool first try uh 801 day streak um cool what is the complexity here right well the complexity here is going to be old one because each character will be at most added to scene once and we move from it once so in total even though there's a while loop here so sometimes a little bit confusing um in total like i said all the numbers will be seen used um added and removed from scene one so that should be good for linear time in terms of space but what is the space right would you say there is a linear space uh trick question the answer is no oh no right because uh technically scene is not over n c is actually o of a where a is the size of the alphabet and in this case the alphabet is oh actually that was wrong so i was going to say 26 but as you can see here it has digit symbols and space so it's even like over i don't know 40 or something like that depending how they how many symbols there are so yeah so this is actually all of our so you can kind of uh adapt it to the number of characters and yeah uh that's the space so let me write it again so o of n time over alpha space uh or technically of a plus n or that's notation for it though technically you really want i think some people will get that's about um something like that right uh is that even true yeah uh space so that's pretty much it uh that's all i have for this one let me know what you think about the intro stay good stay healthy to good mental health i'll see you later and take care bye oh wow 10 million submits anyway see you later
|
Longest Substring Without Repeating Characters
|
longest-substring-without-repeating-characters
|
Given a string `s`, find the length of the **longest** **substring** without repeating characters.
**Example 1:**
**Input:** s = "abcabcbb "
**Output:** 3
**Explanation:** The answer is "abc ", with the length of 3.
**Example 2:**
**Input:** s = "bbbbb "
**Output:** 1
**Explanation:** The answer is "b ", with the length of 1.
**Example 3:**
**Input:** s = "pwwkew "
**Output:** 3
**Explanation:** The answer is "wke ", with the length of 3.
Notice that the answer must be a substring, "pwke " is a subsequence and not a substring.
**Constraints:**
* `0 <= s.length <= 5 * 104`
* `s` consists of English letters, digits, symbols and spaces.
| null |
Hash Table,String,Sliding Window
|
Medium
|
159,340,1034,1813,2209
|
637 |
binary tree well what do i say about it this is such an interesting and a very important data structure and due to this i have often seen that interviewers will come up with some random questions and they just want to test out how well do you actually understand this data structure they want to make sure that you are not just mugging up every concept they want to feel that okay you know how it works and how it behaves so one of the questions that i have found is to find the average of each level in a binary tree and of course this question is also available on lead code so in this question we will be discussing actually that hello friends welcome back to my channel first i will describe you the problem statement and we will look at some sample test case next we will see how this problem actually behaves and what do you need to do to arrive at an optimal solution going forward we will do a dry run of the code as usual so that you understand how all of this is actually working so without further ado let's get started so first of all let us quickly try to make sure that we are understanding the problem statement correctly in this problem you are given a binary tree that means each node has two child nodes correct and you have to return me the average value of nodes in each level right so let us say i have the sample binary tree in front of me the only thing you need to know is what is actually a level so for example in this binary tree this is level one then this is level two this is level three and then this is level four correct and what you need to tell me is what is the average value of the integers at each of these levels so for example at level 1 you only have one value right so the average value would be 2 divided by 1 and that is 2 correct if we go on to level 2 you have two elements 8 and 4 right so the average value would be 8 plus 4 divided by 2 right and that will give you 6 correct similarly you have the third level and the values are 3 7 and 1 so that would be 11 divided by 3 and that is equal to 3.6 and that is equal to 3.6 and that is equal to 3.6 and last you only have one node and that is 6 correct so the average value for level 4 would be 6 divided by 1 and that is equal to 6. so you can see that all of these values are the average values at each level correct in this question you just have to return a list of all of these values in a double representation so when you would return the result it would look something like this right and this will be your answer now if the problem statement is clear to you and you want to try it out on your own that's perfect try it out first otherwise let us dive into the solution as soon as you start solving this problem one thing becomes very obvious you need to figure out a way how you can travel individual level one at a time right what you will do is first travel the first level then move on to level two then level 3 and then level 4 and then so on correct so this is actually the concept of level order traversal if you're new to level order traversal i would highly recommend you to check out my video on level order traversal first because that is the basic concept on which this problem works so i will not go into a lot of depth about how level order traversal works but in this problem specifically what we need to focus is how do you identify that okay a level has ended a level order traversal will simply mean that okay you first get two then eight then four then three right but how do you know that after two the level ends after four the level ends and after one the level ends correct so in this problem we will be only focusing on that part to start things off let us first of all take up our queue data structure that will be used to perform a level order traversal so i have my queue with me where all the elements will go in from this side and they will come out from the other end right because of first and first out now there is a very neat trick which you can use to identify all of the levels what we're gonna do is we get the first element and that is 2 right i will put my 2 in the queue and i will also insert a null pointer what this null pointer will tell me that ok as soon as i get a null that ends a level so now start your level order traversal what is the first element that you get the element two right so what i will do is i will start defining levels over here level one has the element two right now what do you will see how many children the node 2 has correct 2 has the child 8 and 4 so following the level of traversal i will add 8 in my queue and then i will add 4 in my queue and 2 will be removed from the queue correct as soon as you look at the next element in the queue you see a null over here right and this is the interesting part as soon as you see a null this means that you have completed one level so i will complete a level and what i will do is i will take this null and put it in the next position that the queue is available so gradually what you will see is this null will determine where a level is ending now move on with the queue you pop the next element and that is 8 right as soon as you get a 8 this is the next level correct so you get a 8 and then what you're gonna do you will add all the children of 8 to your q so i'm going to add 3 and then 7. this completes the work of 8 so i will remove it from my queue right moving on what is the next element that i have the element 4 and to process it what i will do is i will add all of its children to my queue as soon as i add it i add one in my queue over here and we have processed four so i'm gonna remove it move ahead now what do you see again you see a null and what does null mean a null simply means that a level has been completed so you can see level 2 has also been completed what i will do now is i will take this null and put it in the next element of the queue right so now you can see how this process will follow along right in the next iteration i will get a 3 so this will tell me level 3 and i will get 3 7 and 1 over here and then eventually when all of these elements have been popped out i am left with a null again and this null will once again define the end of level 3. try to work out how 6 will go into level 4 on your own do it as an exercise and you will understand how this is working so now you can start to see how things are becoming easy you are getting all of the individual levels one by one right all you need to do is just keep on adding all of these elements and then you can simply get the average based on this logic let us quickly do a dry run of the code and see how all of this is actually working in action on the left side of your screen you have the actual code to implement the solution and on the right i have the same sample binary tree with me and we will try to perform a level audit reversal to get the average of all levels right oh and by the way this complete code and its test cases are also available on my github profile you can find the link in the description below moving on with our implementation what is the first thing that we do first of all we create a level q so in this queue we will store all the elements one by one and what is the first thing that we do first of all we add the root node and also add a null because root is the only node which is always have one level correct so i have two and a null in my queue correct in the next step i will initialize average list that will store all of my average at each level moving on i start a while loop where i will begin processing this queue so i will start to take elements one by one and then see if they have child nodes and for each level what do we initialize the sum to 0 and this nodes value will keep a count of how many nodes are there at each level now comes the interesting part i will start a while loop that will begin processing each element of the queue so what i do is i take out the first element and that is 2 right and then what i do is i add it to my sum variable and i increment the count of nodes so this is how i'm managing okay this is the sum and this is the count as a next step what do i have to add both the left child and the right child to my queue so this will add 8 and 4 to my q right when this loop runs again 2 has been removed right what i have is i have a null in my queue and what does null mean null means an end of a level as soon as this level ends what i'm gonna do is i will take this null and add it to the back of the queue again and this is happening right over here once i have done this i know that i have completed a level so i'll just add whatever the average is to my average list so for our first case since the only element present is 2 so i will add 2.0 element present is 2 so i will add 2.0 element present is 2 so i will add 2.0 to my left this loop will run again and this time i will be processing 4 and 8. so i know that 6.0 will get added in my so i know that 6.0 will get added in my so i know that 6.0 will get added in my average list right this will continue to happen and at the end we will return this average list as our answer the time complexity of this solution is order of n where n is the total number of nodes in the binary tree and the space complexity of this solution is also order of n that is because we need to maintain a queue where we are storing all of our nodes so this q can be as large as the total number of nodes in your binary tree i hope i was able to simplify the problem and its solution for you as per my final thoughts i just want to say that whenever you see a problem around tree traversal especially binary trees know that there are majorly three or four forms of traversal that is the pre-order traverse post auto traversal pre-order traverse post auto traversal pre-order traverse post auto traversal level audit reversal and the inorder traversal right and all of them have their own use cases if it is a binary search tree an inorder traversal will give you all the elements in a forted order and similarly in a level order traversal you can go on to each element level by level so with this you can see that how many variations of problems you can form right with a level order traversal someone can ask you okay how many levels are there they can ask you okay what is the left view of the tree that will be all the first elements in every level right what is the right view of the tree that will be all the elements at the end of each level correct so you can see that how some of the basic concept can translate into so many problems that is why i always emphasize on okay just clarify the concept first if the underlying concept is clear to you then it does not matter what the problem is because all the problems are built on top of each other right what i want you to do right now is in the comment section below tell me one such question that has been derived from another one for example the height of a binary tree correct and also tell me if you faced any problems during this video what do you want me to improve tell me everything and i would love to help you all of out as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where i can try to simplify these concepts for you also let me know what problems do you want me to solve next until then see ya
|
Average of Levels in Binary Tree
|
average-of-levels-in-binary-tree
|
Given the `root` of a binary tree, return _the average value of the nodes on each level in the form of an array_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[3.00000,14.50000,11.00000\]
Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.
Hence return \[3, 14.5, 11\].
**Example 2:**
**Input:** root = \[3,9,20,15,7\]
**Output:** \[3.00000,14.50000,11.00000\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-231 <= Node.val <= 231 - 1`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
102,107
|
1,007 |
what is up guys Debbie Allen here today we're going over minimum Domino rotations for equal row so this was a popular very popular google question as you can see here I actually picked this for my slack channel because we were discussing Google questions so I'm gonna be going over that today so the description reads in a row of dominoes of I and B a vibe represent the top and bottom halves of the ice Domino we may rotate the ice Domino so that a of I and B of I swap values return the minimum number of rotations so that all the values in a are the same or all the values and B are the same if it cannot be you're done return negative one so one important thing to note is we're just returning the minimum number of rotations so we don't actually have to rotate the dominoes we're just reading a number we're not returning the swapped array so we don't have to return array so that makes it a lot easier so as you can see here they matched up all the top row so it's all twos and it took two rotations and here I guess you can't do it yeah you can't so there's only four scenarios we need to check an important thing to realize is that the value that we're going to be matching is going to be either in a of 0 or B of 0 because it has to be in all the dominoes on that on a single row so it's either going to be in a of 0 or B of 0 or the target value we're trying to swap for so there's gonna be two for a of 0 two scenarios rate is zero in two scenarios for B of 0 on the two for a of zero we're gonna be checking to see if we need to swap we're going to be comparing a two is zero and the second one is we're going to be comparing the B elements to a of zero and then vice versa for B of zero so we're comparing a 2 B of zero and B 2 B of zero those are the only four scenarios we actually need to check so that makes it a little bit easier not easier but that's like the trick or a hint I guess so I created a function to calculate if we need to swap the dominoes so and we're gonna pass in three parameters so in target this is the going to be a of 0 or B of 0 that's the value we're trying to match the rose to and then we're just going to pass in our two arrays oops so in a and int B I can't type all right so then we're gonna create our number variable this is what we're gonna return at the end this is gonna be the number of swaps I should just name it number of swaps it makes more obvious and so let's we have our main for the 4 into by equals 0 I less than eight only it could be read out length as well they're dominoes so they're exact same length I plus so if the first if just test case we're going to do is if both if a of I and B of I do not equal the target then it is not possible so we need to return negative one but up here we're going to be using the math dot min function so we don't want to actually return negative 1 because negative 1 would be the min yeah so let's do a of I does not equal target and B of I does not equal target and if that's the case we return so we're gonna use up placeholder value we're just in return integer dot max value and in the function above we're going to use attorney operator to check to see if the min swaps equals integer top max a then we're gonna return negative one else we're just gonna return min swaps so min swaps vehicles math dot min that's how we're going to code it up there and then just right here we have to return some swaps I actually didn't finish this because there's an else if statement so house if a of I does not equal the target then we need to swap it well if a if we get past this if statement then we know that either a of I or B of I equals the target and if a of I does not equal the target well that's what we're comparing it to so we need to swap so we're going to do all we have to do is increment swap so we don't actually have to swap and if else if it doesn't hit either of these this if statement or this else if statement that means B of no I'm sorry a of I matches the target and we don't have to swap because it's already in the right place so yeah that's this entire function that's how that works and then up here we're going to just call them in swaps function twice and we're gonna pass in our four scenarios I mentioned or earlier so we're going to do a of zero is gonna be the target up here a and then B and minimum swaps a 0 again and a and B are now being a I'm sorry so one important thing to notice here is although this is labeled a in our function we might actually be passing the B array into the a so when we call this function B is actually a and we're checking if so imagine this says B and said if B does not equal target then we actually have to swap it so alright and then we just need to do that two more times basically a minimum swaps oh it's be a zero this time these are this is our other two it's actually gonna be then swaps so we're updating min swaps comparing it to the old min swaps and this one we're comparing the old min swaps to this the value of this function call and then let's do it again for the last scenario so b0 last time we just have to swap B and a and then we just need to return min swaps but because we're returning because we were turning integer top max value we have to check for that so if it returns integer dot max value we're using a ternary operator if it does return negative 1 else return min swaps and the reason for this is because if one scenario doesn't check out then it's going to return negative 1 and that what another scenario might actually work so we're not well you know we might not be able to match a of zero but we might be able to match B of zero so that's why we want to do that and so this accounts for all four scenarios and let's just run it hopefully that made sense I hope my explanations are getting better trying to work on it see it works so that's how you solve that it's o of n run time just because we have one for loop and I believe I don't I think it's constant run time so it's over when are not runtime memory usage so it's all one and that's about it thanks for watching guys I'll see you in the next video
|
Minimum Domino Rotations For Equal Row
|
numbers-with-same-consecutive-differences
|
In a row of dominoes, `tops[i]` and `bottoms[i]` represent the top and bottom halves of the `ith` domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the `ith` domino, so that `tops[i]` and `bottoms[i]` swap values.
Return the minimum number of rotations so that all the values in `tops` are the same, or all the values in `bottoms` are the same.
If it cannot be done, return `-1`.
**Example 1:**
**Input:** tops = \[2,1,2,4,2,2\], bottoms = \[5,2,6,2,3,2\]
**Output:** 2
**Explanation:**
The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
**Example 2:**
**Input:** tops = \[3,5,1,2,3\], bottoms = \[3,6,3,3,4\]
**Output:** -1
**Explanation:**
In this case, it is not possible to rotate the dominoes to make one row of values equal.
**Constraints:**
* `2 <= tops.length <= 2 * 104`
* `bottoms.length == tops.length`
* `1 <= tops[i], bottoms[i] <= 6`
| null |
Backtracking,Breadth-First Search
|
Medium
| null |
371 |
hello everyone welcome to my channel so today we are going to do leave code 975 question sum of two integers so let us first take this question about the constraint then about examples and finally the coding part for the same so here let us first read this question given two integer A and B return the sum of two integers without using operators plus and minus so if plus and minus is not being used then how we will be doing the additional subtraction that's all boil Downs to the bit manually because the integer value or any number comprises of bits right so while adding those bit we can directly get the new number so that's the thing it's not only just adding the first bit but performing several operations so now here the constraints are also like it's from minus thousand to thousand is a and b would I beginnings do the good manipulation okay here A and B if we add them mean basically one plus two would be equal to 3 right and if we write them in the form of bits so it would be like this if this is for one and this is for two right so when we perform with a right but if there is something like 2 plus 3 which is equal to 5 right and here it will be C then 2 is something like this and three is something like this right and when we perform the addition of these bits then how it would be like this one and one when we add them up then there is one carry also there right and because of that only well so it would be something like this right now here the thing is this three which is there if it if in ones or two then surely we will be getting thrilled right when we perform zor operation so wherever there are different bits there we will be having the one and where they are same but there we will be having that zero right so that's what we get after doing so here if we see 0 1 right different bit one same bit 0 same Bit Zero right so here if we choose over of two and three then it is not coming out to be 5 but rather than that it is coming out to be one right so here there is issue of this carry only so for this carry part we are required to do separate operation means the thing is that while doing soil we will be able to add up all those numbers with uh where carry is not required right but wherever carry is required here we are required to keep the track of that carry also and how we can keep the truck of that carry it would be something um we saved to and of the 0 1 and 0 1 0 right so surely we will be getting the 0 1 0 right and one more thing which was there means how we have added this carry here this carry was being added P here this was after doing soil and then Carrie was being added they say that we got this after doing art but Carrie was being guided at this point right so after adding that thing we got her this answer so basically after doing and we are required to lift shift as well so after left shifting bully we are required to add that to a result and this is how we will be doing the addition of both of these numbers which are being given to us in our input so this is the whole scenario now let us go ahead for the coding part of the same so here basically what we are doing is for carry part we are doing that and operation and then we are performing Resort for the first number we are storing that joint and for the second number we are storing the carry part that is left shifted type and then we will be performing this operation until our carry becomes zero so while doing this we will be getting our answer in the a itself and that is what would be after adding up both of the numbers without using plus and minus so basically the time complexity would be order of 32 because we are manipulating the 32 bits so that's 5 it would be out of 32 basically order one only and the space complexity here it is order of one so this was all for this particular question if you have any doubt you could comment that down with the timestamp of wherever you were unable to understand the scene so yeah this goes on thank you
|
Sum of Two Integers
|
sum-of-two-integers
|
Given two integers `a` and `b`, return _the sum of the two integers without using the operators_ `+` _and_ `-`.
**Example 1:**
**Input:** a = 1, b = 2
**Output:** 3
**Example 2:**
**Input:** a = 2, b = 3
**Output:** 5
**Constraints:**
* `-1000 <= a, b <= 1000`
| null |
Math,Bit Manipulation
|
Medium
|
2
|
21 |
this is one of my favorite linked list questions we're given the heads of these two linked lists and they're both sorted in ascending order our job is to get the new list of the same nodes but also in ascending order so we start off with the dummy node D well L1 is smaller so we would rather point this to the first element this is going to be a reference to that node right there so since we used L1 we're going to move L1 over and which one do we prefer now well it doesn't matter let's say that we took this one l1's going to go over to empty and we're going to use Note 2 now but now L1 is pointing to none so we can actually just immediately point this to L2 because that's going to keep the sorted order we'll start our list with a dummy node and we'll have C is equal to the dummy if we want to use the list one node then we've got to set c.ex to be node then we've got to set c.ex to be node then we've got to set c.ex to be list one and we've got to update CER to be that node we want to move list one forward and if we want to use list two it's just the opposite so we can just set c. next to be whichever list is not none and in the end we just return dummy. nextt drop a like if this was helpful
|
Merge Two Sorted Lists
|
merge-two-sorted-lists
|
You are given the heads of two sorted linked lists `list1` and `list2`.
Merge the two lists in a one **sorted** list. The list should be made by splicing together the nodes of the first two lists.
Return _the head of the merged linked list_.
**Example 1:**
**Input:** list1 = \[1,2,4\], list2 = \[1,3,4\]
**Output:** \[1,1,2,3,4,4\]
**Example 2:**
**Input:** list1 = \[\], list2 = \[\]
**Output:** \[\]
**Example 3:**
**Input:** list1 = \[\], list2 = \[0\]
**Output:** \[0\]
**Constraints:**
* The number of nodes in both lists is in the range `[0, 50]`.
* `-100 <= Node.val <= 100`
* Both `list1` and `list2` are sorted in **non-decreasing** order.
| null |
Linked List,Recursion
|
Easy
|
23,88,148,244,1774,2071
|
131 |
Jhal Hello Welcome Parivartan 100 Indian subscribe The Channel And subscribe The Amazing Don't forget to subscribe on Thursday and subscribe chatting loudly and subscribe the Channel Please subscribe And subscribe The Amazing subscribe and subscribe the Channel Please subscribe and subscirbe mein bhi naagin track bandhe ez And Values Which Will Result Subscribe And Values Which Will Result Subscribe And Values Which Will Result Subscribe Zaroor Subscribe To Hain To Mitthu Edifice 19 Friend Starting From Dowry And Values Into Withdrawal Subscribe 508 Ki Into Dar And Need To Return Result And Vid U Mein Naav Palt Dekh Lena Jis Din More Subscribe Aaj Tak News Start Value in this list One to one portion Great Soul When they are planning to approach mid of this train should be in the middle of nowhere In the result will be [ result will be [ result will be Ki ab dekh lete yaar do the result and returned from her character This Mother Case Will Need To Take Into Consideration In Every Value 2014 I 9 Meet Uchhay Egg Subscribe But In Iniquity And Half Loot Subscribe Must List That All Lord Your Current Less Nominate To Call The Method Andar 110 Will Do This Alarm Set A Promise Plus One And Delhi And You Will Do Subscribe To Jai Hind Se Complete Na Mintu Applied As Land Of Mithila Bulletin On A Love You Know What Is The First Trump In Calendars Effective Read And Forward And Backward States Such A Difficult Length And Width This Velvet Start That is not equal to the value that attend Baikuntha it is not you thrust from cylinders further into it's true love never got any country code that right result on this wicket OLX time 10th this tree committee actress paoli dam complexity of algorithm in which of * Roopa of algorithm in which of * Roopa of algorithm in which of * Roopa Not Enough Need To's
|
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,901 |
today we're going to take a look at this peculiar question called find a peak element 2. the reason why I want to make this video is because uh from the solution I sing online the most optimal and correct way to do it is by using a Brute Force search inside a binary search now if you have no idea what I'm talking about go take a look at the solution then come back what we want to discuss is why we need this brute first search and why can't we have two binary search I replaced this brute first search with a binary search okay so let's take a look at fine Peak element first so the original fine Peak element goes like this we have an array and we want to find the peak element it does not have to be the max element in the array it just needs to be a peak for example in this array 2 is a peak because 2 is strictly greater than its neighbors uh six is also a peak because it is strictly greater than its neighbors so in this question how we solve it is by using binary search you can see my code over here where we just simply use binary search we do a three-way check uh if you don't know three-way check uh if you don't know three-way check uh if you don't know what I'm talking about go check out my three different ways of writing binary search and over here we're doing the three-way check uh if we see that the three-way check uh if we see that the three-way check uh if we see that the left and the right are both smaller than our current mid then we return our result if not we go left or right depending on the current situation easy as that now it is important to understand why this binary search works right because inside of binary search when you want to use a binary search the array Ray has to be sorted clearly the array here is not sorted however binary user search still works because uh what we're doing is like basically landing on a number right say hey uh is the neighbor smaller than that uh smaller than the current middle I say it for our three here we can see that yes one is smaller but five is bigger since 5 is bigger it's guaranteed to the right side of our current element 3 that there is a number that is bigger in this case um whether it's a peak with two elements beside it or it's against the wall it's guaranteed that there will be a peak that is why this binary search works now let's take a look at find Peak element 2. so the changes here is that instead of doing a 1D array we're doing a 2d array so we want to find the peak element inside a 2d array meaning that the number has to be greater than its left right up down it has to be greater than all these elements alright so over here in this example you can see that 30 is a peak because it's greater than left right up down 32 it's a peak because it's against the wall for uh right and down but it's greater than up and uh left so you can see this is also my first intuition uh knowing how to solve fine pick element using binary search is to just use nested binary search what I mean is we're going to pretend this is a 1D array 21 30 14. we run the binary search and we find a peak in this case say we find the peak that is 30 and then we're going to run binary search again um on the up down on the column to see hey what is our binary search uh we see that our Peak uh is 30. thus we return our result this is what I mean by running a nested binary search over here in my solution my attempt over here you can see this exact implementation this is exactly what I've done in my first implementation right uh we have a nested binary search first we're going to run binary search from left side to right side what that mean is like seeing like just left side right side find a peak element um so what we have done left side right side we find the current middle and then for the current middle we're going to find a peak element on the current column up and down once we find the peak column up and down we know the max row so this element index over here and then we're going to use our mid we're left and right uh to see to locate our exact position once we locate our exact position we're going to check is left smaller is Right smaller and then if it is we return the exam result if not we go uh either we go left or either we go right depending on the position you can see how there is one binary search here and for each iteration of the binary search we're running fine Peak element the exact same algorithm on the current column so up and down so the smaller binary search up and down larger binary search left and right however when I run this code you can see that it does not work this is extremely odd and even when I ask cheap BT it says that both solution using a similar approach should work and have the correct result it's just saying one solution is more straightforward than the other however in this case the nested binary search does not work only The Brute Force finding the current Max role works so even Chad gbt failed at this question which is very odd and when I search online for other YouTube tutorials none of them explain why nested binary search doesn't work so that's what exactly what we're going to do right now explain why it doesn't work here we have the uh the test case that it failed on I'm gonna make it to a more presentable format here are the positions that the algorithm iterated on we're going to see if maybe the algorithm is wrong or if not why what's happening and what's going all right I have copied it over to a more presentable format uh row Max row okay this is a little bit confusing Max row is just like which role it is zero one two three four five six mid represents our current outer uh binary search left and right so zero one two three so first outer binary search returns three so that means we're on zero one two three on this column and then we're going to do binary search to find the max row which one or like a peak peek role so over here it has turn six so zero one two three four five six you can see that this is indeed a peak for this column right however uh you see that left and right uh it's not a peak so what we're going to do in this case we see that hey left is a right is bigger so we're going to go towards the right uh the right so in the next iteration you can see that we are on zero one two three four five so it's zero one two three four five we're on this column and it's giving me six over here you can see this is six so individually um when we're running the inner binary search to find a peak inside of this column you can see that 13 is indeed a peak on this column however it's not the max this is the max 13 is indeed the peak right so this once again doesn't work because on its right we have 14 is greater than 13. so finally we have our last one which shows that we're on six zero one two three four five six and then it says that hey twenty is a peak on this column and you can see 20 is indeed a peak on this column but 21 is greater than 20. and now we exit the loop because we're like hey we couldn't find anything this test case perfectly illustrate how running a nest to binary search Dodges like the largest number because even though this is a peak uh the largest number is over here right if we instead of doing a binary search uh for the columns and just Brute Force iterate over and find the current Max of that column say what how it will go is like first we have three right so zero one two three we're over here we find a Max we know that the max is 98 so we're like hey is this a peak overall nope because there is number on the left that's greater okay then we go to the left we find the middle right we go over here we find a peak which is here on this column we're like hey is this a uh Pink overall nope because 10 is greater all right so now we're between these two we come over here we find the peak on this column 99 it's 99 a peak overall yes because left and right so like if we just Brute Force to find the max row this algorithm will work to answer our question of why the binary search version running as the binary search does not work is because like we've shown here that binary search on running two binary search does not guarantee that the result will be a peak the reason why binary search work on the single like Peak element on a single array because once we uh say if we have this right just we're going to isolate this as a single array the reason why this works on a single array is because once we land on a point and there's a number bigger on this side it's guarantee so here we landed here there's numbers bigger on this side it's guaranteed that there's a peak there however as we have shown running nested Loop when we run binary search on a single column it's not guaranteed that towards that direction um left or right there is a peak there it's not no longer guaranteed because a single binary search only guarantees a single array this is a 2d array however if we find the max it is guaranteed that element is the maximum of the current column this eliminates this variable whether or not the Max on this column allowing you to use the binary search as if we're finding for a 1D array the peak I hope that makes sense let me rephrase this to make this more understandable the reason why a single array works with binary search is because when we run binary search left and right we're guaranteed to know which side has a peak for example if we rely on 22 once again if 22 is greater than both sides it is the peak if in this situation 98 is bigger than 22 then is guaranteed on the right side that there's a p that's the single variable over here we have a 2d array the peak can be up down left right we want to eliminate this right when we run a nested loop with a binary search we essentially in compresses this array to a single array essentially this array gets transformed into the maximum of each of its columns uh each of its columns yeah the maximum of each of its column so we have it essentially becomes this eight nine ninety eight 22 21 and finally uh 20. it essentially becomes this the maximum of each of the column and basically the Elder binary search is running the same algorithm in a fine peak one where we find the current Peak and it is 99. however nasda binary search does not work because in the same thought when it does the compression it can compress this to 8 9 10 11 12 13 14 right uh in this case it's missing out a lot of the larger numbers and a lot of the cases that might be true so you can see how binary search does not work now that we finally explained why nested binary search doesn't work let's look at the Brute Force plus binary search algorithm over here you can see we're running binary search first we get inj while I is smaller equal to J middle we grab the middle element then we find the current Maxwell Zelda current maximum roll of the middle column right so say mid is here then we find the max role of the current column which is 30. we check is left side smaller is right size smaller um and if left side and right side is both smaller than the current element we can return why because we already know that it's uh we have the number that is the maximum roll meaning it's greater than up and down we just need to check left and right and if left side is smaller if left side is greater sorry then we go to the left if we right side is greater then we go to the right and finally we should never reach this point unless there is a no peak on this map I.E all the numbers are the same map I.E all the numbers are the same map I.E all the numbers are the same now let's talk runtime say if there are M rows and M columns so M and then binary search since we're doing left and right that will be log end time right binary search login time however for each iteration we're doing Brute Force up and down uh which is uh in the runtime of om so overall we're doing log n every time we do M so the overall runtime is M Times log n
|
Find a Peak Element II
|
equal-sum-arrays-with-minimum-number-of-operations
|
A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom.
Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`.
You may assume that the entire matrix is surrounded by an **outer perimeter** with the value `-1` in each cell.
You must write an algorithm that runs in `O(m log(n))` or `O(n log(m))` time.
**Example 1:**
**Input:** mat = \[\[1,4\],\[3,2\]\]
**Output:** \[0,1\]
**Explanation:** Both 3 and 4 are peak elements so \[1,0\] and \[0,1\] are both acceptable answers.
**Example 2:**
**Input:** mat = \[\[10,20,15\],\[21,30,14\],\[7,16,32\]\]
**Output:** \[1,1\]
**Explanation:** Both 30 and 32 are peak elements so \[1,1\] and \[2,2\] are both acceptable answers.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 500`
* `1 <= mat[i][j] <= 105`
* No two adjacent cells are equal.
|
Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one.
|
Array,Hash Table,Greedy,Counting
|
Medium
|
1263
|
1,091 |
Ko same guys welcome to day keida mili vedita and this video wear go into soft faith in binary matrix problem mein jeevan kya hai kya aapko and into and binary matrix hridaya rakha hai hume dhan karna hai land af bhi soft clear path in matric chup clearpath Do they understand here okay so a clear part in the matrix it 5 from the top left to 023 bottom right scene and minus one president all the best just method 580 and all the differences of department seth dictionary connected different And a share and jeans and 15 lemons have been planted that you can say here which is real pure clear plant source of i.e. here which is real pure clear plant source of i.e. here which is real pure clear plant source of i.e. top left end definition of button good N - 16 - World Induction of button good N - 16 - World Induction of button good N - 16 - World Induction Column and okay and what do we Have to do or not dip, that is, feel, the value here is 201 in great, one means here the box is done, you cannot go on the path of one, the value here will be zero, that could be your direction, that could be your pass. Possible park, now you have to do something on that, okay and here you have to give total and not test total, now you have to give notice for the length of 100 tests by calling here, okay, so what is there to say here? Where the value is there, we have to move on it. Okay, from where to where. Now, look at the top left or not the left corner, that is, look in the example and what is this, your bottom right is okay, so you have to go till here to know. Which can be the smallest part of yours, you have to do it there, okay, so the second part of the example, all that is here in the deposit example, you are running from here till here, it is okay and this thing also has to be kept in mind. That the value of on that part should be zero, if it is 1, then located there, now you can't go comment box which is 181 people ca n't go. Okay, if this is your source here, this energy 0 column 0 is this and if this is the one. If you go then what is the condition that what should you do, what will happen to you, the box is done, okay, so you cannot go anywhere from there, then what will we do in that condition - We will do 110. If we what will we do in that condition - We will do 110. If we what will we do in that condition - We will do 110. If we meet someone like this on the way, neither will we. What will we do - We will make it 110. Okay, so do - We will make it 110. Okay, so do - We will make it 110. Okay, so we will see in the example here, we can move it, what is given in it, can we find it by using the base, then how can we find it by using the diameter, so what do we do in the example? To understand this, I have clicked on the example here. Now let's see what can be possible. Question: What can be possible. Question: What can be possible. Question: What can be possible? If we take this meat element, then where can everything go here, that this can go. Yes, you can go here if the lights are not working, you can go here, now you can go here too, now you can go to this corner too, in this cotton too, these bullets can stop here, diagonal here too. These are the directions we can take to free ourselves. What can be the possible direction that we can take to free the direction? Okay, so now let's start from here. How can we use Jalna Vyas? Okay? What we actually have to do here is that we have to point the road column and this is where we actually point that we will do the joint, at what minimum level can this be possible, okay that level let us fine the letter M, that level then that level If we get it then it will be our final answer. So here now how can we make air force graph. Look, which one will start? So friends, it should not be swallowed in one. If there is one, then before that people check 10, what is my one? No, if there is only one value, then check it at the same time - it will be 110 because pause ca - it will be 110 because pause ca - it will be 110 because pause ca n't be further. Ok, first check this. If it is there, then you will see what can be possible. You can go in this direction in this survey. It may be possible in this direction. It may not be possible from here in this direction. In this direction. And in this direction. Okay, now look but from here we said it is possible but for this it is possible to go here, it is not possible. So, you can go there, can go, you can go there, but what are these two forests? Whenever there is tight blockage 54, you cannot participate in that convention, you cannot produce by choosing, then what is possible with us? This is okay, if this is us, this is the first, this is our first level, then the second media forum can do this one can gift, now this is done, this is the first level, your level is done, okay after that. You should know from here what all can be possible, it can be possible and it can be possible but it is already one, it is not invalid, it is not a belt partner, so it is not necessary to use it, you can use it. If we can use this, then what level can this level be, what level can we make prayer, this zero of possible in this one and this one is ok, your form will be formed in the formation No, now tell me if we use this one districts If we do this, then we use this juice that can be said, it can go here, this can go here, blood can go here, it can squirt light, we can go, this can go, see whenever we choose for this, right, for this we We can use this, we can do this, what will we do for this creature, we will forgive it, we will also budget it, OK, we will kill it once, OK, we will mark it as one, what is possible for it, but positive is that. This one is already ready, this one is possible for this, it is zero and as soon as we get it, we will decide whether it is our destination, whether it needs liquid, its weight, its like and so this level, we will joint it. So this is our third level, this is the sucking touch which we have got rid of, this one is zero two on the roof and this one is found on the husband support level on the force, it will be found on the note level if we assume that we use this first. Okay, whatever place we put it, if we use it here, what will it do? This is your plate on the third level, it can go here, well, it can go here, so here it will go here or it will go here, okay? At what time will you get it, you will get it 410 first time, but we will be checking that today we are going to Varanasi, we will check this hot at home level, we will get it at food level only, so there will be no need to go so far because We are checking by level. Along with checking by level, we are also seeing that we have reached the destination. If we have reached the destination then what will we do at that time. We will return it to the level it is. Tight time is coming on this. There will be no need for this because when you will also be at the second level, you will see both the G's of each level, then you will see both of these, whichever is this, when you will look for these Amla gas, then whatever is not suitable for this, you will look for this, but this but adopt this. And first of all, it must have got the destination, right, is this the best? If you look at this first, then it would look as yours, not my number, this is related, otherwise it is already boxer, but here we did not get it. Check at your level. Let's do this one will live at its level, the possible way for this is that it sings behind, there is no destination, but it will like it, whatever it does, it will discuss its level, this zero, what has it got, it must have got this in its construction. You must have received the right, so this must have been received at the same time, what will we do Les Gusta Flavors, you must have returned it, right, so how will we do the code of that, you see, what will we do now, let me show you, look here first. Beta has been given, let's check right som great first, is n't it G-20 only? First, it is n't it G-20 only? First, it is n't it G-20 only? First, it is not only Mysore C's box, then in that condition - will make it medium, ok, in that condition - will make it medium, ok, in that condition - will make it medium, ok, done, now we are busy here, using As for Islam, what will we do because we will use it? Okay, now look, I am coming here, let me explain the code to you here. Well, first do the front. Okay, I told you how the approach route will be and here I have explained to you how to do the code. I am going to use gas here, I have seen in the night how can we do it through chanting, so see Abhay, what will you do here, why wo n't you take it, okay, why will I get cancer now, you will love, you will insult, okay you will insult again. Then Anil Royal is going to do column minutes here, row end column OK 200, what will we do, we will start from here but will check, is this Shyam, you are not my one, if he is running, then what will we do with that condition - 110, other wise. will we do with that condition - 110, other wise. will we do with that condition - 110, other wise. What will we do here, we will make it inside here, okay, we will add inches to it, dip it on the first index, what to do with it, mark it as 1, okay, mark it as 1, either kill We will close it by hitting OK, what will we do after the call, now we will check its direction, in which direction we can go, then what will we do, we will make a bangle batter as much as we can, pickle diet chart is art direction in dictionary, art direction is home made. Okay, what will they do, here we will make what can be the direction, ours can be yours, it can be 0, that is, 108, 8 - 105, 8 - 105, 8 - 105, two, - one, two, - one, two, - one, I, one, minus one, it can be - 121, I, one, minus one, it can be - 121, I, one, minus one, it can be - 121, right can be 121 and Minus one minus one can be possible right, this art direction is possible for you, this side, I have told you, this direction can be possible for you, right, so now when we do it here, we will take it inside. We will kill him and visit him, after that why will we do Mirza, then we will take him out, ok now what will we do on holidays, why are there lights in the elementum states now, what will we do, then we will take him out, and there is another issue, we will take out the top element first. What will happen to you, come and then there will be debt crisis, what will be your problem, it will be zero, okay, take it out yourself, then what will you do, what will you see for it? Direction is validation, we will see, this is one, we will remain, giver is given, we will not go, when we look for it, we will find it in zero, then what will we do, if we will put it inside why, then what is ours, zero is one, isn't it 0wn, what are we with us? We will get a level, you can say answer level, it will start from zero when we will be taking it out from here, that is, now we will be watching for this, it will go from here to our place, it will be finished, okay, it will be finished or we will look for this and its second. Mukesh can set the level, why will I do justice, here I have been zero and one in governments, why is this ours, this is okay, this will be paid, then this will happen, for this, we will come out of this, volume row, now zero problem is your one okay. So taken out, you have level till now, this will control you here, you will level up till OK, then for you have to go here, you can go here, then whatever will be the next level, how can we search both of these in it. Right, why are we going to have cancer, see why I am ours, this is zero and two inside this, then we are like this, Noorjahan's, this is yours, what is one and 212, like this is a new one and two, rice wine and for 2 minutes We will also tweet on Friday, we must have done this also, okay this will also be done, now look, we will take him out now, give zero and two to zero, that means this is the creature, this one, you will get it out of here, you will take it out. Use row and column of Ropkar, what will go to you, then see the answer, what will it be? Here at the third level, what have we done now, we are okay at the third level, then at the tax level, we will see that it can come, it can go. But this audio path has been deleted, so let's leave it won't do anything, okay, now you can't go there for this, you can't go here either, that's what happened here, that's why it happened here too, okay, so you can't go there for this. Why can't I make a level for this? Now we will see for this. Okay, see for this which is your one and turn off the column and this is the how to. Now this can go to any raising, can go here, can go. This is a forest, this is life, but religion can go, this is a forest, this is life, but religion can go, Rohan Column, now we will check this layer and column for blood, otherwise it would have been ours in a few moments, what will we get, look at the destination, when we are on it. This definition will be found on and by whom and will be found on the level. Okay, so lick this helpless Amla tree, we have found this problem, we will take it out and we will go in this direction, according to this section, i.e. and we will go in this direction, according to this section, i.e. in the East direction. So what will this be? If you have got the third examination, then what is its mission? Yes, the level will be medium, and I will explain the code here. Okay, and I will explain it in the court. Look here, now see what validation is there for this. We have selected here that the Rohan column is the tweet arrangement here and which is our total row and column, this is the main in the same total rotal column, my tab is fine, will we alert you, what is your pattern, what is it, through which Chilli one has to be done if kidney which is end column also kirtan thing which is and which is your laddan m requesting him and see in Kollam laddu request is end forget poetry and when your expenditure on enroll pen is like that then it is valid pass of Air Chief If it is tight then what will we do in that condition, we will do it through here, if he folds here, this is what we are checking that the index we are on, through which we check the element, is it Maharaj Valentine part or not, is it a valley element? If it is there or not, then we will check it. We will check it here. Now let us come to the main lead character. First of all, we will check it. What is life on V0, if it is here that our friend I was sold, there is one, but ahead. So can it increase or not, what will we do - we will do 110, now what will we do - we will do 110, now what will we do - we will do 110, now this is our 8 direction, one directional direction, we have taken it here, in which direction we can face, okay, we have taken this, now what will we do, why will we take it because What should we do then we are inserting the row and column, so what will we do, why will we make it happy, now first, this is ours, this is our left corner, this is ours, this is your side, so now what, Guru, set this in here and done next. Churn it or not, let me assume its box as oven value and you ca n't express it by it. Okay, so I did one and the answer is here we will set it according to the total in the beginner's here from the experts here we have Row and Column have taken 21 volumes including N. Now we will check why there is no reminder. There is no entry. After that what will we do. At this level we will take the size of the lining level. The size of I will be zero size which will be dead. Reaction Withdrawal. Will it not happen that if we do violence, then at that time we will be labeled as a plus, it will be a tight one level from the districts, then what should we do, how much of ours is at that level, in what direction is it possible to go for the element of that level. Maybe we will see all the elements, so what will we do, we will take it here because friends will also remove it here, wash it, then we will check what is ours, what we have taken out from here because the element that we have taken out from it, is it the first one? What is enrolled, what is Ma'am's clan, is our enrolled, what is Ma'am's clan, is our enrolled, what is Ma'am's clan, is our destination the last, this is our light record, our destination isn't it, what are its results, what can we drink, this column is suitable for that, if it has its results, which is the answer, which is every level. What will we do, we will do it, okay, now we will not get it, we will review, now we will check how much possible direction cannot be taken, okay, we will check one by one for the side reactions of the added, okay, then sexual plum with for all. Will check the cake and will also check this first, if the IA is valid, if the bully will do something to them and will stop to ask, they can say route visit or the doctor will give a box, mark it here as one, let the IMC know this. Now your answer must not have been returned anywhere. Listen, finally what will we do here - We will do 110 about the finally what will we do here - We will do 110 about the finally what will we do here - We will do 110 about the rights, we submit it is done, we submit it has been submitted, thank you.
|
Shortest Path in Binary Matrix
|
maximum-average-subtree
|
Given an `n x n` binary matrix `grid`, return _the length of the shortest **clear path** in the matrix_. If there is no clear path, return `-1`.
A **clear path** in a binary matrix is a path from the **top-left** cell (i.e., `(0, 0)`) to the **bottom-right** cell (i.e., `(n - 1, n - 1)`) such that:
* All the visited cells of the path are `0`.
* All the adjacent cells of the path are **8-directionally** connected (i.e., they are different and they share an edge or a corner).
The **length of a clear path** is the number of visited cells of this path.
**Example 1:**
**Input:** grid = \[\[0,1\],\[1,0\]\]
**Output:** 2
**Example 2:**
**Input:** grid = \[\[0,0,0\],\[1,1,0\],\[1,1,0\]\]
**Output:** 4
**Example 3:**
**Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,0\]\]
**Output:** -1
**Constraints:**
* `n == grid.length`
* `n == grid[i].length`
* `1 <= n <= 100`
* `grid[i][j] is 0 or 1`
|
Can you find the sum of values and the number of nodes for every sub-tree ? Can you find the sum of values and the number of nodes for a sub-tree given the sum of values and the number of nodes of it's left and right sub-trees ? Use depth first search to recursively find the solution for the children of a node then use their solutions to compute the current node's solution.
|
Tree,Depth-First Search,Binary Tree
|
Medium
|
2126
|
1,773 |
That Aapke Ajay Ko Hua Hai Hello Everyone Welcome To New Video In This Video By Going To Discuss Nazar Problem List Code Problem In This Account Items Matching Rule Knowledge To The Problem He Problem Items Where Items By Tag Color Subscribe And also give you strength and rule 's 's 's item, subscribe, definitely one of the following is in the form, if any of the conditions are met, then what will happen to our item, condition, if there is more of the rule, then this is our condition, if they have color and they have fringes, then There will also be a match and if their name is there and the rule has been deleted by Velu then still our condition will be two. Ok return the number of the match by how many runs in the match. Ok so first of all we see the items which are before that if If you look carefully at the items which are our items list, if you look at this, here we have to write our functions. If our items cannot be done by the union, then we will use some of its functions for that, like we use them here. We will have to use this function to get the square feet but here we will have to use dot net. Keep these two things in mind. Apart from this, we need one more thing here. What do we do? So let us compare it. Let us compare it. By 2030, that thing is subscribed, if by value, if subscribe, this can be our one time because if we do this position, maybe ABC will be subscribed, if we have an appointment here, then we will not check the references, so that's why we need double equal key. If you want to use more cotton in one place, then this should be done. Keep in mind, what do we have to do now, if I show which is our channel, subscribe item, this is our, then first of all, we are our today's subscribe, this is 0 of 10, our tummy, our electronic color, then Altice Kayan. Tower type color and then subscribe Now what do we have to do in this, here we will take A half, first of all, instead of the rule, we have to rule that in these days only, if there is any power type, then there will be color, then there will be N. Okay, so if we Let's take an example, if ours will not be that, after that some rule value will be given. Taking the rule, we will give Ram develop and what we will do is we will subscribe and in this we will subscribe for 100 items if we have 100. Whatever you get, we will return it, so the appointed items are something like this, first of all, what are the first shades in it, what is the limit for loop in axle for next, our jhalu will hit the pixel, okay, what will we do in it, pure computer cylinder. That computer is silver, it is fine, it will be appointed in life and this is how we have given here some of our items, after that we will quote the rule that has been made in the appointment has been made in that, first of all we will check that our rule is that Whose call rule that if we get the result of this can be any three persons type subject if type more and check the for this if he is killed then we our house if I for this then definitely subscribe here and Every time we will subscribe to its color, we will assign it to this village, now again we will eliminate the items in the village, we will make another one and we will return it, okay now let's go, their objective for this will be something like this that the most First let us check that our rule which is if it is our equal subscribe then subscribe us which people do not wash till subscribe item if our which this our if our which this item if our if item if our us for type that young considered a that if this Our dot becomes equal. Whose dot becomes equal? If this is our Whose dot becomes equal? If this is our Whose dot becomes equal? If this is our ghagra then what we have to do is increase our answer by one. Before that we will have to make this answer here so enter first if it is not our rule then we will check. This is necessary for us, if this is a red colored village at any of our places, subscribe, here one thing has to be changed instead of items for 1000, then we take this items dot, then what will happen, want equal, whose equal rule. If the value is finished then we will cut it. Answer plus ok and this will be our finished. Now inside this we have to check that our solar forgot to write call here so yes our item size is something like this. This note of ours is of gold color which is ours which is going to come plus till 2018 and here if our which our item daughter forgets this place of this place then the biggest will give the items of the village returned Gauhar how much awakening has to be done and the rotting hormone is applied This is what we will do with the rule value, we will give a big one to the answer, it is okay, like our three conditions will be eliminated, we will be treated, we will return it, there will be time complexity for this, if we whatever is ours, whether it is our color or it is Our 40 subscribe, here we take its code in any new form on the grater, then what we have to do on our printer, first of all, create a variable answer which we will keep zero, then what we have to do, then we have this To check our rule, if it becomes equal to whom, if it becomes equal to us, TRP type till August, then what we have to do is to run a loop inside it, from where to where, it will continue till 2030. If it's going to be the items, then the items that we will use here, so the items and we will cut it and what we will do inside this is we will check that our if our items, we will use Robert Gates here because here we have the lace. There we have it which will not work with a square packet so dot net come on now which index of the rectangle do we need if the type of the rectangle is zero then it is okay then dot net 0 home this becomes our equal if this is our It becomes equal, it becomes ours, if it becomes ours, then we do, we subscribe to our inner and this, we keep clicking on continue, if it becomes ours, then our rule is that equal pay for equal to is good. Okay come, you know if our rule is not tight for a moment then what will we do that now our house becomes exactly what is the rule of what makes us equal this time dot equal to jhal if this becomes our equal color CEO AOR So what do we have to do, we have to run our same follow again, we will do the same thing here, I paste the modification in it, here we subscribe to this , , , like our rule is that even if the color is there, then we are not getting it. We are in the village, what do we have to do inside the voice mail, inside this again we have to paste the same for all and item don't get it didn't get what to do at this time break it okay we will cut it like finish It is done, we will get the answer and what will we do? We will do it by submitting a solution to the answer. Here this is our acceptance of this curse of this test, chilli and what is the result that Reddy and this is our successful Iran. Which is faster than fifty percent of Kodak, that is our list which is using memory. Try this question to understand the solution from 50% people. This Try this question to understand the solution from 50% people. This Try this question to understand the solution from 50% people. This was a simple solution. Apart from this, if you have any doctor then you can comment in the comment box below. Answer: Please subscribe as soon as possible and if Answer: Please subscribe as soon as possible and if I have subscribed or if I had subscribed before, then this is the speed, this is our internal structure, it keeps on changing, hence, you must, therefore, if you want time complexity, then it does not matter, that is Bigg. Boss, this difference should not be hidden, our judge is talking about how much time, then you understand how things work. Thank you for watching this video
|
Count Items Matching a Rule
|
percentage-of-users-attended-a-contest
|
You are given an array `items`, where each `items[i] = [typei, colori, namei]` describes the type, color, and name of the `ith` item. You are also given a rule represented by two strings, `ruleKey` and `ruleValue`.
The `ith` item is said to match the rule if **one** of the following is true:
* `ruleKey == "type "` and `ruleValue == typei`.
* `ruleKey == "color "` and `ruleValue == colori`.
* `ruleKey == "name "` and `ruleValue == namei`.
Return _the number of items that match the given rule_.
**Example 1:**
**Input:** items = \[\[ "phone ", "blue ", "pixel "\],\[ "computer ", "silver ", "lenovo "\],\[ "phone ", "gold ", "iphone "\]\], ruleKey = "color ", ruleValue = "silver "
**Output:** 1
**Explanation:** There is only one item matching the given rule, which is \[ "computer ", "silver ", "lenovo "\].
**Example 2:**
**Input:** items = \[\[ "phone ", "blue ", "pixel "\],\[ "computer ", "silver ", "phone "\],\[ "phone ", "gold ", "iphone "\]\], ruleKey = "type ", ruleValue = "phone "
**Output:** 2
**Explanation:** There are only two items matching the given rule, which are \[ "phone ", "blue ", "pixel "\] and \[ "phone ", "gold ", "iphone "\]. Note that the item \[ "computer ", "silver ", "phone "\] does not match.
**Constraints:**
* `1 <= items.length <= 104`
* `1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10`
* `ruleKey` is equal to either `"type "`, `"color "`, or `"name "`.
* All strings consist only of lowercase letters.
| null |
Database
|
Easy
|
1338
|
368 |
Hello everyone welcome back to my channel I hope you guys are doing well and today we are going to solve a very interesting problem Largest divisible subset its difficulty level is medium First of all we understand the question that what will we have to do in this we have to do a The given array will be of numbers n size, we have to extract a subset from it. Subset means to create a new array by choosing the elements from the given array, then we call it subset. We have to generate a subset in which a condition. It should follow that whatever we pick two elements from it and make a pair of them and find out their mutual modulus, the result should be zero. What does zero modulus mean, that they should be divisible, like the output we got in this case is 1 2. Only one pair can be formed in this, pair can be formed 1 2, then either this condition should be satisfied or this, then when we take the module of two, from one we will get zero, so this condition is satisfied, it means. That this pair of ours is correct, if we want, another pair could have been formed in it 1 3, then its size would also have been two, its size would have also been two, so what did we have to generate, if there are any multiple solutions here, then we will get a return of any one. All we have to do is now if we look at the second one, the output we have is all 1 2 4 8. Now if we make any pair out of these, it can be 1 2 1 4 1 8 or 2 4 2 8 or Then 4 8, all these pairs will divide each other completely, so this is our output. This is the correct output. If I take an example, in the example, if we had the array one 4 8 10 and if I give 8 10 in the output, then this is the output. This is not possible, so when we divide 10 by 8, its mode will be equal to zero, and when we divide 8 by 10, we will have its mode 8, so this is also not zero, so it means That this cannot be our art, now this is the explanation part of it, now we are going to move on to our explanation part, first of all we may face the problem of identification, so if I was on this index, I would have said that I have First of all, if I am including one because I have to keep it in my subset, then I would add it only when I am confirmed whether it is completely divisible or not, then I do it like this: is completely divisible or not, then I do it like this: is completely divisible or not, then I do it like this: Modulus equal to 0. I would have to do this and check each and every element before including it in my pair. Now a pair would be formed if you included one. Then a pair could be formed. When you exclude one, where would this thing come? Recurs comes in Recurs, if you are not clear that in which questions you have to apply Recurs, then its very basic fund is that wherever it happens, you have to confirm whether you have to choose the value which is there in the question. Or don't do it. If you get this confirmation in the question then in such a case it is 100%. What do you have to put the correction? So 100%. What do you have to put the correction? So 100%. What do you have to put the correction? So here we have pay array nut 3. In this we have the choice whether we will include one or not. If we are doing then will we include two with it or not then it comes to us as a choice, so this is its naive approach. Now how big was its tree, we would have two conditions that we have included one here and If we had included one, then we would have gone to two. Then we would have had a chance whether we should include two or not. If we had included, then we would have gone. Should we include three or not? Same if we had If we did not include two, then we would have had the choice whether to include three or not. If we had not included one, then again we would have seen for three, in this also two would have been included and if we had done so here, it would have been for zero. Even if we don't do two more choices, we would have got two choices for each, we would have had a total of Y number of calculations. Now we only had Y size, but if you see how much more calculations we have done, now whenever we want to optimize the ration. If we have to do this then where do we go but if you are thinking like there is repetition happening here that if we include two then we have calculated first that this is the number of parts and the same further when we include two then this is the tree. And this one is a tree bean, so what will come first in your calculation, the operation that we have is doing multiple calculations, we are storing them in some DP, but that too would have become a very big part, if your size here is 10 or so. 20 or the size we have given here is up to 1000 so if we have to go towards some other optimized operation then you must have solved a question. If not then please go and solve it once or at least. Look at its approach. Questions of Largest Increasing Sequence. Now I will explain to you the logic behind the concept that I am moving forward, like right now we had an array, here we have P, so what do I have to do first of all? I see one thing was that if I had an array, first of all let's understand that if I had the array sorted then only what I had to do and if I had the array in unsorted meaning sorting was not in increasing decreasing order then What approach do I have to take? So let's first start optimizing our solution from here. If we have say one, two and three, then what benefit will I have in this? It will be up to you whether you want to follow this or not. I am not doing it, but surf, I am explaining both the conditions to you which will make it easy for you to solve this question, if suppose I am here to pay, if I can find out this thing till this point, how many numbers off before this. There are elements which are dividing by two, then what condition do I have to impose? I have to check whether one is dividing by one or not. Before this, let us understand one more thing. We had two conditions given that A module is B. E should come 0 or else B modulo A e E e 0 should come. Now what is the condition according to this case we have that B which is either smaller or E is equal to A and what is the condition according to this case I have. That this is smaller and equal to b, so this is the condition that I have these moduli, now either I have if the array is unsorted, suppose I have 2nd and when I have to check between these two pairs then I have to apply both these conditions, A module B also has to be checked and B module A also has to be checked whose value is zero but if I have sorted array then only what do I have to check if I consider it as A and consider it as B. If I agree, then just what condition do I have to check that a b module a to e 0 then my only work left is to sort what I have chosen here, that means it is not compulsory, only if you want. If you want to reduce your time complexity and reduce the number of operations, then you can sort your array and same if we talk about this tree, now we had the array in sorted order and along with the sorted order, what do you check? What has to be done is that if you were including three, here you would have to also check that the elements which are previously included in the array are also divided by this three among themselves, then you would have to see all the conditions, so if Rick and this particular approach If we follow then we come to the problem of time limit action as the number of operations increases, so now we have an approach, that is, the solution we have found is that if we decrease our time complex. So what should we do after sorting our array so that the number of operations will be reduced, so many things, I hope it is clear to you, now let us move on, now what do we have, it means that whatever elements will be there will always be increasing. If we get scared, then let's go with these elements one by one. Now what did I check that when I was on this index, there was nothing before it, so what did I do that all the cells would be divisible by themselves, that means that Whether I take one module or two modules or three modules, everyone will give zero to each other, so what can I say that I give one level to everyone, because of such one and one value, in the beginning you will get things later. It will become clear when I give you the complete explanation. In the beginning, you can assume that I am giving one to everyone. Further, how will I approach it, that when there is no previous element before one, I will not make any changes in one, then I am assuming that right now I have module one and a pair is being formed from module one. Now when I am going here to the index of index number two, then what do I have to check that in its previous one it is like this? What is the number of elements with which to can be included in my array so what will I check I will check if this is my i position then I will run a loop from z0 to a to check this To find out which number of elements are including 2 in your array and the array whose previous size is the maximum, I will include 2 and later on as the array increases we will tell us accordingly. It will be known later that the size of which array is maximum. Now let's start with another example. To understand, suppose I take a slightly bigger array and I took the array here Pay One 6 8 12 15 Now what do I do? I will create a D gym and store it. What is the maximum length I am getting till that particular element in which we can include it. Did I tell you in the beginning that I have to treat everything from one to the other? Now first of all I came here. I do this 0 1 2 3 4 5 6 When my Aa was zero, I got Aa 0 2 Lane Aa, this loop of mine will not run now my Aa has become one, now when my Aa became one, I got J If I had to run the loop of rote lesson one, then I would run it only to see that the one preceding it is dividing it, not doing this, whether this mud is zero or not, so now when I do it, I will check the condition that my D p of aa if that lesson is d p of j psv and also what will I check for a condition that d p of i module d p of j i is dividing into easy for di and to check this its To increase the length, just to check the condition that our length will exceed and will be maximum, only then we will increase it, so we checked that the two module is divisible by one and the dep of two is one, we have the dep of One and deepv plus one, we have two, so I will increase it to two, this means that I can include one and two together in my array, now this was its maximum, it went till this time when we have this equal to i3 then my loop will run for j0 and for jv Now I checked that it means that I can include one and three together then it is greater than one so its length becomes two Now then I went If there is no module 3 to zero on two, then I will not check now. No, I will not update this. Then I moved it forward. On six, one and six pairs can be formed, so it is okay, I have increased it to now. When I went, what is to pe, its length is already two, so d p of 3, what is less then d p ofv pv se, so yes, it is less then it means we went to two and saw what was the maximum array of to till. 1 2 And as soon as six came, I can include it in it, so what I did was updated its value three, now to check on three, from three it saw that dp2 + 1 is greater than dp3 so dp3 dp2 + 1 is greater than dp3 so dp3 dp2 + 1 is greater than dp3 so dp3 How much is 3 and what is this 2 + 1 3 So that's How much is 3 and what is this 2 + 1 3 So that's How much is 3 and what is this 2 + 1 3 So that's not so what we thought was we could include ths but we already have a carry made of twos that have the same length so right now we'll just make it three We will keep it only because its length is also three, what is the maximum that we have to store, what is the maximum length, here again we come to at, then at is divisible by one, so first its length is two, then it is divisible by two. What is the length of two? Two is included with two, this will not happen with three and six, that is why we did not update this. Then we went to f pe f we did not update this. Then we went to f pe, what is 12, so first its pair becomes 1, 12, then its length becomes When we came up with 2, what 2 already had was 2 and if we included 12 here because its length was 2, then we divided 2 into 3 and then we had 12. If we went to pay, we would have already done one's 3 12, this also had its length, so we did not update, then we came forward, what did six have, six already had pair 1 2 s and 1 3 6 if. If both of them can be added to 12, then its maximum length becomes four. But which one are we talking about? It is updated from here, it is not updated from here because if its length was the same, then in the case of four and four five, it would be divisible by one. So the length of two is then divisible by three. What was the length of three? If we add two to the three then its pair tooth will be of three size. Now when we will be updating it, along with this condition, we will also give a maximum value. We will store this so that we will not need to traverse again what is the maximum length in this entire array, so when we keep checking the condition, we will first store that if our max i means maximum length is smaller than what we have right now. The length is formed from the depth of J, so what will we do? We will update it to the maximum i. How much length do we have? From the depth of J, we also have the maximum length, but now we have known how much, which will be such a subset? Whose maximum length will be found, we have found out, we have made the condition that the array will be in sorted order. Now what we have to do is just store the element and see it. So now what will we create a previous array and will we select which value will come in it. If we are updating the value, then let's understand the same example again, tooth 12 8 12 and here 15, so now we will create two arrays for this, one will be D and one will be I will have the one to store the previous value. Now what did I do? First I will store the previous one, it cannot be previous and now I will initialize it all by -1 and here I will initialize it as Navv. Now what do I have to do, here now I have to check whether the depth is This will remain one, what identification have we done for this 1 2 3 4 5 6 Which index has updated this from zero, now we have gone to three, the length of three has become two, who has updated this, zero length has become the 1st pair When we went to six, first the length on six came to two, then we updated it from one to zero index so that one and six became a pair, then it comes to two, it is also divisible by two, its length came to three and who updated it? One index has done that the length of three also comes to three and it is not updated from three already, so we have included only the index of one, now we come to A, if it had been from one, its index would have changed to zero, then two would have changed from this. If it had been updated by one, then who updated it? Now after this, it is not updated, nor does it divide by six. If 12 comes to 12, if it was updated by one before this, then its length would be zero index, hence it would be two. If there was an update then three length index one, after that it would not be updated from our three because in three also the length comes three and in two there is already three, then when we come to six, then after updating it from six, here what was the length of three, then this It becomes four and who has updated it? Now three has updated it. Then we checked that it is not divided by eight. Then we move forward and 15 on 15 is divided by one. Length two index zero. Then it is not divided by two. Three. The length is divided by three index two. Then what else to divide then the array of DP that we would have become one two 2 3 4 3 and this array would have become we have human 0 1 3 2 Now what do we have to do? We would have also got our maximum length. Maximum length or maximum. On which index we are getting the value. So 0 1 2 3 4 5 So assume that we have got the value in max i. On these five indexes we have the maximum value. So whatever element will be here, first we have to store it. What was the element here? 12, so 12, we put it in that and updated the max i from its previous, now you go to three, what is the value on three? If the value is six then we have included six. What value is there in it? One then go away. Now go to one. What value is two then we have kept two. What value is there in it. Zero. Now go away. Zero in the index. What is the value of P? One has come to the value of my. So as soon as we have the value of max aa, we will stop our loop. So this is going to be our entire approach. Let's write the entire algorithm again. The first step is we will have Sorting the array: By sorting the array, we will have Sorting the array: By sorting the array, we will have Sorting the array: By sorting the array, we will have a DB. An array will be created to store the previous index. The maximum value will be stored at which index. We will create an array for our result. We will be done. Then we will run our loop. Then we will We will run the loop 0 lesson aa whatever the index will be then what condition will we check in it that whether our depth of aa is zero if it is yes then we will take end and check whether its length is big. The length of D will be shorter than D Psv. If yes, then what we will do is update it in D P of I. D P J Psv. After doing this, what will we keep checking along with our previous index? We will also keep storing what will be stored in the previous index. We have the one who is dividing it. Also, to store a maximum index, we will check whether the DP of Maximum I is smaller than the Deep I. If so. So what will we store in our maximum i? After this much work is done, we will have the previous array and deep ready. What will we do after that until we get the maximum index? Lesson i remains equal to zero. If you impose a condition then it remains minus plus, till then what will we keep doing in our answer or result? Whatever numbers we have or array, what is the value in the maximum index and how will we keep updating the maximum index? Previous of maximum index, this will be our algorithm, finally we will return later, you must have understood the thing, now let us move on to its coding part, whatever we have written in Ethereum, we are the first to code, we got the work done, we calculated the length. Lee, after that what we did is sorted our array. What we did after sorting the array is that first we will declare all the values that we require, we created D declare all the values that we require, we created D declare all the values that we require, we created D which we gave its size which was equal to the stem size of A. Then we created a previous Re previous result what created new int a and also what we did here is try to fill the array off it with d with dp what was to be treated with no then we filled the array with array dat and fill the previous with dine minus and After doing so much work, we created an index, maximum index in which we will store and in it we will store zero. Now starting maximum zero is zero index. We have imposed the condition that if our is equal to zero then simply return new array list if not. So after that create your result list enter new list What we will do after this is we will run our fo loop which will go from i zero to i a then what we will do in this we will run the loop int j0 burn a and j Increment will keep happening then we had to check our condition in which we were checking whether dp of a module dp of z is 0 and also we were checking dp of a lesson should be p of zp if If both of these conditions are satisfied, then we will increment the DP of A by OFF Z and store it in the previous. Then what we will check here is DP of Max I. This is to update the maximum index in which we will store. We will make DP aa if this lesson comes dp of max aa lesson dp of aa then we will store our index aa in max i. After this what we had to do is we had a while loop then in our while loop we had to check that our Pass if maximum index less greater than equal to 0 minus did not come then what we had to do was to add to our result d p of max a and also update the value of max i d previous of mix i and lastly this After doing this, we had to return the result. Let's check the code. Our condition must have gone wrong in this one. So what did we have to check in this one. We also put D in Nums. We had to check whether our Y but Nums would have passed in the first case. Now here also we have a problem, we have maxed out the DP, we had to store the array that we had, now it is coming fine, let's submit and see, it beat 75 here, if you can optimize it a little more. So try it, if you find any good solution then write in the comment section. If you liked this video and found it informative then please like the video, share it and subscribe the channel. Thank you so much.
|
Largest Divisible Subset
|
largest-divisible-subset
|
Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies:
* `answer[i] % answer[j] == 0`, or
* `answer[j] % answer[i] == 0`
If there are multiple solutions, return any of them.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[1,2\]
**Explanation:** \[1,3\] is also accepted.
**Example 2:**
**Input:** nums = \[1,2,4,8\]
**Output:** \[1,2,4,8\]
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 2 * 109`
* All the integers in `nums` are **unique**.
| null |
Array,Math,Dynamic Programming,Sorting
|
Medium
| null |
1,832 |
hey there guys this is code tutorial for you back with another lead code problem this one's called check of the sentences pangram so it says a pangram is a sentence where every letter of the English alphabet appears at least once given a string sentence containing only lowercase English letters return true if sentence is a pangram or false otherwise so let's go look at the examples so example one uh here we got uh the string sentence as you can see this the quick brown fox jumps over the lazy dog so it's true uh the explanation is because a sentence contains at least one of every letter of the English alphabet in example two string sentence Le code is false because obviously it's missing a bunch of letters and so it's not a penr and it's false so how can we check if it's either true or false we're going to have to do something where um where we're going to be able to uh acknowledge that all 26 uh English alphabet letters appear at least once so what we're going to do is we're going to use uh a map we're going to use a map with the key being a character because we're going to go through the string so we're going to put a chart and the value being an integer so we're going to put an in we are going to name this map MP short for map so to go through every single element of the string sentence we're going to do a for Loop and with this for loop we're going to be able to map our string out we're going to be able to put all the key values which are the character and see how many of those um letters appear in the string so what we're going to do is we're going to have uh every element is a character so we're going to go character and we're going to name the elements we're going to run through is I and the name of where we're going to check is sentence string sentence so we go so what we're going to have to do is just map it out first that's all we're going to do you're going to map it out first so does what does this what this means is uh through every element so let's say the first uh character in index zero the first element is T so with t in here the key of T we're going to add one up and this is going to go to the value section of the map so if we see T again then we're going to add that one up toy the key value T and there's going to be two and if there's a third one there's going to be three etc for every single let's say h once we get there to the next index of one um and this uh string is going to be the characters H so we're going to map that out and so on and so forth so now once we have uh have the string all mapped out which uh with all the character key values and how many times they've appeared if we have 26 letters then the size of the map should be 26 so what we do now is we're going to check if that is true or false and the way we're going to check is we're going to get the map that we have that we've made that's mapped out the whole um string and we're going to check the size of it to be see if it's equal to 26 CU that's how many uh English alphabet letters there are and then we let's run this and see if it pass the test cases and it does pass the test cases I'm going to go to this tab uh show a little bit more detail on how the code worked again initialize a map to count characters a map named MP is created to count the occurrences of each character in the sentence the key represents characters and the values represent the counts so then we iterate through the sentence and count occurrences this Loop iterates through each character in the sentence and increments the count in the map MP the map is effectively used to count the occurrences of each character so as you can see iterations explained for the provided sentence um we have the string that we've been working on the quick round fox jumps over the lazy dog so what's going to happen is as I explained before we get the first index of zero the first element is T So then T we put the currents is one H the currence is one and then e the currence is one and so on and so forth so some might have more than others depending on how many times they've occurred in the string so then uh check if all letters occur at least once the function returns true of the size of the map is equal to 26 indicating that all 26 letters of the alphabet are present in the sentence if the size is less than 26 returns false this is how the code determines whether the given sentence is a pangram or not so if you want more coding Solutions don't forget to like And subscribe thank you
|
Check if the Sentence Is Pangram
|
minimum-operations-to-make-a-subsequence
|
A **pangram** is a sentence where every letter of the English alphabet appears at least once.
Given a string `sentence` containing only lowercase English letters, return `true` _if_ `sentence` _is a **pangram**, or_ `false` _otherwise._
**Example 1:**
**Input:** sentence = "thequickbrownfoxjumpsoverthelazydog "
**Output:** true
**Explanation:** sentence contains at least one of every letter of the English alphabet.
**Example 2:**
**Input:** sentence = "leetcode "
**Output:** false
**Constraints:**
* `1 <= sentence.length <= 1000`
* `sentence` consists of lowercase English letters.
|
The problem can be reduced to computing Longest Common Subsequence between both arrays. Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array. Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n).
|
Array,Hash Table,Binary Search,Greedy
|
Hard
| null |
43 |
Hello Hi Everyone Thoda We Are Going To And Make Multi Product To Idhar Aa That Is To Give Another Form Something Specific Converted Into The Form Of A 220 S2 Cost Multiple Edifice Number Dial Numbers Schedule Yahan Diary Nahi Aa 2015 TV Channel Which Word Between To Do We Are Dividing It Can We Make In The Question Result Set 10th Alarm That Bigg Boss Wonder Android Adhikari Anil Terminal-3 Subscribe To Anil Terminal-3 Subscribe To Anil Terminal-3 Subscribe To 128 Divided In Recent Times And With U 209 2108 210 Career Is Vansh Animals Live In The Forest Minister A Shri Ram Aur Decide 1232 Pieces In Love With U Hey Yaar Tension To Strings In Home Number 212 That Tender Making Answer Chapter Siding Subscribe To That Rani Bana Edition For The Number Nine Size Abhi 1234 A Sense Of Security Force Loot Lo That Nakul this is the ki unauthorized slide answer hai shri ram bhaiya de kintu us aaye send phone number one and intrigued from 11am phone number i serum is the new answer chapter vitamin number two also Come I Plus Gel Ram Ita Dj Plus One Divide Career Question On This Is Dividing Road Volume Un Hello Friends Family Zinc Dros Report Ignore Tribes Of Writing Is Transformed Into A Converted Into A That This Is Transforming Wedding Loot Interesting 2002 That This Is Converting The Of These Things To Train Your Wedding Zero Figure Story From This Ep 9th Complete Is The Same Time Result That National Core 's Juice Public City Of This Point Is The Size 's Juice Public City Of This Point Is The Size 's Juice Public City Of This Point Is The Size Of This Is The Number Two Increase This Missile An Immigrant The World In The First Time Total Of the day
|
Multiply Strings
|
multiply-strings
|
Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`, also represented as a string.
**Note:** You must not use any built-in BigInteger library or convert the inputs to integer directly.
**Example 1:**
**Input:** num1 = "2", num2 = "3"
**Output:** "6"
**Example 2:**
**Input:** num1 = "123", num2 = "456"
**Output:** "56088"
**Constraints:**
* `1 <= num1.length, num2.length <= 200`
* `num1` and `num2` consist of digits only.
* Both `num1` and `num2` do not contain any leading zero, except the number `0` itself.
| null |
Math,String,Simulation
|
Medium
|
2,66,67,415
|
75 |
hey everyone welcome back and let's write some more neat code today so today let's solve sort colors this is a pretty good problem i actually really like this problem we are given an array of nums and they give us a little bit of a description like each number each you know value in nums is a color but let's just skip that because i think it just kind of makes things a little bit over complicated so let's think of it simply we are given array of nums n values in this array any of the values could be of three different integers each value could be a zero one or a two we want to take this array and then sort it in ascending order right so let's say this is the input array we want it to be in ascending order zeros first one's next and then twos right pretty straightforward but there's many different ways you can solve this problem with varying efficiencies and varying memory complexities so they tell us right off the bat we can't use like a library sorting function because of course library sorting functions run in n login time it would just be a single function called just call sort on this array but i guess we could implement our own uh sorting function which would also end up being n login whether you do merge sort or i think quicksort also has the same average time complexity right so we could implement our own sorting and then do it in n log n time but we can see that this problem is a little bit more simple than just a regular sorting problem because we are given only three values in the array only three potential values so if you've heard of the algorithm bucket sort then right off the bat you're gonna think yeah this problem can be solved with bucket sort in linear time we can sort this input array in linear time reason being is we know that there's only three different buckets if the values ranged from zero to you know n where n could be an arbitrarily large value then of course we could not do this in o of n time but we know the values are only going to be between zero and two we can do bucket sort now what is bucket sort and how are we going to use it to solve this problem in linear time well we're going to say we have three buckets one a zero bucket a one bucket and a two bucket and for each of these buckets we're simply going to scan the input array and count how many of each of these values occur in the array so yes we are going to need extra memory but really this is just going to be let's say a hash map or an array of size three right this is just gonna be an array of size three so we'll count how many two so we have a single two so far we have a single zero we have another two so let's say the number of twos is two then we get two ones so yes we have two ones and then we get another zero so in reality we have two of each of these values now we want to build the output array but we are not going to create a separate output array they want us to do this in place we can see up above so what we're just going to do is since we know we have two zeros let's just go at the beginning first two values cross these out replace them with two zeros just like in the output array again we're gonna so now we're done with the zeros portion right we took two zeros put them at the beginning next we know ones go right after zeros so we're going to take these two ones put across cross out these two values right and then add two ones right after the zeros and the exact same thing with the twos right we have two twos so that's going to make up the remaining portion of the array we can place those two twos at the end right so we're over writing this memory so we're not actually using extra memory or anything so this is a of n time solution and o of one solution this solution in terms of complexity is about as good as it gets but this is such a trivial solution that i'm actually going to show you the slightly more hard solution which is actually the one pass solution we can see in this case we actually did have to go through the entire input array twice once to create these buckets and then wants to actually build the output array but we can technically do it with a single pass which is a slightly harder solution that's what i'm going to show you today and that's what we're going to code up so before i show you the solution my first question to you is have you heard of the algorithm quicksort in particular do you know the portion of quicksort that requires the partition algorithm do you know how to partition an array for example you know let's say we had an array and we wanted every single value n value which is less than five to go in the left portion of the array and if we did that let's say we had an array of like we know one two six seven right these values we wanted the values that are less than five to go in the left portion of the array if we did that what does that mean well that means we took these values put them in the left portion of the array now if we did that by swapping values around if these two values are over here and let's say the size of the array is four values these original four values if we took these and put them in the left that means by default these two values which are greater than or equal to five are going to go in the right posit in the right portion of the array by default right that's called partitioning an array that's the same idea we're going to use here so remember how we want the zeros to go at the beginning we want the ones to go in the middle and twos to go at the end so let's partition the array using the same idea we're going to go through every single value in the array right in the example array let's say and every time we get a zero the way this partition algorithm works is we have a single pointer at the left right it's basically we're going to call this let's say the left pointer right it's designated beginning all the way at the left we're going to have another pointer i which is just going to be running through the entire array any time we get a 0 value we're going to take that 0 value let's say it's from over here we're going to take that zero value swap it with the value that's over here right the value that's over here is not going to be a zero right so for so whatever it is maybe it's a one maybe it's a two either way we're going to swap it put it over here and then that zero is gonna go over here so then once we have a zero value here then we can take our left pointer and then shift it over here right because then we know that the next time we encounter a zero we wanna put it in this position now of course what happens if the first value by itself already is zero then we're gonna end up swapping it with itself which is perfectly fine and then we're gonna take our left pointer and then shift it here anyway so it works out in both cases so let's say we do that let's say we run through the entire array what's our oregano look like well in this example we'll have two zeros being at the beginning but then we'll have the remaining portion just being some ones and twos in some arbitrary order right we don't know about the order of these so we successfully partitioned the array we got all the zeros at the beginning right this is one partition now we still need to like partition this right we need to put both of these ones at the beginning and then take all the twos and put them at the end right but remember if we do it like this then we are doing two passes right it's technically allowed but our target was to do this in a single pass so let's maybe try to modify this partition idea how about we take all zeros put them here using our left pointer but why not have a second pointer which is always going to be at the right let's call it our right pointer and then any time we encounter a 2 we put the two over here anytime we encounter a zero we put the zero over here we shift our left pointer accordingly if we end up putting a two here we take our right pointer and shift it accordingly to you know the next position so this idea is definitely going to work but there's just one edge case we have to worry about and let me just show you that edge case let's say we got to some random scenario where our left pointer is going to be over here designating to us that everything to the left over here is already a zero right that's of course what the left pointer is gonna tell us if it's over here that means everything over here is gonna be a zero that makes sense and our right pointer is gonna be over here which is gonna designate to us that everything to the right of it is supposed to be a 2 which makes sense that means there were some arbitrary 2 that we found in the array we moved it over here and then we took our right pointer and then shifted it by 1 over here right and every time we encounter a value like we have our eye pointer over here we're gonna put this wherever it needs to go and then we're gonna shift our eye pointer to the next position right but there's one thing that we have to worry about take a look over here our left pointer could be pointing at a one value right because if we encounter a one value we're just gonna skip it right then our i pointer could be over here let's say our eye pointer is here in this example our left pointer yes could be pointing at a one but notice how our left pointer is never going to be pointing at a two because if it was we would have already swapped it and put it towards the right because see how our eye pointer has already passed this position so if it was a two we would have already swapped it over there since it's not that mean that must mean it's always going to be a one which is good for us but you'll notice with the right pointer you know everything to the right over here is gonna be a two but the right pointer could be pointing at a zero or it could be pointing at a one or it could even be pointing at a two maybe right and if it's pointing at a zero that's going to be a problem for us because watch what happens now our eye pointer is over here we see a 2. what do we do with twos we swap it with the right position right so let's perform that swap let's cross this out change it to a 0 cross this out change it to a two then we're going to take our right pointer shift it over here right which designates to us that these this portion is going to be all twos that's perfectly fine and now we're also going to take our eye pointer and then shift it to the right but now notice what we just did to our array see how the zeros are not all the way at the left right we took a zero and then moved it into the middle of the array so the reason i went through this long explanation is basically to tell you is that if we take a value and swap it with the right pointer it could potentially introduce a zero in the middle of our array which is something we don't want to do so in that case if we do that we don't want to shift our eye pointer so what i'm saying is if we ever encounter a 2 value like this one yes we're going to swap it with the right pointer but in that case we're not going to increment our i pointer that's not going to be the case if we find a 0 and then swap it with the left pointer because our left pointer is only going to be pointing at a 1 value so if we take a 1 value and then introduce it into the middle of our array that's perfectly fine because ones always go in the middle but we can't take a zero and put it in the middle that's not gonna work so that was a pretty long explanation but i hope that you do get the idea the code is gonna be a lot easier so let me just run through the rest of this example so we encounter a 2 so we are going to swap it so we're going to put the 0 here we're going to put the 2 over here and then we're going to take our right pointer shift it to be in this position and we're not going to increment our eye pointer of course the left pointer is not going to be incremented we don't have to do anything with it but since we performed a right swap i stays the same so now we're going to look at again what value is in this i location it's a zero so in this case yes we are gonna swap it in the left position so let's do that let's cross this out uh put the zero over here and then put the one over here so it's gotten pretty messy but uh ignore that so since we performed a left swap this time we're going to take our left pointer increment it by one so left is going to go over here now and we're also going to take i and increment by one right to be in the next position over here it's going to be at the one we don't have to do anything with a one we don't put it in the left and we definitely don't put it in the right ones are just ignored so then i is going to be incremented one more time until i is in this position and once our eye pointer surpasses our right pointer we're done right because we know that the portion to the right of the right pointer is going to be sorted anyway it's going to be all twos right so now we're done if you take a look at our uh output array it's a little bit messy but let me just kind of draw this it's sorted right zero one two so let's dive into the code now okay so now let's write the code like i said we're gonna have two pointers a left pointer at the beginning and a right pointer all the way at the end which is going to be nums length of numbers minus one and we're also going to have a third pointer i which is just going to iterate through the entire array until we exceed our right pointer so while i is less than or equal to right let's continue so there's two cases we worry about if the value that we're at is either a zero or if the value that we're at is a one so if nums of i is equal to or maybe i said one but if nums of i is equal to two right that's our right case so in both of these cases we're going to perform a swap right since we're doing a swap uh in both of these cases i don't want to write it out so i'm just going to define a helper function up above so we're going to pass in two pointers the indices of nums that we're going to be swapping so let's just get a temp value for nums of i the reason i'm not passing nums into this function is since this function is defined inside of another function we actually aren't required to pass in that variable it has access to any variables outside of it so let's get numbs of eyesore in temp and then replace nums of i with nums of j and then do the exact same things with numbers of j we're swapping it with that temp variable which is originally nums of i so we're just swapping the two values at i and j so that's going to be helpful for us so if i equals 0 then that means we're swapping this with a left pointer so let's run swap on our left pointer and our i index right we're swapping these two values and when we do that we have to remember to increment our left pointer right by one the else condition is if this was equal to two in that case we're going to also be doing a swap but we're doing the swap with our index i and our right pointer right and if we do that then we have to take our right pointer and decrement it by one now in either case remember we want to increment i every single time but remember if we performed a right swap we don't want to increment i so in this case i'm just going to say but if we encounter a 2 remember we don't want to increment our i pointer so in this case i'm just going to do the opposite i'm going to decrement i and that's going to be canceled out by the incrementing operator right outside of it which is going to execute every single time so if we encounter a 1 we're not going to enter either of these conditions but we are still going to increment our eye pointer and then outside we don't have to return anything we just have to modify the nums array in place which is exactly what we did with our swap function so this is the entire code you can see that it's very efficient this is the one pass solution so i hope that you found this helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
|
Sort Colors
|
sort-colors
|
Given an array `nums` with `n` objects colored red, white, or blue, sort them **[in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers `0`, `1`, and `2` to represent the color red, white, and blue, respectively.
You must solve this problem without using the library's sort function.
**Example 1:**
**Input:** nums = \[2,0,2,1,1,0\]
**Output:** \[0,0,1,1,2,2\]
**Example 2:**
**Input:** nums = \[2,0,1\]
**Output:** \[0,1,2\]
**Constraints:**
* `n == nums.length`
* `1 <= n <= 300`
* `nums[i]` is either `0`, `1`, or `2`.
**Follow up:** Could you come up with a one-pass algorithm using only constant extra space?
|
A rather straight forward solution is a two-pass algorithm using counting sort. Iterate the array counting number of 0's, 1's, and 2's. Overwrite array with the total number of 0's, then 1's and followed by 2's.
|
Array,Two Pointers,Sorting
|
Medium
|
148,280,324
|
283 |
how's it going guys hey I mean going over a problem called move zeroes delete code problems commonly asked by Facebook Bloomberg Google and a couple other companies like Microsoft so the problem description says given an array numbers write a function to move all zeros to the end of it while maintaining the relative order of nonzero elements so as an example for given 0 1 0 3 12 again we want to move the zeros to the end so we're gonna return 1 3 12 0 and here if you notice we're actually maintaining the relative order just like they asked so it says we have to do this in place we can't make a new copy of the array and we want to minimize and up the total number of operation so what I propose we do is we basically just walk through the array one by one and we keep in a variable called index to just keep track of where we're gonna place a variable if it's not a zero now once we'd actually gone through the entire array once placing all the elements in the correct order all we need to do is basically fill the rest of the array with the zeros that we've encountered so let's get right into the solution we'll make an integer called index set it to zero because initially we're going to start placing things at the 0th index now we want to walk through the array so for and i equals 0 i is less than nums that way i plus and now we're just going to check if nums i so if the number we're at is not equal to 0 we just want to place this number at work at the index that we're at so we'll say nums of index and we'll say plus so it increments after well set it equal to whatever number we're at so again this just translates to if the number is not a zero we're gonna try and place it at whatever index that we're keeping track of so now once this loop is terminated all we need to do is fill the rest of the array with zeros so we'll continue our loop so for int I equals index now while I is less than number and I plus and we'll just set nums of I equal to zero and so now once we submit this hopefully this works it does awesome let's check out the details and the details tell us we passed 21 out of 21 test cases and we are in the hundredth percentile so that's awesome so this is how you move the zeroes to the end of an array in Java common interview question asked by Facebook Google and other big tech companies I hope you guys have a lot of interviews coming up I hope you guys crush them this was helpful be sure to leave a like on this video and subscribe I hope this helps you guys out a lot and I'll see you guys next time
|
Move Zeroes
|
move-zeroes
|
Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements.
**Note** that you must do this in-place without making a copy of the array.
**Example 1:**
**Input:** nums = \[0,1,0,3,12\]
**Output:** \[1,3,12,0,0\]
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[0\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-231 <= nums[i] <= 231 - 1`
**Follow up:** Could you minimize the total number of operations done?
|
In-place means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually. A two-pointer approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array.
|
Array,Two Pointers
|
Easy
|
27
|
127 |
hello everyone welcome back to sudokoda this is raveena and today I'm gonna talk about the high problem Word ladder uh let's start by reading the question here uh it says that a transformation sequence from word begin word to end word using a dictionary word list is a sequence of words begin word and then it goes through series of changes to h s of K such that every adjacent pair of words differ by a single letter every s of I for I is between 1 to K is in the word list note that the begin word does not need to be in the word list and S of K is actually equal to the end word given the two words begin over and end word and a dictionary of word list written the number of words uh in the shortest transformation sequence from begin word to end word or zero if there is no such sequence exists uh so let's start by actually understanding what the question is here the question says that you will be given a begin word and the N word annual word list so you have to start with your begin word change one letter at the time and then try to get the end word and you have to find the most efficient of shortest transformation sequence to get to the end world and in the end you have to return the number of words that you have uh in order to reach from so let's try and understand uh this simple example here example one uh here the begin word is hit the end word is cog and then this is the word list so the shorter transformation would be the starting word is hit if you change I to O it becomes hot and then if you change the H here to D it becomes dot if you change T to G it becomes stock and then finally if you change D to C it becomes Cog and that is our end word if you look at how many words are there in the sequence it's one two three four and five so this is five words long and hence the answer is 5. let's see how we can approach this problem uh I have taken the same example I have a big inward Inward and a word list the first thing that I'm going to do is I'm going to uh convert this word list into a set because I am going to refer to this list and go through that list many times so it will be better if I convert it into a set so that it will give me a constant complexity after that I am going to create a queue my queue and uh the first thing that is going to be there in my queue is going to be my begin word which is in this case is hit and then the number of worded in the transformation so uh right now there's just one word the begin word I am going to pop that out uh into my word and my count is one my word is hit since I popped it out it's going to get it's going to disappear from my queue uh no when I get my word I am going to check if this is my end word is hit my end word no it's not okay so I'm gonna do my substitutions here uh I what I'm going to do is uh I'm gonna take for the first letter which is H I'm going to replace it with all the uh letters all the alphabets so it's gonna be you know a b c d e f g all the way to Z and I'm going to replace my head to Edge to a b c d e and every time I do this replacement I'm going to check oh this new word that I created is it in my word list if it is in my word list then I am going to create a new element which is going to be my new word so my new word that I've created and my count would be my count Plus 1. because I created a new word I'm one step forward so that's why I'm going to increment my count and I am going to have my new word and append it to my queue so what when I replace a h with every other alphabet I see that there is nothing in my word list that matches okay so okay I exhausted H with all the alphabets I'm gonna move to I once I move to I'm going to replace it with you know a uh h a t you know h b t so basically the middle letter is going to be replaced with all the alphabets so at some point I'm going to reach o and my letter is going to be h o t when I see hot oh hot is in the word list so I am going to create a new element with h o t and then my count is 1 so plus one of my count which is going to be 2 and append it to my queue okay moving forward when I move forward uh I see uh you know anything with oti at some point I'm going to reach h something T and I don't have anything else in my uh list so it's not gonna matter okay I'll move on to T I exhausted I With A to Z I just found one letter that matches and is in the word list okay move on to T I do h i a b c d till z I did not find anything in my word list once I exhaust the whole letter or the whole word I go on to my queue again and pop the first element there so I get rid of this or my calculations on my permutation combination and I get on to my new word is you know hot with count as two since I popped it I'm going to remove it from my queue now I concentrate on my first letter of hot and replace it with all the alphabets so it's gonna be a o t b o t c o t and I get d o t when I create a new word every time I check in my word list and see if that is there in my word list once I reach dot I say oh it's in my word list it's right here so I'm going to create a new element with vot and my count is Count plus one so count will be 3 since my current count is 2. move on moving on I get I you know do again substitutions at some point I am going to reach lot is in my word list I am going to create another element which is you know lot and my count will be count plus one count current count is two it will become plus 1 3 and push it to my queue have you noticed we have two things in my queue and that's the reason this solution works because you know when you create an element when you go through every other permutation combination of that word you are actually taking care of what is the shortest distance and since it's a queue it will give you the shortest distance first and you don't have to worry about finding it through you know even if it would have been you know depth first search it would have been difficult to find out oh how which one was the shortest again so this way you are going to reach the shortest path first right it's gonna it's actually breath first search uh so I added two of uh two of my elements to the queue I move on I go to till z and then I move on to O and I replace everything with o a b c d you know the list goes on then I move on to T I replace all the alphabets with t and if I find anything in the word list I just append it to my queue and increment my count by one whenever pop things out of the queue the first thing that I do is check if my word is equal to N1 and that's going to be my break condition if I find some if I find the solution where I am reaching the end one okay so let's uh try and move on to the code and see how we can write the code so the first thing that I have to do is create my uh Set uh convert my word list to a set so I'm going to do set of word list next thing I need to create is my queue so I created my queue I'm going to append my start letter so my sorry my begin word so I'm going to add my big list of my big invert and then the count now while the queue is not empty I want to do those operations so while my cue is not empty I'm going to pop from my queue so my word and my count would be Q dot pop of 0 and once I get the word first thing check if my word is my end word so if my word is my end word then just return the count if that's not the case then I go and you know do the substitutions so for every I in range of my length of the current word I'm going to substitute you know everything in ABCD so there is there are two ways of doing it you can either do a b c d e f g sorry g h i j o all the way to Z or there's other way of doing it in Python which is string dot s sky lowercase oops a sky lower lowercase and then it goes from zero uh 0 to 26 so colon anything is not before the colon so that makes it starting from the zeroth position to the 26th so that actually gives me you know ABC retail C okay so uh next thing I'm going to do is create my next word here very careful about this it should start with the starting point go to the I so how do you read this in Python is you know this is the word this is the string there is nothing before this column that means that you are starting all the way in the start this I uh is uh basically the ielt index that we are talking about the one that you want to replace since in Python the I that we specify is excluded it really means from 0 to I minus 1 that is included so 0 to I minus 1 that means my I is excluded I want to replace that I with my character C and then I want to have the other part of the word so my other part of the word would start with i plus 1 and then go till the end so this is how you want to create your next word the first thing that you create when you uh you do when you create the next word is check if that next word is in uh my word list so if next word is in the word list set if it is there then create append it to the queue right uh you do next word and then append the next two are and then count plus one since you have moved one step forward your account should always be one or count plus one once you append it to the queue there is one thing that you have to do you have to remove that from the word list that particular next word from the word list because you don't want to encounter the same word again and get caught up in a loop and uh we have to use the word just once so I'm going to remove it so word list dot remove I'm going to remove my next word what's this done if what if I don't find anything I exhausted my Q you know exhausted uh the whole list did any other combination permutation I get nothing in that case I just simply return 0. let's try and see if we can run this okay submit it okay so you see this code is accepted by lead code um so let's talk about the space and time complexity here uh if you look at the time complexity is really you know at one point you are going through though begin word to invert that whole journey and though the whole word list right so that is going to be o of n if you look at it this particular thing for I in length of that word so each word we are going through every letter in each word and then replacing it with every alphabet right if you consider every word to be of length so that would be n into l and you are replacing it with every alphabet alphabets are 26 alphabets right this particular for Loop here this is 26 alphabets so it's gonna be n into L into 26. because you have inverse in the word list you are doing this for Loop for uh each word which is of L length and then you are replacing every character in it so it's like you know inside loop so it's uh n into L into 26. the space complexity however is going to be n because your Q at a particular time might hold all the letters that have that in the word list so that makes it you know o of n I hope this uh this particular explanation was helpful uh if you like my videos uh give it a thumbs up comment below that really helps my channel this uh code is gonna be on GitHub I'll include the link in the description below uh I'm gonna make the same video in Hindi as well so stay tuned for it should be released in three to four days and I'm on Discord so if you want to connect you know just talk or have any suggestions for the videos you would like me to concentrate on or in 80 videos you would like me to create you can connect with me on Discord and discuss them or you can just leave a comment below uh Happy coding and I will see you next time bye
|
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
|
978 |
hey what's up guys this is chung here so this time lead code number 978 longest turbulent sub array right so this time we're given like array and then we need to find the turbulent so what is the turbulent turbulence is the rays that you know every adjacent pair of elements uh the comparison sign will be flipped right so which means that you know if the first one right so basically if the first one is greater than the second one right and then the second has to be smaller than the third one and the third one has to be greater than this fourth one so on and so forth right and it asks us to find the longest one right and so it has oh it has to be strictly a greater or smaller right so equal doesn't count that's why for example this one the answer is 5 because we have 4 is greater than 2 is smaller than 10 is greater than 7 is smaller than 8 but 80 it is equal to eight that's why we stop at here that's why the answer is five right four comparisons and then we do a plus one in the end okay and so that's a constraint right i mean this one uh apparently the brutal force is that you know at each of the location right each of the location i here we can just either go left or go right trying to find uh we should find out the longest one right uh starting from i here we go to left all the way until we couldn't find it until we couldn't find like uh a reverse sign here right so we're assuming this current one ending at i right that's how we uh check that but this one is a square time complexity right that's why i do a tle so i so this one we can use dp right the dynamic programming concept because you know let's say we are right i here right we're at i so we're so basically this dpi means that you know uh we're assuming the current i the this turbulent array ending with i right so basically you know if we know and when we can compare the numbers uh i and i my i minus 1 right and i minus 1 if the i is greater than i minus 1 right so if i is greater if this one is greater than i minus one then what no what does it mean then we if we know uh ending with i minus one if it's smaller for the forever this one right if it's like yeah if i minus one is smaller than the previous one then we don't have to go all the way back right that's why you know i uh for this dp we need two values right so basically we need to have greater i and then we have a smaller i'm not sure if this name is proper enough smaller i so this one means that you know ending with i right ending with i and then the last and i is greater than i minus 1 right so this one is similar this one is the i smaller than i minus one right so if we can define this two dp array here then at each i here right base depending on the comparison result for this i and i minus one we can choose to use the either smaller one or greater or the greater one right because if i is greater than i minus one right then we know okay we can use the smaller one because we want to know ending with uh when ending with i minus one and the last one the last sign is small right because currently current one is greater so same thing if the current one is smaller than i minus one then we know okay we need to use the greater one right here just so that we can make sure the uh the raise is it can be guaranteed as is a turbulent array right and apparently when these two are the same we simply we can just keep that because we know if it's the same we don't need to go uh basically the answer for this i will be one right just the number itself and yeah so as you guys can see so in this way right we just need to go uh through one uh for loop because at each of the index here we can just use the previously calculated result either smaller one or greater one instead of going all the way back right um yeah so let's start coding and so we have n because this r and then we have a greater right so i initiate everything into one because the minimum answer for this problem is always one because the number itself can construct a length 1 turbulent array right that's why at each of the location the default value is always 1. for i in range of one to n right so if array so we start from second one okay if the cardinal one is greater than array of i minus one right and then okay so if that's the case right then the greater i right going to be equal to the smaller of i minus one plus one right so b this means that you know since the current y is greater than uh since the i is greater than i minus one then we know okay the greater i means that you know ending with i and that the last sign is greater we can just use that you can just uh we will need to update that one with the smaller i minus one right similarly right if the size smaller and array dot i minus one if that's the case then we know okay so this one the current value is smaller that's why we'll update the smaller one right it's a greater i minus one plus one right so in the end we just do this right because the uh the turbulent array can add can end at any position that's why we just need to do an another max here uh or we can do this actually we can do this let's do a answer is equals to zero equals to one actually um you can do this so answer is going to be the max of answer dot greater i order smaller i right okay yeah we just update the answer along the way right and yeah i think that's it so right see so it works right um yeah as you guys can see the time complexity is it's often right we only have this uh for loop here and the space complexity is also all of it right uh but if you guys look uh take a look so i'll the either the grid greater i or smaller i always depending on the i minus one right so that's why uh that's why we can just uh improve this space complexity from o of n to o of one right how do we how should we do it uh easy we just uh first we instead of array which you simply use like um a variable right and here you know since we're going to update that you know that's why we're gonna are we gonna create like a attempt two temp variables right they're gonna be smaller one right equals the greater one equals to one right so because that's how we uh start those things right and then we do a greater one right equals to smaller uh basically the greater one and the smaller one will be the new greater and smaller and this smaller greater will be the old one right so and we simply just replace them respectfully right this one is going to be a smaller one and it's going to be a greater right okay and then in the end don't forget uh okay you know yeah we can keep this one here so it's gonna be a greater one smaller one right and then in the end don't forget to assign them back right so basically the greater gonna be a greater one right and smaller could be the smaller one right so this should just work right so now we only have a constant uh space complexity now right um yeah i think that's it right i mean it's a pretty uh basic dp problem right um based on the comparison result right of the current one the previous uh previous one we choose to use either the smaller one or the greater one right and then in the end we just combine both of them to get the maximum max number max length of the turbulent array um cool i think that's it for this one and thank you for watching this video guys stay tuned see you guys soon bye
|
Longest Turbulent Subarray
|
valid-mountain-array
|
Given an integer array `arr`, return _the length of a maximum size turbulent subarray of_ `arr`.
A subarray is **turbulent** if the comparison sign flips between each adjacent pair of elements in the subarray.
More formally, a subarray `[arr[i], arr[i + 1], ..., arr[j]]` of `arr` is said to be turbulent if and only if:
* For `i <= k < j`:
* `arr[k] > arr[k + 1]` when `k` is odd, and
* `arr[k] < arr[k + 1]` when `k` is even.
* Or, for `i <= k < j`:
* `arr[k] > arr[k + 1]` when `k` is even, and
* `arr[k] < arr[k + 1]` when `k` is odd.
**Example 1:**
**Input:** arr = \[9,4,2,10,7,8,8,1,9\]
**Output:** 5
**Explanation:** arr\[1\] > arr\[2\] < arr\[3\] > arr\[4\] < arr\[5\]
**Example 2:**
**Input:** arr = \[4,8,12,16\]
**Output:** 2
**Example 3:**
**Input:** arr = \[100\]
**Output:** 1
**Constraints:**
* `1 <= arr.length <= 4 * 104`
* `0 <= arr[i] <= 109`
|
It's very easy to keep track of a monotonically increasing or decreasing ordering of elements. You just need to be able to determine the start of the valley in the mountain and from that point onwards, it should be a valley i.e. no mini-hills after that. Use this information in regards to the values in the array and you will be able to come up with a straightforward solution.
|
Array
|
Easy
|
1766
|
105 |
hello guys so let's talk about construct binary tree from pre-order and in order binary tree from pre-order and in order binary tree from pre-order and in order to traversal so given two individual arrays pre-order so given two individual arrays pre-order so given two individual arrays pre-order in order where pre-order is the pre-order where pre-order is the pre-order where pre-order is the pre-order traversal of a binary tree and in order is the inorder traversal of the century construct and return the expanding tree so you get a basic basically you are given a tree and you will give it to a ray wines period the other one is in order so preorder is you go over yourself first and left and right subtree later and in order is you go your left first and then yourself and right so you will get to this diagram i mean to this array so i'm going to show you a diagram how uh how the pre-order in order to build how the pre-order in order to build how the pre-order in order to build based on the array so you're giving the uh you are going to have a root value in the beginning for your pre-order your pre-order your pre-order no matter what and in order is like somewhere in the between of the left and right or right so whenever you go through the pre-order whenever you go through the pre-order whenever you go through the pre-order you'll find it in order so the size of the router left is equal to from the inorder is equal to the pre-order's is equal to the pre-order's is equal to the pre-order's uh router at f and then explode right in order is equal to preorder router right so uh let's just uh call this a usc id so i will have a helper function definitely public tree node and i'm going to say putri no middleware so i do have the pre-order in a so i do have the pre-order in a so i do have the pre-order in a pre-order array and pre-order star pre-order array and pre-order star pre-order array and pre-order star pre-order store and pre-order store and pre-order store and pre-order in okay so this is two pre-order in okay so this is two pre-order in okay so this is two um two main important stuff for pre-order index pre-order index pre-order index and send as an order and then i have the inorder star and in order and so what you actually need to do is just return view tree and then preorder and 0 to preorder the length -1 and then comma -1 and then comma -1 and then comma and another sentence motor lengths minus one okay so whatever you build from this helper function this is really important so what i will do is uh let's talk about the root value so the value for root is the beginning pre-order dot index the beginning pre-order dot index the beginning pre-order dot index zero which is pre-order star right so i say equal to zero at the beginning right then i need to know what is the index in order when the root value occurred in the pre-order array so for n occurred in the pre-order array so for n occurred in the pre-order array so for n i equal to 0 i less than in order uh actually it's not here sorry uh it's storefront in order to start sorry and with in order that lens and sorry l a plus so i'm going to find final root value if in order at i is equal to root value then you set the index equal to i and then you break this is actually how you find the index root value in the in order so let me just repeat can i say the index that variable for an order to find the value for the root value to find the root value in a in order array so i start from an order star so don't start from zero when you cut into the half to find on your left substrate and red substrate is not actually start from zero you start from where you actually split so in order to start to in order n and then you have the check condition in order i is equal to the value then you set the index now we can actually know what happened for the tree no root equal to new which we know so we can actually know the true value is equal to the root value and we have the root of left and we do have a route.right route.right route.right so root of left and right array is using a recursion idea so i do have a view tree and i do have pre-order array and i'm and i do have pre-order array and i'm and i do have pre-order array and i'm going to skip the pre-order going to skip the pre-order going to skip the pre-order index first then i do have a in order so if you split if sorry if you split the in order index for the left subtree didn't you just do the inorder star to the index you find and then what do you actually need to do plus one or minus one should be minus one right because we already know the root value is equal to the tree root and same thing for the pre-order pre-order pre-order i'm going to skip the period index and to the right is index plus one sorry plus one and an order n this is how you actually know but you actually need to split on your left subtree and right subtree now let's talk about pre-order so we do now let's talk about pre-order so we do now let's talk about pre-order so we do have to know uh there is a result all right i just closed the picture but the pre-order is at least you have a you have the root valve and then after that is with the left after they screw that right and in order it's simple is root the left first root valve and root up right this is how you actually do right so we already know the root value right so we can actually know the size of the root of left how do you actually do is here in size uh i'm going to call left size is equal to the index is at this position right index minus uh another star right why do i have to minus thing or to start because um when you cut into the half right it's it won't be a zero every single time so i mean when you actually split this is how you actually know the size of the left and we can actually know so pre-order and we can actually know so pre-order and we can actually know so pre-order is actually becomes um pre-order is actually becomes um pre-order is actually becomes um pre-order right pre-order star plus one right pre-order star plus one right pre-order star plus one two over here right so how do you actually know what was the index over there so i'm going to say pre-order so i'm going to say pre-order so i'm going to say pre-order pre-start okay so this is pre-start okay so this is pre-start okay so this is uh through the left right so pre-order uh through the left right so pre-order uh through the left right so pre-order star and plus one because we already take a wave the root value right so you start from pre-order star plus one pre-order star plus one pre-order star plus one two pre-order two pre-order two pre-order start plus left size so a good idea right this is how you actually split so plus one you start from here and so you have to know the size of the root of left is uh preorder stop plus left sides so including root value we do have the same length for the root of bell plus root of left so the idea will be the similar to root.right root.right root.right so root.right will become uh so root.right will become uh so root.right will become uh will you actually end so pre-star where would i just start so pre-star where would i just start so pre-star where would i just start so pre-star plus left sides plus one right so we continuous on the left subtree uh yeah continuous on the left substrate to the right subtree so where do you actually end just pre and this is simple and at the end you just return root but beforehand we need a base case because we keep calling yourself right so that would be if i'm going to say pre-star if precise i'm going to say pre-star if precise i'm going to say pre-star if precise greater than pre-end greater than pre-end greater than pre-end you just return now so we know we actually need to stop and let's see do i have error or not but i do have error so probably three no yeah three no okay i do have another pre-order star okay pre-order stop pre-order star okay pre-order stop pre-order star okay pre-order stop pre-order and i'm going to see do i have pre-order and i'm going to see do i have pre-order and i'm going to see do i have typo yes pre-order n and pre-order star typo yes pre-order n and pre-order star typo yes pre-order n and pre-order star sorry making typo in order star in their scene with okay let's just run again and hopefully yes i pause it should be good right so let's talk about time and space so how many times you visit uh in the rain you only visit once right so if you break out if you meet this condition you just break i mean you return the note and then you start backing up so the time is all the time space is all the thing right because you build a tree only once another twice not the third so that would be the time and space complexity all the fun for both so that will be the solution and good luck
|
Construct Binary Tree from Preorder and Inorder Traversal
|
construct-binary-tree-from-preorder-and-inorder-traversal
|
Given two integer arrays `preorder` and `inorder` where `preorder` is the preorder traversal of a binary tree and `inorder` is the inorder traversal of the same tree, construct and return _the binary tree_.
**Example 1:**
**Input:** preorder = \[3,9,20,15,7\], inorder = \[9,3,15,20,7\]
**Output:** \[3,9,20,null,null,15,7\]
**Example 2:**
**Input:** preorder = \[-1\], inorder = \[-1\]
**Output:** \[-1\]
**Constraints:**
* `1 <= preorder.length <= 3000`
* `inorder.length == preorder.length`
* `-3000 <= preorder[i], inorder[i] <= 3000`
* `preorder` and `inorder` consist of **unique** values.
* Each value of `inorder` also appears in `preorder`.
* `preorder` is **guaranteed** to be the preorder traversal of the tree.
* `inorder` is **guaranteed** to be the inorder traversal of the tree.
| null |
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
|
Medium
|
106
|
289 |
hey what's up guys this is zhong so let's take a look at this one today's dating challenge problem number 289 game of life um so you're given like a 2d board m by n grades of cells and each cell only has two values so one represent live and g represents that and each cell interacts with its eight neighbors okay so and you need to use the following four rules to update the boards so they're like four rules right so if any live cell with fewer than two live neighbors it dies okay because of underpopulation and any live cell with two or three live neighbors and leaves on to the next generation and any life that is more than three live neighbors dies and so basically you know so if there's like a cell right so if the cell is one and if this current cell has uh has either less than two neighbors or more than three neighbors then this uh this one will become to zero that's the first rule and second rule is that if the current cell is zero and if there are like three neighbors who has who uh who has the value one right for example in this case then this zero will become one okay and so a key thing here is that you know all this all the cells needs to be updated simultaneously and you just need to return the next state right which means that uh basically each of the cell will apply uh these four rules at the same time and then we have the next state right so this problem seems pretty straightforward right so i mean the most straightforward way is that you know we make a copy out of the board so that it will i mean then we just use it and we use either one as a source and then we do the update on the other one so that you know we can do the all the updates at the same time so the only tricky part for this problem is that you know whenever we change like one to zero we don't want that one or zero affect all the other like cells and like i said so the first the most straightforward one is we straightforward solutions we just make a copy and then we just use that one as a source right and but we have some follow-ups so i'll and but we have some follow-ups so i'll and but we have some follow-ups so i'll be focusing on those follow-up questions so i mean the those follow-up questions so i mean the those follow-up questions so i mean the uh the first one is that can you solve it in place which means that can you solve it without making a copy of the board so to stop to make solve this problem in place so i mean a common trick you know for this kind of like uh update all the cells at the same time is the uh we up we usually update the value to its negative version of it for example if we have one here we update it to minus one so the reason being is that you know we have minus one but so basically we check this one we when we update with negative versions we distinguish with the original status while maintaining the value of the previous of the original state and that's the common trick for to solve this and i think that's the only thing we need to do it here and yeah so about the coding right so we have directions right we have eight directions so the eight directions is something like this right so we're gonna i'm just copying it from a notepad here and then we have m times uh board that's the rows and the column is the board of zero okay and then we just basically loops through all the other cells and then we check we try to update that cell in place so we have i and we have j because all those four rules require us to calculate the live neighbors right for the current cell so for each of the cell i'm going to have like a live neighbors okay to start with it's zero and then for each of the direction right so in directions and then we have a new i equals to the i plus d zero okay and new j goes to j plus d one we check we first we check the uh the border of this uh the new and new j so if the new i is within the 0 to m and similar same for the new j 0 to n so that's that right and what and the uh the board right so and new i and new j is equal to one then we just uh increase the neighbor by one so here i think this is the place where we need to use the that trick basically you know here instead of a board and i uh new ni and j here we should use like the absolute value of that so the reason being is that you know if in case the current one will become to zero and but later on when the underground the other uh cell trying to see to calculate the life neighbors for his uh for his neighbors we can still find this one value here okay yeah and that's and then the uh we check if the current one basically if the board you know sorry if the board is one right if the board i j equals to one and what and the uh and the live neighbor is if it's smaller than two which is the root one right or the live neighbor is greater than three then we will set the board i j to the minus one yeah so that's the uh that's the trick i was talking about so that you know later on we can just uh use this negative value to still find out okay so the neighbors there is like a one that there right um so that's the case for like a person for like a cell changing from one to zero and the next one is the last one is this one the root four here so we also need to check right if the board i and j is equal to zero okay and the live neighbor is three okay so this one is the case like live to that right and this one is the other way around that to life so in this case right so and again we cannot simply change this one to one back to one because that will affect the uh the calculation for the other nodes so here and for the case uh from that to leave here actually we uh we can use like the any other like uh any other um numbers other than one five it doesn't really matter as long as it is not one because later on we'll just use this one to update it back to one yeah so that's that right so at the end of this for loop here so we'll only have like two possible values actually three possible values so i'm sorry two new possible values in this 2d board we'll have like zero and one we also have we it could also have like minus one and a five so for minus one it means that so minus one means that it was live but now it's that so which means that in the end we need to update the minus one to zero and same for the five case so if it is five then we need to update it means that it is live now so we need to update the five to one that's why we simply do a another nested for loop here right j in range and here if the board i j is equal to 5 right and then which is the update board i j equals to 1. and i'll see if right house if the board i and j is equal to -1 i and j is equal to -1 i and j is equal to -1 right and then we just update it change it to zero okay i mean the uh so the time complexity is i think just like off of m times n right and space complexity or one because we're not introducing any of the uh the new space yeah i think that's the main thing for this problem i mean the only things the only trick we need to be to remember is like this right so whenever we're trying to use some values right that will be changed at the same time we usually change it to the to his negative version so that we can just use its value with absolute abs function yep and that's basically the follow-up the first follow-up and follow-up the first follow-up and follow-up the first follow-up and so for the second follow-up right i mean so for the second follow-up right i mean so for the second follow-up right i mean dl i mean if you check the solutions there are already like some many discussions regarding the second follow-up second follow-up second follow-up so basically the second follow-up is so basically the second follow-up is so basically the second follow-up is just saying that you know what if this 2d board is like an infinite it's very it's too big to be fit in the system memory what's gonna so what can we do or another scenario is that where if there's only a few live cells and all the others they're all like that then what's gonna happen right so if there's like which means there's a really sparse uh 2d board what's going to happen so there i mean the discussion it's like basically there are two like possible uh solutions you know so the first one is that you know if there's only a few live cells we can just uh only store those live cells coordinates right into the uh into some like a list and then we only populate tho those lives those live set those live cells so that's the first solution and second one is the uh what if you cannot fit in the uh the this the board into the system memory so what's going to happen so how can we solve it since you know since the cell you know the current cells only can only needs his eight neighbors which is like this one it's eight neighbors and so it means that all we need to always need to load into the memory is only the previous row and the net next row and then we can just keep roll rotating those three rows yeah basically that's the solution for the second follow-up so whenever we cannot load the follow-up so whenever we cannot load the follow-up so whenever we cannot load the uh the entire data set to the memories we just need to load the data that's uh the current cell that needs yep cool i think that's it and thank you so much for watching this video stay tuned guys see you soon bye
|
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
|
1,828 |
hey guys and this is steve um hope you guys are doing well today let's go through little problem 1828 i think this is um today this is this morning's contest the second question um pretty streetville actually brute force but i just want to quickly go through um so that don't be scared just by looking at the graph right there's circles there's different colors there's coordinates so when faced with a problem like this just don't be scary it's actually pretty straightforward so let's take a look at the problem so problem is queries are number of points inside a circle so you are given two array one is points where points is in 2d array so say like this point 1 3 5 3 2. so this is basically x and y coordinates for example 1 3 is 1 is here 3 is here so 1 3 is this point 3 is here three is here is this point so the points it's at it's denoting by two coordinates two dimensions right and then there is the on the 2d plane then there is another parameter which is queries so query is an array that has three dimensions describes a circle so x y and r x y is basically denoting the circle the center of this circle and r is just the radius and the query is asking us for each query queries j compute the number of points inside the j circle so query this is a circle and the first parameter is all of the points that are spread out through this 2d plane the question is asking us to compute the number of points that fall inside or on the border of the circle the number of how many points either in or on the body of the circle for each of the circles so um the idea is pretty straightforward we'll just go through both queries and points for every single query or every single circle we just loop through the points to see how many points are within this circle on the bot or on the border of the circle then we just add the just assign the result for each of the query to the final result there is no i don't think this is brute force or you could call it brute force or that's the only way to do this um yeah so and how do we calculate so then the problem naturally comes down to how do we calculate if a point is within the border or on the border of this given circle very simple math we just do as long as x minus the center of the x on the x dimensions times itself and plus on the y dimension as long as these two add up is smaller than or equal to the square of the radius that's it then that means this point is meeting the requirements meaning it's either weaving or on the border of the circle so that's it that's the idea to solve this problem um actually i thought it should be labeled as easy but it's meaning it's the second uh question and the second problem during the contest so let's quickly put the idea into actual code let's take a look and see result new int query queries length and then return result so what we'll do we'll go through every single point uh we'll go through every single query yeah query queries meaning we'll go through every single circle for every single silver will have to go through every single point points if say p 0 minus what's the minus and q uh zero so this one this is on the x net dimension if this one times itself plus this one on the y dimension times itself is smaller than or equal to q 2 0 1 2 right q has three parameters for each queue which the third parameter index at two is the prime is the radius times itself oops i'll just do like this times itself it's not smaller than or equal to the radius times itself meaning the square of the radius which is to use let's say points how many points are there pts plus and then we'll have another variable as the index for this result i equals points that's it that's the idea so here we have two we have a nasty for loop the first photo is to go through every single circle and the second following is to go through every single point for every single point we need to check whether this point falls within the current circle or on the border of the current circle if that's the case we'll just increment the points and then assign points after going through all of the points we know how many points are within or on the body of the circle then we just assign the points to the result with that and then we increment i we go through this all right now let's run code and see if it works all right yeah accept it now let me hit submit all right yeah accept it 100 although there's an asset follow-up i although there's an asset follow-up i although there's an asset follow-up i don't think again i don't think this is brute force because we have to go through every single point and in order to check for every single query every single circle we have to go through every single circle as well so yeah that's the idea very straightforward problem and time complex time complexity is the length the number of points and the number of queries this is n if this is m then the time complexity is n times m space complexity is one we don't need any extra space if we don't consider the final result if we consider the final result that's just the om if m is the length of the query right all right this is the idea of this problem if this helps you guys understand the problem of the solution please do me a favor and hit that like button that's going to really help i really appreciate that and don't forget to subscribe to my channel as i have accumulated quite a lot of different tutorials videos about data structures algorithms dfs bfs priority queue whatever you name it to help people better prepare for the technical coding interviews uh yeah so hopefully i'll just um so feel free to check them out so hopefully i'll just see you guys in just a few short seconds in my other videos thank you so much for watching
|
Queries on Number of Points Inside a Circle
|
count-ways-to-distribute-candies
|
You are given an array `points` where `points[i] = [xi, yi]` is the coordinates of the `ith` point on a 2D plane. Multiple points can have the **same** coordinates.
You are also given an array `queries` where `queries[j] = [xj, yj, rj]` describes a circle centered at `(xj, yj)` with a radius of `rj`.
For each query `queries[j]`, compute the number of points **inside** the `jth` circle. Points **on the border** of the circle are considered **inside**.
Return _an array_ `answer`_, where_ `answer[j]` _is the answer to the_ `jth` _query_.
**Example 1:**
**Input:** points = \[\[1,3\],\[3,3\],\[5,3\],\[2,2\]\], queries = \[\[2,3,1\],\[4,3,1\],\[1,1,2\]\]
**Output:** \[3,2,2\]
**Explanation:** The points and circles are shown above.
queries\[0\] is the green circle, queries\[1\] is the red circle, and queries\[2\] is the blue circle.
**Example 2:**
**Input:** points = \[\[1,1\],\[2,2\],\[3,3\],\[4,4\],\[5,5\]\], queries = \[\[1,2,2\],\[2,2,2\],\[4,3,2\],\[4,3,3\]\]
**Output:** \[2,3,2,4\]
**Explanation:** The points and circles are shown above.
queries\[0\] is green, queries\[1\] is red, queries\[2\] is blue, and queries\[3\] is purple.
**Constraints:**
* `1 <= points.length <= 500`
* `points[i].length == 2`
* `0 <= xi, yi <= 500`
* `1 <= queries.length <= 500`
* `queries[j].length == 3`
* `0 <= xj, yj <= 500`
* `1 <= rj <= 500`
* All coordinates are integers.
**Follow up:** Could you find the answer for each query in better complexity than `O(n)`?
|
Try to define a recursive approach. For the ith candies, there will be one of the two following cases: If the i - 1 previous candies are already distributed into k bags for the ith candy, you can have k * dp[n - 1][k] ways to distribute the ith candy. We need then to solve the state of (n - 1, k). If the i - 1 previous candies are already distributed into k - 1 bags for the ith candy, you can have dp[n - 1][k - 1] ways to distribute the ith candy. We need then to solve the state of (n - 1, k - 1). This approach will be too slow and will traverse some states more than once. We should use memoization to make the algorithm efficient.
|
Dynamic Programming
|
Hard
| null |
304 |
a look about the zero Lee code 304 range sum query 2D immutable given 2D Matrix handle the multiple queries of the following types calculate the sum of the element of Matrix inside the rectangle defined by its upper left corner Row 1 and column 1 and lower right corner Row 2 and the column to implement number Matrix class number Matrix initialize object with in integer Matrix in some region Row one and column one Row 2 column two Returns the sum of the element of the Matrix inside the rectangle defined by its upper left corner Row one row one roll call column one and right lower right corner row two and column two you must design an algorithm where some range works at o1 complexities um it shows how you behave The Constructor you can see in here um uh accept the 2D Matrix right 2D Matrix and pre-compute some data that 2D Matrix and pre-compute some data that 2D Matrix and pre-compute some data that the some region function takes four parameters the solution use a technique called 2D prefix sum speed up the sum region query some region query and tell right down here some region query queries um speed up the some region query it computes the uh pre-computes the sum of computes the uh pre-computes the sum of computes the uh pre-computes the sum of sub rectangle pre-computes sum of sub rectangle pre-computes sum of sub rectangle pre-computes sum of sub rectangle pre-compute sum of sub rectangle starting from o to the ending at the IG right ending coordinate the sum of sub precompute the sum of sub rectangles starting from 002 IG the pre-computation allows system to IG the pre-computation allows system to IG the pre-computation allows system to answer in constant time the original the sum region functions use the C plus and D plus to match the indexes of the sum in 2D array the adjustment is needed because some array is y in the exposed Dimension well the query coordinates a b c d are zero indexed right in other words some array has an extra row and extra column to facilitate easier calculation therefore when you query the sub rectangle you have to adjust the bottom right corner coordinate CD to C plus one the D plus one to get the sum of the correct sub rectangle in one index sum array according to AV for top uh top right left corner do not need adjustment in the query because when you subtract the value at this coordinate you are effectively working with one index logics a b remains up is it Remains the Same because it's a right down here so it's a uh it's a CD is a bottom right we'll write down here where it's here okay bottom right and bottom right C two c to get the sum of the one and in one indexes right because this is for you to get the it's one indexed and coordinate a B for top corner do not need to adjust because uh do not need to adjust in the query because you subtract the value at this coordinate you effectively working with one index logics so AP remains acid well CT get increments by one gets equipment by one that's increments the bottom right down to bottom Left Right increased by one why sub region function say they are incremented the increments ensure the sum of the element is in the correct sub triangle returns sub triangles Erectors so it's a Logix right left CD B minus one right B minus one B minus 1 then a minus 1 B minus one uh look at here A minus a minus 1 D A minus a minus 1 d k minus a so uh I will put this one in here you will see more clearly about the uh about the I want to copy you can see over here can be smaller CT what is CT equal to minus a g and G1 and G one then this is the region of the sum okay so you keep minusing so you can see over here so you want to Take minusing 2 and plus the correct one right plus the correct one so this is to calculate the but this is for the software and but this one is for the L plus upper this is left right left then plus minus what left upper that's the Logics okay uh let's understand another question
|
Range Sum Query 2D - Immutable
|
range-sum-query-2d-immutable
|
Given a 2D matrix `matrix`, handle multiple queries of the following type:
* Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`.
Implement the `NumMatrix` class:
* `NumMatrix(int[][] matrix)` Initializes the object with the integer matrix `matrix`.
* `int sumRegion(int row1, int col1, int row2, int col2)` Returns the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`.
You must design an algorithm where `sumRegion` works on `O(1)` time complexity.
**Example 1:**
**Input**
\[ "NumMatrix ", "sumRegion ", "sumRegion ", "sumRegion "\]
\[\[\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]\], \[2, 1, 4, 3\], \[1, 1, 2, 2\], \[1, 2, 2, 4\]\]
**Output**
\[null, 8, 11, 12\]
**Explanation**
NumMatrix numMatrix = new NumMatrix(\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]);
numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)
numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)
numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 200`
* `-104 <= matrix[i][j] <= 104`
* `0 <= row1 <= row2 < m`
* `0 <= col1 <= col2 < n`
* At most `104` calls will be made to `sumRegion`.
| null |
Array,Design,Matrix,Prefix Sum
|
Medium
|
303,308
|
1,971 |
welcome back everyone we're going to be solving Lee code 1971 find if path exists in graph so there is a bi-directional graph with so there is a bi-directional graph with so there is a bi-directional graph with n vertices where each vertex is labeled from 0 to n minus 1. the edges in the graph are represented as a 2d integer array called edges where each edges of I is going to be equal to U of I V of I which it denotes a bi-directional edge between the vertex U bi-directional edge between the vertex U bi-directional edge between the vertex U of I and vertex V of I every vertex pair is connected by at most one Edge and no vertex has an edge to itself we want to determine if there is a valid path that exists from vertex source to vertex destination Okay so this is clearly a graph problem we need to find let's take a look at example one we need to find a way to get from zero to two and we can see in the picture that we can either go from zero straight to two or we can go from zero to one to two so whenever we can get from our source to our destination we return true now what do they give us an edge list so whenever we're given an edge list we have to either create an adjacency Matrix or an adjacency list and the most common thing to do is to create an adjacency list so that is what I'm going to be doing here but if you want to go the Matrix route you can go right ahead and do that so we'll say graph is going to be equal to a dictionary we will say 4 Edge in edges we will grab the vertex u and v which I'm going to call A and B and that's going to be equal to our Edge now we need to check if a and b are in our graph so we'll say if a is not in our graph what do we do that means we have to add it so we'll say graph of a will be equal to an empty list now we have to do the same thing for B so if B not in graph what do we say graph of B is going to be equal to an empty list now what happens if a and b are in our graph that means we just have to add the edge to the uh to the list right so we can say graph of a dot append B in graph of B dot append a so let's print this out so we can see what we're working with print out our graph run this okay so now we can see node 0 has an edge to one and two and we can see that in this picture right zero goes to 1 and 0 goes to two we can see Node 1 has an edge to zero and two right node one zero node one to two okay now we need to find out how to find a path from an example one's case Zero to two how can we do that well we know it's a graph problem and we know we have to Traverse right so what are our graph traversal algorithms their depth first search and breadth first search right so you can use whatever you want either or will work but I am more comfortable with a breadth first search so that's what I'm going to be using so we will say Q will be a DQ and what do we have to put on our queue in order to start this algorithm right we have to put something on here and we can't just put any node we want right we have to have a starting point well as a matter of fact they give us that starting point right it's the source so we put the source node on our queue and let me just import our queue from our collections so from collections we will import the DQ okay now we don't ever want to be traversing the same note twice so we're going to use something called a visited set right and it's just going to be a set and every time we pop a note off of our queue we're just going to add it to our visited set so now it's just a matter of running our breadth first search algorithm right so we can say well the length of our Q is not equal to zero what are we going to do we're gonna pop that leftmost node off of our queue right Q dot pop left okay now what well now we have to make sure that the node actually is not no and it exists within our graph and we haven't visited it before so the first thing we'll do is we'll say if node is not none we're going to do something what are we going to do we're going to check is that node have we already visited yet if um if node is in our graph and it's not in visited set so we'll say if node not in graph and node not in our visited set then we can do something what are we going to do we have to grab all of the edges right that our node has and we have to add those edges to our queue so we'll say four neighbor in graph of the current working node we are going to add that neighbor to our cue so we'll say Q dot append neighbor okay now what right we're done we've added all of the neighbors to our queue what do we do now well once we've done that we can add that node that current working node to our visited set so after this for loop we're going to say visited dot add the working node now we have forgotten something if you've been paying attention and that is to check whether we have found a path from our source to our destination how are we going to do that well if we ever run into if this node ever equals our destination value right that means we have found a path so we just checked that we just checked if node ever equals destination we can return true otherwise we're going to run this part of the loop and then if we ever exit this while loop and we never ran this condition I'll just never returned true we can just return a latent return false meaning we have there exists no path from our source to our destination so let's run this is looking pretty good to me yep we'll run this we fail one test case or Y let's see here visited and set 1990 zero if no is equal to destination we return true if node is not none okay if node is not in our graph ah this should be in our graph not in our graph endnote Is Not Invisible okay now yes this should run now so we'll run this yep we passed both test cases so we'll submit perfect it does run so what are the time and space complexities for this problem the time complexity is going to be o of the number of edges that we have to Traverse in order to find you know a path if it exists from our source to our destination the space complexity is going to be o of n right the number of nodes that we're storing within our graph okay that'll do it for Lee code 1971
|
Find if Path Exists in Graph
|
incremental-memory-leak
|
There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by **at most one** edge, and no vertex has an edge to itself.
You want to determine if there is a **valid path** that exists from vertex `source` to vertex `destination`.
Given `edges` and the integers `n`, `source`, and `destination`, return `true` _if there is a **valid path** from_ `source` _to_ `destination`_, or_ `false` _otherwise__._
**Example 1:**
**Input:** n = 3, edges = \[\[0,1\],\[1,2\],\[2,0\]\], source = 0, destination = 2
**Output:** true
**Explanation:** There are two paths from vertex 0 to vertex 2:
- 0 -> 1 -> 2
- 0 -> 2
**Example 2:**
**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[3,5\],\[5,4\],\[4,3\]\], source = 0, destination = 5
**Output:** false
**Explanation:** There is no path from vertex 0 to vertex 5.
**Constraints:**
* `1 <= n <= 2 * 105`
* `0 <= edges.length <= 2 * 105`
* `edges[i].length == 2`
* `0 <= ui, vi <= n - 1`
* `ui != vi`
* `0 <= source, destination <= n - 1`
* There are no duplicate edges.
* There are no self edges.
|
What is the upper bound for the number of seconds? Simulate the process of allocating memory.
|
Simulation
|
Medium
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.